프로세서 가져오기(v1)

기존 Document AI 프로세서의 세부정보를 가져옵니다.

코드 샘플

Go

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

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


import (
	"context"
	"fmt"
	"io"

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

// getProcessor retrieves a Document AI processor.
func getProcessor(ctx context.Context, w io.Writer, projectID string, locationID string, processorID string) error {
	name := fmt.Sprintf("projects/%s/locations/%s/processors/%s", projectID, locationID, processorID)

	// Document AI requires the regional endpoint corresponding to the processor location.
	endpoint := fmt.Sprintf("%s-documentai.googleapis.com:443", locationID)
	client, err := documentai.NewDocumentProcessorClient(ctx, option.WithEndpoint(endpoint))
	if err != nil {
		return fmt.Errorf("NewDocumentProcessorClient: %w", err)
	}
	defer client.Close()

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

	processor, err := client.GetProcessor(ctx, req)
	if err != nil {
		return fmt.Errorf("GetProcessor: %w", err)
	}

	fmt.Fprintf(w, "Processor Name: %s\n", processor.GetName())
	fmt.Fprintf(w, "Display Name: %s\n", processor.GetDisplayName())
	fmt.Fprintf(w, "Type: %s\n", processor.GetType())
	fmt.Fprintf(w, "State: %s\n", processor.GetState())

	return nil
}

Java

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

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

import com.google.cloud.documentai.v1.DocumentProcessorServiceClient;
import com.google.cloud.documentai.v1.DocumentProcessorServiceSettings;
import com.google.cloud.documentai.v1.GetProcessorRequest;
import com.google.cloud.documentai.v1.Processor;
import com.google.cloud.documentai.v1.ProcessorName;

public class GetProcessor {

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

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

    // Initialize the client with Application Default Credentials.
    try (DocumentProcessorServiceClient client = DocumentProcessorServiceClient.create(settings)) {
      String name = ProcessorName.of(projectId, locationId, processorId).toString();

      GetProcessorRequest request = GetProcessorRequest.newBuilder().setName(name).build();

      Processor response = client.getProcessor(request);

      System.out.println("Processor Name: " + response.getName());
      System.out.println("Display Name: " + response.getDisplayName());
      System.out.println("Processor Type: " + response.getType());
      System.out.println("Processor State: " + response.getState());
    }
  }
}

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

/**
 * Use the getProcessor method to retrieve details about an existing processor.
 *
 * @param {string} projectId - The Google Cloud project ID.
 * @param {string} locationId - The Document AI location (for example, 'us' or 'eu').
 * @param {string} processorId - The server-generated ID of the processor to retrieve.
 */
async function getProcessor(projectId, locationId, processorId) {
  try {
    const name = `projects/${projectId}/locations/${locationId}/processors/${processorId}`;

    const request = {
      name,
    };

    const [processor] = await client.getProcessor(request);

    console.log(`Processor Name: ${processor.name}`);
    console.log(`Display Name: ${processor.displayName}`);
    console.log(`Processor Type: ${processor.type}`);
    console.log(`State: ${processor.state}`);

    return processor;
  } catch (err) {
    if (err.code === status.NOT_FOUND) {
      console.error(`Processor not found: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { getProcessor };

Python

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

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

import google.api_core.exceptions
from google.cloud import documentai_v1

client = documentai_v1.DocumentProcessorServiceClient()


def get_processor(project_id: str, location_id: str, processor_id: str) -> None:
    """Retrieves information about a processor.

    Args:
        project_id: The Google Cloud project ID.
        location_id: The Google Cloud location ID (for example, 'us' or 'eu').
        processor_id: The ID of the processor to retrieve.
    """
    name = f"projects/{project_id}/locations/{location_id}/processors/{processor_id}"

    request = documentai_v1.GetProcessorRequest(name=name)

    try:
        response = client.get_processor(request=request)
        print(f"Processor name: {response.name}")
        print(f"Display name: {response.display_name}")
        print(f"Processor type: {response.type_}")
        print(f"Processor state: {response.state.name}")
    except google.api_core.exceptions.GoogleAPICallError as e:
        print(f"API call failed: {e}")

다음 단계

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