適用于 JavaScript 的 Azure 文字分析 用戶端程式庫 - 5.1.0 版

Azure TextAnalytics 是雲端式服務,可針對原始文字提供進階的自然語言處理,並包含六個主要功能:

注意:此 SDK 的目標是 Azure 文字分析 服務 API 3.1.0 版。

  • 語言偵測
  • 情感分析
  • 關鍵片語擷取
  • 具名實體辨識
  • 辨識個人識別資訊
  • 連結實體辨識
  • 醫療保健分析
  • 支援每份檔的多個動作

使用用戶端程式庫可以:

  • 偵測寫入的語言輸入文字。
  • 藉由分析原始文字以取得正面或負面情感的線索,來判斷客戶對品牌或主題的想法。
  • 自動擷取關鍵片語,以快速識別重點。
  • 將文字中的實體識別並分類為人員、地點、組織、日期/時間、數量、百分比、貨幣、醫療保健特定等等。
  • 一次執行多個上述工作。

重要連結:

開始使用

目前支援的環境

如需詳細資訊,請參閱我們的支援原則

必要條件

如果您使用 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 套件

使用 npm 安裝適用于 JavaScript 的 Azure 文字分析 用戶端程式庫:

npm install @azure/ai-text-analytics

建立和驗證 TextAnalyticsClient

若要建立用戶端物件來存取文字分析 API,您需要 endpoint 文字分析資源和 credential 的 。 文字分析用戶端可以使用 Azure Active Directory 認證或 API 金鑰認證來進行驗證。

您可以在 Azure 入口網站或 使用下列 Azure CLI 程式碼片段,找到文字分析資源的端點:

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

使用 API 金鑰

使用Azure 入口網站流覽至您的文字分析資源並擷取 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 身分識別程式庫向 Azure Active Directory 進行驗證。 若要使用如下所示的 DefaultAzureCredential 提供者,或其他 Azure SDK 提供的認證提供者,請安裝 @azure/identity 套件:

npm install @azure/identity

您也需要註冊新的 AAD 應用程式,並將角色指派 "Cognitive Services User" 給服務主體來授與文字分析的存取權 (附注:其他角色,例如 "Owner" 不會授與必要的許可權,只會 "Cognitive Services User" 足以執行範例和範例程式碼) 。

將 AAD 應用程式的用戶端識別碼、租使用者識別碼和用戶端密碼的值設定為環境變數: AZURE_CLIENT_ID 、、 AZURE_TENANT_IDAZURE_CLIENT_SECRET

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

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

重要概念

TextAnalyticsClient

TextAnalyticsClient是開發人員使用 文字分析 用戶端程式庫的主要介面。 探索此用戶端物件上的方法,以瞭解您可以存取之文字分析服務的不同功能。

輸入

代表文字分析服務中預測模型要分析的單一輸入單位。 上的 TextAnalyticsClient 作業會接受要分析為批次的輸入集合。 作業方法具有多載,可讓輸入以字串表示,或做為具有附加中繼資料的物件。

例如,每個檔都可以當做陣列中的字串傳遞,例如

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

或者,如果您想要傳入個別專案的檔 idlanguagecountryHint/ ,則可以根據作業提供或 DetectLanguageInput 清單; TextDocumentInput

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!" }
];

請參閱輸入 的服務限制 ,包括檔長度限制、批次大小上限和支援的文字編碼。

傳回值

對應至單一檔的傳回值是成功的結果或錯誤物件。 每個 TextAnalyticsClient 方法都會傳回依索引對應至輸入的結果和錯誤的異質陣列。 文字輸入及其結果在輸入和結果集合中會有相同的索引。 集合也可以選擇性地包含輸入批次的相關資訊,以及該批次在 statistics 欄位中的處理方式。

例如AnalyzeSentimentResult 的結果是文字分析作業的結果,其中包含單一文字輸入的預測或預測。 作業的結果類型也可以選擇性地包含輸入檔的相關資訊及其處理方式。

error物件 TextAnalyticsErrorResult 表示服務在處理檔時發生錯誤,並包含錯誤的相關資訊。

檔錯誤處理

在作業傳回的集合中,如果發生錯誤,錯誤會與屬性是否存在 error 而區分為成功的回應,其中包含內部 TextAnalyticsError 物件。 對於成功的結果物件,這個屬性一律undefined 為 。

例如,若要篩選掉所有錯誤,您可以使用下列 filter 專案:

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

注意:如果 compilerOptions.strictNullCheckstrue 設定為 tsconfig.json ,TypeScript 使用者可以受益于更妥善地檢查結果和錯誤物件。 例如:

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();

辨識連結實體

「連結」實體存在於維琪百科) 等知識庫 (中。 作業 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();

擷取關鍵字組

關鍵字組擷取會識別檔中的主要交談點。 例如,假設輸入文字為「The food was delicious and there were wonderful staff」,服務會傳回「food」和「wonderful staff」。

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 雙字母國家/地區代碼 (,例如美國的 「us」 或日本的 「jp」) 或值 "none" 。 如果未提供 參數,則會使用預設 "us" (美國) 模型。 如果您不知道檔的來源國家/地區,則應該使用 參數 "none" ,而文字分析服務會套用針對未知來源國家/地區進行調整的模型。

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,每天採用兩次」,服務會傳回分類為「」的「100mg」、「ibuprofen」為「一天」為「一般」,而「每日兩次」則傳回為 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_LEVEL 環境變數設定為 info。 或者,您可以在 @azure/logger 中呼叫 setLogLevel,以在執行階段啟用記錄:

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

setLogLevel("info");

如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件

下一步

如需如何使用此程式庫的詳細 範例 ,請參閱範例目錄。

參與

如果您希望向此程式庫投稿,請參閱投稿指南,深入瞭解如何組建與測試程式碼。

曝光數