データセットの作成と管理

データセットには、翻訳するコンテンツ タイプの代表サンプルが、ソース言語とターゲット言語の対応する文のペアとして含まれています。このデータセットを入力として利用してモデルをトレーニングします。

データセットの主な作成手順は次のとおりです。

  1. データセットを作成し、ソース言語とターゲット言語を指定します。
  2. データセットに文のペアをインポートします。

1 つのプロジェクトに複数のデータセットを含めることができ、それぞれ別個のモデルのトレーニングに使用されます。使用可能なデータセットの一覧の取得と、不要になったデータセットの削除ができます。

データセットの作成

カスタムモデルを作成するには、まず空のデータセットを作成します。作成したデータセットには、最終的にそのモデルのトレーニング データが格納されます。データセットの作成時に、モデルのソース言語とターゲット言語を指定します。サポートされている言語とバリエーションの詳細については、カスタムモデルに対する言語サポートをご覧ください。

ウェブ UI

AutoML Translation UI を使用すると、新しいデータセットの作成とそのデータセットへの項目のインポートを同じページで行えます。

  1. AutoML Translation UI にアクセスします。

  2. タイトルバーの右上のプルダウン リストから、AutoML Translation を有効にしたプロジェクトを選択します。

  3. [データセット] タブで、[データセットを作成] をクリックします。

    1 つのデータセットを含む [データセット] ページ

  4. [データセットを作成] ダイアログで、次の操作を行います。

    • データセットの名前を入力します。
    • ソース言語とターゲット言語をプルダウン リストから選択します。[原文の言語] で言語を選択すると、[ターゲット言語] に使用可能な言語が表示されます。

    • [作成] をクリックします。[インポート] タブが開きます。

REST

データセット作成リクエストを送信する

POST リクエストを project.locations.datasets/create メソッドに送信する方法を以下に示します。この例では、Google Cloud CLI を使ってプロジェクト用に設定されたサービス アカウントのアクセス トークンを使用します。

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: Google Cloud Platform プロジェクト ID
  • dataset-name: 新しいデータセットの名前
  • source-language-code: 翻訳元の言語(「en」などの ISO 639-1 コード)
  • target-language-code: 翻訳先の言語(「es」などの ISO 639-1 コード)

HTTP メソッドと URL:

POST https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/datasets

リクエストの本文(JSON):

{
    "displayName": "dataset-name",
    "translationDatasetMetadata": {
       "sourceLanguageCode": "source-language-code",
       "targetLanguageCode": "target-language-code"
     }
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-01T22:13:48.155710Z",
    "updateTime": "2019-10-01T22:13:48.155710Z",
    "createDatasetDetails": {}
  }
}

結果を取得する

リクエストの結果を取得するには、GET リクエストを operations リソースに送信します。このようなリクエストを送信する方法は次のとおりです。

リクエストのデータを使用する前に、次のように置き換えます。

  • operation-name: 元の API への呼び出しへのレスポンスで返されるオペレーションの名前
  • project-id: Google Cloud Platform プロジェクト ID

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/operation-name

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-01T22:13:48.155710Z",
    "updateTime": "2019-10-01T22:13:52.321072Z",
    ...
  },
  "done": true,
  "response": {
    "@type": "resource-type",
    "name": "resource-name"
  }
}

Go

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Go API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

