JavaScript 用 Azure Text Analytics クライアント ライブラリ - バージョン 5.1.0

Azure TextAnalytics は、生テキストに対する高度な自然言語処理を提供するクラウドベースのサービスであり、次の 6 つの主要な機能が含まれています。

メモ:この SDK は、Azure Text Analytics サービス API バージョン 3.1.0 を対象とします。

  • 言語検出
  • 感情分析
  • キー フレーズ抽出
  • 名前付きエンティティの認識
  • 個人を特定できる情報の認識
  • リンクされたエンティティ認識
  • 医療分析
  • ドキュメントごとに複数のアクションをサポートする

以下の場合にクライアント ライブラリを使用します。

  • 書き込まれる言語入力テキストを検出します。
  • 肯定的または否定的な感情に関する手がかりを得るための生テキストを分析して、顧客がブランドやトピックに対して何を考えているかを判断します。
  • 重要なフレーズを自動的に抽出し、重要な点を迅速に特定します。
  • テキスト内のエンティティを、ユーザー、場所、組織、日付/時刻、数量、パーセンテージ、通貨、医療固有などとして識別して分類します。
  • 上記のタスクの複数を一度に実行します。

主要リンク:

はじめに

現在サポートされている環境

詳細については、Microsoft のサポート ポリシーを参照してください。

前提条件

Azure CLI を使用する場合は、 と <your-resource-name> を独自の一意の名前に置き換えます<your-resource-group-name>

az cognitiveservices account create --kind TextAnalytics --resource-group <your-resource-group-name> --name <your-resource-name> --sku <your-sku-name> --location <your-location>

@azure/ai-text-analytics パッケージのインストール

を使用して、JavaScript 用の Azure Text Analytics クライアント ライブラリをnpmインストールします。

npm install @azure/ai-text-analytics

TextAnalyticsClient を作成して認証する

Text Analytics API にアクセスするためのクライアント オブジェクトを作成するには、Text Analytics リソースの と credentialが必要endpointです。 Text Analytics クライアントは、認証に Azure Active Directory 資格情報または API キー資格情報のいずれかを使用できます。

テキスト分析リソースのエンドポイントは、 Azure Portal または以下Azure CLI スニペットを使用して確認できます。

az cognitiveservices account show --name <your-resource-name> --resource-group <your-resource-group-name> --query "endpoint"

API キーの使用

Azure Portal を使用してText Analytics リソースを参照し、API キーを取得するか、次の Azure CLI スニペットを使用します。

メモ: API キーは、"サブスクリプション キー" または "サブスクリプション API キー" と呼ばれる場合があります。

az cognitiveservices account keys list --resource-group <your-resource-group-name> --name <your-resource-name>

API キーとエンドポイントを取得したら、 クラスを AzureKeyCredential 使用して、次のようにクライアントを認証できます。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

Azure Active Directory 資格情報の使用

クライアント API キー認証はほとんどの例で使用されますが、Azure Id ライブラリを使用して Azure Active Directory で認証することもできます。 次に示す DefaultAzureCredential プロバイダー、または Azure SDK で提供されている他の資格情報プロバイダーを使用するには、パッケージを @azure/identity インストールしてください。

npm install @azure/identity

また、新しい AAD アプリケーションを登録し、サービス プリンシパルにロールを割り当てること"Cognitive Services User"で、Text Analyticsへのアクセス権を付与する必要があります (注: などの"Owner"他のロールは必要なアクセス許可を付与せず、例とサンプル コードを実行するだけで"Cognitive Services User"十分です)。

AAD アプリケーションのクライアント ID、テナント ID、およびクライアント シークレットの値を、環境変数 AZURE_CLIENT_IDAZURE_TENANT_ID、、AZURE_CLIENT_SECRET、 として設定します。

const { TextAnalyticsClient } = require("@azure/ai-text-analytics");
const { DefaultAzureCredential } = require("@azure/identity");

