문서 분석

모델을 만들어 학습시킨 후에는 모델에서 예측을 요청할 수 있습니다. 예측은 모델에 문서를 제출하고 해당 모델의 목표(분류, 항목 추출 또는 감정 분석)에 따라 문서를 분석하도록 요청할 때 발생합니다.

AutoML Natural Language는 모델이 제출된 단일 문서에 대해 동기식 분석을 수행하는 온라인 예측 뿐 아니라 문서 모음에 대해 비동기식 분석을 수행하는 일괄 예측도 지원합니다.

온라인 예측

AutoML Natural Language UI를 사용하여 예측하려면 다음 안내를 따르세요.

  1. 왼쪽 탐색 메뉴에서 전구 아이콘을 클릭하여 사용 가능한 모델을 표시합니다.

    다른 프로젝트의 모델을 보려면 제목 표시줄 오른쪽 위에 있는 드롭다운 목록에서 프로젝트를 선택하세요.

  2. 문서 분석에 사용할 모델의 행을 클릭합니다.

  3. 제목 표시줄 바로 아래에 있는 테스트 및 사용 탭을 클릭합니다.

  4. 텍스트 상자에 분석할 텍스트를 입력하거나 Cloud Storage에서 파일 선택을 클릭하고 PDF 또는 TIFF 파일의 Cloud Storage 경로를 입력합니다.

  5. 예측을 클릭합니다.

코드 샘플

분류

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • model-id: 모델 ID

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models/model-id:predict

JSON 요청 본문:

{
  "payload" : {
    "textSnippet": {
      "content": "Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show.  Sundar Pichai said in his keynote that users love their new Android phones.",
        "mime_type": "text/plain"
      },
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "payload": [
    {
      "displayName": "Technology",
      "classification": {
        "score": 0.8989502
      }
    },
    {
      "displayName": "Automobiles",
      "classification": {
        "score": 0.10098731
      }
    }
  ]
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# content = "text to predict"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Supported mime_types: 'text/plain', 'text/html'
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsnippet
text_snippet = automl.TextSnippet(content=content, mime_type="text/plain")
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)

for annotation_payload in response.payload:
    print(f"Predicted class name: {annotation_payload.display_name}")
    print(f"Predicted class score: {annotation_payload.classification.score}")

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

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

import com.google.cloud.automl.v1.AnnotationPayload;
import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;

class LanguageTextClassificationPredict {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String content = "text to predict";
    predict(projectId, modelId, content);
  }

  static void predict(String projectId, String modelId, String content) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // For available mime types, see:
      // https://cloud.google.com/automl/docs/reference/rest/v1/projects.locations.models/predict#textsnippet
      TextSnippet textSnippet =
          TextSnippet.newBuilder()
              .setContent(content)
              .setMimeType("text/plain") // Types: text/plain, text/html
              .build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);

      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
        System.out.format(
            "Predicted sentiment score: %.2f\n\n",
            annotationPayload.getClassification().getScore());
      }
    }
  }
}

Node.js

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const content = 'text to predict'

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new PredictionServiceClient();

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
        mimeType: 'text/plain', // Types: 'text/plain', 'text/html'
      },
    },
  };

  const [response] = await client.predict(request);

  for (const annotationPayload of response.payload) {
    console.log(`Predicted class name: ${annotationPayload.displayName}`);
    console.log(
      `Predicted class score: ${annotationPayload.classification.score}`
    );
  }
}

predict();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageTextClassificationPredict does a prediction for text classification.
func languageTextClassificationPredict(w io.Writer, projectID string, location string, modelID string, content string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TCN123456789..."
	// content := "text to classify"

	ctx := context.Background()
	client, err := automl.NewPredictionClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPredictionClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.PredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		Payload: &automlpb.ExamplePayload{
			Payload: &automlpb.ExamplePayload_TextSnippet{
				TextSnippet: &automlpb.TextSnippet{
					Content:  content,
					MimeType: "text/plain", // Types: "text/plain", "text/html"
				},
			},
		},
	}

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

	for _, payload := range resp.GetPayload() {
		fmt.Fprintf(w, "Predicted class name: %v\n", payload.GetDisplayName())
		fmt.Fprintf(w, "Predicted class score: %v\n", payload.GetClassification().GetScore())
	}

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

항목 추출

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • model-id: 모델 ID

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models/model-id:predict

JSON 요청 본문:

