Amazon Comprehend を API から利用する #reinvent

2017.12.04

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

ども、藤本です。

AWS re:Invent 2017 にて自然言語処理(Natural Language Processing)サービスの Amazon Comprehend がリリースされました。先日、Amazon Comprehend に関してまとめた記事をエントリしました。

自然言語処理サービスの Amazon Comprehend についてまとめてみた #reinvent

マネジメントコンソールから触るのもいいですが、サービスとして利用する場合は API として利用することがほとんどのケースになるかと思います。そこで今回は awscli から Comprehend を操作してみました。awscli でプログラムを組むケースは少ないかと思いますが、API を利用する観点ではその他言語の SDK(例えば、AWS SDK for Python (Boto3) でも、AWS SDK for Java でも)同様の利用方法になります。

概要

Amazon Comprehend はマネジメントコンソールではAPI explorerTopic modelingの 2つの画面がありますが、API explorerでの検出機能はそれぞれ API が分かれています。マネジメントコンソールでの「analyze」ボタンは裏では複数の API を呼んでいます。本エントリで API 単位で機能を確認していきます。

試してみた

利用環境

Aamzon Comprehend を awscli で利用するためには awscli が 1.14.0以上、botocore が 1.8.4以上である必要があります。

とりあえず手元の環境を最新にアップデートします。

$ pip install -U awscli

Successfully installed awscli-1.14.2 botocore-1.8.6 futures-3.2.0 pyasn1-0.4.2 s3transfer-0.1.12

awscli のサブコマンドに comprehend が追加されました。

$ aws comprehend help
COMPREHEND() COMPREHEND()

NAME
comprehend -

DESCRIPTION
Amazon Comprehend is an AWS service for gaining insight into the con-
tent of documents. Use these actions to determine the topics contained
in your documents, the topics they discuss, the predominant sentiment
expressed in them, the predominant language used, and more.

AVAILABLE COMMANDS
o batch-detect-dominant-language

o batch-detect-entities

o batch-detect-key-phrases

o batch-detect-sentiment

o describe-topics-detection-job

o detect-dominant-language

o detect-entities

o detect-key-phrases

o detect-sentiment

o help

o list-topics-detection-jobs

o start-topics-detection-job

COMPREHEND()

前回のエントリに沿って一つ一つの機能を試していきます。

Entity の検出

$ aws comprehend detect-entities help
NAME
detect-entities -

DESCRIPTION
Inspects text for entities, and returns information about them. For
more information, about entities, see how-entities .

See also: AWS API Documentation

SYNOPSIS
detect-entities
--text
--language-code
[--cli-input-json ]
[--generate-cli-skeleton ]

指定するオプションは検出対象となるドキュメント、検出する言語のコードを入力します。言語のコードは今現在、英語en、スペイン語esのみ指定可能です。

今回は Amazon Comprehend のドキュメントページの冒頭の英文をドキュメントに利用します。また awscli のデフォルトリージョンが ap-northeast-1 になっている方は Amazon Comprehend が利用可能なリージョンを指定する必要があります。

$ doc="Amazon Comprehend uses natural language processing (NLP) to extract insights about the content of documents. Amazon Comprehend processes any text file in UTF-8 format. It develops insights by recognizing the entities, key phrases, language, sentiments, and other common elements in a document. Use Amazon Comprehend to create new products based on understanding the structure of documents. For example, using Amazon Comprehend you can search social networking feeds for mentions of products or scan an entire document repository for key phrases."
$ aws --region us-east-1 comprehend detect-entities --text ${doc} --language-code en
{
"Entities": [
{
"Text": "Amazon",
"Score": 0.9306687712669373,
"Type": "ORGANIZATION",
"BeginOffset": 0,
"EndOffset": 6
},
{
"Text": "Comprehend",
"Score": 1.0,
"Type": "COMMERCIAL_ITEM",
"BeginOffset": 7,
"EndOffset": 17
},
{
"Text": "Amazon",
"Score": 0.9080390334129333,
"Type": "ORGANIZATION",
"BeginOffset": 109,
"EndOffset": 115
},
{
"Text": "Comprehend",
"Score": 1.0,
"Type": "COMMERCIAL_ITEM",
"BeginOffset": 116,
"EndOffset": 126
},
{
"Text": "UTF-8",
"Score": 0.8076030015945435,
"Type": "OTHER",
"BeginOffset": 154,
"EndOffset": 159
},
{
"Text": "Amazon",
"Score": 0.8206202387809753,
"Type": "ORGANIZATION",
"BeginOffset": 298,
"EndOffset": 304
},
{
"Text": "Comprehend",
"Score": 1.0,
"Type": "COMMERCIAL_ITEM",
"BeginOffset": 305,
"EndOffset": 315
},
{
"Text": "Amazon",
"Score": 0.880025327205658,
"Type": "ORGANIZATION",
"BeginOffset": 409,
"EndOffset": 415
},
{
"Text": "Comprehend",
"Score": 1.0,
"Type": "COMMERCIAL_ITEM",
"BeginOffset": 416,
"EndOffset": 426
}
]
}

