Detectar texto en archivos PDF o TIFF

La API Vision puede detectar y transcribir texto de archivos PDF y TIFF almacenados en Cloud Storage.

La detección de texto de documentos PDF y TIFF debe solicitarse mediante la función files:asyncBatchAnnotate, que realiza una solicitud sin conexión (asíncrona) y proporciona su estado mediante los recursos operations.

La salida de una solicitud de PDF o TIFF se escribe en un archivo JSON creado en el segmento de Cloud Storage especificado.

Limitaciones

La API Vision acepta archivos PDF o TIFF de hasta 2000 páginas. Los archivos más grandes devolverán un error.

Autenticación

Las claves de API no se admiten en las solicitudes de files:asyncBatchAnnotate. Consulta Usar una cuenta de servicio para obtener instrucciones sobre cómo autenticarte con una cuenta de servicio.

La cuenta que se utilice para la autenticación debe tener acceso al segmento de Cloud Storage que especifiques para la salida (roles/editor o roles/storage.objectCreator o versiones posteriores).

Puedes usar una clave de API para consultar el estado de la operación. Consulta las instrucciones en Usar una clave de API.

Solicitudes de detección de texto en documentos

Actualmente, la detección de documentos PDF o TIFF solo está disponible para los archivos almacenados en segmentos de Cloud Storage. Los archivos JSON de respuesta se guardan de forma similar en un segmento de Cloud Storage.

Página PDF del censo de EE. UU. del 2010
gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf, Fuente: Oficina del Censo de los Estados Unidos.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • CLOUD_STORAGE_BUCKET: un segmento o directorio de Cloud Storage en el que guardar los archivos de salida. Se expresa de la siguiente forma:
    • gs://bucket/directory/
    El usuario que hace la solicitud debe tener permiso de escritura en el cubo.
  • CLOUD_STORAGE_FILE_URI: la ruta a un archivo válido (PDF o TIFF) en un segmento de Cloud Storage. Debe tener al menos privilegios de lectura en el archivo. Ejemplo:
    • gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf
  • FEATURE_TYPE: un tipo de función válido. Para las solicitudes files:asyncBatchAnnotate, puede usar los siguientes tipos de funciones:
    • DOCUMENT_TEXT_DETECTION
    • TEXT_DETECTION
  • PROJECT_ID: tu ID de proyecto Google Cloud .

Consideraciones específicas de los campos:

  • inputConfig: sustituye al campo image que se usa en otras solicitudes de la API Vision. Contiene dos campos secundarios:
    • gcsSource.uri: el URI de Google Cloud Storage del archivo PDF o TIFF (accesible para el usuario o la cuenta de servicio que hace la solicitud).
    • mimeType: uno de los tipos de archivo aceptados: application/pdf o image/tiff.
  • outputConfig: especifica los detalles de la salida. Contiene dos campos secundarios:
    • gcsDestination.uri: un URI de Google Cloud Storage válido. El usuario o la cuenta de servicio que hace la solicitud debe tener permiso de escritura en el segmento. El nombre del archivo será output-x-to-y, donde x y y representan los números de página del PDF o TIFF incluidos en ese archivo de salida. Si el archivo existe, su contenido se sobrescribirá.
    • batchSize: especifica cuántas páginas de salida se deben incluir en cada archivo JSON de salida.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "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 tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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"

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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
Respuesta:

Una solicitud asyncBatchAnnotate correcta devuelve una respuesta con un solo campo de nombre:

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

Este nombre representa una operación de larga duración con un ID asociado (por ejemplo, 1efec2285bd442df), que se puede consultar mediante la API v1.operations.

Para recuperar la respuesta de anotación de Vision, envía una solicitud GET al endpoint v1.operations y pasa el ID de operación en la URL:

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

Por ejemplo:

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

Si la operación está en curso:

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