{
  "payload" : {
    "textSnippet": {
      "content": "The Wilms tumor-suppressor gene, WT1, plays a key role in urogenital development, and WT1 dysfunction is implicated in both neoplastic and nonneoplastic (glomerulosclerosis) disease. The analysis of diseases linked specifically with WT1 mutations, such as Denys-Drash syndrome (DDS), can provide valuable insight concerning the role of WT1 in development and disease.  We report that heterozygosity for a targeted murine Wt1 allele, Wt1 (tmT396), which truncates ZF3 at codon 396, induces mesangial sclerosis characteristic of DDS in adult heterozygous and chimeric mice. Male genital defects also were evident and there was a single case of Wilms tumor in which the transcript of the nontargeted allele showed an exon 9 skipping event, implying a causal link between Wt1 dysfunction and Wilms tumorigenesis in mice. However, the mutant WT1 (tmT396) protein accounted for only 5% of WT1 in both heterozygous embryonic stem cells and the WT. This has implications regarding the mechanism by which the mutant allele exerts its effect.",
      "mime_type": "text/plain"
      },
   }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "annotations": [
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 67,
          "start_offset": 62
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 158,
          "start_offset": 141
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 330,
          "start_offset": 290
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 337,
          "start_offset": 332
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 627,
          "start_offset": 610
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 754,
          "start_offset": 749
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 875,
          "start_offset": 865
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 968,
          "start_offset": 951
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 1553,
          "start_offset": 1548
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 1652,
          "start_offset": 1606
        }
      },
      "display_name": "CompositeMention"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 1833,
          "start_offset": 1826
        }
      },
      "display_name": "DiseaseClass"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 1860,
          "start_offset": 1843
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 1930,
          "start_offset": 1913
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 2129,
          "start_offset": 2111
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 2188,
          "start_offset": 2160
        }
      },
      "display_name": "SpecificDisease"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 2260,
          "start_offset": 2243
        }
      },
      "display_name": "Modifier"
    },
    {
      "text_extraction": {
        "text_segment": {
          "end_offset": 2356,
          "start_offset": 2339
        }
      },
      "display_name": "Modifier"
    }
  ],
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# content = "text to predict"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Supported mime_types: 'text/plain', 'text/html'
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsnippet
text_snippet = automl.TextSnippet(content=content, mime_type="text/plain")
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)

for annotation_payload in response.payload:
    print(f"Text Extract Entity Types: {annotation_payload.display_name}")
    print(f"Text Score: {annotation_payload.text_extraction.score}")
    text_segment = annotation_payload.text_extraction.text_segment
    print(f"Text Extract Entity Content: {text_segment.content}")
    print(f"Text Start Offset: {text_segment.start_offset}")
    print(f"Text End Offset: {text_segment.end_offset}")

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

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

import com.google.cloud.automl.v1.AnnotationPayload;
import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSegment;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;

class LanguageEntityExtractionPredict {

  static void predict() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String content = "text to predict";
    predict(projectId, modelId, content);
  }

  static void predict(String projectId, String modelId, String content) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // For available mime types, see:
      // https://cloud.google.com/automl/docs/reference/rest/v1/projects.locations.models/predict#textsnippet
      TextSnippet textSnippet =
          TextSnippet.newBuilder()
              .setContent(content)
              .setMimeType("text/plain") // Types: text/plain, text/html
              .build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);

      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        System.out.format("Text Extract Entity Type: %s\n", annotationPayload.getDisplayName());
        System.out.format("Text score: %.2f\n", annotationPayload.getTextExtraction().getScore());
        TextSegment textSegment = annotationPayload.getTextExtraction().getTextSegment();
        System.out.format("Text Extract Entity Content: %s\n", textSegment.getContent());
        System.out.format("Text Start Offset: %s\n", textSegment.getStartOffset());
        System.out.format("Text End Offset: %s\n\n", textSegment.getEndOffset());
      }
    }
  }
}

Node.js

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const content = 'text to predict'

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new PredictionServiceClient();

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
        mimeType: 'text/plain', // Types: 'test/plain', 'text/html'
      },
    },
  };

  const [response] = await client.predict(request);

  for (const annotationPayload of response.payload) {
    console.log(
      `Text Extract Entity Types: ${annotationPayload.displayName}`
    );
    console.log(`Text Score: ${annotationPayload.textExtraction.score}`);
    const textSegment = annotationPayload.textExtraction.textSegment;
    console.log(`Text Extract Entity Content: ${textSegment.content}`);
    console.log(`Text Start Offset: ${textSegment.startOffset}`);
    console.log(`Text End Offset: ${textSegment.endOffset}`);
  }
}