// translateCreateDataset creates a dataset for translate.
func translateCreateDataset(w io.Writer, projectID string, location string, datasetName string, sourceLanguageCode string, targetLanguageCode string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetName := "dataset_display_name"

	// Supported languages:
	//   https://cloud.google.com/translate/automl/docs/languages
	// sourceLanguageCode := "en"
	// targetLanguageCode := "ja"

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

	req := &automlpb.CreateDatasetRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Dataset: &automlpb.Dataset{
			DisplayName: datasetName,
			DatasetMetadata: &automlpb.Dataset_TranslationDatasetMetadata{
				TranslationDatasetMetadata: &automlpb.TranslationDatasetMetadata{
					SourceLanguageCode: sourceLanguageCode,
					TargetLanguageCode: targetLanguageCode,
				},
			},
		},
	}

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

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

	fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())

	return nil
}

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.LocationName;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.cloud.automl.v1.TranslationDatasetMetadata;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class TranslateCreateDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String displayName = "YOUR_DATASET_NAME";
    createDataset(projectId, displayName);
  }

  // Create a dataset
  static void createDataset(String projectId, String displayName)
      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 (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");

      // Specify the source and target language.
      TranslationDatasetMetadata translationDatasetMetadata =
          TranslationDatasetMetadata.newBuilder()
              .setSourceLanguageCode("en")
              .setTargetLanguageCode("ja")
              .build();
      Dataset dataset =
          Dataset.newBuilder()
              .setDisplayName(displayName)
              .setTranslationDatasetMetadata(translationDatasetMetadata)
              .build();
      OperationFuture<Dataset, OperationMetadata> future =
          client.createDatasetAsync(projectLocation, dataset);

      Dataset createdDataset = future.get();

      // Display the dataset information.
      System.out.format("Dataset name: %s\n", createdDataset.getName());
      // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
      // required for other methods.
      // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
      String[] names = createdDataset.getName().split("/");
      String datasetId = names[names.length - 1];
      System.out.format("Dataset id: %s\n", datasetId);
    }
  }
}

Node.js

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const displayName = 'YOUR_DISPLAY_NAME';

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

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

async function createDataset() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    dataset: {
      displayName: displayName,
      translationDatasetMetadata: {
        sourceLanguageCode: 'en',
        targetLanguageCode: 'ja',
      },
    },
  };

  // Create dataset
  const [operation] = await client.createDataset(request);

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

  console.log(`Dataset name: ${response.name}`);
  console.log(`
    Dataset id: ${
      response.name
        .split('/')
        [response.name.split('/').length - 1].split('\n')[0]
    }`);
}

createDataset();

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# display_name = "YOUR_DATASET_NAME"

client = automl.AutoMlClient()

# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"
# For a list of supported languages, see:
# https://cloud.google.com/translate/automl/docs/languages
dataset_metadata = automl.TranslationDatasetMetadata(
    source_language_code="en", target_language_code="ja"
)
dataset = automl.Dataset(
    display_name=display_name,
    translation_dataset_metadata=dataset_metadata,
)

# Create a dataset with the dataset metadata in the region.
response = client.create_dataset(parent=project_location, dataset=dataset)

created_dataset = response.result()

# Display the dataset information
print(f"Dataset name: {created_dataset.name}")
print("Dataset id: {}".format(created_dataset.name.split("/")[-1]))

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Translation リファレンス ドキュメントをご覧ください。

データセットへの項目のインポート

データセットを作成したら、トレーニング用の文のペアをそこにインポートできます。トレーニング データの準備の詳細については、トレーニング データの準備方法をご覧ください。

ウェブ UI

AutoML Translation UI を使用すると、新しいデータセットの作成とデータセットへの項目のインポートを同じページで行えます(データセットの作成をご覧ください)。以下の手順では、既存のデータセットに項目をインポートします。

データセット フォルダを作成したら、データをアップロードします。

  1. モデルのトレーニングに使用する文のペアをアップロードします。

    [インポート] タブでは、TSV または TMX ファイルをローカル コンピュータまたは Cloud Storage からアップロードできます。ローカルにインポートされたファイルの場合は、ファイルを選択して [参照] をクリックします。フォルダ一覧が表示されます。ファイルをアップロードするフォルダを選択します。Cloud Storage でホストされているこのディレクトリは、データ所在地を保証するために必要です。

    文のペアを含む複数のファイルをアップロードする場合は、[トレーニング、検証、テストに別のファイルを使用します(上級者向け)] のチェックボックスをオンにします。データセットに 100,000 個を超える文のペアが含まれる場合は、このオプションの使用をおすすめします。検証とテストセットには最大 10,000 個の文のペアを割り当てる必要があります。割り当てられていない場合、AutoML Translation はエラーを返します。

    [インポート] タブ

  2. [続行] をクリックします。

    [データセット] ページに戻ります。ドキュメントのインポート中はデータセットに進行中のアニメーションが表示されます。データセットが正常にアップロードされると、プログラムの登録に使用したメールアドレスにメッセージが送信されます。

  3. データセットを確認します。

    データをインポートできたら、[データセット] タブからデータセットを選択して詳細を確認します。[センテンス] タブが有効になり、データセットの名前が表示されます。センテンスペアが一覧表示されます。各ペアには「トレーニング」、「検証」、「テスト」が割り当てられ、ペアが使用される処理段階が示されます。