const client = new TextAnalyticsClient("<endpoint>", new DefaultAzureCredential());

主要な概念

TextAnalyticsClient

TextAnalyticsClientは、Text Analytics クライアント ライブラリを使用する開発者向けの主要なインターフェイスです。 このクライアント オブジェクトのメソッドを調べて、アクセスできるText Analytics サービスのさまざまな機能を理解します。

入力

ドキュメントは、Text Analytics サービスの予測モデルによって分析される単一の入力単位を表します。 に対する TextAnalyticsClient 操作は、バッチとして分析される入力のコレクションを受け取ります。 操作メソッドには、入力を文字列として、または添付されたメタデータを持つオブジェクトとして表すオーバーロードがあります。

たとえば、各ドキュメントを配列内の文字列として渡すことができます(例: )。

const documents = [
  "I hated the movie. It was so slow!",
  "The movie made it into my top ten favorites.",
  "What a great movie!"
];

または、アイテムごとのドキュメントidまたは を渡す場合は、 の一覧TextDocumentInputとして、またはcountryHintlanguage/DetectLanguageInput操作に応じて指定できます。

const textDocumentInputs = [
  { id: "1", language: "en", text: "I hated the movie. It was so slow!" },
  { id: "2", language: "en", text: "The movie made it into my top ten favorites." },
  { id: "3", language: "en", text: "What a great movie!" }
];

ドキュメントの長さの制限、最大バッチ サイズ、サポートされているテキスト エンコードなど、入力の サービス 制限に関するページを参照してください。

戻り値

1 つのドキュメントに対応する戻り値は、成功した結果またはエラー オブジェクトです。 各メソッドは TextAnalyticsClient 、インデックスによる入力に対応する結果とエラーの異種配列を返します。 テキスト入力とその結果は、入力コレクションと結果コレクション内で同じインデックスを持ちます。 コレクションには、必要に応じて、入力バッチに関する情報と、入力バッチがフィールドでどのように処理されたかに関する情報を statistics 含めることもできます。

などのAnalyzeSentimentResult結果は、1 つのテキスト入力に関する予測または予測を含むText Analytics操作の結果です。 操作の結果の種類には、必要に応じて、入力ドキュメントとその処理方法に関する情報を含めることもできます。

error オブジェクト は、TextAnalyticsErrorResultドキュメントの処理中にサービスでエラーが発生し、エラーに関する情報が含まれていることを示します。

ドキュメント エラー処理

操作によって返されるコレクションでは、エラーは、エラーが発生した場合に内部TextAnalyticsErrorオブジェクトをerror含む プロパティが存在することで、成功した応答と区別されます。 成功した結果オブジェクトの場合、このプロパティは 常にundefined です。

たとえば、すべてのエラーを除外するには、次を使用できます filter

const results = await client.analyzeSentiment(documents);
const onlySuccessful = results.filter((result) => result.error === undefined);

: TypeScript ユーザーは、構成で が にtrue設定されている場合compilerOptions.strictNullChecks、結果オブジェクトとエラー オブジェクトの型チェックの方が優れた利点がありますtsconfig.json。 次に例を示します。

const [result] = await client.analyzeSentiment(["Hello world!"]);

if (result.error !== undefined) {
  // In this if block, TypeScript will be sure that the type of `result` is
  // `TextAnalyticsError` if compilerOptions.strictNullChecks is enabled in
  // the tsconfig.json

  console.log(result.error);
}

この機能は TypeScript 3.2 で導入されたため、TypeScript 3.1 のユーザーは、次のように、対応する成功バリアントに結果値をキャストする必要があります。

const [result] = await client.detectLanguage(["Hello world!"]);

if (result.error === undefined) {
  const { primaryLanguage } = result as DetectLanguageSuccessResult;
}

センチメントの分析

テキストのセンチメントを分析して、文章ごとのセンチメント分析や信頼度スコアなど、肯定的、否定的、中立的、または混合であるかどうかを判断します。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "I did not like the restaurant. The food was too spicy.",
  "The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
  "The food was yummy. :)"
];

