Options
All
  • Public
  • Public/Protected
  • All
Menu

Class TextAnalysisClient

Package version

A client for interacting with the text analysis features in Azure Cognitive Language Service.

The client needs the endpoint of a Language resource and an authentication method such as an API key or AAD. The API key and endpoint can be found in the Language resource page in the Azure portal. They will be located in the resource's Keys and Endpoint page, under Resource Management.

Examples for authentication:

API Key

import { TextAnalysisClient, AzureKeyCredential } from "@azure/ai-text-analytics";

const endpoint = "https://<resource name>.cognitiveservices.azure.com";
const credential = new AzureKeyCredential("<api key>");

const client = new TextAnalysisClient(endpoint, credential);

Azure Active Directory

See the @azure/identity package for more information about authenticating with Azure Active Directory.

import { TextAnalysisClient } from "@azure/ai-text-analytics";
import { DefaultAzureCredential } from "@azure/identity";

const endpoint = "https://<resource name>.cognitiveservices.azure.com";
const credential = new DefaultAzureCredential();

const client = new TextAnalysisClient(endpoint, credential);

Hierarchy

  • TextAnalysisClient

Index

Constructors

constructor

  • Creates an instance of TextAnalysisClient with the endpoint of a Language resource and an authentication method such as an API key or AAD.

    The API key and endpoint can be found in the Language resource page in the Azure portal. They will be located in the resource's Keys and Endpoint page, under Resource Management.

    Example

    import { TextAnalysisClient, AzureKeyCredential } from "@azure/ai-text-analytics";
    
    const endpoint = "https://<resource name>.cognitiveservices.azure.com";
    const credential = new AzureKeyCredential("<api key>");
    
    const client = new TextAnalysisClient(endpoint, credential);

    Parameters

    • endpointUrl: string

      The URL to the endpoint of a Cognitive Language Service resource

    • credential: KeyCredential

      Key credential to be used to authenticate requests to the service.

    • Optional options: TextAnalysisClientOptions

      Used to configure the TextAnalytics client.

    Returns TextAnalysisClient

  • Creates an instance of TextAnalysisClient with the endpoint of a Language resource and an authentication method such as an API key or AAD.

    The API key and endpoint can be found in the Language resource page in the Azure portal. They will be located in the resource's Keys and Endpoint page, under Resource Management.

    Example

    See the @azure/identity package for more information about authenticating with Azure Active Directory.

    import { TextAnalysisClient } from "@azure/ai-text-analytics";
    import { DefaultAzureCredential } from "@azure/identity";
    
    const endpoint = "https://<resource name>.cognitiveservices.azure.com";
    const credential = new DefaultAzureCredential();
    
    const client = new TextAnalysisClient(endpoint, credential);

    Parameters

    • endpointUrl: string

      The URL to the endpoint of a Cognitive Language Service resource

    • credential: TokenCredential

      Key credential to be used to authenticate requests to the service.

    • Optional options: TextAnalysisClientOptions

      Used to configure the TextAnalytics client.

    Returns TextAnalysisClient

Methods

