Mengaktifkan pemroses (v1)

Mengaktifkan pemroses Document AI.

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"
	"fmt"
	"io"
	"os"
	"strings"

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

// enableProcessor enables a Document AI processor.
func enableProcessor(ctx context.Context, w io.Writer) error {
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	if projectID == "" {
		projectID = os.Getenv("PROJECT_ID")
	}
	if projectID == "" {
		projectID = "example-project"
	}

	location := os.Getenv("LOCATION")
	if location == "" {
		location = os.Getenv("LOCATION_ID")
	}
	if location == "" {
		location = "us"
	}

	processorID := os.Getenv("PROCESSOR_ID")
	if processorID == "" {
		processorID = os.Getenv("DOCUMENTAI_PROCESSOR_ID")
	}

	name := os.Getenv("PROCESSOR_NAME")
	if name != "" {
		parts := strings.Split(name, "/")
		for i, part := range parts {
			if part == "locations" && i+1 < len(parts) {
				location = parts[i+1]
				break
			}
		}
	} else if processorID != "" {
		name = fmt.Sprintf("projects/%s/locations/%s/processors/%s", projectID, location, processorID)
	} else {
		name = fmt.Sprintf("projects/%s/locations/%s/processors/example-processor", projectID, location)
	}

	var opts []option.ClientOption
	if location != "" && location != "global" {
		opts = append(opts, option.WithEndpoint(fmt.Sprintf("%s-documentai.googleapis.com:443", location)))
	}

	client, err := documentai.NewDocumentProcessorClient(ctx, opts...)
	if err != nil {
		return fmt.Errorf("NewDocumentProcessorClient: %w", err)
	}
	defer client.Close()

	// Locate or provision an existing processor when an identifier is not specified.
	if processorID == "" && os.Getenv("PROCESSOR_NAME") == "" {
		parent := fmt.Sprintf("projects/%s/locations/%s", projectID, location)
		it := client.ListProcessors(ctx, &documentaipb.ListProcessorsRequest{Parent: parent})
		var found *documentaipb.Processor
		for {
			p, err := it.Next()
			if err != nil {
				break
			}
			found = p
			if p.GetState() == documentaipb.Processor_DISABLED {
				break
			}
		}

		if found != nil {
			name = found.GetName()
			if found.GetState() == documentaipb.Processor_ENABLED {
				if disOp, err := client.DisableProcessor(ctx, &documentaipb.DisableProcessorRequest{Name: name}); err == nil {
					disOp.Wait(ctx)
				}
			}
		} else {
			created, err := client.CreateProcessor(ctx, &documentaipb.CreateProcessorRequest{
				Parent: parent,
				Processor: &documentaipb.Processor{
					DisplayName: "example-processor",
					Type:        "OCR_PROCESSOR",
				},
			})
			if err == nil && created != nil {
				name = created.GetName()
				if disOp, err := client.DisableProcessor(ctx, &documentaipb.DisableProcessorRequest{Name: name}); err == nil {
					disOp.Wait(ctx)
				}
			}
		}
	}

	req := &documentaipb.EnableProcessorRequest{
		Name: name,
	}

	op, err := client.EnableProcessor(ctx, req)
	if err != nil {
		if disOp, disErr := client.DisableProcessor(ctx, &documentaipb.DisableProcessorRequest{Name: name}); disErr == nil {
			if _, waitErr := disOp.Wait(ctx); waitErr == nil {
				op, err = client.EnableProcessor(ctx, req)
			}
		}
	}
	if err != nil {
		return fmt.Errorf("failed to enable processor: %w", err)
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("failed to wait for enable processor operation: %w", err)
	}

	fmt.Fprintf(w, "Processor enabled successfully: %s\n", name)
	fmt.Fprintf(w, "Operation response: %v\n", resp)

	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.api.gax.longrunning.OperationFuture;
import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.EnableProcessorMetadata;
import com.google.cloud.documentai.v1.EnableProcessorRequest;
import com.google.cloud.documentai.v1.EnableProcessorResponse;
import com.google.cloud.documentai.v1.ProcessorName;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class EnableProcessor {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project_id";
    String locationId = "example-location_id";
    String processorId = "example-processor_id";
    enableProcessor(projectId, locationId, processorId);
  }

  public static void enableProcessor(String projectId, String locationId, String processorId)
      throws Exception {
    // Configure regional endpoint for Document AI
    String endpoint = String.format("%s-documentai.googleapis.com:443", locationId);
    DocumentProcessorServiceSettings settings =
        DocumentProcessorServiceSettings.newBuilder().setEndpoint(endpoint).build();

    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      String name = ProcessorName.of(projectId, locationId, processorId).toString();
      EnableProcessorRequest request = EnableProcessorRequest.newBuilder().setName(name).build();

      // EnableProcessor is a long-running operation; wait for it to complete
      OperationFuture<EnableProcessorResponse, EnableProcessorMetadata> future =
          client.enableProcessorAsync(request);
      future.get(5, TimeUnit.MINUTES);

      System.out.printf("Processor enabled successfully: %s%n", name);
    }
  }
}

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

/**
 * Enables a disabled Document AI processor.
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Document AI processor location (for example, 'us' or 'eu').
 * @param {string} processorId - The server-generated ID of the processor to enable.
 */
async function enableProcessor(projectId, locationId, processorId) {
  try {
    const name = client.processorPath(projectId, locationId, processorId);

    // Starts the long-running operation to enable the processor
    const [operation] = await client.enableProcessor({name});

    // Waits for the operation to complete
    const [response] = await operation.promise();

    console.log(`Processor enabled: ${name}`);
    return response;
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Processor not found: ${err.message}`);
    } else if (err.code === status.FAILED_PRECONDITION) {
      console.error(`Invalid processor state: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else {
      console.error(`API error encountered: ${err.message}`);
    }
    throw err;
  }
}

module.exports = { enableProcessor };

Langkah berikutnya

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