프로세서 사용 설정(v1)

Document AI 프로세서를 사용 설정합니다.

코드 샘플

Go

자세한 내용은 Document AI Go API 참고 문서를 참조하세요.

Document AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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

자세한 내용은 Document AI Java API 참고 문서를 참조하세요.

Document AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

자세한 내용은 Document AI Node.js API 참고 문서를 참조하세요.

Document AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

'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 };

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기