Share via


JavaScript용 Azure Text Analytics 클라이언트 라이브러리 - 버전 5.1.0

Azure TextAnalytics 는 원시 텍스트에 대한 고급 자연어 처리를 제공하는 클라우드 기반 서비스이며 다음과 같은 6가지 주요 기능을 포함합니다.

참고: 이 SDK는 Azure Text Analytics 서비스 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 패키지를 설치합니다.

을 사용하여 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에서 또는 아래 AzureCLI 코드 조각을 사용하여 텍스트 분석 리소스에 대한 엔드포인트를 찾을 수 있습니다.

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_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는 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 또는 languagecountryHint/을 전달하려는 경우 작업에 따라 또는 목록 TextDocumentInputDetectLanguageInput 으로 지정할 수 있습니다.

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결과는 단일 텍스트 입력에 대한 예측 또는 예측을 포함하는 Text Analytics 작업의 결과입니다. 작업의 결과 형식에는 입력 문서 및 처리 방법에 대한 정보가 선택적으로 포함될 수도 있습니다.

오류 개체인 TextAnalyticsErrorResult는 문서를 처리하는 동안 서비스에서 오류가 발생했으며 오류에 대한 정보를 포함했음을 나타냅니다.

문서 오류 처리

작업에서 반환된 컬렉션에서 오류는 오류가 발생한 경우 내부 TextAnalyticsError 개체를 포함하는 속성의 error 존재로 성공적인 응답과 구별됩니다. 성공적인 결과 개체의 경우 이 속성은 항상undefined 입니다.

예를 들어 모든 오류를 필터링하려면 다음 filter을 사용할 수 있습니다.

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

참고: TypeScript 사용자는 가 구성에서 로 설정된 경우 compilerOptions.strictNullChecks 결과 및 오류 개체를 보다 효율적으로 형식 검사할 true 수 있습니다 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 작업은 참조할 가능성이 있는 기술 자료 항목을 결정하여 엔터티를 구분할 수 있습니다(예: 텍스트에서 "화성"이라는 단어는 행성을 참조하거나 로마 전쟁의 신을 참조함). 연결된 엔터티는 엔터티의 정의를 제공하는 기술 자료 연결된 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 두 글자 국가 코드(예: 미국 "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 이부프로펜, 매일 두 번 촬영"이 제공되면 서비스는 복용량으로 분류된 "100mg", "ibuprofen"을 MedicationName으로, "매일 두 번"을 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 package docs를 참조하세요.

다음 단계

이 라이브러리를 사용하는 방법에 대한 자세한 예제는 샘플 디렉터리를 참조하세요.

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

Impressions