Annotazione file batch offline

L'API Vision può rilevare qualsiasi funzionalità dell'API Vision da file PDF e TIFF archiviati in Cloud Storage.

Il rilevamento delle funzionalità da PDF e TIFF deve essere richiesto utilizzando la funzione files:asyncBatchAnnotate, che esegue una richiesta offline (asincrona) e fornisce il proprio stato utilizzando le risorse operations.

L'output di una richiesta PDF/TIFF viene scritto in un file JSON creato nel bucket Cloud Storage specificato.

Limitazioni

L'API Vision accetta file PDF/TIFF fino a 2000 pagine. I file più grandi restituiranno un errore.

Autenticazione

Le chiavi API non sono supportate per le richieste files:asyncBatchAnnotate. Per istruzioni sull'autenticazione con un account di servizio, consulta Utilizzo di un account di servizio.

L'account utilizzato per l'autenticazione deve avere accesso al bucket Cloud Storage specificato per l'output (roles/editor o roles/storage.objectCreator o superiore).

Puoi utilizzare una chiave API per eseguire query sullo stato dell'operazione. Per le istruzioni, consulta la sezione Utilizzo di una chiave API.

Richieste di rilevamento di funzionalità

Attualmente il rilevamento di documenti PDF/TIFF è disponibile solo per i file archiviati nei bucket Cloud Storage. I file JSON di risposta vengono salvati in modo simile in un bucket Cloud Storage.

Riga di comando

Per eseguire il rilevamento del testo dei documenti PDF/TIFF, effettua una richiesta POST e fornisci il corpo della richiesta appropriato:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
https://vision.googleapis.com/v1/files:asyncBatchAnnotate -d "{
  'requests':[
    {
      'inputConfig': {
        'gcsSource': {
          'uri': 'gs://your-source-bucket-name/folder/multi-page-file.pdf'
        },
        'mimeType': 'application/pdf'
      },
      'features': [
        {
          'type': 'DOCUMENT_TEXT_DETECTION'
        }
      ],
      'outputConfig': {
        'gcsDestination': {
          'uri': 'gs://your-bucket-name/folder/'
        },
        'batchSize': 1
      }
    }
  ]
}"

Dove:

  • inputConfig: sostituisce il campo image utilizzato in altre richieste dell'API Vision. Contiene due campi secondari:

    • gcsSource.uri: l'URI Cloud Storage del file PDF o TIFF (accessibile all'account utente o di servizio che effettua la richiesta)
    • mimeType. Uno dei tipi di file accettati: application/pdf o image/tiff.
  • outputConfig: specifica i dettagli dell'output. Contiene due campi secondari:

    • gcsDestination.uri: un URI Cloud Storage valido. Il bucket deve essere scrivibile dall'account utente o di servizio che effettua la richiesta. Il nome del file sarà output-x-to-y, dove x e y rappresentano i numeri di pagina PDF/TIFF inclusi nel file di output. Se il file esiste, i relativi contenuti verranno sovrascritti.
    • batchSize: specifica quante pagine di output devono essere incluse in ogni file JSON di output.

Risposta:

Una richiesta asyncBatchAnnotate riuscita restituisce una risposta con un singolo campo nome:

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

Questo nome rappresenta un'operazione a lunga esecuzione con un ID associato (ad esempio 1efec2285bd442df), su cui è possibile eseguire una query utilizzando l'API v1.operations.

Per recuperare la risposta dell'annotazione di Vision, invia una richiesta GET all'endpoint v1.operations, passando l'ID operazione nell'URL.

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

Se l'operazione è in corso:

{
  "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"
  }
}

Al termine dell'operazione, state viene visualizzato come DONE e i risultati vengono scritti nel file Cloud Storage specificato:

{
  "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
        }
      }
    ]
  }
}

Il JSON nel file di output è simile a quello di una richiesta di rilevamento del testo del documento di un'immagine, con l'aggiunta di un campo context che mostra la posizione del PDF o TIFF specificato e il numero di pagine nel file:

output-1-to-1.json

Go

Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Vision Go.

Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Java

Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di Vision sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Vision Java.

Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

/**
 * 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");
    }
  }
}

Node.js

Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Vision Node.js.

Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


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

Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision sull'utilizzo delle librerie client. Per maggiori informazioni, consulta la documentazione di riferimento dell'API Vision Python.

Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per maggiori informazioni, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

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"])

gcloud

Il comando gcloud che utilizzi dipende dal tipo di file.

  • Per eseguire il rilevamento del testo dei PDF, utilizza il comando gcloud ml vision detect-text-pdf come mostrato nell'esempio seguente:

    gcloud ml vision detect-text-pdf gs://my_bucket/input_file  gs://my_bucket/out_put_prefix
    
  • Per eseguire il rilevamento del testo TIFF, usa il comando gcloud ml vision detect-text-tiff come mostrato nell'esempio seguente:

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

Linguaggi aggiuntivi

C#: segui le istruzioni di configurazione di C# nella pagina delle librerie client e poi consulta la documentazione di riferimento di Vision per .NET.

PHP: segui le istruzioni per la configurazione dei file PHP nella pagina delle librerie client e poi consulta la documentazione di riferimento di Vision per PHP.

Ruby: segui le istruzioni di configurazione di Ruby nella pagina delle librerie client e poi visita la documentazione di riferimento di Vision per Ruby.