

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# カスタムワーカータスクテンプレートを作成する
<a name="a2i-custom-templates"></a>

*crowd HTML 要素*は、質問したい内容に合わせて調整できるさまざまなタスクウィジェットとデザイン要素を提供するウェブコンポーネントです。これらの crowd 要素を使用してカスタムワーカーテンプレートを作成し、それを Amazon Augmented AI (Amazon A2I) の人間によるレビューワークフローと統合して、ワーカーコンソールと手順をカスタマイズできます。

Amazon A2I ユーザーが使用できるすべての HTML crowd 要素のリストについては、「[Crowd HTML 要素のリファレンス](sms-ui-template-reference.md)」を参照してください。テンプレートの例を確認するには、60 を超えるサンプルのカスタムタスクテンプレートがある「[AWS Github リポジトリ](https://github.com/aws-samples/amazon-a2i-sample-task-uis)」を参照してください。

## ローカルでテンプレートを開発する
<a name="developing-templates-locally"></a>

テンプレートによって入力データがどのように処理されるかをコンソールでテストする場合、次のコードを HTML ファイルの先頭に追加することによって、テンプレートの HTML およびカスタム要素のブラウザでのルックアンドフィールをテストできます。

```
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
```

これによって、カスタム HTML 要素のレンダリングに必要なコードがロードされます。このコードは、テンプレートのルックアンドフィールをコンソールではなく任意のエディタで作成する場合に使用します。

このコードでは、変数は解析されません。ローカルでの作成時には、それらを仮の内容で置き換えておくことができます。

## 外部アセットを使用する
<a name="a2i-custom-template-using-external-assets"></a>

Amazon Augmented AI カスタムテンプレートを使用すると、外部スクリプトやスタイルシートを埋め込むことができます。たとえば、次のヘッダーは、`https://www.example.com/my-enhancement-styles.css` にある `stylesheet` という名前の `text/css` スタイルシートをカスタムテンプレートに埋め込みます。

**Example**  

```
<script src="https://www.example.com/my-enhancment-script.js"></script>
<link rel="stylesheet" type="text/css" href="https://www.example.com/my-enhancement-styles.css">
```

エラーが発生した場合は、元のサーバーがアセットを含む正しい MIME タイプとエンコードヘッダーを送信していることを確認します。

例えば、リモートスクリプト用の MIME およびエンコードタイプは `application/javascript;CHARSET=UTF-8` です。

リモートスタイルシート用の MIME およびエンコードタイプは `text/css;CHARSET=UTF-8` です。

## 変数を追跡する
<a name="a2i-custom-template-step2-UI-vars"></a>

カスタムテンプレートの作成時には、タスクやワーカーごとに異なる可能性のあるデータを表す変数を追加する必要があります。サンプルテンプレートの 1 つから開始する場合、そのテンプレートで既に使用されている変数を確実に把握する必要があります。

例えば、Augmented AI の人間によるレビューループと Amazon Textract のテキストレビューループを統合するカスタムテンプレートの場合、初期値の入力データに `{{ task.input.selectedAiServiceResponse.blocks }}` を使用します。Amazon Augmented AI (Amazon A2I) を Amazon Rekognition と統合する場合、`{{ task.input.selectedAiServiceResponse.moderationLabels }}` が使用されます。カスタムタスクタイプの場合、タスクタイプの入力パラメータを決定する必要があります。`{{ task.input.customInputValuesForStartHumanLoop}}` を使用して、`customInputValuesForStartHumanLoop` を指定します。

## Amazon Textract のカスタムテンプレートの例
<a name="a2i-custom-templates-textract-sample"></a>

すべてのカスタムテンプレートは `<crowd-form> </crowd-form>` 要素で開始および終了します。標準の HTML の `<form>` 要素と同じく、これらの要素の間にすべてのフォームのコードを記述します。

Amazon Textract のドキュメント分析タスクには、`<crowd-textract-analyze-document>` 要素を使用します。次の属性が含まれています。
+ `src` – 注釈を付ける画像ファイルの URL を指定します。
+ `initialValue` – ワーカー UI で見つかった属性の初期値を設定します。
+ `blockTypes` (必須) – ワーカーが実行できる分析のタイプを決定します。現在、`KEY_VALUE_SET` のみがサポートされています。
+ `keys` (必須) – ワーカーが追加できる新しいキーとそれに関連付けるテキストの値を指定します。
+ `no-key-edit` (必須) – `initialValue` を通過したアノテーションのキーをワーカーが編集できないようにします。
+ `no-geometry-edit` – ワーカーが `initialValue` を介して渡されたアノテーションのポリゴンを編集できなくなります。

`<crowd-textract-analyze-document>` 要素の子要素には、2 つのリージョンを用意する必要があります。これらのリージョンで任意の HTML および CSS 要素を使用することができます。
+ `<full-instructions>` - ツールの **[View full instructions]** (詳細な手順を表示) リンクから使用できる手順。空白のままにしておくこともできますが、よりよい結果を得るために、完全な手順を入力することをお勧めします。
+ `<short-instructions>` - ツールのサイドバーに表示されるタスクの簡単な説明。空白のままにしておくこともできますが、よりよい結果を得るために、完全な手順を入力することをお勧めします。

 Amazon Textract のテンプレートの例を以下に示します。

**Example**  

```
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
{% capture s3_uri %}http://s3.amazonaws.com/{{ task.input.aiServiceRequest.document.s3Object.bucket }}/{{ task.input.aiServiceRequest.document.s3Object.name }}{% endcapture %}

<crowd-form>
  <crowd-textract-analyze-document
    src="{{ s3_uri | grant_read_access }}"
    initial-value="{{ task.input.selectedAiServiceResponse.blocks }}"
    header="Review the key-value pairs listed on the right and correct them if they don't match the following document."
    no-key-edit
    no-geometry-edit
    keys="{{ task.input.humanLoopContext.importantFormKeys }}"
    block-types="['KEY_VALUE_SET']"
  >
    <short-instructions header="Instructions">
      <style>
        .instructions {
          white-space: pre-wrap;
        }
        .instructionsImage {
          display: inline-block;
          max-width: 100%;
        }
      </style>
      <p class='instructions'>Choose a key-value block to highlight the corresponding key-value pair in the document.

If it is a valid key-value pair, review the content for the value. If the content is incorrect, correct it.

The text of the value is incorrect, correct it.
<img class='instructionsImage' src="https://example-site/correct-value-text.png" />

A wrong value is identified, correct it.
<img class='instructionsImage' src="https://example-site/correct-value.png" />

If it is not a valid key-value relationship, choose No.
<img class='instructionsImage' src="https://example-site/not-a-key-value-pair.png" />

If you can’t find the key in the document, choose Key not found.
<img class='instructionsImage' src="https://example-site/key-is-not-found.png" />

If the content of a field is empty, choose Value is blank.
<img class='instructionsImage' src="https://example-site/value-is-blank.png" />

<b>Examples</b>
Key and value are often displayed next to or below to each other.

Key and value displayed in one line.
<img class='instructionsImage' src="https://example-site/sample-key-value-pair-1.png" />

Key and value displayed in two lines.
<img class='instructionsImage' src="https://example-site/sample-key-value-pair-2.png" />

If the content of the value has multiple lines, enter all the text without a line break. Include all value text even if it extends beyond the highlight box.
<img class='instructionsImage' src="https://assets.crowd.aws/images/a2i-console/multiple-lines.png" /></p>
    </short-instructions>

    <full-instructions header="Instructions"></full-instructions>
  </crowd-textract-analyze-document>
</crowd-form>
```

## Amazon Rekognition のカスタムテンプレートの例
<a name="a2i-custom-templates-rekognition-sample"></a>

すべてのカスタムテンプレートは `<crowd-form> </crowd-form>` 要素で開始および終了します。標準の HTML の `<form>` 要素と同じく、これらの要素の間にすべてのフォームのコードを記述します。Amazon Rekognition カスタムタスクテンプレートの場合、`<crowd-rekognition-detect-moderation-labels>` 要素を使用します。この要素は、次の属性をサポートします。
+ `categories` - 文字列の配列または各オブジェクトが `name` フィールドを持つオブジェクトの配列。**
  + カテゴリがオブジェクトとして提供された場合は、次の条件が適用されます。
    + 表示されるカテゴリは、`name` フィールドの値です。
    + 返される値には、選択したカテゴリの*すべて*のオブジェクトが含まれます。
  + カテゴリが文字列として提供される場合は、次のようになります。
    + 返された答えは、選択されたすべての文字列の配列です。
+ `exclusion-category` – この属性を設定すると、UI のカテゴリの下にボタンが作成されます。ユーザーがこのボタンを選択すると、すべてのカテゴリの選択が解除されて無効になります。ワーカーがこのボタンを再度選択すると、ユーザーがまたカテゴリを選択できるようになります。このボタンを選択した後にワーカーが **[Submit]** (送信) ボタンを選択してタスクを送信すると、そのタスクは空の配列を返します。

`<crowd-rekognition-detect-moderation-labels>` 要素の子要素には、2 つのリージョンを用意する必要があります。
+ `<full-instructions>` - ツールの **[View full instructions]** (詳細な手順を表示) リンクから使用できる手順。空白のままにしておくこともできますが、よりよい結果を得るために、完全な手順を入力することをお勧めします。
+ `<short-instructions>` - ツールのサイドバーに表示されるタスクの簡単な説明。空白のままにしておくこともできますが、よりよい結果を得るために、完全な手順を入力することをお勧めします。

これらの要素を使用するテンプレートの例を以下に示します。

```
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
{% capture s3_uri %}http://s3.amazonaws.com/{{ task.input.aiServiceRequest.image.s3Object.bucket }}/{{ task.input.aiServiceRequest.image.s3Object.name }}{% endcapture %}

<crowd-form>
  <crowd-rekognition-detect-moderation-labels
    categories='[
      {% for label in task.input.selectedAiServiceResponse.moderationLabels %}
        {
          name: "{{ label.name }}",
          parentName: "{{ label.parentName }}",
        },
      {% endfor %}
    ]'
    src="{{ s3_uri | grant_read_access }}"
    header="Review the image and choose all applicable categories."
  >
    <short-instructions header="Instructions">
      <style>
        .instructions {
          white-space: pre-wrap;
        }
      </style>
      <p class='instructions'>Review the image and choose all applicable categories.
If no categories apply, choose None.

<b>Nudity</b>
Visuals depicting nude male or female person or persons

<b>Graphic Male Nudity</b>
Visuals depicting full frontal male nudity, often close ups

<b>Graphic Female Nudity</b>
Visuals depicting full frontal female nudity, often close ups

<b>Sexual Activity</b>
Visuals depicting various types of explicit sexual activities and pornography

<b>Illustrated Nudity or Sexual Activity</b>
Visuals depicting animated or drawn sexual activity, nudity, or pornography

<b>Adult Toys</b>
Visuals depicting adult toys, often in a marketing context

<b>Female Swimwear or Underwear</b>
Visuals depicting female person wearing only swimwear or underwear

<b>Male Swimwear Or Underwear</b>
Visuals depicting male person wearing only swimwear or underwear

<b>Partial Nudity</b>
Visuals depicting covered up nudity, for example using hands or pose

<b>Revealing Clothes</b>
Visuals depicting revealing clothes and poses, such as deep cut dresses

<b>Graphic Violence or Gore</b>
Visuals depicting prominent blood or bloody injuries

<b>Physical Violence</b>
Visuals depicting violent physical assault, such as kicking or punching

<b>Weapon Violence</b>
Visuals depicting violence using weapons like firearms or blades, such as shooting

<b>Weapons</b>
Visuals depicting weapons like firearms and blades

<b>Self Injury</b>
Visuals depicting self-inflicted cutting on the body, typically in distinctive patterns using sharp objects

<b>Emaciated Bodies</b>
Visuals depicting extremely malnourished human bodies

<b>Corpses</b>
Visuals depicting human dead bodies

<b>Hanging</b>
Visuals depicting death by hanging</p>
    </short-instructions>

    <full-instructions header="Instructions"></full-instructions>
  </crowd-rekognition-detect-moderation-labels>
</crowd-form>
```

## Liquid を使用して自動化を追加する
<a name="a2i-custom-templates-step2-automate"></a>

カスタムテンプレートシステムは、自動化に [Liquid](https://shopify.github.io/liquid/) を使用します。*Liquid* はオープンソースのインラインマークアップ言語です。詳細およびドキュメントについては、[Liquid のホームページ](https://shopify.github.io/liquid/)を参照してください。

Liquid では、一重波括弧とパーセント記号で囲まれたテキストは、制御フローやイテレーションなどを実行する 1 つの手順またはタグになります。**二重波括弧で囲まれたテキストは、値を出力する 1 つの変数または*オブジェクト*です。次のリストには、テンプレート入力データの処理を自動化するのに便利な 2 種類の Liquid タグが含まれています。以下のタグタイプのいずれかを選択すると、Liquid のドキュメントにリダイレクトされます。
+ [フロー制御](https://shopify.github.io/liquid/tags/control-flow/): `if/else`、`unless`、`case/when` のようなプログラミングロジック演算子が含まれています。
+ [イテレーション](https://shopify.github.io/liquid/tags/iteration/): FOR LOOP などのステートメントを使用して、コードのブロックを繰り返し実行できます。

  例えば、次のコード例は Liquid の `for` タグを使用して `for` loop を作成する方法を示しています。この例では、Amazon Rekognition から返された [https://docs.aws.amazon.com/rekognition/latest/dg/API_ModerationLabel.html](https://docs.aws.amazon.com/rekognition/latest/dg/API_ModerationLabel.html) をループ処理し、`moderationLabels` 属性 `name` と `parentName` をワーカーのレビュー用に表示します。

  ```
   {% for label in task.input.selectedAiServiceResponse.moderationLabels %}
      {
        name: &quot;{{ label.name }}&quot;,
        parentName: &quot;{{ label.parentName }}&quot;,
      },
   {% endfor %}
  ```

### 変数フィルターを使用する
<a name="a2i-custom-templates-step2-automate-filters"></a>

標準の [Liquid のフィルター](https://shopify.github.io/liquid/filters/abs/)とアクションに加えて、Amazon Augmented AI (Amazon A2I) には追加のフィルターが用意されています。フィルターを適用するには、変数名の後をパイプ (`|`) 文字で区切ってからフィルター名を指定します。フィルターを追加するには、次の形式を使用します。

**Example**  

```
{{ <content> | <filter> | <filter> }}
```

#### 自動的なエスケープおよび明示的なエスケープ
<a name="a2i-custom-templates-step2-automate-filters-autoescape"></a>

デフォルトでは、変数のテキストと HTML との間の混乱を避けるために、入力は HTML エスケープされます。`escape` フィルターを明示的に追加すると、テンプレートのソースを確認するユーザーに、エスケープ処理が行われていることをより明確に示すことができます。

#### escape\$1once
<a name="a2i-custom-templates-step2-automate-escapeonce"></a>

`escape_once` を使用すると、既にエスケープしたコードは確実に再度エスケープされなくなります。例えば、`&amp;` が `&amp;amp;` にならないようにします。

#### skip\$1autoescape
<a name="a2i-custom-templates-step2-automate-skipautoescape"></a>

`skip_autoescape` は、コンテンツが HTML として使用されるよう設計されている場合に便利です。例えば、いくつかの段落のテキストとイメージが境界ボックスの詳細な手順にある場合です。

**注記**  
`skip_autoescape` は慎重に使用してください。テンプレートにおけるベストプラクティスは、渡す値を厳重に管理できることが確実な場合を除いて、`skip_autoescape` を使用して関数のコードやマークアップを渡さないことです。ユーザー入力を渡している場合は、ワーカーをクロスサイトスクリプティング攻撃に対して開放している可能性があります。

#### to\$1json
<a name="a2i-custom-templates-step2-automate-tojson"></a>

`to_json` は、指定したデータを JavaScript Object Notation (JSON) にエンコードします。オブジェクトを指定すると、シリアル化します。

#### grant\$1read\$1access
<a name="a2i-custom-templates-step2-automate-grantreadaccess"></a>

`grant_read_access` は Amazon Simple Storage Service (Amazon S3) URI を使用し、そのリソースに対する存続期間の短いアクセストークンを使用する HTTPS URL にエンコードします。これにより、ワーカーに公開していない S3 バケットに保存されている写真、音声、動画などのオブジェクトをワーカーに表示できるようになります。

#### s3\$1presign
<a name="a2i-custom-templates-step2-automate-s3"></a>

 `s3_presign` フィルターは `grant_read_access` フィルターと同様に機能します。`s3_presign` は Amazon S3 URI を使用し、そのリソースに対する存続期間の短いアクセストークンを使用する HTTPS URL にエンコードします。これにより、ワーカーに公開していない S3 バケットに保存されている写真、音声、動画などのオブジェクトをワーカーに表示できるようになります。

**Example 変数フィルターの例**  
Input  

```
auto-escape: {{ "Have you read 'James & the Giant Peach'?" }}
explicit escape: {{ "Have you read 'James & the Giant Peach'?" | escape }}
explicit escape_once: {{ "Have you read 'James &amp; the Giant Peach'?" | escape_once }}
skip_autoescape: {{ "Have you read 'James & the Giant Peach'?" | skip_autoescape }}
to_json: {{ jsObject | to_json }}                
grant_read_access: {{ "s3://amzn-s3-demo-bucket/myphoto.png" | grant_read_access }}
s3_presign: {{ "s3://amzn-s3-demo-bucket/myphoto.png" | s3_presign }}
```

**Example**  
Output  

```
auto-escape: Have you read &#39;James &amp; the Giant Peach&#39;?
explicit escape: Have you read &#39;James &amp; the Giant Peach&#39;?
explicit escape_once: Have you read &#39;James &amp; the Giant Peach&#39;?
skip_autoescape: Have you read 'James & the Giant Peach'?
to_json: { "point_number": 8, "coords": [ 59, 76 ] }
grant_read_access: https://s3.amazonaws.com/amzn-s3-demo-bucket/myphoto.png?<access token and other params>
s3_presign: https://s3.amazonaws.com/amzn-s3-demo-bucket/myphoto.png?<access token and other params>
```

**Example 自動分類テンプレートの例**  
この単純なテキスト分類のサンプルを自動化するには、Liquid タグの `{{ task.input.source }}` を含めます。この例では、[crowd-classifier](sms-ui-template-crowd-classifier.md) 要素を使用します。  

```
<script src="https://assets.crowd.aws/crowd-html-elements.js"></script>
<crowd-form>
  <crowd-classifier 
    name="tweetFeeling"
    categories="['positive', 'negative', 'neutral', 'cannot determine']"
    header="Which term best describes this tweet?" 
  >
    <classification-target>
       {{ task.input.source }}
    </classification-target>

    <full-instructions header="Analyzing a sentiment">
      Try to determine the feeling the author 
      of the tweet is trying to express. 
      If none seems to match, choose "other."
    </full-instructions>

    <short-instructions>
      Pick the term that best describes the sentiment 
      of the tweet. 
    </short-instructions>

  </crowd-classifier>
</crowd-form>
```

## ワーカータスクテンプレートをプレビューする
<a name="a2i-preview-your-custom-template"></a>

カスタムワーカータスクテンプレートをプレビューするには、SageMaker AI の `RenderUiTemplate` オペレーションを使用します。`RenderUiTemplate` オペレーションは、 AWS CLI または任意の AWS SDK で使用できます。この API オペレーションでサポートされている言語固有の SDK に関するドキュメントについては、「[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html)」の「[https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_SeeAlso](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_SeeAlso)」セクションを参照してください。

**前提条件**

ワーカータスクテンプレート、 AWS Identity and Access Management (IAM) ロール Amazon リソースネーム (ARN)、または をプレビューするには`RoleArn`、テンプレートで使用される S3 オブジェクトへのアクセス許可が必要です。ロールまたはユーザーを設定する方法については、「[ワーカータスクテンプレートプレビューを有効にする](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai)」を参照してください。

**`RenderUiTemplate` オペレーションを使用してワーカータスクテンプレートをプレビューするには**

1. カスタムテンプレートをプレビューするために必要なポリシーをアタッチしたロールの **`RoleArn`** を指定します。

1. **`Task`** の **`Input`** パラメータで、テンプレートで定義されている変数の値を含む JSON オブジェクトを指定します。これらは、`task.input.source` 変数に代入される変数です。例えば、テンプレートで task.input.text という変数を定義する場合、JSON オブジェクトの変数は `text`: `sample text` のように指定できます。

1. **`UiTemplate`** の **`Content`** パラメータで、テンプレートを挿入します。

`RenderUiTemplate` を設定したら、任意の SDK または AWS CLI を使用して、テンプレートをレンダリングするリクエストを送信します。リクエストが成功した場合、レスポンスには、ワーカーの UI の HTML をレンダリングする Liquid テンプレートである [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_ResponseSyntax](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_RenderUiTemplate.html#API_RenderUiTemplate_ResponseSyntax) が含まれます。

**重要**  
テンプレートをプレビューするには、ユーザーインターフェイスでレンダリングされる Amazon S3 オブジェクトの読み取り権限を持つ IAM ロールが必要です。これらのアクセス許可を付与するために IAM ロールにアタッチできるサンプルポリシーについては、「[ワーカータスクテンプレートプレビューを有効にする](a2i-permissions-security.md#permissions-for-worker-task-templates-augmented-ai)」を参照してください。