async function main() {
  const results = await client.analyzeSentiment(documents);

  for (const result of results) {
    if (result.error === undefined) {
      console.log("Overall sentiment:", result.sentiment);
      console.log("Scores:", result.confidenceScores);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

製品/サービスの側面 (自然言語処理 (NLP) のアスペクトベースの感情分析とも呼ばれます) に関連する意見に関するより詳細な情報を取得するには、オピニオン マイニングを使用したセンチメント分析のサンプル を参照してください

エンティティを認識する

テキスト内のエンティティを認識し、人物、場所、組織、日付/時刻、数量、通貨などとして分類します。

language パラメーターは省略可能です。 指定しない場合は、既定の英語モデルが使用されます。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "Jeff bought three dozen eggs because there was a 50% discount."
];

async function main() {
  const results = await client.recognizeEntities(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

PII エンティティを認識する

社会保障番号、銀行口座情報、クレジット カード番号などのテキストで個人を特定できる情報 (PII) を認識するための個別のエンドポイントと操作があります。その使用法は、上記の標準エンティティ認識とよく似ています。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");
const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));
const documents = [
  "The employee's SSN is 555-55-5555.",
  "The employee's phone number is (555) 555-5555."
];
async function main() {
  const results = await client.recognizePiiEntities(documents, "en");
  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized PII entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.text, ":", entity.category, "(Score:", entity.confidenceScore, ")");
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}
main();

リンクされたエンティティを認識する

"リンクされた" エンティティは、サポート情報 (Wikipedia など) に存在するエンティティです。 操作はrecognizeLinkedEntities、エンティティが参照する可能性が高いサポート情報のどのエントリを決定することによってエンティティを明確にすることができます (たとえば、テキストの一部では、"Mars" という単語は惑星を指すか、ローマの戦争の神を指します)。 リンクされたエンティティには、エンティティの定義を提供するサポート情報に関連付けられた URL が含まれています。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product."
];