Una vez que se haya completado la operación, el state se mostrará como DONE y los resultados se escribirán en el archivo de Google Cloud Storage que hayas 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
        }
      }
    ]
  }
}

El JSON de tu archivo de salida es similar al de una [solicitud de detección de texto de documento](/vision/docs/ocr) de una imagen, con la adición de un campo context que muestra la ubicación del PDF o TIFF especificado y el número de páginas del archivo:

output-1-to-1.json

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración de Go que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración de Java que se indican en la guía de inicio rápido de la API Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Vision en 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");
    }
  }
}

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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);

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración de Python que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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"])

gcloud

El comando gcloud que uses dependerá del tipo de archivo.

  • Para realizar la detección de texto en PDF, usa el comando gcloud ml vision detect-text-pdf, como se muestra en el siguiente ejemplo:

    gcloud ml vision detect-text-pdf gs://my_bucket/input_file  gs://my_bucket/out_put_prefix
    
  • Para realizar la detección de texto TIFF, usa el comando gcloud ml vision detect-text-tiff como se muestra en el siguiente ejemplo:

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

Idiomas adicionales

C#: Sigue las instrucciones de configuración de C# en la página de bibliotecas de cliente y, a continuación, consulta la documentación de referencia de Vision para .NET.

PHP Sigue las instrucciones de configuración de PHP en la página de bibliotecas de cliente y, a continuación, consulta la documentación de referencia de Vision para PHP.

Ruby: Sigue las instrucciones de configuración de Ruby en la página de bibliotecas de cliente y, a continuación, consulta la documentación de referencia de Vision para Ruby.

Asistencia multirregional

Ahora puedes especificar el almacenamiento de datos y el procesamiento OCR a nivel continental. Actualmente se admiten las siguientes regiones:

  • us: solo en EE. UU.
  • eu: la Unión Europea

Ubicaciones

Cloud Vision te ofrece cierto control sobre dónde se almacenan y procesan los recursos de tu proyecto. En concreto, puede configurar Cloud Vision para que almacene y trate sus datos únicamente en la Unión Europea.

De forma predeterminada, Cloud Vision almacena y procesa los recursos en una ubicación global, lo que significa que Cloud Vision no garantiza que tus recursos permanezcan en una ubicación o región concretas. Si eliges la ubicación Unión Europea, Google almacenará tus datos y los tratará únicamente en la Unión Europea. Tanto tú como tus usuarios podéis acceder a los datos desde cualquier ubicación.

Definir la ubicación mediante la API

La API Vision admite un punto de conexión de API global (vision.googleapis.com) y dos puntos de conexión basados en regiones: uno para la Unión Europea (eu-vision.googleapis.com) y otro para Estados Unidos (us-vision.googleapis.com). Usa estos puntos de conexión para el procesamiento específico de cada región. Por ejemplo, para almacenar y tratar tus datos solo en la Unión Europea, usa el URI eu-vision.googleapis.com en lugar de vision.googleapis.com en tus llamadas a la 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 almacenar y tratar tus datos solo en Estados Unidos, usa el endpoint de EE. UU. (us-vision.googleapis.com) con los métodos anteriores.

Definir la ubicación mediante las bibliotecas de cliente

Las bibliotecas de cliente de la API Vision acceden al endpoint de la API global (vision.googleapis.com) de forma predeterminada. Para almacenar y tratar sus datos únicamente en la Unión Europea, debe definir explícitamente el endpoint (eu-vision.googleapis.com). En los siguientes ejemplos de código se muestra cómo configurar este ajuste.

REST