マネジメントコンソールでは集約されて結果が表示されましたが、API では一件一件分かれて返ってくるようです。

キーフレーズの検出

$ aws comprehend detect-key-phrases help
NAME
detect-key-phrases -

DESCRIPTION
Detects the key noun phrases found in the text.

See also: AWS API Documentation

SYNOPSIS
detect-key-phrases
--text
--language-code
[--cli-input-json ]
[--generate-cli-skeleton ]

指定するオプションは先ほどと同じです。

$ aws --region us-east-1 comprehend detect-key-phrases --text ${doc} --language-code en
{
"KeyPhrases": [
{
"Text": "Amazon Comprehend",
"Score": 0.9887688755989075,
"BeginOffset": 0,
"EndOffset": 17
},
{
"Text": "natural language processing",
"Score": 0.9474413394927979,
"BeginOffset": 23,
"EndOffset": 50
},
{
"Text": "NLP",
"Score": 0.9456636905670166,
"BeginOffset": 52,
"EndOffset": 55
},
{
"Text": "insights",
"Score": 0.9938620328903198,
"BeginOffset": 68,
"EndOffset": 76
},

]
}

ちょっとデータ量が多かったの省略。Entity の検出同様、集約されず一件一件の結果が返ってきます。

主要言語の検出

$ aws comprehend detect-dominant-language help
NAME
detect-dominant-language -

DESCRIPTION
Determines the dominant language of the input text. For a list of lan-
guages that Amazon Comprehend can detect, see Amazon Comprehend Sup-
ported Languages .

See also: AWS API Documentation

SYNOPSIS
detect-dominant-language
--text
[--cli-input-json ]
[--generate-cli-skeleton ]

オプションはドキュメントのみです。

$ aws --region us-east-1 comprehend detect-dominant-language --text ${doc}
{
"Languages": [
{
"LanguageCode": "en",
"Score": 0.99240642786026
}
]
}

もちろん主要言語の検出は日本語も OK です。

$ aws --region us-east-1 comprehend detect-dominant-language --text "日本語です"
{
"Languages": [
{
"LanguageCode": "ja",
"Score": 0.4999854564666748
}
]
}

感情の検出

$ aws comprehend detect-sentiment help
NAME
detect-sentiment -

DESCRIPTION
Inspects text and returns an inference of the prevailing sentiment
(POSITIVE , NEUTRAL , MIXED , or NEGATIVE ).

See also: AWS API Documentation

SYNOPSIS
detect-sentiment
--text
--language-code
[--cli-input-json ]
[--generate-cli-skeleton ]

指定するオプションは Entity の検出と同じです。

$ aws --region us-east-1 comprehend detect-sentiment --text ${doc} --language-code en
{
"SentimentScore": {
"Mixed": 0.003262663958594203,
"Positive": 0.05940398573875427,
"Neutral": 0.9269714951515198,
"Negative": 0.010361868888139725
},
"Sentiment": "NEUTRAL"
}

Topic Modeling

$ aws comprehend start-topics-detection-job help
NAME
start-topics-detection-job -

DESCRIPTION
Starts an asynchronous topic detection job. Use the DescribeTopicDetec-
tionJob operation to track the status of a job.

See also: AWS API Documentation