analyze

  • Runs a predictive model to determine the language that the passed-in input strings are written in, and returns, for each one, the detected language as well as a score indicating the model's confidence that the inferred language is correct. Scores close to 1 indicate high certainty in the result. 120 languages are supported.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Language detection

    const documents = [<input strings>];
    const countryHint = "us";
    const results = await client.analyze("LanguageDetection", documents, countryHint);
    
    for (let i = 0; i < results.length; i++) {
      const result = results[i];
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { name, confidenceScore, iso6391Name } = result.primaryLanguage;
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/language-detection/overview for more information on language detection.

    Type parameters

    • ActionName: "LanguageDetection"

    Parameters

    Returns Promise<AnalyzeResult<ActionName>>

    an array of results where each element contains the primary language for the corresponding input document.

  • Runs a predictive model to determine the language that the passed-in input strings are written in, and returns, for each one, the detected language as well as a score indicating the model's confidence that the inferred language is correct. Scores close to 1 indicate high certainty in the result. 120 languages are supported.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Language detection

    const documents = [<input strings>];
    const countryHint = "us";
    const results = await client.analyze("LanguageDetection", documents, countryHint);
    
    for (const result of results) {
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { name, confidenceScore, iso6391Name } = result.primaryLanguage;
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/language-detection/overview for more information on language detection.

    Type parameters

    • ActionName: "LanguageDetection"

    Parameters

    • actionName: ActionName

      the name of the action to be performed on the input documents, see $AnalyzeActionName

    • documents: string[]

      the input documents to be analyzed

    • Optional countryHint: undefined | string

      Indicates the country of origin for all of the input strings to assist the model in predicting the language they are written in. If unspecified, this value will be set to the default country hint in TextAnalysisClientOptions. If set to an empty string, or the string "none", the service will apply a model where the country is explicitly unset. The same country hint is applied to all strings in the input collection.

    • Optional options: AnalyzeActionParameters<ActionName> & TextAnalysisOperationOptions

      optional action parameters and settings for the operation

    Returns Promise<AnalyzeResult<ActionName>>

    an array of results where each element contains the primary language for the corresponding input document.

  • Runs a predictive model to perform the action of choice on the input documents. See $AnalyzeActionName for a list of supported actions.

    The layout of each item in the results array depends on the action chosen. For example, each PIIEntityRecognition document result consists of both entities and redactedText where the former is a list of all Pii entities in the text and the latter is the original text after all such Pii entities have been redacted from it.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Opinion mining

    const documents = [{
     id: "1",
     text: "The food and service aren't the best",
     language: "en"
    }];
    const results = await client.analyze("SentimentAnalysis", documents, {
      includeOpinionMining: true,
    });
    
    for (const result of results) {
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { sentiment, confidenceScores, sentences } = result;
        for (const { sentiment, confidenceScores, opinions } of sentences) {
          for (const { target, assessments } of opinions) {
            const { text, sentiment, confidenceScores } = target;
            for (const { text, sentiment } of assessments) {
              // Do something
            }
          }
        }
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/sentiment-opinion-mining/overview for more information on opinion mining.

    Personally identifiable information

    const documents = [<input documents>];
    const categoriesFilter = [KnownPiiCategory.USSocialSecurityNumber];
    const domainFilter = KnownPiiDomain.Phi;
    const results = await client.analyze("PiiEntityRecognition", documents, {
      domainFilter, categoriesFilter
    });
    
    for (const result of results) {
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { entities, redactedText } = result;
        for (const { text, category, confidenceScore, length, offset } of entities) {
          // Do something
        }
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/personally-identifiable-information/overview for more information on personally identifiable information.

    Type parameters

    Parameters

    Returns Promise<AnalyzeResult<ActionName>>

    an array of results corresponding to the input documents

  • Runs a predictive model to perform the action of choice on the input strings. See $AnalyzeActionName for a list of supported actions.

    The layout of each item in the results array depends on the action chosen. For example, each PIIEntityRecognition document result consists of both entities and redactedText where the former is a list of all Pii entities in the text and the latter is the original text after all such Pii entities have been redacted from it.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Opinion mining

    const documents = ["The food and service aren't the best"];
    const results = await client.analyze("SentimentAnalysis", documents, {
      includeOpinionMining: true,
    });
    
    for (const result of results) {
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { sentiment, confidenceScores, sentences } = result;
        for (const { sentiment, confidenceScores, opinions } of sentences) {
          for (const { target, assessments } of opinions) {
            const { text, sentiment, confidenceScores } = target;
            for (const { text, sentiment } of assessments) {
              // Do something
            }
          }
        }
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/sentiment-opinion-mining/overview for more information on opinion mining.

    Personally identifiable information

    const documents = [<input strings>];
    const languageHint = "en";
    const categoriesFilter = [KnownPiiCategory.USSocialSecurityNumber];
    const domainFilter = KnownPiiDomain.Phi;
    const results = await client.analyze("PiiEntityRecognition", documents, languageHint, {
      domainFilter, categoriesFilter
    });
    
    for (const result of results) {
      if (result.error) {
        // a document has an error instead of results
      } else {
        const { entities, redactedText } = result;
        for (const { text, category, confidenceScore, length, offset } of entities) {
          // Do something
        }
      }
    }

    See https://docs.microsoft.com//azure/cognitive-services/language-service/personally-identifiable-information/overview for more information on personally identifiable information.

    Type parameters

    Parameters

    Returns Promise<AnalyzeResult<ActionName>>

    an array of results corresponding to the input documents

beginAnalyzeBatch

  • Performs an array (batch) of actions on the input documents. Each action has a kind field that specifies the nature of the action. See $AnalyzeBatchActionNames for a list of supported actions. In addition to kind, actions could also have other parameters such as disableServiceLogs and modelVersion.

    The results array contains the results for those input actions where each item also has a kind field that specifies the type of the results.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Key phrase extraction and Pii entity recognition

    const poller = await client.beginAnalyzeBatch(
     [{ kind: "KeyPhraseExtraction" }, { kind: "PiiEntityRecognition" }],
     documents
    );
    const actionResults = await poller.pollUntilDone();
    
    for await (const actionResult of actionResults) {
     if (actionResult.error) {
       throw new Error(`Unexpected error`);
     }
     switch (actionResult.kind) {
       case "KeyPhraseExtraction": {
         for (const doc of actionResult.results) {
           // do something
         }
         break;
       }
       case "PiiEntityRecognition": {
         for (const doc of actionResult.results) {
           // do something
         }
         break;
       }
     }
    }

    Parameters

    • actions: AnalyzeBatchAction[]

      an array of actions that will be run on the input documents

    • documents: string[]

      the input documents to be analyzed

    • Optional languageCode: undefined | string

      the code of the language that all the input strings are written in. If unspecified, this value will be set to the default language in TextAnalysisClientOptions. If set to an empty string, the service will apply a model where the language is explicitly set to "None". Language support varies per action, for example, more information about the languages supported for Entity Recognition actions can be found in https://docs.microsoft.com//azure/cognitive-services/language-service/named-entity-recognition/language-support

    • Optional options: BeginAnalyzeBatchOptions

      optional settings for the operation

    Returns Promise<AnalyzeBatchPoller>

    an array of results corresponding to the input actions

  • Performs an array (batch) of actions on the input documents. Each action has a kind field that specifies the nature of the action. See $AnalyzeBatchActionNames for a list of supported actions. In addition to kind, actions could also have other parameters such as disableServiceLogs and modelVersion.

    The results array contains the results for those input actions where each item also has a kind field that specifies the type of the results.

    See https://docs.microsoft.com//azure/cognitive-services/language-service/concepts/data-limits for data limits.

    Examples

    Keyphrase extraction and Pii entity recognition

    const poller = await client.beginAnalyzeBatch(
     [{ kind: "KeyPhraseExtraction" }, { kind: "PiiEntityRecognition" }],
     documents
    );
    const actionResults = await poller.pollUntilDone();
    
    for await (const actionResult of actionResults) {
     if (actionResult.error) {
       throw new Error(`Unexpected error`);
     }
     switch (actionResult.kind) {
       case "KeyPhraseExtraction": {
         for (const doc of actionResult.results) {
           // do something
         }
         break;
       }
       case "PiiEntityRecognition": {
         for (const doc of actionResult.results) {
           // do something
         }
         break;
       }
     }
    }

    Parameters

    Returns Promise<AnalyzeBatchPoller>

    an array of results corresponding to the input actions

restoreAnalyzeBatchPoller

  • Creates a poller from the serialized state of another poller. This can be useful when you want to create pollers on a different host or a poller needs to be constructed after the original one is not in scope.

    Parameters

    • serializedState: string

      the serialized state of another poller. It is the result of poller.toString()

    • Optional options: RestoreAnalyzeBatchPollerOptions

      optional settings for the operation

      Example

      client.beginAnalyzeBatch returns a promise that will resolve to a poller. The state of the poller can be serialized and used to create another as follows:

      const serializedState = poller.toString();
      const rehydratedPoller = await client.createAnalyzeBatchPoller(serializedState);
      const actionResults = await rehydratedPoller.pollUntilDone();

    Returns Promise<AnalyzeBatchPoller>

Generated using TypeDoc