predict();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageEntityExtractionPredict does a prediction for text entity extraction.
func languageEntityExtractionPredict(w io.Writer, projectID string, location string, modelID string, content string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TEN123456789..."
	// content := "text to extract entities"

	ctx := context.Background()
	client, err := automl.NewPredictionClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPredictionClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.PredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		Payload: &automlpb.ExamplePayload{
			Payload: &automlpb.ExamplePayload_TextSnippet{
				TextSnippet: &automlpb.TextSnippet{
					Content:  content,
					MimeType: "text/plain", // Types: "text/plain", "text/html"
				},
			},
		},
	}

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

	for _, payload := range resp.GetPayload() {
		fmt.Fprintf(w, "Text extract entity types: %v\n", payload.GetDisplayName())
		fmt.Fprintf(w, "Text score: %v\n", payload.GetTextExtraction().GetScore())
		textSegment := payload.GetTextExtraction().GetTextSegment()
		fmt.Fprintf(w, "Text extract entity content: %v\n", textSegment.GetContent())
		fmt.Fprintf(w, "Text start offset: %v\n", textSegment.GetStartOffset())
		fmt.Fprintf(w, "Text end offset: %v\n", textSegment.GetEndOffset())
	}

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

감정 분석

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • model-id: 모델 ID

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models/model-id:predict

JSON 요청 본문:

{
  "payload" : {
    "textSnippet": {
      "content": "Enjoy your vacation!",
         "mime_type": "text/plain"
       },
  }
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

성공 상태 코드(2xx)와 빈 응답을 받게 됩니다.

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# content = "text to predict"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = automl.AutoMlClient.model_path(project_id, "us-central1", model_id)

# Supported mime_types: 'text/plain', 'text/html'
# https://cloud.google.com/automl/docs/reference/rpc/google.cloud.automl.v1#textsnippet
text_snippet = automl.TextSnippet(content=content, mime_type="text/plain")
payload = automl.ExamplePayload(text_snippet=text_snippet)

response = prediction_client.predict(name=model_full_id, payload=payload)

for annotation_payload in response.payload:
    print(f"Predicted class name: {annotation_payload.display_name}")
    print(
        "Predicted sentiment score: {}".format(
            annotation_payload.text_sentiment.sentiment
        )
    )

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

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

import com.google.cloud.automl.v1.AnnotationPayload;
import com.google.cloud.automl.v1.ExamplePayload;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.PredictRequest;
import com.google.cloud.automl.v1.PredictResponse;
import com.google.cloud.automl.v1.PredictionServiceClient;
import com.google.cloud.automl.v1.TextSnippet;
import java.io.IOException;

class LanguageSentimentAnalysisPredict {

  static void predict() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String content = "text to predict";
    predict(projectId, modelId, content);
  }

  static void predict(String projectId, String modelId, String content) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);

      // For available mime types, see:
      // https://cloud.google.com/automl/docs/reference/rest/v1/projects.locations.models/predict#textsnippet
      TextSnippet textSnippet =
          TextSnippet.newBuilder()
              .setContent(content)
              .setMimeType("text/plain") // Types: text/plain, text/html
              .build();
      ExamplePayload payload = ExamplePayload.newBuilder().setTextSnippet(textSnippet).build();
      PredictRequest predictRequest =
          PredictRequest.newBuilder().setName(name.toString()).setPayload(payload).build();

      PredictResponse response = client.predict(predictRequest);

      for (AnnotationPayload annotationPayload : response.getPayloadList()) {
        System.out.format("Predicted class name: %s\n", annotationPayload.getDisplayName());
        System.out.format(
            "Predicted sentiment score: %d\n", annotationPayload.getTextSentiment().getSentiment());
      }
    }
  }
}

Node.js

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const content = 'text to predict'

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new PredictionServiceClient();

async function predict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    payload: {
      textSnippet: {
        content: content,
        mimeType: 'text/plain', // Types: 'test/plain', 'text/html'
      },
    },
  };

  const [response] = await client.predict(request);

  for (const annotationPayload of response.payload) {
    console.log(`Predicted class name: ${annotationPayload.displayName}`);
    console.log(
      `Predicted sentiment score: ${annotationPayload.textSentiment.sentiment}`
    );
  }
}

