diff --git a/sdk/textanalytics/azure-ai-textanalytics/README.md b/sdk/textanalytics/azure-ai-textanalytics/README.md index 116121544709..f820272ef84f 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/README.md @@ -28,8 +28,8 @@ and includes six main functions: ``` [//]: # ({x-version-update-end}) - -### Create a Text Analytics resource +### Authenticate the client +#### Create a Cognitive Services or Text Analytics resource Text Analytics supports both [multi-service and single-service access][service_access]. Create a Cognitive Services resource if you plan to access multiple cognitive services under a single endpoint/key. For Text Analytics access only, create a Text Analytics resource. @@ -58,34 +58,40 @@ az cognitiveservices account create \ --location westus2 \ --yes ``` -### Authenticate the client -In order to interact with the Text Analytics service, you will need to create an instance of the `TextAnalyticsClient` -class. You will need an **endpoint** and either an **API key** or **AAD TokenCredential** to instantiate a client -object. And they can be found in the [Azure Portal][azure_portal] under the "Quickstart" in your created -Text Analytics resource. See the full details regarding [authentication][authentication] of Cognitive Services. +In order to interact with the Text Analytics service, you will need to create an instance of the Text Analytics client, +both the asynchronous and synchronous clients can be created by using `TextAnalyticsClientBuilder` invoking `buildClient()` +creates a synchronous client while `buildAsyncClient()` creates its asynchronous counterpart. -#### Get credentials -The authentication credential may be provided as the API key to your resource or as a token from Azure Active Directory. +You will need an **endpoint** and either a **key** or **AAD TokenCredential** to instantiate a client object. +##### Looking up the endpoint +You can find the **endpoint** for your Text Analytics resource in the [Azure Portal][azure_portal] under the "Keys and Endpoint", +or [Azure CLI][azure_cli_endpoint]. +```bash +# Get the endpoint for the text analytics resource +az cognitiveservices account show --name "resource-name" --resource-group "resource-group-name" --query "endpoint" +``` -##### **Option 1**: Create TextAnalyticsClient with AzureKeyCredential -To use AzureKeyCredential authentication, provide the [key][key] as a string to the [AzureKeyCredential][azure_key_credential]. This can be found in the [Azure Portal][azure_portal] - under the "Quickstart" section or by running the following Azure CLI command: +##### Create a Text Analytics client with key credential +Once you have the value for the [key][key], provide it as a string to the [AzureKeyCredential][azure_key_credential]. +This can be found in the [Azure Portal][azure_portal] under the "Keys and Endpoint" section in your created Text Analytics +resource or by running the following Azure CLI command: ```bash az cognitiveservices account keys list --resource-group --name ``` + Use the key as the credential parameter to authenticate the client: - + ```java TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); ``` -The Azure Text Analytics client library provides a way to **rotate the existing key**. - +The Azure Text Analytics client library provides a way to **rotate the existing key**. + ```java AzureKeyCredential credential = new AzureKeyCredential("{key}"); TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() @@ -95,30 +101,40 @@ TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() credential.update("{new_key}"); ``` -##### **Option 2**: Create TextAnalyticsClient with Azure Active Directory Credential -To use an [Azure Active Directory (AAD) token credential][aad_credential], -provide an instance of the desired credential type obtained from the [azure-identity][azure_identity] library. -Note that regional endpoints do not support AAD authentication. Create a [custom subdomain][custom_subdomain] -name for your resource in order to use this type of authentication. +##### Create a Text Analytics client with Azure Active Directory credential +Azure SDK for Java supports an Azure Identity package, making it easy to get credentials from Microsoft identity +platform. Authentication with AAD requires some initial setup: -* [Install azure-identity][install_azure_identity] -* [Register a new AAD application][register_AAD_application] -* [Grant access][grant_access] to Text Analytics by assigning the `"Cognitive Services User"` role to your service principal. +* Add the Azure Identity package -After setup, you can choose which type of [credential][credential_type] from azure.identity to use. -As an example, [DefaultAzureCredential][default_azure_credential] -can be used to authenticate the client: +[//]: # ({x-version-update-start;com.azure:azure-identity;dependency}) +```xml + + com.azure + azure-identity + 1.0.6 + +``` +[//]: # ({x-version-update-end}) +* [Register a new Azure Active Directory application][register_AAD_application] +* [Grant access][grant_access] to Text Analytics by assigning the `"Cognitive Services User"` role to your service principal. +After setup, you can choose which type of [credential][azure_identity_credential_type] from azure.identity to use. +As an example, [DefaultAzureCredential][wiki_identity] can be used to authenticate the client: Set the values of the client ID, tenant ID, and client secret of the AAD application as environment variables: -AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. +AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET. -Use the returned token credential to authenticate the client: - +Authorization is easiest using [DefaultAzureCredential][wiki_identity]. It finds the best credential to use in its +running environment. For more information about using Azure Active Directory authorization with Text Analytics, please +refer to [the associated documentation][aad_authorization]. + + ```java +TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") - .credential(new DefaultAzureCredentialBuilder().build()) + .credential(defaultCredential) .buildAsyncClient(); ``` @@ -130,11 +146,18 @@ asynchronous operations to access a specific use of Text Analytics, such as lang ### Input A **text input**, also called a **document**, is a single unit of document to be analyzed by the predictive models -in the Text Analytics service. Operations on Text Analytics client may take a single document or a collection +in the Text Analytics service. Operations on a Text Analytics client may take a single document or a collection of documents to be analyzed as a batch. See [service limitations][service_input_limitation] for the document, including document length limits, maximum batch size, and supported text encoding. +### Operation on multiple documents +For each supported operation, the Text Analytics client provides method overloads to take a single document, a batch +of documents as strings, or a batch of either `TextDocumentInput` or `DetectLanguageInput` objects. The overload +taking the `TextDocumentInput` or `DetectLanguageInput` batch allows callers to give each document a unique ID, +indicate that the documents in the batch are written in different languages, or provide a country hint about the +language of the document. + ### Return value An operation result, such as `AnalyzeSentimentResult`, is the result of a Text Analytics operation, containing a prediction or predictions about a single document and a list of warnings inside of it. An operation's result type also @@ -150,13 +173,6 @@ An operation result collection, such as `TextAnalyticsPagedResponse + ``` java TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) .endpoint("{endpoint}") .buildClient(); ``` - + ``` java TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .credential(new AzureKeyCredential("{key}")) @@ -215,7 +237,10 @@ TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() ``` ### Analyze sentiment - +Run a Text Analytics predictive model to identify the positive, negative, neutral or mixed sentiment contained in the +passed-in document or batch of documents. + + ```java String document = "The hotel was dark and unclean. I like microsoft."; DocumentSentiment documentSentiment = textAnalyticsClient.analyzeSentiment(document); @@ -223,27 +248,54 @@ System.out.printf("Analyzed document sentiment: %s.%n", documentSentiment.getSen documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Analyzed sentence sentiment: %s.%n", sentenceSentiment.getSentiment())); ``` +For samples on using the production recommended option `AnalyzeSentimentBatch` see [here][analyze_sentiment_sample]. +Please refer to the service documentation for a conceptual discussion of [sentiment analysis][sentiment_analysis]. ### Detect language - +Run a Text Analytics predictive model to determine the language that the provided document or batch of documents are written in. + + ```java String document = "Bonjour tout le monde"; DetectedLanguage detectedLanguage = textAnalyticsClient.detectLanguage(document); System.out.printf("Detected language name: %s, ISO 6391 name: %s, confidence score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getConfidenceScore()); ``` +For samples on using the production recommended option `DetectLanguageBatch` see [here][detect_language_sample]. +Please refer to the service documentation for a conceptual discussion of [language detection][language_detection]. -### Recognize entity - +### Extract key phrases +Run a model to identify a collection of significant phrases found in the passed-in document or batch of documents. + + +```java +String document = "My cat might need to see a veterinarian."; +System.out.println("Extracted phrases:"); +textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); +``` +For samples on using the production recommended option `ExtractKeyPhrasesBatch` see [here][extract_key_phrases_sample]. +Please refer to the service documentation for a conceptual discussion of [key phrase extraction][key_phrase_extraction]. + +### Recognize entities +Run a predictive model to identify a collection of named entities in the passed-in document or batch of documents and +categorize those entities into categories such as person, location, or organization. For more information on available +categories, see [Text Analytics Named Entity Categories][named_entities_categories]. + + ```java String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsClient.recognizeEntities(document).forEach(entity -> System.out.printf("Recognized entity: %s, category: %s, subcategory: %s, confidence score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubcategory(), entity.getConfidenceScore())); ``` +For samples on using the production recommended option `RecognizeEntitiesBatch` see [here][recognize_entities_sample]. +Please refer to the service documentation for a conceptual discussion of [named entity recognition][named_entity_recognition]. -### Recognize linked entity - +### Recognize linked entities +Run a predictive model to identify a collection of entities found in the passed-in document or batch of documents, +and include information linking the entities to their corresponding entries in a well-known knowledge base. + + ```java String document = "Old Faithful is a geyser at Yellowstone Park."; @@ -255,16 +307,11 @@ textAnalyticsClient.recognizeLinkedEntities(document).forEach(linkedEntity -> { System.out.printf("Text: %s, confidence score: %f.%n", match.getText(), match.getConfidenceScore())); }); ``` -### Extract key phrases - -```java -String document = "My cat might need to see a veterinarian."; -System.out.println("Extracted phrases:"); -textAnalyticsClient.extractKeyPhrases(document).forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); -``` +For samples on using the production recommended option `RecognizeLinkedEntitiesBatch` see [here][recognize_linked_entities_sample]. +Please refer to the service documentation for a conceptual discussion of [entity linking][named_entity_recognition]. + -The above examples cover the scenario of having a single document as input. -For more examples, such as batch operation, refer to [here][samples_readme]. +For more examples, such as asynchronous samples, refer to [here][samples_readme]. ## Troubleshooting ### General @@ -272,7 +319,7 @@ Text Analytics clients raise exceptions. For example, if you try to detect the l document IDs, `400` error is return that indicating bad request. In the following code snippet, the error is handled gracefully by catching the exception and display the additional information about the error. - + ```java List documents = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "us"), @@ -314,11 +361,14 @@ When you submit a pull request, a CLA-bot will automatically determine whether y This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. +[aad_authorization]: https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory [aad_credential]: https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory [api_reference_doc]: https://aka.ms/azsdk-java-textanalytics-ref-docs [authentication]: https://docs.microsoft.com/azure/cognitive-services/authentication [azure_cli]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli?tabs=windows -[azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#credentials +[azure_cli_endpoint]: https://docs.microsoft.com/cli/azure/cognitiveservices/account?view=azure-cli-latest#az-cognitiveservices-account-show +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity +[azure_identity_credential_type]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity#credentials [azure_key_credential]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/credential/AzureKeyCredential.java [azure_portal]: https://ms.portal.azure.com [azure_subscription]: https://azure.microsoft.com/free @@ -327,30 +377,35 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com [create_new_resource]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#create-a-new-azure-cognitive-services-resource -[credential_type]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#credentials [custom_subdomain]: https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain -[default_azure_credential]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#defaultazurecredential [grant_access]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal -[install_azure_identity]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#install-the-package [key]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource [key_phrase_extraction]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-keyword-extraction [language_detection]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-language-detection [language_regional_support]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support [named_entity_recognition]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-entity-linking [named_entity_recognition_types]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/named-entity-types?tabs=personal +[named_entities_categories]: https://docs.microsoft.com/azure/cognitive-services/Text-Analytics/named-entity-types [package]: https://mvnrepository.com/artifact/com.azure/azure-ai-textanalytics [performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning [product_documentation]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview [register_AAD_application]: https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal -[samples_readme]: src/samples/README.md [service_access]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows [service_input_limitation]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview#data-limits [sentiment_analysis]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-sentiment-analysis [source_code]: src -[supported_language]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support#language-detection +[supported_languages]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support#language-detection [text_analytics_account]: https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows [text_analytics_async_client]: src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java [text_analytics_sync_client]: src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java +[wiki_identity]: https://github.com/Azure/azure-sdk-for-java/wiki/Identity-and-Authentication [LogLevels]: ../../core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java +[samples_readme]: src/samples/README.md +[detect_language_sample]: src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java +[analyze_sentiment_sample]: src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java +[extract_key_phrases_sample]: src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java +[recognize_entities_sample]: src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java +[recognize_linked_entities_sample]: src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java + ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Ftextanalytics%2Fazure-ai-textanalytics%2FREADME.png) diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md index 426a5402f6e5..7bb2213f8954 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md @@ -63,8 +63,7 @@ Troubleshooting steps can be found [here][SDK_README_TROUBLESHOOTING]. See [Next steps][SDK_README_NEXT_STEPS]. ## Contributing -If you would like to become an active contributor to this project please refer to our [Contribution -Guidelines](../../CONTRIBUTING.md) for more information. +This project welcomes contributions and suggestions. Find [more contributing][SDK_README_CONTRIBUTING] details here. [KEYS_SDK_README]: ../../README.md diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java index de08ebd1aea1..fa6217a84059 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java @@ -7,6 +7,7 @@ import com.azure.ai.textanalytics.models.DetectedLanguage; import com.azure.ai.textanalytics.models.DocumentSentiment; import com.azure.core.credential.AzureKeyCredential; +import com.azure.core.credential.TokenCredential; import com.azure.core.exception.HttpResponseException; import com.azure.core.http.HttpClient; import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; @@ -60,9 +61,10 @@ public void useAzureKeyCredentialAsyncClient() { * Code snippet for getting async client using AAD authentication. */ public void useAadAsyncClient() { + TokenCredential defaultCredential = new DefaultAzureCredentialBuilder().build(); TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() .endpoint("{endpoint}") - .credential(new DefaultAzureCredentialBuilder().build()) + .credential(defaultCredential) .buildAsyncClient(); }