async function main() {
  const results = await client.recognizeLinkedEntities(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Recognized linked entities for input", result.id, "--");
      for (const entity of result.entities) {
        console.log(entity.name, "(URL:", entity.url, ", Source:", entity.dataSource, ")");
        for (const match of entity.matches) {
          console.log(
            "  Occurrence:",
            '"' + match.text + '"',
            "(Score:",
            match.confidenceScore,
            ")"
          );
        }
      }
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

キー フレーズを抽出する

キー フレーズ抽出は、ドキュメント内の主要な話し合いポイントを識別します。 たとえば、「食べ物はおいしくて、すばらしいスタッフがいた」というテキストを入力すると、 "食べ物" と "すばらしいスタッフ" がサービスによって返されます。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Redmond is a city in King County, Washington, United States, located 15 miles east of Seattle.",
  "I need to take my cat to the veterinarian.",
  "I will travel to South America in the summer."
];

async function main() {
  const results = await client.extractKeyPhrases(documents, "en");

  for (const result of results) {
    if (result.error === undefined) {
      console.log(" -- Extracted key phrases for input", result.id, "--");
      console.log(result.keyPhrases);
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

言語を検出する

テキストの言語を決定します。

パラメーターは countryHint 省略可能ですが、配信元の国がわかっている場合は、サービスが正しい出力を提供するのに役立ちます。 指定する場合は、ISO-3166 Alpha-2 の 2 文字の国コード (米国の場合は "us"、日本の場合は "jp" など) または値 "none"に設定する必要があります。 パラメーターが指定されていない場合は、既定"us"の (米国) モデルが使用されます。 ドキュメントの原産国がわからない場合は、 パラメーター"none"を使用する必要があります。Text Analytics サービスは、不明な原産国に合わせて調整されたモデルを適用します。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "This is written in English.",
  "Il documento scritto in italiano.",
  "Dies ist in deutscher Sprache verfasst."
];

async function main() {
  const results = await client.detectLanguage(documents, "none");

  for (const result of results) {
    if (result.error === undefined) {
      const { primaryLanguage } = result;
      console.log(
        "Input #",
        result.id,
        "identified as",
        primaryLanguage.name,
        "( ISO6391:",
        primaryLanguage.iso6391Name,
        ", Score:",
        primaryLanguage.confidenceScore,
        ")"
      );
    } else {
      console.error("Encountered an error:", result.error);
    }
  }
}

main();

医療エンティティを分析する

医療分析では、医療エンティティが識別されます。 たとえば、"100mg の ibuprofen を処方し、1 日に 2 回服用する" という入力テキストを指定すると、このサービスでは、"100mg" が [投与量] に分類され、"ibuprofen" が MedicationName として、"1 日に 2 回" が Frequency として返されます。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Prescribed 100mg ibuprofen, taken twice daily.",
  "Patient does not suffer from high blood pressure."
];

async function main() {
  const poller = await client.beginAnalyzeHealthcareEntities(documents);
  const results = await poller.pollUntilDone();

  for await (const result of results) {
    console.log(`- Document ${result.id}`);
    if (!result.error) {
      console.log("\tRecognized Entities:");
      for (const entity of result.entities) {
        console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
      }
    } else console.error("\tError:", result.error);
  }
}

main();

アクションの分析

分析アクションを使用すると、複数の分析 (名前付きアクション) を一度に適用できます。

const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");

const client = new TextAnalyticsClient("<endpoint>", new AzureKeyCredential("<API key>"));

const documents = [
  "Microsoft was founded by Bill Gates and Paul Allen.",
  "The employee's SSN is 555-55-5555.",
  "Easter Island, a Chilean territory, is a remote volcanic island in Polynesia.",
  "I use Azure Functions to develop my product."
];

async function main() {
  const actions = {
    recognizeEntitiesActions: [{ modelVersion: "latest" }],
    recognizePiiEntitiesActions: [{ modelVersion: "latest" }],
    extractKeyPhrasesActions: [{ modelVersion: "latest" }]
  };
  const poller = await client.beginAnalyzeActions(documents, actions);
  const resultPages = await poller.pollUntilDone();
  for await (const page of resultPages) {
    const keyPhrasesAction = page.extractKeyPhrasesResults[0];
    if (!keyPhrasesAction.error) {
      for (const doc of keyPhrasesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tKey phrases:");
          for (const phrase of doc.keyPhrases) {
            console.log(`\t- ${phrase}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }

    const entitiesAction = page.recognizeEntitiesResults[0];
    if (!entitiesAction.error) {
      for (const doc of entitiesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tEntities:");
          for (const entity of doc.entities) {
            console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }

    const piiEntitiesAction = page.recognizePiiEntitiesResults[0];
    if (!piiEntitiesAction.error) {
      for (const doc of piiEntitiesAction.results) {
        console.log(`- Document ${doc.id}`);
        if (!doc.error) {
          console.log("\tPii Entities:");
          for (const entity of doc.entities) {
            console.log(`\t- Entity ${entity.text} of type ${entity.category}`);
          }
        } else {
          console.error("\tError:", doc.error);
        }
      }
    }
  }
}

main();

トラブルシューティング

ログの記録

ログの記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、環境変数 AZURE_LOG_LEVELinfo に設定します。 または、@azure/loggersetLogLevel を呼び出して、実行時にログ記録を有効にすることもできます。

import { setLogLevel } from "@azure/logger";

setLogLevel("info");

ログを有効にする方法の詳細については、@azure/logger パッケージに関するドキュメントを参照してください。

次のステップ

このライブラリの使用方法の詳細な例については、 サンプル ディレクトリを参照してください。

共同作成

このライブラリに投稿する場合、コードをビルドしてテストする方法の詳細については、投稿ガイドを参照してください。

インプレッション数