predict();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// languageSentimentAnalysisPredict does a prediction for text sentiment analysis.
func languageSentimentAnalysisPredict(w io.Writer, projectID string, location string, modelID string, content string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "TST123456789..."
	// content := "text to analyze sentiment"

	ctx := context.Background()
	client, err := automl.NewPredictionClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPredictionClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.PredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		Payload: &automlpb.ExamplePayload{
			Payload: &automlpb.ExamplePayload_TextSnippet{
				TextSnippet: &automlpb.TextSnippet{
					Content:  content,
					MimeType: "text/plain", // Types: "text/plain", "text/html"
				},
			},
		},
	}

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

	for _, payload := range resp.GetPayload() {
		fmt.Fprintf(w, "Predicted class name: %v\n", payload.GetDisplayName())
		fmt.Fprintf(w, "Predicted sentiment score: %v\n", payload.GetTextSentiment().GetSentiment())
	}

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.

일괄 예측

모델에서 문서 코퍼스에 대해 처리량이 높은 비동기식 예측을 수행하도록 하려면 batchPredict 메서드를 사용하세요. 일괄 예측 방법을 사용하려면 Cloud Storage 버킷의 위치를 가리키는 입력 및 출력 URI를 지정해야 합니다.

입력 URI는 분석할 콘텐츠를 지정하는 CSV 또는 JSONL 파일을 가리킵니다. 분류 및 감정 분석에 CSV 파일을 사용합니다. 항목 추출에는 JSONL 파일을 사용합니다. 출력은 AutoML Natural Language가 일괄 예측의 결과를 저장하는 위치를 지정합니다.

분류 및 감정 분석에 분류할 입력 파일을 나열하는 단일 열이 있는 CSV 파일을 행마다 하나씩 만듭니다. CSV 파일과 각 입력 파일은 Cloud Storage 버킷에 저장되어야 합니다.

gs://folder/text1.txt
gs://folder/text2.pdf

항목 추출의 경우 분석할 모든 콘텐츠가 포함된 JSONL 파일을 인라인으로 또는 Cloud Storage 버킷에 저장된 파일의 링크로 준비해야 합니다. 다음 예시에서는 JSONL 파일에 포함된 인라인 콘텐츠를 보여줍니다. 각 항목은 고유 ID를 포함해야 합니다.

{ "id": "0", "text_snippet": { "content": "First item content to be analyzed." } }
{ "id": "1", "text_snippet": { "content": "Second item content to be analyzed." } }
...
{ "id": "n", "text_snippet": { "content": "Last item content to be analyzed." } }

다음 예시에서는 Cloud Storage 버킷에 있어야 하는 입력 파일의 링크를 포함하는 JSONL 파일을 보여줍니다.

{ "document": { "input_config": { "gcs_source": { "input_uris": [ "gs://folder/document1.pdf" ] } } } }
{ "document": { "input_config": { "gcs_source": { "input_uris": [ "gs://folder/document2.tif" ] } } } }
...

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • project-id: 프로젝트 ID입니다.
  • location-id: 리소스의 위치로, 전역 위치의 경우 us-central1, 유럽 연합의 경우 eu
  • model-id: 모델 ID

HTTP 메서드 및 URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/location-id/models/model-id:batchPredict

JSON 요청 본문:

{
  "input_config": { "gcs_source": { "input_uris": [ "csv-file-URI"] } },
  "output_config": { "gcs_destination": { "output_uri_prefix": "dest-dir-URI" } }
 }

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 출력이 표시됩니다. 작업 ID를 사용하여 작업 상태를 가져올 수 있습니다. 예제를 보려면 작업 상태 가져오기를 참조하세요.

{
  "name": "projects/434039606874/locations/us-central1/operations/TCN8195786061721370625",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2019-03-13T15:37:49.972372Z",
    "updateTime": "2019-03-13T15:37:49.972372Z"
  }
}

Python

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Python API 참조 문서를 참조하세요.

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

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# model_id = "YOUR_MODEL_ID"
# input_uri = "gs://YOUR_BUCKET_ID/path/to/your/input/csv_or_jsonl"
# output_uri = "gs://YOUR_BUCKET_ID/path/to/save/results/"

prediction_client = automl.PredictionServiceClient()

# Get the full path of the model.
model_full_id = f"projects/{project_id}/locations/us-central1/models/{model_id}"

gcs_source = automl.GcsSource(input_uris=[input_uri])

input_config = automl.BatchPredictInputConfig(gcs_source=gcs_source)
gcs_destination = automl.GcsDestination(output_uri_prefix=output_uri)
output_config = automl.BatchPredictOutputConfig(gcs_destination=gcs_destination)

response = prediction_client.batch_predict(
    name=model_full_id, input_config=input_config, output_config=output_config
)

print("Waiting for operation to complete...")
print(
    f"Batch Prediction results saved to Cloud Storage bucket. {response.result()}"
)

