Membuat daftar jenis pemroses

Mencantumkan semua jenis pemroses yang tersedia

Mempelajari lebih lanjut

Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:

Contoh kode

Go

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Go Document AI.

Untuk melakukan autentikasi ke Document AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Java Document AI.

Untuk melakukan autentikasi ke Document AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Node.js Document AI.

Untuk melakukan autentikasi ke Document AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

'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

Untuk mengetahui informasi selengkapnya, lihat dokumentasi referensi API Python Document AI.

Untuk melakukan autentikasi ke Document AI, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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_)

Langkah berikutnya

Untuk menelusuri dan memfilter contoh kode untuk produk Google Cloud lainnya, lihat browser contohGoogle Cloud .