Enumera los tipos de procesadores

Enumera todos los tipos de procesadores disponibles

Explora más

Para obtener documentación detallada en la que se incluya esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Para obtener más información, consulta la documentación de referencia de la API de Document AI para Go.

Para autenticarte en Document AI, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


import (
	"context"
	"errors"
	"fmt"
	"io"

	documentai "cloud.google.com/go/documentai/apiv1beta3"
	documentaipb "cloud.google.com/go/documentai/apiv1beta3/documentaipb"
	"google.golang.org/api/iterator"
	"google.golang.org/api/option"
)

// listProcessorTypes retrieves all processor types available in the specified location.
func listProcessorTypes(ctx context.Context, w io.Writer, projectID string, locationID string) error {
	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID)

	endpoint := fmt.Sprintf("%s-documentai.googleapis.com:443", locationID)
	client, err := documentai.NewDocumentProcessorClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewDocumentProcessorClient failed: %w", err)
	}
	defer client.Close()

	req := &documentaipb.ListProcessorTypesRequest{
		Parent: parent,
	}

	it := client.ListProcessorTypes(ctx, req)
	for {
		pt, err := it.Next()
		if errors.Is(err, iterator.Done) {
			break
		}
		if err != nil {
			return fmt.Errorf("failed to retrieve processor type: %w", err)
		}

		fmt.Fprintf(w, "Processor type: %s, category: %s\n", pt.GetType(), pt.GetCategory())
	}

	return nil
}

Java

Para obtener más información, consulta la documentación de referencia de la API de Document AI para Java.

Para autenticarte en Document AI, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.ListProcessorTypesRequest;
import com.google.cloud.documentai.v1.ProcessorType;
import java.io.IOException;

public class ListProcessorTypes {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    String locationId = "us";
    listProcessorTypes(projectId, locationId);
  }

  public static void listProcessorTypes(String projectId, String locationId) throws Exception {
    // Initialize the client with the regional endpoint.
    String endpoint = String.format("%s-documentai.googleapis.com:443", locationId);
    DocumentProcessorServiceSettings settings =
        DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();

    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      String parent = String.format("projects/%s/locations/%s", projectId, locationId);
      ListProcessorTypesRequest request =
          ListProcessorTypesRequest.newBuilder().setParent(parent).build();

      for (ProcessorType processorType : client.listProcessorTypes(request).iterateAll()) {
        System.out.printf("Processor type: %s%n", processorType.getType());
        System.out.printf("Category: %s%n", processorType.getCategory());
      }
    }
  }
}

Node.js

Para obtener más información, consulta la documentación de referencia de la API de Document AI para Node.js.

Para autenticarte en Document AI, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

'use strict';

const {DocumentProcessorServiceClient} = require('@google-cloud/documentai');
const {status} = require('@grpc/grpc-js');

const client = new DocumentProcessorServiceClient();

/**
 * Use the listProcessorTypes method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 * @param {string} locationId - The Google Cloud region where the service is located (for example, 'us-central1')
 */
async function listProcessorTypes(projectId, locationId) {
  try {
    const parent = client.locationPath(projectId, locationId);

    const request = {
      parent,
    };

    const [processorTypes] = await client.listProcessorTypes(request);

    for (const processorType of processorTypes) {
      console.log(`Type: ${processorType.type}`);
      console.log(`Category: ${processorType.category}`);
      console.log(`Allow creation: ${processorType.allowCreation}`);
    }
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error('Location or project not found.', err.message);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error('Permission denied for the requested resource.', err.message);
    } else if (err.code !== undefined) {
      console.error(`API request failed with status code ${err.code}:`, err.message);
    } else {
      console.error('An unexpected error occurred:', err);
    }
  }
}

module.exports = { listProcessorTypes };

Python

Para obtener más información, consulta la documentación de referencia de la API de Document AI para Python.

Para autenticarte en Document AI, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.


from google.api_core.client_options import ClientOptions
from google.cloud import documentai  # type: ignore

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_PROCESSOR_LOCATION' # Format is 'us' or 'eu'


def fetch_processor_types_sample(project_id: str, location: str) -> None:
    # You must set the api_endpoint if you use a location other than 'us'.
    opts = ClientOptions(api_endpoint=f"{location}-documentai.googleapis.com")

    client = documentai.DocumentProcessorServiceClient(client_options=opts)

    # The full resource name of the location
    # e.g.: projects/project_id/locations/location
    parent = client.common_location_path(project_id, location)

    # Fetch all processor types
    response = client.fetch_processor_types(parent=parent)

    print("Processor types:")
    # Print the available processor types
    for processor_type in response.processor_types:
        if processor_type.allow_creation:
            print(processor_type.type_)

¿Qué sigue?

Si quieres buscar y filtrar muestras de código para otros productos de Google Cloud , consulta el navegador de muestras deGoogle Cloud .