REST

projects.locations.datasets.importData メソッドを使用して、アイテムをデータセットにインポートします。

リクエストのデータを使用する前に、次のように置き換えます。

  • dataset-name: データセットを作成したときに API から返されたデータセットの名前
  • bucket-name: データセットを記述する入力 CSV を含む Cloud Storage バケット
  • csv-file-name: データセットを記述する入力 CSV ファイルの名前
  • project-id: Google Cloud Platform プロジェクト ID

HTTP メソッドと URL:

POST https://automl.googleapis.com/v1/dataset-name:importData

リクエストの本文(JSON):

{
  "inputConfig": {
    "gcsSource": {
      "inputUris": "gs://bucket-name/csv-file-name"
    }
  }
}

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1beta1.OperationMetadata",
    "createTime": "2018-04-27T01:28:36.128120Z",
    "updateTime": "2018-04-27T01:28:36.128150Z",
    "cancellable": true
  }
}

Go

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Go API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

// importDataIntoDataset imports data into a dataset.
func importDataIntoDataset(w io.Writer, projectID string, location string, datasetID string, inputURI string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."
	// inputURI := "gs://BUCKET_ID/path_to_training_data.csv"

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

	req := &automlpb.ImportDataRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
		InputConfig: &automlpb.InputConfig{
			Source: &automlpb.InputConfig_GcsSource{
				GcsSource: &automlpb.GcsSource{
					InputUris: []string{inputURI},
				},
			},
		},
	}

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

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

	fmt.Fprintf(w, "Data imported.\n")

	return nil
}

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.cloud.automl.v1.GcsSource;
import com.google.cloud.automl.v1.InputConfig;
import com.google.cloud.automl.v1.OperationMetadata;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

class ImportDataset {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    String path = "gs://BUCKET_ID/path_to_training_data.csv";
    importDataset(projectId, datasetId, path);
  }

  // Import a dataset
  static void importDataset(String projectId, String datasetId, String path)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // 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 (AutoMlClient client = AutoMlClient.create()) {
      // Get the complete path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);

      // Get multiple Google Cloud Storage URIs to import data from
      GcsSource gcsSource =
          GcsSource.newBuilder().addAllInputUris(Arrays.asList(path.split(","))).build();

      // Import data from the input URI
      InputConfig inputConfig = InputConfig.newBuilder().setGcsSource(gcsSource).build();
      System.out.println("Processing import...");

      // Start the import job
      OperationFuture<Empty, OperationMetadata> operation =
          client.importDataAsync(datasetFullId, inputConfig);

      System.out.format("Operation name: %s%n", operation.getName());

      // If you want to wait for the operation to finish, adjust the timeout appropriately. The
      // operation will still run if you choose not to wait for it to complete. You can check the
      // status of your operation using the operation's name.
      Empty response = operation.get(45, TimeUnit.MINUTES);
      System.out.format("Dataset imported. %s%n", response);
    } catch (TimeoutException e) {
      System.out.println("The operation's polling period was not long enough.");
      System.out.println("You can use the Operation's name to get the current status.");
      System.out.println("The import job is still running and will complete as expected.");
      throw e;
    }
  }
}

Node.js

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DISPLAY_ID';
// const path = 'gs://BUCKET_ID/path_to_training_data.csv';

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

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