Antes de usar los datos de la solicitud, haz las siguientes sustituciones:

  • REGION_ID: uno de los identificadores de ubicación regional válidos:
    • us: solo en EE. UU.
    • eu: la Unión Europea
  • CLOUD_STORAGE_IMAGE_URI: la ruta a un archivo de imagen válido en un segmento de Cloud Storage. Debe tener al menos privilegios de lectura en el archivo. Ejemplo:
    • gs://cloud-samples-data/vision/pdf_tiff/census2010.pdf
  • CLOUD_STORAGE_BUCKET: un segmento o directorio de Cloud Storage en el que guardar los archivos de salida. Se expresa de la siguiente forma:
    • gs://bucket/directory/
    El usuario que hace la solicitud debe tener permiso de escritura en el cubo.
  • FEATURE_TYPE: un tipo de función válido. Para las solicitudes files:asyncBatchAnnotate, puede usar los siguientes tipos de funciones:
    • DOCUMENT_TEXT_DETECTION
    • TEXT_DETECTION
  • PROJECT_ID: tu ID de proyecto Google Cloud .

Consideraciones específicas de los campos:

  • inputConfig: sustituye al campo image que se usa en otras solicitudes de la API Vision. Contiene dos campos secundarios:
    • gcsSource.uri: el URI de Google Cloud Storage del archivo PDF o TIFF (accesible para el usuario o la cuenta de servicio que hace la solicitud).
    • mimeType: uno de los tipos de archivo aceptados: application/pdf o image/tiff.
  • outputConfig: especifica los detalles de la salida. Contiene dos campos secundarios:
    • gcsDestination.uri: un URI de Google Cloud Storage válido. El usuario o la cuenta de servicio que hace la solicitud debe tener permiso de escritura en el segmento. El nombre del archivo será output-x-to-y, donde x y y representan los números de página del PDF o TIFF incluidos en ese archivo de salida. Si el archivo existe, su contenido se sobrescribirá.
    • batchSize: especifica cuántas páginas de salida se deben incluir en cada archivo JSON de salida.

Método HTTP y URL:

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

Cuerpo JSON de la solicitud:

{
  "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 tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

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"

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$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
Respuesta:

Una solicitud asyncBatchAnnotate correcta devuelve una respuesta con un solo campo de nombre:

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

Este nombre representa una operación de larga duración con un ID asociado (por ejemplo, 1efec2285bd442df), que se puede consultar mediante la API v1.operations.

Para recuperar la respuesta de anotación de Vision, envía una solicitud GET al endpoint v1.operations y pasa el ID de operación en la URL:

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

Por ejemplo:

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

Si la operación está en curso:

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

Una vez que se haya completado la operación, el state se mostrará como DONE y los resultados se escribirán en el archivo de Google Cloud Storage que hayas 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
        }
      }
    ]
  }
}

El JSON de tu archivo de salida es similar al de la respuesta de detección de texto de un documento de una imagen si has usado la función DOCUMENT_TEXT_DETECTION, o al de la respuesta de detección de texto si has usado la función TEXT_DETECTION. El resultado tendrá un campo context adicional que mostrará la ubicación del PDF o TIFF especificado y el número de páginas del archivo:

output-1-to-1.json

Go

Antes de probar este ejemplo, sigue las instrucciones de configuración de Go que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Go de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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
}

Java

Antes de probar este ejemplo, sigue las instrucciones de configuración de Java que se indican en la guía de inicio rápido de la API Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Vision en 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);

Node.js

Antes de probar este ejemplo, sigue las instrucciones de configuración de Node.js que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Node.js de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo 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();

Python

Antes de probar este ejemplo, sigue las instrucciones de configuración de Python que se indican en la guía de inicio rápido de Vision con bibliotecas de cliente. Para obtener más información, consulta la documentación de referencia de la API Python de Vision.

Para autenticarte en Vision, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

from google.cloud import vision

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

client = vision.ImageAnnotatorClient(client_options=client_options)

Pruébalo

Si es la primera vez que utilizas Google Cloud, crea una cuenta para evaluar el rendimiento de Cloud Vision API en situaciones reales. Los nuevos clientes también reciben 300 USD en crédito gratuito para ejecutar, probar y desplegar cargas de trabajo.

Prueba la API Cloud Vision gratis