Java

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Java API 참조 문서를 참조하세요.

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

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.BatchPredictInputConfig;
import com.google.cloud.automl.v1.BatchPredictOutputConfig;
import com.google.cloud.automl.v1.BatchPredictRequest;
import com.google.cloud.automl.v1.BatchPredictResult;
import com.google.cloud.automl.v1.GcsDestination;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.ModelName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.PredictionServiceClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

abstract class BatchPredict {

  static void batchPredict() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String modelId = "YOUR_MODEL_ID";
    String inputUri = "gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl";
    String outputUri = "gs://YOUR_BUCKET_ID/path_to_save_results/";
    batchPredict(projectId, modelId, inputUri, outputUri);
  }

  static void batchPredict(String projectId, String modelId, String inputUri, String outputUri)
      throws IOException, ExecutionException, InterruptedException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (PredictionServiceClient client = PredictionServiceClient.create()) {
      // Get the full path of the model.
      ModelName name = ModelName.of(projectId, "us-central1", modelId);
      GcsSource gcsSource = GcsSource.newBuilder().addInputUris(inputUri).build();
      BatchPredictInputConfig inputConfig =
          BatchPredictInputConfig.newBuilder().setGcsSource(gcsSource).build();
      GcsDestination gcsDestination =
          GcsDestination.newBuilder().setOutputUriPrefix(outputUri).build();
      BatchPredictOutputConfig outputConfig =
          BatchPredictOutputConfig.newBuilder().setGcsDestination(gcsDestination).build();
      BatchPredictRequest request =
          BatchPredictRequest.newBuilder()
              .setName(name.toString())
              .setInputConfig(inputConfig)
              .setOutputConfig(outputConfig)
              .build();

      OperationFuture<BatchPredictResult, OperationMetadata> future =
          client.batchPredictAsync(request);

      System.out.println("Waiting for operation to complete...");
      future.get();
      System.out.println("Batch Prediction results saved to specified Cloud Storage bucket.");
    }
  }
}

Node.js

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Node.js API 참조 문서를 참조하세요.

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

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const modelId = 'YOUR_MODEL_ID';
// const inputUri = 'gs://YOUR_BUCKET_ID/path_to_your_input_csv_or_jsonl';
// const outputUri = 'gs://YOUR_BUCKET_ID/path_to_save_results/';

// Imports the Google Cloud AutoML library
const {PredictionServiceClient} = require('@google-cloud/automl').v1;

// Instantiates a client
const client = new PredictionServiceClient();

async function batchPredict() {
  // Construct request
  const request = {
    name: client.modelPath(projectId, location, modelId),
    inputConfig: {
      gcsSource: {
        inputUris: [inputUri],
      },
    },
    outputConfig: {
      gcsDestination: {
        outputUriPrefix: outputUri,
      },
    },
  };

  const [operation] = await client.batchPredict(request);

  console.log('Waiting for operation to complete...');
  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(
    `Batch Prediction results saved to Cloud Storage bucket. ${response}`
  );
}

batchPredict();

Go

AutoML Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 AutoML Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 AutoML Natural Language Go API 참조 문서를 참조하세요.

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

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
)

// batchPredict does a batch prediction.
func batchPredict(w io.Writer, projectID string, location string, modelID string, inputURI string, outputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// modelID := "ICN123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_your_input_csv_or_jsonl"
	// outputURI := "gs://BUCKET_ID/path_to_save_results/"

	ctx := context.Background()
	client, err := automl.NewPredictionClient(ctx)
	if err != nil {
		return fmt.Errorf("NewPredictionClient: %w", err)
	}
	defer client.Close()

	req := &automlpb.BatchPredictRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/models/%s", projectID, location, modelID),
		InputConfig: &automlpb.BatchPredictInputConfig{
			Source: &automlpb.BatchPredictInputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
		OutputConfig: &automlpb.BatchPredictOutputConfig{
			Destination: &automlpb.BatchPredictOutputConfig_GcsDestination{
				GcsDestination: &automlpb.GcsDestination{
					OutputUriPrefix: outputURI,
				},
			},
		},
		Params: map[string]string{
			"score_threshold": "0.8", // [0.0-1.0] Only produce results higher than this value
		},
	}

	op, err := client.BatchPredict(ctx, req)
	if err != nil {
		return fmt.Errorf("BatchPredict: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	resp, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Batch Prediction results saved to Cloud Storage bucket.\n")
	fmt.Fprintf(w, "%v", resp)

	return nil
}

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 AutoML 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 AutoML 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 AutoML 자연 언어 참조 문서를 참조하세요.