async function importDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
    inputConfig: {
      gcsSource: {
        inputUris: path.split(','),
      },
    },
  };

  // Import dataset
  console.log('Proccessing import');
  const [operation] = await client.importData(request);

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset imported: ${response}`);
}

importDataset();

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"
# path = "gs://YOUR_BUCKET_ID/path/to/data.csv"

client = automl.AutoMlClient()
# Get the full path of the dataset.
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
# Get the multiple Google Cloud Storage URIs
input_uris = path.split(",")
gcs_source = automl.GcsSource(input_uris=input_uris)
input_config = automl.InputConfig(gcs_source=gcs_source)
# Import data from the input URI
response = client.import_data(name=dataset_full_id, input_config=input_config)

print("Processing import...")
print(f"Data imported. {response.result()}")

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Translation リファレンス ドキュメントをご覧ください。

データセットを作成して入力すると、モデルをトレーニングできるようになります(モデルの作成と管理をご覧ください)。

データセットの管理

データセットの一覧表示

1 つのプロジェクトには多数のデータセットを含めることができます。このセクションでは、プロジェクトで使用できるデータセットを一覧表示する方法を説明します。

ウェブ UI

AutoML Translation UI を使用して利用可能なデータセットを一覧表示するには、左側のナビゲーション メニューの上部にある [データセット] リンクをクリックします。

1 つのデータセットを含む [データセット] ページ

別のプロジェクトのデータセットを表示するには、タイトルバーの右上にあるプルダウン リストからプロジェクトを選択します。

REST

リクエストのデータを使用する前に、次のように置き換えます。

  • project-id: Google Cloud Platform プロジェクト ID

HTTP メソッドと URL:

GET https://automl.googleapis.com/v1/projects/project-id/locations/us-central1/datasets

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "datasets": [
    {
      "name": "projects/project-number/locations/us-central1/datasets/dataset-id",
      "displayName": "dataset-display-name",
      "createTime": "2019-10-01T22:47:38.347689Z",
      "etag": "AB3BwFpPWn6klFqJ867nz98aXr_JHcfYFQBMYTf7rcO-JMi8Ez4iDSNrRW4Vv501i488",
      "translationDatasetMetadata": {
        "sourceLanguageCode": "source-language",
        "targetLanguageCode": "target-language"
      }
    },
    ...
  ]
}

Go

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Go API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

	automl "cloud.google.com/go/automl/apiv1"
	"cloud.google.com/go/automl/apiv1/automlpb"
	"google.golang.org/api/iterator"
)

// listDatasets lists existing datasets.
func listDatasets(w io.Writer, projectID string, location string) error {
	// projectID := "my-project-id"
	// location := "us-central1"

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

	req := &automlpb.ListDatasetsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
	}

	it := client.ListDatasets(ctx, req)

	// Iterate over all results
	for {
		dataset, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return fmt.Errorf("ListGlossaries.Next: %w", err)
		}

		fmt.Fprintf(w, "Dataset name: %v\n", dataset.GetName())
		fmt.Fprintf(w, "Dataset display name: %v\n", dataset.GetDisplayName())
		fmt.Fprintf(w, "Dataset create time:\n")
		fmt.Fprintf(w, "\tseconds: %v\n", dataset.GetCreateTime().GetSeconds())
		fmt.Fprintf(w, "\tnanos: %v\n", dataset.GetCreateTime().GetNanos())

		// Translate
		if metadata := dataset.GetTranslationDatasetMetadata(); metadata != nil {
			fmt.Fprintf(w, "Translation dataset metadata:\n")
			fmt.Fprintf(w, "\tsource_language_code: %v\n", metadata.GetSourceLanguageCode())
			fmt.Fprintf(w, "\ttarget_language_code: %v\n", metadata.GetTargetLanguageCode())
		}

	}

	return nil
}

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.Dataset;
import com.google.cloud.automl.v1.ListDatasetsRequest;
import com.google.cloud.automl.v1.LocationName;
import java.io.IOException;

class ListDatasets {

  static void listDatasets() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    listDatasets(projectId);
  }

  // List the datasets
  static void listDatasets(String projectId) 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 (AutoMlClient client = AutoMlClient.create()) {
      // A resource that represents Google Cloud Platform location.
      LocationName projectLocation = LocationName.of(projectId, "us-central1");
      ListDatasetsRequest request =
          ListDatasetsRequest.newBuilder().setParent(projectLocation.toString()).build();

      // List all the datasets available in the region by applying filter.
      System.out.println("List of datasets:");
      for (Dataset dataset : client.listDatasets(request).iterateAll()) {
        // Display the dataset information
        System.out.format("\nDataset name: %s\n", dataset.getName());
        // To get the dataset id, you have to parse it out of the `name` field. As dataset Ids are
        // required for other methods.
        // Name Form: `projects/{project_id}/locations/{location_id}/datasets/{dataset_id}`
        String[] names = dataset.getName().split("/");
        String retrievedDatasetId = names[names.length - 1];
        System.out.format("Dataset id: %s\n", retrievedDatasetId);
        System.out.format("Dataset display name: %s\n", dataset.getDisplayName());
        System.out.println("Dataset create time:");
        System.out.format("\tseconds: %s\n", dataset.getCreateTime().getSeconds());
        System.out.format("\tnanos: %s\n", dataset.getCreateTime().getNanos());
        System.out.println("Translation dataset metadata:");
        System.out.format(
            "\tSource language code: %s\n",
            dataset.getTranslationDatasetMetadata().getSourceLanguageCode());
        System.out.format(
            "\tTarget language code: %s\n",
            dataset.getTranslationDatasetMetadata().getTargetLanguageCode());
      }
    }
  }
}

Node.js

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

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

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

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

async function listDatasets() {
  // Construct request
  const request = {
    parent: client.locationPath(projectId, location),
    filter: 'translation_dataset_metadata:*',
  };

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

  console.log('List of datasets:');
  for (const dataset of response) {
    console.log(`Dataset name: ${dataset.name}`);
    console.log(
      `Dataset id: ${
        dataset.name.split('/')[dataset.name.split('/').length - 1]
      }`
    );
    console.log(`Dataset display name: ${dataset.displayName}`);
    console.log('Dataset create time');
    console.log(`\tseconds ${dataset.createTime.seconds}`);
    console.log(`\tnanos ${dataset.createTime.nanos / 1e9}`);
    if (dataset.translationDatasetMetadata !== undefined) {
      console.log('Translation dataset metadata:');
      console.log(
        `\tSource language code: ${dataset.translationDatasetMetadata.sourceLanguageCode}`
      );
      console.log(
        `\tTarget language code: ${dataset.translationDatasetMetadata.targetLanguageCode}`
      );
    }
  }
}

listDatasets();

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"

client = automl.AutoMlClient()
# A resource that represents Google Cloud Platform location.
project_location = f"projects/{project_id}/locations/us-central1"

# List all the datasets available in the region.
request = automl.ListDatasetsRequest(parent=project_location, filter="")
response = client.list_datasets(request=request)

print("List of datasets:")
for dataset in response:
    print(f"Dataset name: {dataset.name}")
    print("Dataset id: {}".format(dataset.name.split("/")[-1]))
    print(f"Dataset display name: {dataset.display_name}")
    print(f"Dataset create time: {dataset.create_time}")
    print("Translation dataset metadata:")
    print(
        "\tsource_language_code: {}".format(
            dataset.translation_dataset_metadata.source_language_code
        )
    )
    print(
        "\ttarget_language_code: {}".format(
            dataset.translation_dataset_metadata.target_language_code
        )
    )

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Translation リファレンス ドキュメントをご覧ください。

データセットの削除

ウェブ UI

  1. AutoML Translation UI で、左側のナビゲーション メニューの上部にある [データセット] リンクをクリックし、使用可能なデータセットを一覧表示します。

    1 つのデータセットを含む [データセット] ページ

  2. 削除する行の右端にあるその他メニューをクリックし、[削除] を選択します。

  3. 確認ダイアログ ボックスで [確認] をクリックします。

REST

  • dataset-name は、データセットを作成したときにレスポンスで返されたデータセットの完全な名前に置き換えます。完全な名前の形式は projects/{project-id}/locations/us-central1/datasets/{dataset-id} です。

リクエストのデータを使用する前に、次のように置き換えます。

  • dataset-name: 削除するデータセットの名前(project/project-id/locations/us-central1/datasets/dataset-id 形式)。

HTTP メソッドと URL:

DELETE https://automl.googleapis.com/v1/dataset-name

リクエストを送信するには、次のいずれかのオプションを展開します。

次のような JSON レスポンスが返されます。

{
  "name": "projects/project-number/locations/us-central1/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.automl.v1.OperationMetadata",
    "createTime": "2019-10-02T16:43:03.923442Z",
    "updateTime": "2019-10-02T16:43:03.923442Z",
    "deleteDetails": {}
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.protobuf.Empty"
  }
}

Go

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Go API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import (
	"context"
	"fmt"
	"io"

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

// deleteDataset deletes a dataset.
func deleteDataset(w io.Writer, projectID string, location string, datasetID string) error {
	// projectID := "my-project-id"
	// location := "us-central1"
	// datasetID := "TRL123456789..."

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

	req := &automlpb.DeleteDatasetRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/datasets/%s", projectID, location, datasetID),
	}

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

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

	fmt.Fprintf(w, "Dataset deleted.\n")

	return nil
}

Java

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Java API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

import com.google.cloud.automl.v1.AutoMlClient;
import com.google.cloud.automl.v1.DatasetName;
import com.google.protobuf.Empty;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

class DeleteDataset {

  static void deleteDataset() throws IOException, ExecutionException, InterruptedException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR_PROJECT_ID";
    String datasetId = "YOUR_DATASET_ID";
    deleteDataset(projectId, datasetId);
  }

  // Delete a dataset
  static void deleteDataset(String projectId, String datasetId)
      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 (AutoMlClient client = AutoMlClient.create()) {
      // Get the full path of the dataset.
      DatasetName datasetFullId = DatasetName.of(projectId, "us-central1", datasetId);
      Empty response = client.deleteDatasetAsync(datasetFullId).get();
      System.out.format("Dataset deleted. %s\n", response);
    }
  }
}

Node.js

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Node.js API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'us-central1';
// const datasetId = 'YOUR_DATASET_ID';

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

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

async function deleteDataset() {
  // Construct request
  const request = {
    name: client.datasetPath(projectId, location, datasetId),
  };

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

  // Wait for operation to complete.
  const [response] = await operation.promise();
  console.log(`Dataset deleted: ${response}`);
}

deleteDataset();

Python

AutoML Translation 用のクライアント ライブラリをインストールして使用する方法については、AutoML Translation クライアント ライブラリをご覧ください。詳細については、AutoML Translation Python API のリファレンス ドキュメントをご覧ください。

AutoML Translation で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証を設定するをご覧ください。

from google.cloud import automl

# TODO(developer): Uncomment and set the following variables
# project_id = "YOUR_PROJECT_ID"
# dataset_id = "YOUR_DATASET_ID"

client = automl.AutoMlClient()
# Get the full path of the dataset
dataset_full_id = client.dataset_path(project_id, "us-central1", dataset_id)
response = client.delete_dataset(name=dataset_full_id)

print(f"Dataset deleted. {response.result()}")

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の AutoML Translation リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の AutoML Translation リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby 用の AutoML Translation リファレンス ドキュメントをご覧ください。

インポートに関する問題

データセットの作成時に、文章が長すぎる場合や、ソース言語とターゲット言語でまったく同じ文章のペアである場合、AutoML Translation で文章のペアを削除する可能性があります。

長すぎる文章のペアでは、文章を約 200 単語ずつに分割して、削除されたペアを含めるようにデータセットを再作成することをおすすめします。データの処理中に、AutoML Translation は内部プロセスを使用して入力データをトークン化します。これにより、文章のサイズが大きくなる可能性があります。このトークン化されたデータは、AutoML Translation でデータサイズの測定に使用するものです。したがって、最大長は 200 語です。

ソース言語とターゲット言語で同じである文章のペアの場合は、データセットから削除できます。こうした文章を翻訳しない場合は、用語集リソースを使用して、AutoML Translation での特定の用語の処理方法を定義するカスタム辞書を作成します。