SYNOPSIS
start-topics-detection-job
--input-data-config
--output-data-config
--data-access-role-arn
[--job-name ]
[--number-of-topics ]
[--client-request-token ]
[--cli-input-json ]
[--generate-cli-skeleton ]

指定するオプションはインプットとなるドキュメント群が配置された S3 の URL、ドキュメントがファイル内の1行単位なのか、ファイル単位なのか、結果となる CSV ファイル出力先の S3 の URL、S3 にアクセスするための IAM Role の ARN が必要となります。

インプットとなるドキュメント群は AWS が用意するサンプルデータを利用します。

$ input='{"S3Uri":"s3://public-sample-us-east-1","InputFormat":"ONE_DOC_PER_LINE"}'
$ output='{"S3Uri":"s3://comprehend-fujimoto"}'
$ role_arn="arn:aws:iam::000000000000:role/service-role/AmazonComprehendServiceRole-AmazonComprehendServiceRole-"
$ aws --region us-east-1 comprehend start-topics-detection-job --input-data-config ${input} --output-data-config ${output} --data-access-role-arn ${role_arn}
{
"JobStatus": "SUBMITTED",
"JobId": "e67d2a3a9672b82b377ff687a5decf0e"
}

Topic Modeling のジョブが開始されました。確認用のコマンドも用意されています。複数件確認する場合はlist-topics-detection-jobs、1件確認する場合はdescribe-topics-detection-jobにより確認することができます。

$ aws --region us-east-1 comprehend list-topics-detection-jobs
{
"TopicsDetectionJobPropertiesList": [
{
"InputDataConfig": {
"S3Uri": "s3://public-sample-us-east-1",
"InputFormat": "ONE_DOC_PER_LINE"
},
"NumberOfTopics": 10,
"JobStatus": "IN_PROGRESS",
"JobId": "e67d2a3a9672b82b377ff687a5decf0e",
"SubmitTime": 1512206714.721,
"OutputDataConfig": {
"S3Uri": "s3://comprehend-fujimoto/341946975188-e67d2a3a9672b82b377ff687a5decf0e-1512206714721/output/output.tar.gz"
}
}
]
}

$ aws --region us-east-1 comprehend describe-topics-detection-job --job-id e67d2a3a9672b82b377ff687a5decf0e
{
"TopicsDetectionJobProperties": {
"InputDataConfig": {
"S3Uri": "s3://public-sample-us-east-1",
"InputFormat": "ONE_DOC_PER_LINE"
},
"NumberOfTopics": 10,
"JobStatus": "IN_PROGRESS",
"JobId": "e67d2a3a9672b82b377ff687a5decf0e",
"SubmitTime": 1512206714.721,
"OutputDataConfig": {
"S3Uri": "s3://comprehend-fujimoto/341946975188-e67d2a3a9672b82b377ff687a5decf0e-1512206714721/output/output.tar.gz"
}
}
}

完了すると、JobStatus が COMPLETED になります。

$ aws --region us-east-1 comprehend describe-topics-detection-job --job-id e67d2a3a9672b82b377ff687a5decf0e
{
"TopicsDetectionJobProperties": {
"InputDataConfig": {
"S3Uri": "s3://public-sample-us-east-1",
"InputFormat": "ONE_DOC_PER_LINE"
},
"NumberOfTopics": 10,
"JobStatus": "COMPLETED",
"JobId": "e67d2a3a9672b82b377ff687a5decf0e",
"SubmitTime": 1512206714.721,
"OutputDataConfig": {
"S3Uri": "s3://comprehend-fujimoto/341946975188-e67d2a3a9672b82b377ff687a5decf0e-1512206714721/output/output.tar.gz"
},
"EndTime": 1512207079.687
}
}

結果ファイルも記載された Uri に出力されています。

$ aws s3 ls s3://comprehend-fujimoto/341946975188-e67d2a3a9672b82b377ff687a5decf0e-1512206714721/output/output.tar.gz
2017-12-02 18:30:44 13389 output.tar.gz

まとめ

いかがでしたでしょうか? 今現在、Amazon Comprehend はオプションの種類も少なく非常に簡単に API を扱うことができます。次回は何かしらのユースケースを元に試してみます。