diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index 5597aec314e9..5b049a71dcf4 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -122,6 +122,7 @@ known_content_issues: - ['sdk/storage/microsoft-azure-storage-blob/README.md', '#3113'] - ['sdk/storage/microsoft-azure-storage-blob/swagger/README.md', '#3113'] - ['sdk/storage/README.md', '#3113'] + - ['sdk/textanalytics/azure-ai-textanalytics/swagger/README.md', '#3113'] - ['sdk/template/azure-sdk-template/README.md','has other required sections'] - ['sdk/storage/azure-storage-file-share/swagger/README.md','has other required sections'] diff --git a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml index 7621885dcc95..5c4752c84813 100755 --- a/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml +++ b/eng/code-quality-reports/src/main/resources/checkstyle/checkstyle-suppressions.xml @@ -261,4 +261,15 @@ + + + + + + + + + + + diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index c9becf11065e..83d24ddebc8e 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -36,6 +36,11 @@ + + com.azure + azure-ai-textanalytics + 1.0.0-beta.1 + com.azure azure-core diff --git a/eng/spotbugs-aggregate-report/pom.xml b/eng/spotbugs-aggregate-report/pom.xml index 932473cd6df7..b4a8ae359e20 100644 --- a/eng/spotbugs-aggregate-report/pom.xml +++ b/eng/spotbugs-aggregate-report/pom.xml @@ -73,6 +73,7 @@ ..\..\sdk\storage\azure-storage-file-datalake\src\samples\java\com ..\..\sdk\storage\azure-storage-queue\src\main\java\com ..\..\sdk\storage\azure-storage-queue\src\samples\java\com + ..\..\sdk\textanalytics\azure-ai-textanalytics\src\main\java\com @@ -144,6 +145,11 @@ true + + com.azure + azure-ai-textanalytics + 1.0.0-beta.1 + com.azure azure-data-appconfiguration diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index c4a929a98876..73536ee4e377 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -4,6 +4,7 @@ com.azure:azure-sdk-all;1.0.0;1.0.0 com.azure:azure-sdk-parent;1.6.0;1.6.0 com.azure:azure-client-sdk-parent;1.7.0;1.7.0 +com.azure:azure-ai-textanalytics;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-core;1.1.0;1.2.0-beta.1 com.azure:azure-core-amqp;1.0.0-beta.9;1.0.0-beta.9 com.azure:azure-core-http-netty;1.1.0;1.2.0-beta.1 @@ -13,12 +14,13 @@ com.azure:azure-core-test;1.1.0-beta.1;1.1.0-beta.2 com.azure:azure-core-tracing-opencensus;1.0.0-beta.5;1.0.0-beta.6 com.azure:azure-core-tracing-opentelemetry;1.0.0-beta.1;1.0.0-beta.2 com.azure:azure-data-appconfiguration;1.0.0-beta.7;1.0.0-beta.8 +com.azure:azure-e2e;1.0.0-beta.1;1.0.0-beta.1 com.azure:azure-identity;1.0.1;1.1.0-beta.1 +com.azure:azure-messaging-eventhubs;5.0.0-beta.6;5.0.0-beta.7 +com.azure:azure-messaging-eventhubs-checkpointstore-blob;1.0.0-beta.4;1.0.0-beta.5 com.azure:azure-security-keyvault-certificates;4.0.0-beta.7;4.0.0-beta.8 com.azure:azure-security-keyvault-keys;4.0.1;4.1.0-beta.1 com.azure:azure-security-keyvault-secrets;4.0.1;4.1.0-beta.1 -com.azure:azure-messaging-eventhubs;5.0.0-beta.6;5.0.0-beta.7 -com.azure:azure-messaging-eventhubs-checkpointstore-blob;1.0.0-beta.4;1.0.0-beta.5 com.azure:azure-sdk-template;1.0.4-beta.2;1.0.4-beta.2 com.azure:azure-storage-blob;12.2.0-beta.1;12.2.0-beta.2 com.azure:azure-storage-blob-batch;12.1.0;12.2.0-beta.1 @@ -27,7 +29,6 @@ com.azure:azure-storage-common;12.2.0-beta.1;12.2.0-beta.2 com.azure:azure-storage-file-share;12.1.0-beta.1;12.1.0-beta.2 com.azure:azure-storage-file-datalake;12.0.0-beta.8;12.0.0-beta.9 com.azure:azure-storage-queue;12.2.0-beta.1;12.2.0-beta.2 -com.azure:azure-e2e;1.0.0-beta.1;1.0.0-beta.1 # This is a temporary fix for libaries that need the unreleased dependency version of core unreleased_com.azure:azure-core;1.2.0-beta.1;1.2.0-beta.1 diff --git a/pom.client.xml b/pom.client.xml index 5f80c0d5bbc1..b16aaaf56573 100644 --- a/pom.client.xml +++ b/pom.client.xml @@ -474,6 +474,10 @@ Azure Telemetry - OpenCensus com.azure.core.tracing* + + Azure Text Analytics + com.azure.ai.textanalytics* + https://docs.oracle.com/javase/8/docs/api/ @@ -647,6 +651,7 @@ -snippetpath ${project.basedir}/sdk/storage/azure-storage-common/src/samples/java -snippetpath ${project.basedir}/sdk/storage/azure-storage-file-share/src/samples/java -snippetpath ${project.basedir}/sdk/storage/azure-storage-queue/src/samples/java + -snippetpath ${project.basedir}/sdk/textanalytics/azure-ai-textanalytics/src/samples/java all @@ -1063,7 +1068,7 @@ - + @@ -1223,6 +1228,7 @@ sdk/core/azure-core-test sdk/core/azure-core-tracing-opencensus sdk/core/azure-core-tracing-opentelemetry + sdk/e2e sdk/eventhubs/azure-messaging-eventhubs sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob sdk/identity/azure-identity @@ -1236,6 +1242,6 @@ sdk/storage/azure-storage-file-share sdk/storage/azure-storage-file-datalake sdk/storage/azure-storage-queue - sdk/e2e + sdk/textanalytics/azure-ai-textanalytics diff --git a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md new file mode 100644 index 000000000000..3c3d47dc2d7b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md @@ -0,0 +1,16 @@ +# Release History + +## 1.0.0-beta.1 (Unreleased) + +For details on the Azure SDK for Java (January 2020 Preview) release refer to the [release announcement](). + +### Added +- Initial release of this module. +- Support for subscription key and AAD authentication for both synchronous and asynchronous clients. +- Added Detect Language, Recognize Entity, Recognize PII entity, Recognize Linking Entity, Analyze Sentiment APIs. + +This package's +[documentation]() +and +[samples]() +demonstrate the new API. diff --git a/sdk/textanalytics/azure-ai-textanalytics/README.md b/sdk/textanalytics/azure-ai-textanalytics/README.md new file mode 100644 index 000000000000..3658bd1bc0b8 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/README.md @@ -0,0 +1,348 @@ +# Azure Text Analytics client library for Java +Text Analytics is a cloud-based service that provides advanced natural language processing over raw text, +and includes four main functions: + +- Sentiment Analysis +- Named Entity Recognition +- Language Detection +- Key Phrase Extraction + +## Getting started + +### Prerequisites +- Java Development Kit (JDK) with version 8 or above +- [Azure Subscription][azure_subscription] +- [Cognitive Services or Text Analytics account](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows) to use this package. + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure:azure-ai-textanalytics;current}) +```xml + + com.azure + azure-ai-textanalytics + 1.0.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +### Default HTTP Client +All client libraries, by default, use Netty HTTP client. Adding the above dependency will automatically configure +Text Analytics to use Netty HTTP client. + +[//]: # ({x-version-update-start;com.azure:azure-core-http-netty;dependency}) +```xml + + com.azure + azure-core-http-netty + 1.1.0 + +``` +[//]: # ({x-version-update-end}) + +### Alternate HTTP Client +If, instead of Netty it is preferable to use OkHTTP, there is a HTTP client available for that too. Exclude the default +Netty and include OkHTTP client in your pom.xml. + +[//]: # ({x-version-update-start;com.azure:azure-ai-textanalytics;current}) +```xml + + + com.azure + azure-ai-textanalytics + 1.0.0-beta.1 + + + com.azure + azure-core-http-netty + + + +``` +[//]: # ({x-version-update-end}) + +[//]: # ({x-version-update-start;com.azure:azure-core-http-okhttp;dependency}) +```xml + + + com.azure + azure-core-http-okhttp + 1.1.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +### Configuring HTTP Clients +When an HTTP client is included on the classpath, as shown above, it is not necessary to specify it in the client library [builders](#create-a-client), unless you want to customize the HTTP client in some fashion. If this is desired, the `httpClient` builder method is often available to achieve just this, by allowing users to provide a custom (or customized) `com.azure.core.http.HttpClient` instances. + +For starters, by having the Netty or OkHTTP dependencies on your classpath, as shown above, you can create new instances of these `HttpClient` types using their builder APIs. For example, here is how you would create a Netty HttpClient instance: + +```java +HttpClient client = new NettyAsyncHttpClientBuilder() + .port(8080) + .wiretap(true) + .build(); +``` + +### Default SSL library +All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an uber jar containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the [performance tuning][performance_tuning] section of the wiki. + +### Create a Text Analytics resource +Text Analytics supports both [multi-service and single-service access](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows). 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. + +You can create either resource using the +[Azure Portal](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#create-a-new-azure-cognitive-services-resource) +or [Azure CLI](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account-cli?tabs=windows). +Below is an example of how you can create a Text Analytics resource using the CLI: + +```bash +# Create a new resource group to hold the text analytics resource - +# if using an existing resource group, skip this step +az group create --name my-resource-group --location westus2 +``` + +```bash +# Create text analytics +az cognitiveservices account create \ + --name text-analytics-resource \ + --resource-group my-resource-group \ + --kind TextAnalytics \ + --sku F0 \ + --location westus2 \ + --yes +``` +### Authenticate the client +In order to interact with the Text Analytics service, you'll need to create an instance of the [TextAnalyticsClient](#create-ta-client) class. You would need an **endpoint** and **subscription key** to instantiate a client object. + +#### Get credentials +##### Types of credentials +The `subscriptionKey` parameter may be provided as the subscription key to your resource or as a token from Azure Active Directory. +See the full details regarding [authentication](https://docs.microsoft.com/azure/cognitive-services/authentication) of +cognitive services. + +1. To use a [subscription key](https://docs.microsoft.com/azure/cognitive-services/cognitive-services-apis-create-account?tabs=multiservice%2Cwindows#get-the-keys-for-your-resource), + provide the key as a string. This can be found in the Azure Portal under the "Quickstart" + section or by running the following Azure CLI command: + + ```az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name"``` + + Use the key as the credential parameter to authenticate the client: + ```java + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + ``` + +2. To use an [Azure Active Directory (AAD) token credential](https://docs.microsoft.com/azure/cognitive-services/authentication#authenticate-with-azure-active-directory), + provide an instance of the desired credential type obtained from the + [azure-identity](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#credentials) library. + Note that regional endpoints do not support AAD authentication. Create a [custom subdomain](https://docs.microsoft.com/azure/cognitive-services/authentication#create-a-resource-with-a-custom-subdomain) + name for your resource in order to use this type of authentication. + + Authentication with AAD requires some initial setup: + * [Install azure-identity](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#install-the-package) + * [Register a new AAD application](https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal) + * [Grant access](https://docs.microsoft.com/azure/cognitive-services/authentication#assign-a-role-to-a-service-principal) to Text Analytics by assigning the `"Cognitive Services User"` role to your service principal. + + After setup, you can choose which type of [credential](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#credentials) from azure.identity to use. + As an example, [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/identity/azure-identity#defaultazurecredential) + 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 + + Use the returned token credential to authenticate the client: + ```java + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .endpoint("https://servicename.cognitiveservices.azure.com/") + .credential(new DefaultAzureCredentialBuilder().build()) + .buildClient(); + ``` + +#### Create a Client +The Azure Text Analytics client library for Java allows you to engage with the Text Analytics service to +analyze sentiment, recognize entities, detect language, and extract key phrases from text. +To create a client object, you will need the cognitive services or text analytics endpoint to +your resource and a subscription key that allows you access: + +```java +// Instantiate a client that will be used to call the service. +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); +``` + +## Key concepts + +The following are types of text analysis that the service offers: + +1. [Sentiment Analysis](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-sentiment-analysis) + + Use sentiment analysis to find out what customers think of your brand or topic by analyzing raw text for clues about positive or negative sentiment. + Scores closer to `1` indicate positive sentiment, while scores closer to `0` indicate negative sentiment. + Sentiment analysis returns scores and labels at a document and sentence level. + +2. [Named Entity Recognition](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-entity-linking) + + Use named entity recognition (NER) to identify different entities in text and categorize them into pre-defined classes, or types. + Entity recognition in the client library provides three different methods depending on what you are interested in. + * `recognizeEntities()` can be used to identify and categorize entities in your text as people, places, organizations, date/time, quantities, percentages, currencies, and more. + * `recognizePiiEntities()` can be used to recognize personally identifiable information such as SSNs and bank account numbers. + * `recognizeLinkedEntities()` can be used to identify and disambiguate the identity of an entity found in text (For example, determining whether + "Mars" is being used as the planet or as the Roman god of war). This process uses Wikipedia as the knowledge base to which recognized entities are linked. + + See a full list of [Named Entity Recognition Types](https://docs.microsoft.com/azure/cognitive-services/text-analytics/named-entity-types?tabs=personal). + +3. [Language Detection](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-language-detection) + + Detect the language of the input text and report a single language code for every document submitted on the request. + The language code is paired with a score indicating the strength of the score. + A wide range of languages, variants, dialects, and some regional/cultural languages are supported - + see [supported languages](https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support#language-detection) for full details. + +4. [Key Phrase Extraction](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-keyword-extraction) + + Extract key phrases to quickly identify the main points in text. + For example, for the input text "The food was delicious and there were wonderful staff", the main talking points returned: "food" and "wonderful staff". + +See [Language and regional support](https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support) for what is currently available for each operation. + +### Text Analytics Client +``` java +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); +``` + +``` java +TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildAsyncClient(); +``` + +## Examples +The following sections provide several code snippets covering some of the most common text analytics tasks, including: + +### Detect language +Detect language in a batch of documents. + +```java +TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildAsyncClient(); + +String inputText = "Bonjour tout le monde"; + +for(DetectedLanguage detectedLanguage : client.detectLanguage(text, "US").getDetectedLanguages()) { + System.out.printf("Other detected languages: %s, ISO 6391 Name: %s, Score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); +} +``` + +### Recognize entity +```java +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + +String text = "Satya Nadella is the CEO of Microsoft"; + +for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized NamedEntity: %s, Type: %s, Subtype: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); +} +``` + +### Recognize PII(Personally Identifiable Information) entity +```java +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + +// The text that need be analysed. +String text = "My SSN is 555-55-5555"; + +for (NamedEntity entity : client.recognizePiiEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized PII Entity: %s, Type: %s, Subtype: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getScore())); +} +``` + +### Recognize linked entity +```java +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + +// The text that need be analysed. +String text = "Old Faithful is a geyser at Yellowstone Park."; + +for (LinkedEntity linkedEntity : client.recognizeLinkedEntities(text).getLinkedEntities()) { + System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s.%n", + linkedEntity.getName(), + linkedEntity.getUri(), + linkedEntity.getDataSource()); +} +``` + +### Analyze sentiment +```java +TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + +String text = "The hotel was dark and unclean."; + +for (TextSentiment textSentiment : client.analyzeSentiment(text).getSentenceSentiments()) { + System.out.printf( + "Recognized Sentence TextSentiment: %s.%n", + textSentiment.getTextSentimentClass()); +} +``` + +## Troubleshooting +## General + +## Next steps +- Samples are explained in detail [here][samples_readme]. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a [Contributor License Agreement (CLA)][cla] declaring that you have the right to, and actually do, grant us the rights to use your contribution. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +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. + + +[azure_subscription]: https://azure.microsoft.com/free +[cla]: https://cla.microsoft.com +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ +[coc_contact]: mailto:opencode@microsoft.com +[samples_readme]: src/samples/README.md +[source_code]: src + +![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/pom.xml b/sdk/textanalytics/azure-ai-textanalytics/pom.xml new file mode 100644 index 000000000000..46602c601baf --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/pom.xml @@ -0,0 +1,62 @@ + + + 4.0.0 + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../../pom.client.xml + + + com.azure + azure-ai-textanalytics + 1.0.0-beta.1 + + Microsoft Azure client library for Text Analytics + This package contains the Microsoft Azure Cognitive Services Text Analytics SDK. + https://github.com/Azure/azure-sdk-for-java + + + + azure-java-build-docs + ${site.url}/site/${project.artifactId} + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + + com.azure + azure-core-http-netty + 1.1.0 + + + + + com.azure + azure-core-test + 1.1.0-beta.1 + test + + + org.junit.jupiter + junit-jupiter-api + 5.4.2 + test + + + com.azure + azure-identity + 1.0.1 + test + + + diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java new file mode 100644 index 000000000000..c969f8c0d74c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java @@ -0,0 +1,1385 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentEntities; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.DocumentKeyPhrases; +import com.azure.ai.textanalytics.implementation.models.DocumentLanguage; +import com.azure.ai.textanalytics.implementation.models.DocumentLinkedEntities; +import com.azure.ai.textanalytics.implementation.models.DocumentSentiment; +import com.azure.ai.textanalytics.implementation.models.DocumentStatistics; +import com.azure.ai.textanalytics.implementation.models.EntitiesResult; +import com.azure.ai.textanalytics.implementation.models.EntityLinkingResult; +import com.azure.ai.textanalytics.implementation.models.LanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.LanguageInput; +import com.azure.ai.textanalytics.implementation.models.LanguageResult; +import com.azure.ai.textanalytics.implementation.models.LinkedEntity; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageInput; +import com.azure.ai.textanalytics.implementation.models.RequestStatistics; +import com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel; +import com.azure.ai.textanalytics.implementation.models.SentimentResponse; +import com.azure.ai.textanalytics.implementation.models.TextAnalyticsError; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ErrorCodeValue; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.LinkedEntityMatch; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsClientOptions; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextDocumentStatistics; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.TextSentimentClass; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import static com.azure.core.util.FluxUtil.monoError; +import static com.azure.core.util.FluxUtil.withContext; + +/** + * This class provides an asynchronous client that contains all the operations that apply to Azure Text Analytics. + * Operations allowed by the client are language detection, sentiment analysis, and recognition entities, PII entities, + * and linked entities of a text input or list of test inputs. + * + *

Instantiating an asynchronous Text Analytics Client

+ * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsAsyncClient.instantiation} + * + *

View {@link TextAnalyticsClientBuilder} for additional ways to construct the client.

+ * + * @see TextAnalyticsClientBuilder + */ +@ServiceClient(builder = TextAnalyticsClientBuilder.class, isAsync = true) +public final class TextAnalyticsAsyncClient { + private final ClientLogger logger = new ClientLogger(TextAnalyticsAsyncClient.class); + private final TextAnalyticsClientImpl service; + private final TextAnalyticsServiceVersion serviceVersion; + private final String defaultCountryHint; + private final String defaultLanguage; + + /** + * Create a {@code TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each + * service call goes through the {@link TextAnalyticsClientBuilder#pipeline http pipeline}. + * + * @param service The proxy service used to perform REST calls. + * @param serviceVersion The versions of Azure Text Analytics supported by this client library. + * @param clientOptions The {@link TextAnalyticsClientOptions client option} contains + * {@link TextAnalyticsClientOptions#getDefaultLanguage default language} and + * {@link TextAnalyticsClientOptions#getDefaultCountryHint()} default country hint} that could be used as default + * values for each request. + */ + TextAnalyticsAsyncClient(TextAnalyticsClientImpl service, TextAnalyticsServiceVersion serviceVersion, + TextAnalyticsClientOptions clientOptions) { + this.service = service; + this.serviceVersion = serviceVersion; + defaultCountryHint = clientOptions == null ? null : clientOptions.getDefaultCountryHint(); + defaultLanguage = clientOptions == null ? null : clientOptions.getDefaultLanguage(); + } + + /** + * Get default country hint code. + * + * @return the default country hint code + */ + public String getDefaultCountryHint() { + return defaultCountryHint; + } + + /** + * Get default language when the builder is setup. + * + * @return the default language + */ + public String getDefaultLanguage() { + return defaultLanguage; + } + + /** + * Gets the service version the client is using. + * + * @return the service version the client is using. + */ + public TextAnalyticsServiceVersion getServiceVersion() { + return serviceVersion; + } + + /** + * Returns the detected language and a numeric score between zero and one. Scores close to one indicate 100% + * certainty that the identified language is true. + * + * @param text The text to be analyzed. + * + * @return A {@link Mono} containing the {@link DetectLanguageResult detected language} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono detectLanguage(String text) { + try { + return detectLanguageWithResponse(text, defaultCountryHint).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a {@link Response} containing the detected language and a numeric score between zero and one. Scores + * close to one indicate 100% certainty that the identified language is true. + * + * @param text The text to be analyzed. + * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not + * specified. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link DetectLanguageResult detected language} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> detectLanguageWithResponse(String text, String countryHint) { + try { + return withContext(context -> detectLanguageWithResponse(text, countryHint, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> detectLanguageWithResponse(String text, String countryHint, Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + List languageInputs = Collections.singletonList(new DetectLanguageInput("0", + text, countryHint)); + return detectBatchLanguagesWithResponse(languageInputs, null, context).map(response -> + new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns the detected language for a batch of input. + * + * @param textInputs The list of texts to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link DetectLanguageResult detected languages}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> detectLanguages(List textInputs) { + try { + return detectLanguagesWithResponse(textInputs, defaultCountryHint).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns the detected language for a batch of input with the provided country hint. + * + * @param textInputs The list of texts to be analyzed. + * @param countryHint A country hint for the entire batch. Accepts two letter country codes specified by ISO + * 3166-1 alpha-2. Defaults to "US" if not specified. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link DetectLanguageResult detected languages}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> detectLanguagesWithResponse( + List textInputs, String countryHint) { + try { + return withContext(context -> detectLanguagesWithResponse(textInputs, countryHint, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> detectLanguagesWithResponse(List textInputs, + String countryHint, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + List detectLanguageInputs = mapByIndex(textInputs, (index, value) -> + new DetectLanguageInput(index, value, countryHint)); + + return detectBatchLanguagesWithResponse(detectLanguageInputs, null, context); + } + + /** + * Returns the detected language for a batch of input. + * + * @param textInputs The list of {@link DetectLanguageInput inputs/documents} to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link DetectLanguageResult detected languages}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> detectBatchLanguages( + List textInputs) { + try { + return detectBatchLanguagesWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns the detected language for a batch of input. + * + * @param textInputs The list of {@link DetectLanguageInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link DetectLanguageResult detected languages}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> detectBatchLanguagesWithResponse( + List textInputs, TextAnalyticsRequestOptions options) { + try { + return withContext( + context -> detectBatchLanguagesWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> detectBatchLanguagesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final LanguageBatchInput languageBatchInput = new LanguageBatchInput() + .setDocuments(textInputs.stream().map(detectLanguageInput -> new LanguageInput() + .setId(detectLanguageInput.getId()).setText(detectLanguageInput.getText()) + .setCountryHint(detectLanguageInput.getCountryHint())).collect(Collectors.toList())); + + return service.languagesWithRestResponseAsync( + languageBatchInput, options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of language input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of detected language output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to detected languages - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + // Named Entity + /** + * Returns a list of general named entities in the provided text. For a list of supported entity types, check: + * . For a list of enabled languages, + * check: + * + * @param text the text to recognize entities for. + * + * @return A {@link Mono} containing the {@link RecognizeEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono recognizeEntities(String text) { + try { + return recognizeEntitiesWithResponse(text, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of general named entities in the provided text. For a list of supported entity types, check: + * . For a list of enabled languages, + * check: + * + * @param text the text to recognize entities for. + * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as + * default. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link RecognizeEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeEntitiesWithResponse(String text, String language) { + try { + return withContext(context -> recognizeEntitiesWithResponse(text, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> recognizeEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns a list of general named entities for the provided list of texts. + * + * @param textInputs A list of texts to recognize entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeEntities(List textInputs) { + try { + return recognizeEntitiesWithResponse(textInputs, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of general named entities for the provided list of texts. + * + * @param textInputs A list of texts to recognize entities for. + * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as + * default. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> recognizeEntitiesWithResponse( + List textInputs, String language) { + try { + return withContext(context -> recognizeEntitiesWithResponse(textInputs, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizeEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return recognizeBatchEntitiesWithResponse(documentInputs, null, context); + } + + /** + * Returns a list of general named entities for the provided list of text inputs. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeBatchEntities( + List textInputs) { + try { + return recognizeBatchEntitiesWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of general named entities for the provided list of text inputs. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> recognizeBatchEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options) { + try { + return withContext(context -> recognizeBatchEntitiesWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizeBatchEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(convertToMultiLanguageInput(textInputs)); + return service.entitiesRecognitionGeneralWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to named entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + // PII Entity + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the text. For the list of + * supported entity types, check . See + * for the list of enabled languages. + * + * @param text the text to recognize PII entities for. + * + * @return A {@link Mono} containing the {@link RecognizeEntitiesResult PII entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono recognizePiiEntities(String text) { + try { + return recognizePiiEntitiesWithResponse(text, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the text. For the list of + * supported entity types, check: . For a list of enabled languages, + * check: . + * + * @param text the text to recognize PII entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link RecognizeEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizePiiEntitiesWithResponse(String text, String language) { + try { + return withContext(context -> recognizePiiEntitiesWithResponse(text, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> recognizePiiEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchPiiEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the list of texts. For the list + * of supported entity types, check: . For a list of enabled languages, + * check: for the list of enabled languages. + * + * @param textInputs A list of text to recognize PII entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizePiiEntities(List textInputs) { + try { + return recognizePiiEntitiesWithResponse(textInputs, defaultLanguage) + .flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the list of texts. For the list + * of supported entity types, check . For a list of enabled languages, + * check: . + * + * @param textInputs A list of text to recognize PII entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> recognizePiiEntitiesWithResponse( + List textInputs, String language) { + try { + return withContext(context -> recognizePiiEntitiesWithResponse(textInputs, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizePiiEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + try { + return recognizeBatchPiiEntitiesWithResponse(documentInputs, null, context); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the batch of document inputs. For + * the list of supported entity types, check: + * For a list of enabled languages, check: . + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize PII entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeBatchPiiEntities( + List textInputs) { + try { + return recognizeBatchPiiEntitiesWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the batch of document inputs. For + * the list of supported entity types,check: . For a list of enabled languages, + * check: . + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize PII entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeEntitiesResult named entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> recognizeBatchPiiEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options) { + try { + return withContext(context -> recognizeBatchPiiEntitiesWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizeBatchPiiEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(convertToMultiLanguageInput(textInputs)); + return service.entitiesRecognitionPiiWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of PII entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of PII entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to PII entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toPiiDocumentResultCollection(response.getValue()))); + } + + // Linked Entity + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the provided text. See + * for supported languages in Text Analytics API. + * + * @param text the text to recognize linked entities for. + * + * @return A {@link Mono} containing the {@link RecognizeLinkedEntitiesResult linked entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono recognizeLinkedEntities(String text) { + try { + return recognizeLinkedEntitiesWithResponse(text, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the provided text. See + * for supported languages in Text Analytics API. + * + * @param text the text to recognize linked entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link RecognizeLinkedEntitiesResult named entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeLinkedEntitiesWithResponse(String text, + String language) { + try { + return withContext(context -> recognizeLinkedEntitiesWithResponse(text, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> recognizeLinkedEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchLinkedEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of texts. See + * for supported languages in Text Analytics API. + * + * @param textInputs A list of text to recognize linked entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeLinkedEntitiesResult linked entity} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeLinkedEntities( + List textInputs) { + try { + return recognizeLinkedEntitiesWithResponse(textInputs, defaultLanguage) + .flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of texts. See + * for supported languages in Text Analytics API. + * + * @param textInputs A list of text to recognize linked entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeLinkedEntitiesResult linked entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> recognizeLinkedEntitiesWithResponse( + List textInputs, String language) { + try { + return withContext(context -> recognizeLinkedEntitiesWithResponse(textInputs, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizeLinkedEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + try { + return recognizeBatchLinkedEntitiesWithResponse(documentInputs, null, context); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of inputs. See + * for supported languages in Text Analytics API. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize linked entities for. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeLinkedEntitiesResult linked entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> recognizeBatchLinkedEntities( + List textInputs) { + try { + return recognizeBatchLinkedEntitiesWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of inputs. See + * supported languages in Text Analytics API. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize linked entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeLinkedEntitiesResult linked entity}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> + recognizeBatchLinkedEntitiesWithResponse(List textInputs, + TextAnalyticsRequestOptions options) { + try { + return withContext(context -> recognizeBatchLinkedEntitiesWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> recognizeBatchLinkedEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(convertToMultiLanguageInput(textInputs)); + return service.entitiesLinkingWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + + // Key Phrases + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param text the text to be analyzed. + * + * @return A {@link Mono} containing the {@link ExtractKeyPhraseResult key phrases} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono extractKeyPhrases(String text) { + try { + return extractKeyPhrasesWithResponse(text, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of strings denoting the key phrases in the input text. See + * for the list of enabled languages. + * + * @param text the text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link ExtractKeyPhraseResult key phrases} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> extractKeyPhrasesWithResponse(String text, String language) { + try { + return withContext(context -> extractKeyPhrasesWithResponse(text, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> extractKeyPhrasesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return extractBatchKeyPhrasesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param textInputs A list of text to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link ExtractKeyPhraseResult key phrases} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> extractKeyPhrases(List textInputs) { + try { + return extractKeyPhrasesWithResponse(textInputs, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of strings denoting the key phrases in the input text. See + * for the list of enabled languages. + * + * @param textInputs A list of text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link ExtractKeyPhraseResult key phrases}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> extractKeyPhrasesWithResponse( + List textInputs, String language) { + try { + return withContext(context -> extractKeyPhrasesWithResponse(textInputs, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> extractKeyPhrasesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + try { + return extractBatchKeyPhrasesWithResponse(documentInputs, null, context); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link ExtractKeyPhraseResult key phrases}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> extractBatchKeyPhrases( + List textInputs) { + try { + return extractBatchKeyPhrasesWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a list of strings denoting the key phrases in the input text. See + * for the list of enabled languages. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link ExtractKeyPhraseResult key phrases}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> extractBatchKeyPhrasesWithResponse( + List textInputs, TextAnalyticsRequestOptions options) { + try { + return withContext(context -> extractBatchKeyPhrasesWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> extractBatchKeyPhrasesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(convertToMultiLanguageInput(textInputs)); + return service.keyPhrasesWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of key phrases input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to key phrases - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + private DocumentResultCollection toDocumentResultCollection( + final com.azure.ai.textanalytics.implementation.models.KeyPhraseResult keyPhraseResult) { + List keyPhraseResultList = new ArrayList<>(); + for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { + keyPhraseResultList.add(new ExtractKeyPhraseResult(documentKeyPhrases.getId(), + documentKeyPhrases.getStatistics() == null ? null + : convertToTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, + documentKeyPhrases.getKeyPhrases())); + } + + for (DocumentError documentError : keyPhraseResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(keyPhraseResultList, + keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null + : mapBatchStatistics(keyPhraseResult.getStatistics())); + } + + // Sentiment + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within i + * + * @param text the text to be analyzed. + * + * @return A {@link Mono} containing the {@link AnalyzeSentimentResult text sentiment} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono analyzeSentiment(String text) { + try { + return analyzeSentimentWithResponse(text, defaultLanguage).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within i + * + * @param text the text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} has the + * {@link AnalyzeSentimentResult text sentiment} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> analyzeSentimentWithResponse(String text, String language) { + try { + return withContext(context -> analyzeSentimentWithResponse(text, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono> analyzeSentimentWithResponse(String text, String language, Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return analyzeBatchSentimentWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within it. + * + * @param textInputs A list of text to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link AnalyzeSentimentResult text sentiment} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> analyzeSentiment(List textInputs) { + try { + return analyzeSentimentWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within it. + * + * @param textInputs A list of text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * + * @return A {@link Response} of {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link AnalyzeSentimentResult text sentiment}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> analyzeSentimentWithResponse( + List textInputs, String language) { + try { + return withContext(context -> analyzeSentimentWithResponse(textInputs, language, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> analyzeSentimentWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return analyzeBatchSentimentWithResponse(documentInputs, null, context); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within it. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * + * @return A {@link Mono} containing the {@link DocumentResultCollection batch} of the + * {@link AnalyzeSentimentResult text sentiment}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> analyzeBatchSentiment( + List textInputs) { + try { + return analyzeBatchSentimentWithResponse(textInputs, null).flatMap(FluxUtil::toMono); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and + * Neutral) for the document and each sentence within it. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * + * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link AnalyzeSentimentResult text sentiment}. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono>> analyzeBatchSentimentWithResponse( + List textInputs, TextAnalyticsRequestOptions options) { + try { + return withContext(context -> analyzeBatchSentimentWithResponse(textInputs, options, context)); + } catch (RuntimeException ex) { + return monoError(logger, ex); + } + } + + Mono>> analyzeBatchSentimentWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(convertToMultiLanguageInput(textInputs)); + return service.sentimentWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of text sentiment input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of text sentiment output - {}", response)) + .doOnError(error -> logger.warning("Failed to text sentiment - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + private List convertToMultiLanguageInput(List textInputs) { + List multiLanguageInputs = new ArrayList<>(); + for (TextDocumentInput textDocumentInput : textInputs) { + multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) + .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); + } + return multiLanguageInputs; + } + + /** + * Helper method to convert the service response of {@link SentimentResponse} to {@link DocumentResultCollection}. + * + * @param sentimentResponse the {@link SentimentResponse} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link AnalyzeSentimentResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final SentimentResponse sentimentResponse) { + List analyzeSentimentResults = new ArrayList<>(); + for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { + analyzeSentimentResults.add(convertToTextSentimentResult(documentSentiment)); + } + for (DocumentError documentError : sentimentResponse.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, error, null, + null)); + } + return new DocumentResultCollection<>(analyzeSentimentResults, + sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null + : mapBatchStatistics(sentimentResponse.getStatistics())); + } + + private AnalyzeSentimentResult convertToTextSentimentResult(final DocumentSentiment documentSentiment) { + // Document text sentiment + final TextSentimentClass documentSentimentClass = TextSentimentClass.fromString(documentSentiment. + getSentiment().toString()); + if (documentSentimentClass == null) { + // Not throw exception for an invalid Sentiment type because we should not skip processing the + // other response. It is a service issue. + logger.logExceptionAsWarning( + new RuntimeException(String.format("'%s' is not valid text sentiment.", + documentSentiment.getSentiment()))); + } + final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getDocumentScores(); + + // Sentence text sentiment + final List sentenceSentimentTexts = documentSentiment.getSentences().stream() + .map(sentenceSentiment -> { + TextSentimentClass sentimentClass = TextSentimentClass.fromString(sentenceSentiment + .getSentiment().toString()); + if (sentimentClass == null) { + // Not throw exception for an invalid Sentiment type because we should not skip processing the + // other response. It is a service issue. + logger.logExceptionAsWarning( + new RuntimeException(String.format("'%s' is not valid text sentiment.", + sentenceSentiment.getSentiment()))); + } + SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getSentenceScores(); + + return new TextSentiment(sentimentClass, confidenceScorePerSentence.getNegative(), + confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive(), + sentenceSentiment.getLength(), sentenceSentiment.getOffset()); + + }).collect(Collectors.toList()); + + return new AnalyzeSentimentResult(documentSentiment.getId(), + documentSentiment.getStatistics() == null ? null + : convertToTextDocumentStatistics(documentSentiment.getStatistics()), null, + new TextSentiment(documentSentimentClass, confidenceScorePerLabel.getNegative(), + confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive(), + sentenceSentimentTexts.stream().mapToInt(TextSentiment::getLength).sum(), 0), + sentenceSentimentTexts); + } + + /** + * Helper method to convert the service response of {@link LanguageResult} to {@link DocumentResultCollection}. + * + * @param languageResult the {@link LanguageResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final LanguageResult languageResult) { + + final List detectLanguageResults = new ArrayList<>(); + for (DocumentLanguage documentLanguage : languageResult.getDocuments()) { + DetectedLanguage primaryLanguage = null; + if (documentLanguage.getDetectedLanguages().size() >= 1) { + com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguageResult = + documentLanguage.getDetectedLanguages().get(0); + primaryLanguage = new DetectedLanguage(detectedLanguageResult.getName(), + detectedLanguageResult.getIso6391Name(), detectedLanguageResult.getScore()); + } + detectLanguageResults.add(new DetectLanguageResult(documentLanguage.getId(), + documentLanguage.getStatistics() == null + ? null : convertToTextDocumentStatistics(documentLanguage.getStatistics()), + null, + primaryLanguage, + documentLanguage.getDetectedLanguages().stream().map(detectedLanguage -> + new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), + detectedLanguage.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : languageResult.getErrors()) { + com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + detectLanguageResults.add( + new DetectLanguageResult(documentError.getId(), null, error, null, null)); + } + + return new DocumentResultCollection<>(detectLanguageResults, languageResult.getModelVersion(), + languageResult.getStatistics() == null ? null : mapBatchStatistics(languageResult.getStatistics())); + } + + /** + * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. + * + * @param entitiesResult the {@link EntitiesResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final EntitiesResult entitiesResult) { + List recognizeEntitiesResults = new ArrayList<>(); + for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { + recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentEntities.getId(), + documentEntities.getStatistics() == null ? null + : convertToTextDocumentStatistics(documentEntities.getStatistics()), + null, documentEntities.getEntities().stream().map(entity -> + new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), + entity.getLength(), entity.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : entitiesResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(recognizeEntitiesResults, + entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null + : mapBatchStatistics(entitiesResult.getStatistics())); + } + + /** + * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. + * + * @param entitiesResult the {@link EntitiesResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link RecognizePiiEntitiesResult} to be returned by the SDK. + */ + private DocumentResultCollection toPiiDocumentResultCollection( + final EntitiesResult entitiesResult) { + List recognizePiiEntitiesResults = new ArrayList<>(); + for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { + recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentEntities.getId(), + documentEntities.getStatistics() == null ? null + : convertToTextDocumentStatistics(documentEntities.getStatistics()), + null, documentEntities.getEntities().stream().map(entity -> + new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), + entity.getLength(), entity.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : entitiesResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(recognizePiiEntitiesResults, + entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null + : mapBatchStatistics(entitiesResult.getStatistics())); + } + + /** + * Helper method to convert the service response of {@link EntityLinkingResult} to {@link DocumentResultCollection}. + * + * @param entityLinkingResult the {@link EntityLinkingResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link RecognizeLinkedEntitiesResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final EntityLinkingResult entityLinkingResult) { + List linkedEntitiesResults = new ArrayList<>(); + for (DocumentLinkedEntities documentLinkedEntities : entityLinkingResult.getDocuments()) { + linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentLinkedEntities.getId(), + documentLinkedEntities.getStatistics() == null ? null + : convertToTextDocumentStatistics(documentLinkedEntities.getStatistics()), + null, mapLinkedEntity(documentLinkedEntities.getEntities()))); + } + for (DocumentError documentError : entityLinkingResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); + linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(linkedEntitiesResults, + entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null + : mapBatchStatistics(entityLinkingResult.getStatistics())); + } + + private static List mapByIndex(List textInputs, BiFunction mappingFunction) { + return IntStream.range(0, textInputs.size()) + .mapToObj(index -> mappingFunction.apply(String.valueOf(index), textInputs.get(index))) + .collect(Collectors.toList()); + } + + private TextDocumentStatistics convertToTextDocumentStatistics(DocumentStatistics statistics) { + return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); + } + + private TextDocumentBatchStatistics mapBatchStatistics(RequestStatistics statistics) { + return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getErroneousDocumentsCount(), + statistics.getValidDocumentsCount(), statistics.getTransactionsCount()); + } + + private List mapLinkedEntity(List linkedEntities) { + List linkedEntitiesList = new ArrayList<>(); + for (LinkedEntity linkedEntity : linkedEntities) { + linkedEntitiesList.add(new com.azure.ai.textanalytics.models.LinkedEntity(linkedEntity.getName(), + linkedEntity.getMatches().stream().map(match -> + new LinkedEntityMatch(match.getText(), match.getScore(), match.getLength(), + match.getOffset())).collect(Collectors.toList()), linkedEntity.getLanguage(), + linkedEntity.getId(), linkedEntity.getUrl(), linkedEntity.getDataSource())); + } + return linkedEntitiesList; + } + + private com.azure.ai.textanalytics.models.TextAnalyticsError convertToError(TextAnalyticsError textAnalyticsError) { + return new com.azure.ai.textanalytics.models.TextAnalyticsError( + ErrorCodeValue.fromString(textAnalyticsError.getCode().toString()), textAnalyticsError.getMessage(), + textAnalyticsError.getTarget(), textAnalyticsError.getDetails() == null ? null + : setErrors(textAnalyticsError.getDetails())); + } + + private List setErrors(List details) { + List detailsList = new ArrayList<>(); + for (TextAnalyticsError error : details) { + detailsList.add(new com.azure.ai.textanalytics.models.TextAnalyticsError( + ErrorCodeValue.fromString(error.getCode().toString()), + error.getMessage(), + error.getTarget(), error.getDetails() == null ? null : setErrors(error.getDetails()))); + } + return detailsList; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java new file mode 100644 index 000000000000..a549176746e1 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java @@ -0,0 +1,663 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceClient; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; + +import java.util.List; + +/** + * This class provides a synchronous client that contains all the operations that apply to Azure Text Analytics. + * Operations allow by the client to detect language, recognize entities, recognize pii entities, + * recognize linked entities, and analyze sentiment for a text input or a list of text input. + * + *

Instantiating a synchronous Text Analytics Client

+ * {@codesnippet com.azure.ai.textanalytics.TextAnalyticsClient.instantiation} + * + *

View {@link TextAnalyticsClientBuilder this} for additional ways to construct the client.

+ * + * @see TextAnalyticsClientBuilder + */ +@ServiceClient(builder = TextAnalyticsClientBuilder.class) +public final class TextAnalyticsClient { + private final TextAnalyticsAsyncClient client; + + /** + * Create a {@code TextAnalyticsClient client} that sends requests to the Text Analytics service's endpoint. + * Each service call goes through the {@link TextAnalyticsClientBuilder#pipeline http pipeline}. + * + * @param client The {@link TextAnalyticsClient} that the client routes its request through. + */ + TextAnalyticsClient(TextAnalyticsAsyncClient client) { + this.client = client; + } + + /** + * Returns the detected language and a numeric score between zero and one. Scores close to one indicate 100% + * certainty that the identified language is true. + * + * @param text The text to be analyzed. + * @return the {@link DetectLanguageResult detected language} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DetectLanguageResult detectLanguage(String text) { + return detectLanguage(text, client.getDefaultCountryHint()); + } + + /** + * Returns the detected language and a numeric score between zero and one when the hint of country specified. + * Scores close to one indicate 100% certainty that the identified language is true. + * + * @param text The text to be analyzed. + * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not + * specified. + * + * @return the {@link DetectLanguageResult detected language} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DetectLanguageResult detectLanguage(String text, String countryHint) { + return detectLanguageWithResponse(text, countryHint, Context.NONE).getValue(); + } + + /** + * Returns a {@link Response} containing the detected language and a numeric score between zero and one. + * Scores close to one indicate 100% certainty that the identified language is true. + * + * @param text The text to be analyzed. + * @param countryHint Accepts two letter country codes specified by ISO 3166-1 alpha-2. Defaults to "US" if not + * specified. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DetectLanguageResult detected language} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response detectLanguageWithResponse(String text, String countryHint, Context context) { + return client.detectLanguageWithResponse(text, countryHint, context).block(); + } + + /** + * Detects Language for a batch of input. + * + * @param textInputs The list of texts to be analyzed. + * + * @return A {@link DocumentResultCollection batch} containing the list of + * {@link DetectLanguageResult detected languages} with their numeric scores. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection detectLanguages(List textInputs) { + return detectLanguagesWithResponse(textInputs, client.getDefaultCountryHint(), Context.NONE).getValue(); + } + + /** + * Detects Language for a batch of input with the provided country hint. + * + * @param textInputs The list of texts to be analyzed. + * @param countryHint A country hint for the entire batch. Accepts two letter country codes specified by ISO 3166-1 + * alpha-2. Defaults to "US" if not specified. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of + * {@link DetectLanguageResult detected languages} with their numeric scores. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> detectLanguagesWithResponse( + List textInputs, String countryHint, Context context) { + return client.detectLanguagesWithResponse(textInputs, countryHint, context).block(); + } + + /** + * Detects Language for a batch of input. + * + * @param textInputs The list of {@link DetectLanguageInput inputs/documents} to be analyzed. + * + * @return A {@link DocumentResultCollection batch} of {@link DetectLanguageResult detected languages}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection detectBatchLanguages(List textInputs) { + return detectBatchLanguagesWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Detects Language for a batch of input. + * + * @param textInputs The list of {@link DetectLanguageInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of + * {@link DetectLanguageResult detected languages}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> detectBatchLanguagesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.detectBatchLanguagesWithResponse(textInputs, options, context).block(); + } + + // Named Entity + + /** + * Returns a list of general named entities in the provided text. + * For a list of supported entity types, check: + * + * @param text the text to recognize entities for. + * + * @return the {@link RecognizeEntitiesResult named entity} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public RecognizeEntitiesResult recognizeEntities(String text) { + return recognizeEntitiesWithResponse(text, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of general named entities in the provided text. + * For a list of supported entity types, check: + * For a list of enabled languages, check: + * + * @param text the text to recognize entities for. + * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link RecognizeEntitiesResult named entity} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response recognizeEntitiesWithResponse( + String text, String language, Context context) { + return client.recognizeEntitiesWithResponse(text, language, context).block(); + } + + /** + * Returns a list of general named entities for the provided list of texts. + * + * @param textInputs A list of texts to recognize entities for. + * + * @return A {@link DocumentResultCollection batch} containing the list of + * {@link RecognizeEntitiesResult named entity} of the text. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizeEntities(List textInputs) { + return recognizeEntitiesWithResponse(textInputs, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of general named entities for the provided list of texts. + * + * @param textInputs A list of texts to recognize entities for. + * @param language The 2 letter ISO 639-1 representation of language. If not set, uses "en" for English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizeEntitiesWithResponse( + List textInputs, String language, Context context) { + return client.recognizeEntitiesWithResponse(textInputs, language, context).block(); + } + + /** + * Returns a list of general named entities for the provided list of text inputs. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize entities for. + * + * @return A {@link DocumentResultCollection batch} of the {@link RecognizeEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizeBatchEntities( + List textInputs) { + return recognizeBatchEntitiesWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Returns a list of general named entities for the provided list of text inputs. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizeBatchEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.recognizeBatchEntitiesWithResponse(textInputs, options, context).block(); + } + + // PII Entities + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the text. + * For the list of supported entity types, check pii. + * See for the list of enabled languages. + * + * @param text the text to recognize pii entities for. + * @return A {@link RecognizePiiEntitiesResult PII entity} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public RecognizePiiEntitiesResult recognizePiiEntities(String text) { + return recognizePiiEntitiesWithResponse(text, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the text. + * For the list of supported entity types, check https://aka.ms/tanerpii. + * See for the list of enabled languages. + * + * @param text the text to recognize pii entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} has the + * {@link RecognizePiiEntitiesResult named entity} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response recognizePiiEntitiesWithResponse(String text, String language, + Context context) { + return client.recognizePiiEntitiesWithResponse(text, language, context).block(); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the list of texts. + * For the list of supported entity types, check https://aka.ms/tanerpii. + * See for the list of enabled languages. + * + * @param textInputs A list of text to recognize pii entities for. + * + * @return A {@link DocumentResultCollection batch} of the {@link RecognizePiiEntitiesResult named entity} + * of the text. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizePiiEntities(List textInputs) { + return recognizePiiEntitiesWithResponse(textInputs, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the list of texts. + * For the list of supported entity types, check . + * See for the list of enabled languages. + * * + * @param textInputs A list of text to recognize pii entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizePiiEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizePiiEntitiesWithResponse( + List textInputs, String language, Context context) { + return client.recognizePiiEntitiesWithResponse(textInputs, language, context).block(); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the batch of document inputs. + * For the list of supported entity types, check . + * See for the list of enabled languages. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize pii entities for. + * + * @return A {@link DocumentResultCollection batch} of the {@link RecognizeEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizeBatchPiiEntities( + List textInputs) { + return recognizeBatchPiiEntitiesWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the batch of document inputs. + * For the list of supported entity types, check . + * See for the list of enabled languages. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize pii entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeEntitiesResult named entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizeBatchPiiEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.recognizeBatchPiiEntitiesWithResponse(textInputs, options, context).block(); + } + + // Linked Entities + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the provided text. + * See for supported languages in Text Analytics API. + * + * @param text the text to recognize linked entities for. + * + * @return A {@link RecognizeLinkedEntitiesResult linked entity} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public RecognizeLinkedEntitiesResult recognizeLinkedEntities(String text) { + return recognizeLinkedEntitiesWithResponse(text, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the provided text. + * See for supported languages in Text Analytics API. + * + * @param text the text to recognize linked entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} has the + * {@link RecognizeLinkedEntitiesResult named entity} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response recognizeLinkedEntitiesWithResponse(String text, String language, + Context context) { + return client.recognizeLinkedEntitiesWithResponse(text, language, context).block(); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of texts. + * See for supported languages in Text Analytics API. + * + * @param textInputs A list of text to recognize linked entities for. + * + * @return A {@link DocumentResultCollection batch} of the + * {@link RecognizeLinkedEntitiesResult linked entity} of the text. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizeLinkedEntities(List textInputs) { + return recognizeLinkedEntitiesWithResponse(textInputs, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of texts. + * See for supported languages in Text Analytics API. + * + * @param textInputs A list of text to recognize linked entities for. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of the + * {@link RecognizeLinkedEntitiesResult linked entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizeLinkedEntitiesWithResponse( + List textInputs, String language, Context context) { + return client.recognizeLinkedEntitiesWithResponse(textInputs, language, context).block(); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of inputs. + * See for supported languages in Text Analytics API. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize linked entities for. + * + * @return A {@link DocumentResultCollection batch} of the {@link RecognizeLinkedEntitiesResult linked entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection recognizeBatchLinkedEntities( + List textInputs) { + return recognizeBatchLinkedEntitiesWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Returns a list of recognized entities with links to a well-known knowledge base for the list of inputs. + * See for supported languages in Text Analytics API. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to recognize linked entities for. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link RecognizeLinkedEntitiesResult linked entity}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> recognizeBatchLinkedEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.recognizeBatchLinkedEntitiesWithResponse(textInputs, options, context).block(); + } + + // Key Phrase + + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param text the text to be analyzed. + * + * @return A {@link ExtractKeyPhraseResult key phrases} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public ExtractKeyPhraseResult extractKeyPhrases(String text) { + return extractKeyPhrasesWithResponse(text, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * See for the list of enabled languages. + * + * @param text the text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} has the + * {@link ExtractKeyPhraseResult key phrases} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response extractKeyPhrasesWithResponse(String text, String language, + Context context) { + return client.extractKeyPhrasesWithResponse(text, language, context).block(); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param textInputs A list of text to be analyzed. + * @return A {@link DocumentResultCollection batch} of the {@link ExtractKeyPhraseResult key phrases} of the text. + * + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection extractKeyPhrases(List textInputs) { + return extractKeyPhrasesWithResponse(textInputs, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * See for the list of enabled languages. + * + * @param textInputs A list of text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of the + * {@link ExtractKeyPhraseResult key phrases}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> extractKeyPhrasesWithResponse( + List textInputs, String language, Context context) { + return client.extractKeyPhrasesWithResponse(textInputs, language, context).block(); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * + * @return A {@link DocumentResultCollection batch} of the {@link ExtractKeyPhraseResult key phrases}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection extractBatchKeyPhrases(List textInputs) { + return extractBatchKeyPhrasesWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Returns a list of strings denoting the key phrases in the input text. + * See for the list of enabled languages. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} whose {@link Response#getValue() value} contains the + * {@link DocumentResultCollection batch} of {@link ExtractKeyPhraseResult key phrases}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> extractBatchKeyPhrasesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.extractBatchKeyPhrasesWithResponse(textInputs, options, context).block(); + } + + // Sentiment + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within i + * + * @param text the text to be analyzed. + * @return the {@link AnalyzeSentimentResult text sentiments} of the text. + * + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public AnalyzeSentimentResult analyzeSentiment(String text) { + return analyzeBatchSentimentWithResponse(text, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within i + * + * @param text the text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link AnalyzeSentimentResult text sentiments} of the text. + * @throws NullPointerException if {@code text} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response analyzeBatchSentimentWithResponse( + String text, String language, Context context) { + return client.analyzeSentimentWithResponse(text, language, context).block(); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within it. + * + * @param textInputs A list of text to be analyzed. + * + * @return A {@link DocumentResultCollection batch} containing the list of + * {@link AnalyzeSentimentResult text sentiments} with their numeric scores. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection analyzeSentiment(List textInputs) { + return analyzeSentimentWithResponse(textInputs, client.getDefaultLanguage(), Context.NONE).getValue(); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within it. + * + * @param textInputs A list of text to be analyzed. + * @param language The 2 letter ISO 639-1 representation of language for the text. If not set, uses "en" for + * English as default. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of + * {@link AnalyzeSentimentResult text sentiments} with their numeric scores. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> analyzeSentimentWithResponse( + List textInputs, String language, Context context) { + return client.analyzeSentimentWithResponse(textInputs, language, context).block(); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within it. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * + * @return A {@link DocumentResultCollection batch} of {@link AnalyzeSentimentResult text sentiments}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public DocumentResultCollection analyzeBatchSentiment(List textInputs) { + return analyzeBatchSentimentWithResponse(textInputs, null, Context.NONE).getValue(); + } + + /** + * Returns a sentiment prediction, as well as sentiment scores for each sentiment class + * (Positive, Negative, and Neutral) for the document and each sentence within it. + * + * @param textInputs A list of {@link TextDocumentInput inputs/documents} to be analyzed. + * @param options The {@link TextAnalyticsRequestOptions options} to configure the scoring model for documents + * and show statistics. + * @param context Additional context that is passed through the Http pipeline during the service call. + * + * @return A {@link Response} containing the {@link DocumentResultCollection batch} of + * {@link AnalyzeSentimentResult text sentiments}. + * @throws NullPointerException if {@code textInputs} is {@code null}. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Response> analyzeBatchSentimentWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + return client.analyzeBatchSentimentWithResponse(textInputs, options, context).block(); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClientBuilder.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClientBuilder.java new file mode 100644 index 000000000000..2c265fdb8a29 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClientBuilder.java @@ -0,0 +1,367 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImplBuilder; +import com.azure.ai.textanalytics.models.TextAnalyticsClientOptions; +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.AddHeadersPolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.core.util.logging.ClientLogger; + +import java.net.MalformedURLException; +import java.net.URL; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * This class provides a fluent builder API to help instantiation of {@link TextAnalyticsClient TextAnalyticsClients} + * and {@link TextAnalyticsAsyncClient TextAnalyticsAsyncClients}, call {@link #buildClient()} buildClient} and + * {@link #buildAsyncClient() buildAsyncClient} respectively to construct an instance of the desired client. + * + *

+ * The client needs the service endpoint of the Azure Text Analytics to access the resource service. + * {@link #subscriptionKey(String) subscriptionKey(String)} or + * {@link #credential(TokenCredential) credential(TokenCredential)} give the builder access credential. + *

+ * + *

+ * Another way to construct the client is using a {@link HttpPipeline}. The pipeline gives the client an + * authenticated way to communicate with the service. Set the pipeline with {@link #pipeline(HttpPipeline) this} and + * set the service endpoint with {@link #endpoint(String) this}. Using a + * pipeline requires additional setup but allows for finer control on how the {@link TextAnalyticsClient} and + * {@link TextAnalyticsAsyncClient} is built. + *

+ * + * @see TextAnalyticsAsyncClient + * @see TextAnalyticsClient + */ +@ServiceClientBuilder(serviceClients = {TextAnalyticsAsyncClient.class, TextAnalyticsClient.class}) +public final class TextAnalyticsClientBuilder { + private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; + private static final String CONTENT_TYPE_HEADER = "Content-Type"; + private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; + private static final String ACCEPT_HEADER = "Accept"; + private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; + private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key"; + private static final String NAME = "name"; + private static final String VERSION = "version"; + private static final RetryPolicy DEFAULT_RETRY_POLICY = new RetryPolicy("retry-after-ms", ChronoUnit.MILLIS); + private static final String DEFAULT_SCOPE = "https://cognitiveservices.azure.com/.default"; + + private final ClientLogger logger = new ClientLogger(TextAnalyticsClientBuilder.class); + private final List policies; + private final HttpHeaders headers; + private final String clientName; + private final String clientVersion; + + private String endpoint; + private String subscriptionKey; + private TokenCredential tokenCredential; + private HttpClient httpClient; + private HttpLogOptions httpLogOptions; + private HttpPipeline httpPipeline; + private Configuration configuration; + private RetryPolicy retryPolicy; + private TextAnalyticsClientOptions clientOptions; + private TextAnalyticsServiceVersion version; + + /** + * The constructor with defaults. + */ + public TextAnalyticsClientBuilder() { + policies = new ArrayList<>(); + httpLogOptions = new HttpLogOptions(); + + Map properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); + clientName = properties.getOrDefault(NAME, "UnknownName"); + clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); + + headers = new HttpHeaders() + .put(ECHO_REQUEST_ID_HEADER, "true") + .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) + .put(ACCEPT_HEADER, CONTENT_TYPE_HEADER_VALUE); + } + + /** + * Creates a {@link TextAnalyticsClient} based on options set in the builder. Every time + * {@code buildClient()} is called a new instance of {@link TextAnalyticsClient} is created. + * + *

+ * If {@link #pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and + * {@link #endpoint(String) endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder + * settings are ignored + *

+ * + * @return A TextAnalyticsClient with the options set from the builder. + * @throws NullPointerException if {@link #endpoint(String) endpoint} or + * {@link #subscriptionKey(String) subscriptionKey} has not been set. + * @throws IllegalArgumentException if {@link #endpoint(String) endpoint} cannot be parsed into a valid URL. + */ + public TextAnalyticsClient buildClient() { + return new TextAnalyticsClient(buildAsyncClient()); + } + + + /** + * Creates a {@link TextAnalyticsAsyncClient} based on options set in the builder. Every time + * {@code buildAsyncClient()} is called a new instance of {@link TextAnalyticsAsyncClient} is created. + * + *

+ * If {@link #pipeline(HttpPipeline) pipeline} is set, then the {@code pipeline} and + * {@link #endpoint(String) endpoint} are used to create the {@link TextAnalyticsClient client}. All other builder + * settings are ignored. + *

+ * + * @return A TextAnalyticsAsyncClient with the options set from the builder. + * @throws NullPointerException if {@link #endpoint(String) endpoint} or + * {@link #subscriptionKey(String) subscriptionKey} has not been set. + * @throws IllegalArgumentException if {@link #endpoint(String) endpoint} cannot be parsed into a valid URL. + */ + public TextAnalyticsAsyncClient buildAsyncClient() { + // Global Env configuration store + final Configuration buildConfiguration = (configuration == null) + ? Configuration.getGlobalConfiguration().clone() : configuration; + // Service Version + final TextAnalyticsServiceVersion serviceVersion = + version != null ? version : TextAnalyticsServiceVersion.getLatest(); + + // Endpoint cannot be null, which is required in request authentication + Objects.requireNonNull(endpoint, "'Endpoint' is required and can not be null."); + + HttpPipeline pipeline = httpPipeline; + // Create a default Pipeline if it is not given + if (pipeline == null) { + // Closest to API goes first, closest to wire goes last. + final List policies = new ArrayList<>(); + + // Authentications + if (tokenCredential != null) { + // User token based policy + policies.add(new BearerTokenAuthenticationPolicy(tokenCredential, DEFAULT_SCOPE)); + } else if (subscriptionKey != null) { + headers.put(OCP_APIM_SUBSCRIPTION_KEY, subscriptionKey); + } else { + // Throw exception that credential and tokenCredential cannot be null + throw logger.logExceptionAsError( + new IllegalArgumentException("Missing credential information while building a client.")); + } + + policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, + buildConfiguration)); + policies.add(new RequestIdPolicy()); + policies.add(new AddHeadersPolicy(headers)); + policies.add(new AddDatePolicy()); + + HttpPolicyProviders.addBeforeRetryPolicies(policies); + policies.add(retryPolicy == null ? DEFAULT_RETRY_POLICY : retryPolicy); + policies.addAll(this.policies); + HttpPolicyProviders.addAfterRetryPolicies(policies); + + policies.add(new HttpLoggingPolicy(httpLogOptions)); + + pipeline = new HttpPipelineBuilder() + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .build(); + } + + final TextAnalyticsClientImpl textAnalyticsAPI = new TextAnalyticsClientImplBuilder() + .endpoint(endpoint) + .pipeline(pipeline) + .build(); + + return new TextAnalyticsAsyncClient(textAnalyticsAPI, serviceVersion, clientOptions); + } + + /** + * Set the default client option for one client. + * + * @param clientOptions TextAnalyticsClientOptions model that includes + * {@link TextAnalyticsClientOptions#getDefaultLanguage() default language} and + * {@link TextAnalyticsClientOptions#getDefaultCountryHint() default country hint} + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder clientOptions(TextAnalyticsClientOptions clientOptions) { + this.clientOptions = clientOptions; + return this; + } + + /** + * Sets the service endpoint for the Azure Text Analytics instance. + * + * @param endpoint The URL of the Azure Text Analytics instance service requests to and receive responses from. + * @return The updated TextAnalyticsClientBuilder object. + * @throws NullPointerException if {@code endpoint} is null + * @throws IllegalArgumentException if {@code endpoint} cannot be parsed into a valid URL. + */ + public TextAnalyticsClientBuilder endpoint(String endpoint) { + Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); + + try { + new URL(endpoint); + } catch (MalformedURLException ex) { + throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); + } + this.endpoint = endpoint; + return this; + } + + /** + * Sets the credential to use when authenticating HTTP requests for this TextAnalyticsClientBuilder. + * + * @param subscriptionKey subscription key + * + * @return The updated TextAnalyticsClientBuilder object. + * @throws NullPointerException If {@code subscriptionKey} is {@code null} + */ + public TextAnalyticsClientBuilder subscriptionKey(String subscriptionKey) { + Objects.requireNonNull(subscriptionKey, "'subscriptionKey' cannot be null."); + this.subscriptionKey = subscriptionKey; + return this; + } + + /** + * Sets the {@link TokenCredential} used to authenticate HTTP requests. + * + * @param tokenCredential TokenCredential used to authenticate HTTP requests. + * @return The updated TextAnalyticsClientBuilder object. + * @throws NullPointerException If {@code tokenCredential} is {@code null}. + */ + public TextAnalyticsClientBuilder credential(TokenCredential tokenCredential) { + Objects.requireNonNull(tokenCredential, "'tokenCredential' cannot be null."); + this.tokenCredential = tokenCredential; + return this; + } + + /** + * Sets the logging configuration for HTTP requests and responses. + * + *

If logLevel is not provided, default value of {@link HttpLogDetailLevel#NONE} is set.

+ * + * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder httpLogOptions(HttpLogOptions logOptions) { + this.httpLogOptions = logOptions; + return this; + } + + /** + * Adds a policy to the set of existing policies that are executed after required policies. + * + * @param policy The retry policy for service requests. + * + * @return The updated TextAnalyticsClientBuilder object. + * @throws NullPointerException If {@code policy} is {@code null}. + */ + public TextAnalyticsClientBuilder addPolicy(HttpPipelinePolicy policy) { + Objects.requireNonNull(policy, "'policy' cannot be null."); + policies.add(policy); + return this; + } + + /** + * Sets the HTTP client to use for sending and receiving requests to and from the service. + * + * @param client The HTTP client to use for requests. + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder httpClient(HttpClient client) { + if (this.httpClient != null && client == null) { + logger.info("HttpClient is being set to 'null' when it was previously configured."); + } + + this.httpClient = client; + return this; + } + + /** + * Sets the HTTP pipeline to use for the service client. + *

+ * If {@code pipeline} is set, all other settings are ignored, aside from + * {@link TextAnalyticsClientBuilder#endpoint(String) endpoint} to build {@link TextAnalyticsAsyncClient} or + * {@link TextAnalyticsClient}. + * + * @param httpPipeline The HTTP pipeline to use for sending service requests and receiving responses. + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder pipeline(HttpPipeline httpPipeline) { + if (this.httpPipeline != null && httpPipeline == null) { + logger.info("HttpPipeline is being set to 'null' when it was previously configured."); + } + + this.httpPipeline = httpPipeline; + return this; + } + + /** + * Sets the configuration store that is used during construction of the service client. + *

+ * The default configuration store is a clone of the {@link Configuration#getGlobalConfiguration() global + * configuration store}, use {@link Configuration#NONE} to bypass using configuration settings during construction. + * + * @param configuration The configuration store used to + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder configuration(Configuration configuration) { + this.configuration = configuration; + return this; + } + + /** + * Sets the {@link RetryPolicy} that is used when each request is sent. + *

+ * The default retry policy will be used if not provided {@link TextAnalyticsClientBuilder#buildAsyncClient()} + * to build {@link TextAnalyticsAsyncClient} or {@link TextAnalyticsClient}. + * + * @param retryPolicy user's retry policy applied to each request. + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder retryPolicy(RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + /** + * Sets the {@link TextAnalyticsServiceVersion} that is used when making API requests. + *

+ * If a service version is not provided, the service version that will be used will be the latest known service + * version based on the version of the client library being used. If no service version is specified, updating to a + * newer version the client library will have the result of potentially moving to a newer service version. + * + * @param version {@link TextAnalyticsServiceVersion} of the service to be used when making requests. + * + * @return The updated TextAnalyticsClientBuilder object. + */ + public TextAnalyticsClientBuilder serviceVersion(TextAnalyticsServiceVersion version) { + this.version = version; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsServiceVersion.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsServiceVersion.java new file mode 100644 index 000000000000..bb7b1a516842 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsServiceVersion.java @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.core.util.ServiceVersion; + +/** + * The versions of Azure Text Analytics supported by this client library. + */ +public enum TextAnalyticsServiceVersion implements ServiceVersion { + V3_0_preview_1("v3.0-preview.1"); + + private final String version; + + TextAnalyticsServiceVersion(String version) { + this.version = version; + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return this.version; + } + + /** + * Gets the latest service version supported by this client library + * + * @return the latest {@link TextAnalyticsServiceVersion} + */ + public static TextAnalyticsServiceVersion getLatest() { + return V3_0_preview_1; + } + +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImpl.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImpl.java new file mode 100644 index 000000000000..357d1f180e49 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImpl.java @@ -0,0 +1,328 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation; + +import com.azure.ai.textanalytics.implementation.models.EntitiesResult; +import com.azure.ai.textanalytics.implementation.models.EntityLinkingResult; +import com.azure.ai.textanalytics.implementation.models.KeyPhraseResult; +import com.azure.ai.textanalytics.implementation.models.LanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.LanguageResult; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.SentimentResponse; +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.QueryParam; +import com.azure.core.annotation.ReturnType; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.annotation.ServiceMethod; +import com.azure.core.annotation.UnexpectedResponseExceptionType; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.CookiePolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.util.Context; +import reactor.core.publisher.Mono; + +/** + * Initializes a new instance of the TextAnalyticsClient type. + */ +public final class TextAnalyticsClientImpl { + /** + * The proxy service used to perform REST calls. + */ + private TextAnalyticsClientService service; + + /** + * Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). + */ + private String endpoint; + + /** + * Gets Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). + * + * @return the endpoint value. + */ + public String getEndpoint() { + return this.endpoint; + } + + /** + * Sets Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). + * + * @param endpoint the endpoint value. + */ + TextAnalyticsClientImpl setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * The HTTP pipeline to send requests through. + */ + private HttpPipeline httpPipeline; + + /** + * Gets The HTTP pipeline to send requests through. + * + * @return the httpPipeline value. + */ + public HttpPipeline getHttpPipeline() { + return this.httpPipeline; + } + + /** + * Initializes an instance of TextAnalyticsClient client. + */ + public TextAnalyticsClientImpl() { + new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()).build(); + } + + /** + * Initializes an instance of TextAnalyticsClient client. + * + * @param httpPipeline The HTTP pipeline to send requests through. + */ + public TextAnalyticsClientImpl(HttpPipeline httpPipeline) { + this.httpPipeline = httpPipeline; + this.service = RestProxy.create(TextAnalyticsClientService.class, this.httpPipeline); + } + + /** + * The interface defining all the services for TextAnalyticsClient to be + * used by the proxy service to perform REST calls. + */ + @Host("{Endpoint}/text/analytics/v3.0-preview.1") + @ServiceInterface(name = "TextAnalyticsClient") + private interface TextAnalyticsClientService { + @Post("entities/recognition/general") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> entitiesRecognitionGeneral(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") MultiLanguageBatchInput input, Context context); + + @Post("entities/recognition/pii") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> entitiesRecognitionPii(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") MultiLanguageBatchInput input, Context context); + + @Post("entities/linking") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> entitiesLinking(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") MultiLanguageBatchInput input, Context context); + + @Post("keyPhrases") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> keyPhrases(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") MultiLanguageBatchInput input, Context context); + + @Post("languages") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> languages(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") LanguageBatchInput input, Context context); + + @Post("sentiment") + @ExpectedResponses({200}) + @UnexpectedResponseExceptionType(HttpResponseException.class) + Mono> sentiment(@HostParam("Endpoint") String endpoint, @QueryParam("model-version") String modelVersion, @QueryParam("showStats") Boolean showStats, @BodyParam("application/json; charset=utf-8") MultiLanguageBatchInput input, Context context); + } + + /** + * Named Entity Recognition + * The API returns a list of general named entities in a given document. For the list of supported entity types, check <a href="https://aka.ms/taner">Supported Entity Types in Text Analytics API</a>. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesRecognitionGeneralWithRestResponseAsync(MultiLanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.entitiesRecognitionGeneral(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Named Entity Recognition + * The API returns a list of general named entities in a given document. For the list of supported entity types, check <a href="https://aka.ms/taner">Supported Entity Types in Text Analytics API</a>. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesRecognitionGeneralWithRestResponseAsync(MultiLanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.entitiesRecognitionGeneral(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Entities containing personal information + * The API returns a list of entities with personal information (\"SSN\", \"Bank Account\" etc) in the document. For the list of supported entity types, check <a href="https://aka.ms/tanerpii">Supported Entity Types in Text Analytics API</a>. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesRecognitionPiiWithRestResponseAsync(MultiLanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.entitiesRecognitionPii(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Entities containing personal information + * The API returns a list of entities with personal information (\"SSN\", \"Bank Account\" etc) in the document. For the list of supported entity types, check <a href="https://aka.ms/tanerpii">Supported Entity Types in Text Analytics API</a>. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesRecognitionPiiWithRestResponseAsync(MultiLanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.entitiesRecognitionPii(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Linked entities from a well-known knowledge base + * The API returns a list of recognized entities with links to a well-known knowledge base. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesLinkingWithRestResponseAsync(MultiLanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.entitiesLinking(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Linked entities from a well-known knowledge base + * The API returns a list of recognized entities with links to a well-known knowledge base. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> entitiesLinkingWithRestResponseAsync(MultiLanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.entitiesLinking(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Key Phrases + * The API returns a list of strings denoting the key phrases in the input text. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. Documents can now contain a language field to indicate the text language. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> keyPhrasesWithRestResponseAsync(MultiLanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.keyPhrases(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Key Phrases + * The API returns a list of strings denoting the key phrases in the input text. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. Documents can now contain a language field to indicate the text language. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> keyPhrasesWithRestResponseAsync(MultiLanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.keyPhrases(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Detect Language + * The API returns the detected language and a numeric score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> languagesWithRestResponseAsync(LanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.languages(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Detect Language + * The API returns the detected language and a numeric score between 0 and 1. Scores close to 1 indicate 100% certainty that the identified language is true. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> languagesWithRestResponseAsync(LanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.languages(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Sentiment + * The API returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral) for the document and each sentence within it. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> sentimentWithRestResponseAsync(MultiLanguageBatchInput input, Context context) { + final String modelVersion = null; + final Boolean showStats = null; + return service.sentiment(this.getEndpoint(), modelVersion, showStats, input, context); + } + + /** + * Sentiment + * The API returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and Neutral) for the document and each sentence within it. See the <a href="https://aka.ms/talangs">Supported languages in Text Analytics API</a> for the list of enabled languages. + * + * @param input Collection of documents to analyze. + * @param modelVersion (Optional) This value indicates which model will be used for scoring. If a model-version is not specified, the API should default to the latest, non-preview version. + * @param showStats (Optional) if set to true, response will contain input and document level statistics. + * @param context The context to associate with this operation. + * @throws IllegalArgumentException thrown if parameters fail the validation. + * @return a Mono which performs the network request upon subscription. + */ + @ServiceMethod(returns = ReturnType.SINGLE) + public Mono> sentimentWithRestResponseAsync(MultiLanguageBatchInput input, String modelVersion, Boolean showStats, Context context) { + return service.sentiment(this.getEndpoint(), modelVersion, showStats, input, context); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImplBuilder.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImplBuilder.java new file mode 100644 index 000000000000..dc59d2fc68aa --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/TextAnalyticsClientImplBuilder.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation; + +import com.azure.core.annotation.ServiceClientBuilder; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.CookiePolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; + +/** + * A builder for creating a new instance of the TextAnalyticsClient type. + */ +@ServiceClientBuilder(serviceClients = TextAnalyticsClientImpl.class) +public final class TextAnalyticsClientImplBuilder { + /* + * Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). + */ + private String endpoint; + + /** + * Sets Supported Cognitive Services endpoints (protocol and hostname, for example: https://westus.api.cognitive.microsoft.com). + * + * @param endpoint the endpoint value. + * @return the TextAnalyticsClientImplBuilder. + */ + public TextAnalyticsClientImplBuilder endpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /* + * The HTTP pipeline to send requests through + */ + private HttpPipeline pipeline; + + /** + * Sets The HTTP pipeline to send requests through. + * + * @param pipeline the pipeline value. + * @return the TextAnalyticsClientImplBuilder. + */ + public TextAnalyticsClientImplBuilder pipeline(HttpPipeline pipeline) { + this.pipeline = pipeline; + return this; + } + + /** + * Builds an instance of TextAnalyticsClientImpl with the provided parameters. + * + * @return an instance of TextAnalyticsClientImpl. + */ + public TextAnalyticsClientImpl build() { + if (pipeline == null) { + this.pipeline = new HttpPipelineBuilder().policies(new UserAgentPolicy(), new RetryPolicy(), new CookiePolicy()).build(); + } + TextAnalyticsClientImpl client = new TextAnalyticsClientImpl(pipeline); + if (this.endpoint != null) { + client.setEndpoint(this.endpoint); + } + return client; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DetectedLanguage.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DetectedLanguage.java new file mode 100644 index 000000000000..5eec388b2d15 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DetectedLanguage.java @@ -0,0 +1,100 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The DetectedLanguage model. + */ +@Fluent +public final class DetectedLanguage { + /* + * Long name of a detected language (e.g. English, French). + */ + @JsonProperty(value = "name", required = true) + private String name; + + /* + * A two letter representation of the detected language according to the + * ISO 639-1 standard (e.g. en, fr). + */ + @JsonProperty(value = "iso6391Name", required = true) + private String iso6391Name; + + /* + * A confidence score between 0 and 1. Scores close to 1 indicate 100% + * certainty that the identified language is true. + */ + @JsonProperty(value = "score", required = true) + private double score; + + /** + * Get the name property: Long name of a detected language (e.g. English, + * French). + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Set the name property: Long name of a detected language (e.g. English, + * French). + * + * @param name the name value to set. + * @return the DetectedLanguage object itself. + */ + public DetectedLanguage setName(String name) { + this.name = name; + return this; + } + + /** + * Get the iso6391Name property: A two letter representation of the + * detected language according to the ISO 639-1 standard (e.g. en, fr). + * + * @return the iso6391Name value. + */ + public String getIso6391Name() { + return this.iso6391Name; + } + + /** + * Set the iso6391Name property: A two letter representation of the + * detected language according to the ISO 639-1 standard (e.g. en, fr). + * + * @param iso6391Name the iso6391Name value to set. + * @return the DetectedLanguage object itself. + */ + public DetectedLanguage setIso6391Name(String iso6391Name) { + this.iso6391Name = iso6391Name; + return this; + } + + /** + * Get the score property: A confidence score between 0 and 1. Scores close + * to 1 indicate 100% certainty that the identified language is true. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } + + /** + * Set the score property: A confidence score between 0 and 1. Scores close + * to 1 indicate 100% certainty that the identified language is true. + * + * @param score the score value to set. + * @return the DetectedLanguage object itself. + */ + public DetectedLanguage setScore(double score) { + this.score = score; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentEntities.java new file mode 100644 index 000000000000..dffd817a1919 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentEntities.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The DocumentEntities model. + */ +@Fluent +public final class DocumentEntities { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * Recognized entities in the document. + */ + @JsonProperty(value = "entities", required = true) + private List entities; + + /* + * if showStats=true was specified in the request this field will contain + * information about the document payload. + */ + @JsonProperty(value = "statistics") + private DocumentStatistics statistics; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the DocumentEntities object itself. + */ + public DocumentEntities setId(String id) { + this.id = id; + return this; + } + + /** + * Get the entities property: Recognized entities in the document. + * + * @return the entities value. + */ + public List getEntities() { + return this.entities; + } + + /** + * Set the entities property: Recognized entities in the document. + * + * @param entities the entities value to set. + * @return the DocumentEntities object itself. + */ + public DocumentEntities setEntities(List entities) { + this.entities = entities; + return this; + } + + /** + * Get the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @return the statistics value. + */ + public DocumentStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @param statistics the statistics value to set. + * @return the DocumentEntities object itself. + */ + public DocumentEntities setStatistics(DocumentStatistics statistics) { + this.statistics = statistics; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentError.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentError.java new file mode 100644 index 000000000000..7813edbe60a9 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentError.java @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The DocumentError model. + */ +@Fluent +public final class DocumentError { + /* + * Document Id. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * Document Error. + */ + @JsonProperty(value = "error", required = true) + private TextAnalyticsError error; + + /** + * Get the id property: Document Id. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Document Id. + * + * @param id the id value to set. + * @return the DocumentError object itself. + */ + public DocumentError setId(String id) { + this.id = id; + return this; + } + + /** + * Get the error property: Document Error. + * + * @return the error value. + */ + public TextAnalyticsError getError() { + return this.error; + } + + /** + * Set the error property: Document Error. + * + * @param error the error value to set. + * @return the DocumentError object itself. + */ + public DocumentError setError(TextAnalyticsError error) { + this.error = error; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentKeyPhrases.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentKeyPhrases.java new file mode 100644 index 000000000000..e7def8e817f2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentKeyPhrases.java @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The DocumentKeyPhrases model. + */ +@Fluent +public final class DocumentKeyPhrases { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * A list of representative words or phrases. The number of key phrases + * returned is proportional to the number of words in the input document. + */ + @JsonProperty(value = "keyPhrases", required = true) + private List keyPhrases; + + /* + * if showStats=true was specified in the request this field will contain + * information about the document payload. + */ + @JsonProperty(value = "statistics") + private DocumentStatistics statistics; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the DocumentKeyPhrases object itself. + */ + public DocumentKeyPhrases setId(String id) { + this.id = id; + return this; + } + + /** + * Get the keyPhrases property: A list of representative words or phrases. + * The number of key phrases returned is proportional to the number of + * words in the input document. + * + * @return the keyPhrases value. + */ + public List getKeyPhrases() { + return this.keyPhrases; + } + + /** + * Set the keyPhrases property: A list of representative words or phrases. + * The number of key phrases returned is proportional to the number of + * words in the input document. + * + * @param keyPhrases the keyPhrases value to set. + * @return the DocumentKeyPhrases object itself. + */ + public DocumentKeyPhrases setKeyPhrases(List keyPhrases) { + this.keyPhrases = keyPhrases; + return this; + } + + /** + * Get the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @return the statistics value. + */ + public DocumentStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @param statistics the statistics value to set. + * @return the DocumentKeyPhrases object itself. + */ + public DocumentKeyPhrases setStatistics(DocumentStatistics statistics) { + this.statistics = statistics; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLanguage.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLanguage.java new file mode 100644 index 000000000000..588292564911 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLanguage.java @@ -0,0 +1,96 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The DocumentLanguage model. + */ +@Fluent +public final class DocumentLanguage { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * A list of extracted languages. + */ + @JsonProperty(value = "detectedLanguages", required = true) + private List detectedLanguages; + + /* + * if showStats=true was specified in the request this field will contain + * information about the document payload. + */ + @JsonProperty(value = "statistics") + private DocumentStatistics statistics; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the DocumentLanguage object itself. + */ + public DocumentLanguage setId(String id) { + this.id = id; + return this; + } + + /** + * Get the detectedLanguages property: A list of extracted languages. + * + * @return the detectedLanguages value. + */ + public List getDetectedLanguages() { + return this.detectedLanguages; + } + + /** + * Set the detectedLanguages property: A list of extracted languages. + * + * @param detectedLanguages the detectedLanguages value to set. + * @return the DocumentLanguage object itself. + */ + public DocumentLanguage setDetectedLanguages(List detectedLanguages) { + this.detectedLanguages = detectedLanguages; + return this; + } + + /** + * Get the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @return the statistics value. + */ + public DocumentStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @param statistics the statistics value to set. + * @return the DocumentLanguage object itself. + */ + public DocumentLanguage setStatistics(DocumentStatistics statistics) { + this.statistics = statistics; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLinkedEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLinkedEntities.java new file mode 100644 index 000000000000..f3345e8d3cc9 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentLinkedEntities.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The DocumentLinkedEntities model. + */ +@Fluent +public final class DocumentLinkedEntities { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * Recognized well-known entities in the document. + */ + @JsonProperty(value = "entities", required = true) + private List entities; + + /* + * if showStats=true was specified in the request this field will contain + * information about the document payload. + */ + @JsonProperty(value = "statistics") + private DocumentStatistics statistics; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the DocumentLinkedEntities object itself. + */ + public DocumentLinkedEntities setId(String id) { + this.id = id; + return this; + } + + /** + * Get the entities property: Recognized well-known entities in the + * document. + * + * @return the entities value. + */ + public List getEntities() { + return this.entities; + } + + /** + * Set the entities property: Recognized well-known entities in the + * document. + * + * @param entities the entities value to set. + * @return the DocumentLinkedEntities object itself. + */ + public DocumentLinkedEntities setEntities(List entities) { + this.entities = entities; + return this; + } + + /** + * Get the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @return the statistics value. + */ + public DocumentStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: if showStats=true was specified in the + * request this field will contain information about the document payload. + * + * @param statistics the statistics value to set. + * @return the DocumentLinkedEntities object itself. + */ + public DocumentLinkedEntities setStatistics(DocumentStatistics statistics) { + this.statistics = statistics; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentiment.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentiment.java new file mode 100644 index 000000000000..a02c8fabadc3 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentiment.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The DocumentSentiment model. + */ +@Fluent +public final class DocumentSentiment { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * Predicted sentiment for document (Negative, Neutral, Positive, or + * Mixed). Possible values include: 'positive', 'neutral', 'negative', + * 'mixed' + */ + @JsonProperty(value = "sentiment", required = true) + private DocumentSentimentValue sentiment; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private DocumentStatistics statistics; + + /* + * Document level sentiment confidence scores between 0 and 1 for each + * sentiment class. + */ + @JsonProperty(value = "documentScores", required = true) + private SentimentConfidenceScorePerLabel documentScores; + + /* + * Sentence level sentiment analysis. + */ + @JsonProperty(value = "sentences", required = true) + private List sentences; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the DocumentSentiment object itself. + */ + public DocumentSentiment setId(String id) { + this.id = id; + return this; + } + + /** + * Get the sentiment property: Predicted sentiment for document (Negative, + * Neutral, Positive, or Mixed). Possible values include: 'positive', + * 'neutral', 'negative', 'mixed'. + * + * @return the sentiment value. + */ + public DocumentSentimentValue getSentiment() { + return this.sentiment; + } + + /** + * Set the sentiment property: Predicted sentiment for document (Negative, + * Neutral, Positive, or Mixed). Possible values include: 'positive', + * 'neutral', 'negative', 'mixed'. + * + * @param sentiment the sentiment value to set. + * @return the DocumentSentiment object itself. + */ + public DocumentSentiment setSentiment(DocumentSentimentValue sentiment) { + this.sentiment = sentiment; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public DocumentStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the DocumentSentiment object itself. + */ + public DocumentSentiment setStatistics(DocumentStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the documentScores property: Document level sentiment confidence + * scores between 0 and 1 for each sentiment class. + * + * @return the documentScores value. + */ + public SentimentConfidenceScorePerLabel getDocumentScores() { + return this.documentScores; + } + + /** + * Set the documentScores property: Document level sentiment confidence + * scores between 0 and 1 for each sentiment class. + * + * @param documentScores the documentScores value to set. + * @return the DocumentSentiment object itself. + */ + public DocumentSentiment setDocumentScores(SentimentConfidenceScorePerLabel documentScores) { + this.documentScores = documentScores; + return this; + } + + /** + * Get the sentences property: Sentence level sentiment analysis. + * + * @return the sentences value. + */ + public List getSentences() { + return this.sentences; + } + + /** + * Set the sentences property: Sentence level sentiment analysis. + * + * @param sentences the sentences value to set. + * @return the DocumentSentiment object itself. + */ + public DocumentSentiment setSentences(List sentences) { + this.sentences = sentences; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentimentValue.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentimentValue.java new file mode 100644 index 000000000000..96af38b7ab1a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentSentimentValue.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for DocumentSentimentValue. + */ +public enum DocumentSentimentValue { + /** + * Enum value positive. + */ + POSITIVE("positive"), + + /** + * Enum value neutral. + */ + NEUTRAL("neutral"), + + /** + * Enum value negative. + */ + NEGATIVE("negative"), + + /** + * Enum value mixed. + */ + MIXED("mixed"); + + /** + * The actual serialized value for a DocumentSentimentValue instance. + */ + private final String value; + + DocumentSentimentValue(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a DocumentSentimentValue instance. + * + * @param value the serialized value to parse. + * @return the parsed DocumentSentimentValue object, or null if unable to parse. + */ + @JsonCreator + public static DocumentSentimentValue fromString(String value) { + DocumentSentimentValue[] items = DocumentSentimentValue.values(); + for (DocumentSentimentValue item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentStatistics.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentStatistics.java new file mode 100644 index 000000000000..6dac964785f1 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/DocumentStatistics.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * if showStats=true was specified in the request this field will contain + * information about the document payload. + */ +@Fluent +public final class DocumentStatistics { + /* + * Number of text elements recognized in the document. + */ + @JsonProperty(value = "charactersCount", required = true) + private int charactersCount; + + /* + * Number of transactions for the document. + */ + @JsonProperty(value = "transactionsCount", required = true) + private int transactionsCount; + + /** + * Get the charactersCount property: Number of text elements recognized in + * the document. + * + * @return the charactersCount value. + */ + public int getCharactersCount() { + return this.charactersCount; + } + + /** + * Set the charactersCount property: Number of text elements recognized in + * the document. + * + * @param charactersCount the charactersCount value to set. + * @return the DocumentStatistics object itself. + */ + public DocumentStatistics setCharactersCount(int charactersCount) { + this.charactersCount = charactersCount; + return this; + } + + /** + * Get the transactionsCount property: Number of transactions for the + * document. + * + * @return the transactionsCount value. + */ + public int getTransactionsCount() { + return this.transactionsCount; + } + + /** + * Set the transactionsCount property: Number of transactions for the + * document. + * + * @param transactionsCount the transactionsCount value to set. + * @return the DocumentStatistics object itself. + */ + public DocumentStatistics setTransactionsCount(int transactionsCount) { + this.transactionsCount = transactionsCount; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntitiesResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntitiesResult.java new file mode 100644 index 000000000000..e80597e11c8e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntitiesResult.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The EntitiesResult model. + */ +@Fluent +public final class EntitiesResult { + /* + * Response by document + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /* + * Errors by document id. + */ + @JsonProperty(value = "errors", required = true) + private List errors; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private RequestStatistics statistics; + + /* + * This field indicates which model is used for scoring. + */ + @JsonProperty(value = "modelVersion", required = true) + private String modelVersion; + + /** + * Get the documents property: Response by document. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: Response by document. + * + * @param documents the documents value to set. + * @return the EntitiesResult object itself. + */ + public EntitiesResult setDocuments(List documents) { + this.documents = documents; + return this; + } + + /** + * Get the errors property: Errors by document id. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Set the errors property: Errors by document id. + * + * @param errors the errors value to set. + * @return the EntitiesResult object itself. + */ + public EntitiesResult setErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public RequestStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the EntitiesResult object itself. + */ + public EntitiesResult setStatistics(RequestStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the modelVersion property: This field indicates which model is used + * for scoring. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Set the modelVersion property: This field indicates which model is used + * for scoring. + * + * @param modelVersion the modelVersion value to set. + * @return the EntitiesResult object itself. + */ + public EntitiesResult setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Entity.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Entity.java new file mode 100644 index 000000000000..1c781826bd9b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Entity.java @@ -0,0 +1,178 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The Entity model. + */ +@Fluent +public final class Entity { + /* + * Entity text as appears in the request. + */ + @JsonProperty(value = "text", required = true) + private String text; + + /* + * Entity type, such as Person/Location/Org/SSN etc + */ + @JsonProperty(value = "type", required = true) + private String type; + + /* + * Entity sub type, such as Age/Year/TimeRange etc + */ + @JsonProperty(value = "subtype") + private String subtype; + + /* + * Start position (in Unicode characters) for the entity text. + */ + @JsonProperty(value = "offset", required = true) + private int offset; + + /* + * Length (in Unicode characters) for the entity text. + */ + @JsonProperty(value = "length", required = true) + private int length; + + /* + * Confidence score between 0 and 1 of the extracted entity. + */ + @JsonProperty(value = "score", required = true) + private double score; + + /** + * Get the text property: Entity text as appears in the request. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Set the text property: Entity text as appears in the request. + * + * @param text the text value to set. + * @return the Entity object itself. + */ + public Entity setText(String text) { + this.text = text; + return this; + } + + /** + * Get the type property: Entity type, such as Person/Location/Org/SSN etc. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Set the type property: Entity type, such as Person/Location/Org/SSN etc. + * + * @param type the type value to set. + * @return the Entity object itself. + */ + public Entity setType(String type) { + this.type = type; + return this; + } + + /** + * Get the subtype property: Entity sub type, such as Age/Year/TimeRange + * etc. + * + * @return the subtype value. + */ + public String getSubtype() { + return this.subtype; + } + + /** + * Set the subtype property: Entity sub type, such as Age/Year/TimeRange + * etc. + * + * @param subtype the subtype value to set. + * @return the Entity object itself. + */ + public Entity setSubtype(String subtype) { + this.subtype = subtype; + return this; + } + + /** + * Get the offset property: Start position (in Unicode characters) for the + * entity text. + * + * @return the offset value. + */ + public int getOffset() { + return this.offset; + } + + /** + * Set the offset property: Start position (in Unicode characters) for the + * entity text. + * + * @param offset the offset value to set. + * @return the Entity object itself. + */ + public Entity setOffset(int offset) { + this.offset = offset; + return this; + } + + /** + * Get the length property: Length (in Unicode characters) for the entity + * text. + * + * @return the length value. + */ + public int getLength() { + return this.length; + } + + /** + * Set the length property: Length (in Unicode characters) for the entity + * text. + * + * @param length the length value to set. + * @return the Entity object itself. + */ + public Entity setLength(int length) { + this.length = length; + return this; + } + + /** + * Get the score property: Confidence score between 0 and 1 of the + * extracted entity. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } + + /** + * Set the score property: Confidence score between 0 and 1 of the + * extracted entity. + * + * @param score the score value to set. + * @return the Entity object itself. + */ + public Entity setScore(double score) { + this.score = score; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntityLinkingResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntityLinkingResult.java new file mode 100644 index 000000000000..8c0d733e4b67 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/EntityLinkingResult.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The EntityLinkingResult model. + */ +@Fluent +public final class EntityLinkingResult { + /* + * Response by document + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /* + * Errors by document id. + */ + @JsonProperty(value = "errors", required = true) + private List errors; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private RequestStatistics statistics; + + /* + * This field indicates which model is used for scoring. + */ + @JsonProperty(value = "modelVersion", required = true) + private String modelVersion; + + /** + * Get the documents property: Response by document. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: Response by document. + * + * @param documents the documents value to set. + * @return the EntityLinkingResult object itself. + */ + public EntityLinkingResult setDocuments(List documents) { + this.documents = documents; + return this; + } + + /** + * Get the errors property: Errors by document id. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Set the errors property: Errors by document id. + * + * @param errors the errors value to set. + * @return the EntityLinkingResult object itself. + */ + public EntityLinkingResult setErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public RequestStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the EntityLinkingResult object itself. + */ + public EntityLinkingResult setStatistics(RequestStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the modelVersion property: This field indicates which model is used + * for scoring. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Set the modelVersion property: This field indicates which model is used + * for scoring. + * + * @param modelVersion the modelVersion value to set. + * @return the EntityLinkingResult object itself. + */ + public EntityLinkingResult setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorCodeValue.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorCodeValue.java new file mode 100644 index 000000000000..2a00a654b655 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorCodeValue.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for ErrorCodeValue. + */ +public enum ErrorCodeValue { + /** + * Enum value invalidRequest. + */ + INVALID_REQUEST("invalidRequest"), + + /** + * Enum value invalidArgument. + */ + INVALID_ARGUMENT("invalidArgument"), + + /** + * Enum value internalServerError. + */ + INTERNAL_SERVER_ERROR("internalServerError"), + + /** + * Enum value serviceUnavailable. + */ + SERVICE_UNAVAILABLE("serviceUnavailable"); + + /** + * The actual serialized value for a ErrorCodeValue instance. + */ + private final String value; + + ErrorCodeValue(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a ErrorCodeValue instance. + * + * @param value the serialized value to parse. + * @return the parsed ErrorCodeValue object, or null if unable to parse. + */ + @JsonCreator + public static ErrorCodeValue fromString(String value) { + ErrorCodeValue[] items = ErrorCodeValue.values(); + for (ErrorCodeValue item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorException.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorException.java new file mode 100644 index 000000000000..a163a5638869 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/ErrorException.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpResponse; + +/** + * Exception thrown for an invalid response with Error information. + */ +public final class ErrorException extends HttpResponseException { + /** + * Initializes a new instance of the ErrorException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + */ + public ErrorException(String message, HttpResponse response) { + super(message, response); + } + + /** + * Initializes a new instance of the ErrorException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + * @param value the deserialized response value. + */ + public ErrorException(String message, HttpResponse response, Error value) { + super(message, response, value); + } + + @Override + public Error getValue() { + return (Error) super.getValue(); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerError.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerError.java new file mode 100644 index 000000000000..ea1339baed9e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerError.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; + +/** + * The InnerError model. + */ +@Fluent +public final class InnerError { + /* + * Error code. Possible values include: 'invalidParameterValue', + * 'invalidRequestBodyFormat', 'emptyRequest', 'missingInputRecords', + * 'invalidDocument', 'modelVersionIncorrect', 'invalidDocumentBatch', + * 'unsupportedLanguageCode', 'invalidCountryHint' + */ + @JsonProperty(value = "code", required = true) + private InnerErrorCodeValue code; + + /* + * Error message. + */ + @JsonProperty(value = "message", required = true) + private String message; + + /* + * Error details. + */ + @JsonProperty(value = "details") + private Map details; + + /* + * Error target. + */ + @JsonProperty(value = "target") + private String target; + + /* + * Inner error contains more specific information. + */ + @JsonProperty(value = "innerError") + private InnerError innerError; + + /** + * Get the code property: Error code. Possible values include: + * 'invalidParameterValue', 'invalidRequestBodyFormat', 'emptyRequest', + * 'missingInputRecords', 'invalidDocument', 'modelVersionIncorrect', + * 'invalidDocumentBatch', 'unsupportedLanguageCode', 'invalidCountryHint'. + * + * @return the code value. + */ + public InnerErrorCodeValue getCode() { + return this.code; + } + + /** + * Set the code property: Error code. Possible values include: + * 'invalidParameterValue', 'invalidRequestBodyFormat', 'emptyRequest', + * 'missingInputRecords', 'invalidDocument', 'modelVersionIncorrect', + * 'invalidDocumentBatch', 'unsupportedLanguageCode', 'invalidCountryHint'. + * + * @param code the code value to set. + * @return the InnerError object itself. + */ + public InnerError setCode(InnerErrorCodeValue code) { + this.code = code; + return this; + } + + /** + * Get the message property: Error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message property: Error message. + * + * @param message the message value to set. + * @return the InnerError object itself. + */ + public InnerError setMessage(String message) { + this.message = message; + return this; + } + + /** + * Get the details property: Error details. + * + * @return the details value. + */ + public Map getDetails() { + return this.details; + } + + /** + * Set the details property: Error details. + * + * @param details the details value to set. + * @return the InnerError object itself. + */ + public InnerError setDetails(Map details) { + this.details = details; + return this; + } + + /** + * Get the target property: Error target. + * + * @return the target value. + */ + public String getTarget() { + return this.target; + } + + /** + * Set the target property: Error target. + * + * @param target the target value to set. + * @return the InnerError object itself. + */ + public InnerError setTarget(String target) { + this.target = target; + return this; + } + + /** + * Get the innerError property: Inner error contains more specific + * information. + * + * @return the innerError value. + */ + public InnerError getInnerError() { + return this.innerError; + } + + /** + * Set the innerError property: Inner error contains more specific + * information. + * + * @param innerError the innerError value to set. + * @return the InnerError object itself. + */ + public InnerError setInnerError(InnerError innerError) { + this.innerError = innerError; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerErrorCodeValue.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerErrorCodeValue.java new file mode 100644 index 000000000000..caec203e43b7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/InnerErrorCodeValue.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for InnerErrorCodeValue. + */ +public enum InnerErrorCodeValue { + /** + * Enum value invalidParameterValue. + */ + INVALID_PARAMETER_VALUE("invalidParameterValue"), + + /** + * Enum value invalidRequestBodyFormat. + */ + INVALID_REQUEST_BODY_FORMAT("invalidRequestBodyFormat"), + + /** + * Enum value emptyRequest. + */ + EMPTY_REQUEST("emptyRequest"), + + /** + * Enum value missingInputRecords. + */ + MISSING_INPUT_RECORDS("missingInputRecords"), + + /** + * Enum value invalidDocument. + */ + INVALID_DOCUMENT("invalidDocument"), + + /** + * Enum value modelVersionIncorrect. + */ + MODEL_VERSION_INCORRECT("modelVersionIncorrect"), + + /** + * Enum value invalidDocumentBatch. + */ + INVALID_DOCUMENT_BATCH("invalidDocumentBatch"), + + /** + * Enum value unsupportedLanguageCode. + */ + UNSUPPORTED_LANGUAGE_CODE("unsupportedLanguageCode"), + + /** + * Enum value invalidCountryHint. + */ + INVALID_COUNTRY_HINT("invalidCountryHint"); + + /** + * The actual serialized value for a InnerErrorCodeValue instance. + */ + private final String value; + + InnerErrorCodeValue(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a InnerErrorCodeValue instance. + * + * @param value the serialized value to parse. + * @return the parsed InnerErrorCodeValue object, or null if unable to parse. + */ + @JsonCreator + public static InnerErrorCodeValue fromString(String value) { + InnerErrorCodeValue[] items = InnerErrorCodeValue.values(); + for (InnerErrorCodeValue item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/KeyPhraseResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/KeyPhraseResult.java new file mode 100644 index 000000000000..7c19d60a2e5c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/KeyPhraseResult.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The KeyPhraseResult model. + */ +@Fluent +public final class KeyPhraseResult { + /* + * Response by document + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /* + * Errors by document id. + */ + @JsonProperty(value = "errors", required = true) + private List errors; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private RequestStatistics statistics; + + /* + * This field indicates which model is used for scoring. + */ + @JsonProperty(value = "modelVersion", required = true) + private String modelVersion; + + /** + * Get the documents property: Response by document. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: Response by document. + * + * @param documents the documents value to set. + * @return the KeyPhraseResult object itself. + */ + public KeyPhraseResult setDocuments(List documents) { + this.documents = documents; + return this; + } + + /** + * Get the errors property: Errors by document id. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Set the errors property: Errors by document id. + * + * @param errors the errors value to set. + * @return the KeyPhraseResult object itself. + */ + public KeyPhraseResult setErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public RequestStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the KeyPhraseResult object itself. + */ + public KeyPhraseResult setStatistics(RequestStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the modelVersion property: This field indicates which model is used + * for scoring. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Set the modelVersion property: This field indicates which model is used + * for scoring. + * + * @param modelVersion the modelVersion value to set. + * @return the KeyPhraseResult object itself. + */ + public KeyPhraseResult setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageBatchInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageBatchInput.java new file mode 100644 index 000000000000..dff194489582 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageBatchInput.java @@ -0,0 +1,41 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The LanguageBatchInput model. + */ +@Fluent +public final class LanguageBatchInput { + /* + * The documents property. + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /** + * Get the documents property: The documents property. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: The documents property. + * + * @param documents the documents value to set. + * @return the LanguageBatchInput object itself. + */ + public LanguageBatchInput setDocuments(List documents) { + this.documents = documents; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageInput.java new file mode 100644 index 000000000000..da18b248fa8a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageInput.java @@ -0,0 +1,92 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The LanguageInput model. + */ +@Fluent +public final class LanguageInput { + /* + * Unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * The text property. + */ + @JsonProperty(value = "text", required = true) + private String text; + + /* + * The countryHint property. + */ + @JsonProperty(value = "countryHint") + private String countryHint; + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the LanguageInput object itself. + */ + public LanguageInput setId(String id) { + this.id = id; + return this; + } + + /** + * Get the text property: The text property. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Set the text property: The text property. + * + * @param text the text value to set. + * @return the LanguageInput object itself. + */ + public LanguageInput setText(String text) { + this.text = text; + return this; + } + + /** + * Get the countryHint property: The countryHint property. + * + * @return the countryHint value. + */ + public String getCountryHint() { + return this.countryHint; + } + + /** + * Set the countryHint property: The countryHint property. + * + * @param countryHint the countryHint value to set. + * @return the LanguageInput object itself. + */ + public LanguageInput setCountryHint(String countryHint) { + this.countryHint = countryHint; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageResult.java new file mode 100644 index 000000000000..82e11308d49c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LanguageResult.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The LanguageResult model. + */ +@Fluent +public final class LanguageResult { + /* + * Response by document + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /* + * Errors by document id. + */ + @JsonProperty(value = "errors", required = true) + private List errors; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private RequestStatistics statistics; + + /* + * This field indicates which model is used for scoring. + */ + @JsonProperty(value = "modelVersion", required = true) + private String modelVersion; + + /** + * Get the documents property: Response by document. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: Response by document. + * + * @param documents the documents value to set. + * @return the LanguageResult object itself. + */ + public LanguageResult setDocuments(List documents) { + this.documents = documents; + return this; + } + + /** + * Get the errors property: Errors by document id. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Set the errors property: Errors by document id. + * + * @param errors the errors value to set. + * @return the LanguageResult object itself. + */ + public LanguageResult setErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public RequestStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the LanguageResult object itself. + */ + public LanguageResult setStatistics(RequestStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the modelVersion property: This field indicates which model is used + * for scoring. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Set the modelVersion property: This field indicates which model is used + * for scoring. + * + * @param modelVersion the modelVersion value to set. + * @return the LanguageResult object itself. + */ + public LanguageResult setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LinkedEntity.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LinkedEntity.java new file mode 100644 index 000000000000..0c3b2fd9f859 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/LinkedEntity.java @@ -0,0 +1,177 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The LinkedEntity model. + */ +@Fluent +public final class LinkedEntity { + /* + * Entity Linking formal name. + */ + @JsonProperty(value = "name", required = true) + private String name; + + /* + * List of instances this entity appears in the text. + */ + @JsonProperty(value = "matches", required = true) + private List matches; + + /* + * Language used in the data source. + */ + @JsonProperty(value = "language", required = true) + private String language; + + /* + * Unique identifier of the recognized entity from the data source. + */ + @JsonProperty(value = "id") + private String id; + + /* + * URL for the entity's page from the data source. + */ + @JsonProperty(value = "url", required = true) + private String url; + + /* + * Data source used to extract entity linking, such as Wiki/Bing etc. + */ + @JsonProperty(value = "dataSource", required = true) + private String dataSource; + + /** + * Get the name property: Entity Linking formal name. + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Set the name property: Entity Linking formal name. + * + * @param name the name value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setName(String name) { + this.name = name; + return this; + } + + /** + * Get the matches property: List of instances this entity appears in the + * text. + * + * @return the matches value. + */ + public List getMatches() { + return this.matches; + } + + /** + * Set the matches property: List of instances this entity appears in the + * text. + * + * @param matches the matches value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setMatches(List matches) { + this.matches = matches; + return this; + } + + /** + * Get the language property: Language used in the data source. + * + * @return the language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Set the language property: Language used in the data source. + * + * @param language the language value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setLanguage(String language) { + this.language = language; + return this; + } + + /** + * Get the id property: Unique identifier of the recognized entity from the + * data source. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: Unique identifier of the recognized entity from the + * data source. + * + * @param id the id value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setId(String id) { + this.id = id; + return this; + } + + /** + * Get the url property: URL for the entity's page from the data source. + * + * @return the url value. + */ + public String getUrl() { + return this.url; + } + + /** + * Set the url property: URL for the entity's page from the data source. + * + * @param url the url value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setUrl(String url) { + this.url = url; + return this; + } + + /** + * Get the dataSource property: Data source used to extract entity linking, + * such as Wiki/Bing etc. + * + * @return the dataSource value. + */ + public String getDataSource() { + return this.dataSource; + } + + /** + * Set the dataSource property: Data source used to extract entity linking, + * such as Wiki/Bing etc. + * + * @param dataSource the dataSource value to set. + * @return the LinkedEntity object itself. + */ + public LinkedEntity setDataSource(String dataSource) { + this.dataSource = dataSource; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Match.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Match.java new file mode 100644 index 000000000000..cdd4e4a6fa18 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/Match.java @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The Match model. + */ +@Fluent +public final class Match { + /* + * If a well-known item is recognized, a decimal number denoting the + * confidence level between 0 and 1 will be returned. + */ + @JsonProperty(value = "score", required = true) + private double score; + + /* + * Entity text as appears in the request. + */ + @JsonProperty(value = "text", required = true) + private String text; + + /* + * Start position (in Unicode characters) for the entity match text. + */ + @JsonProperty(value = "offset", required = true) + private int offset; + + /* + * Length (in Unicode characters) for the entity match text. + */ + @JsonProperty(value = "length", required = true) + private int length; + + /** + * Get the score property: If a well-known item is recognized, a decimal + * number denoting the confidence level between 0 and 1 will be returned. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } + + /** + * Set the score property: If a well-known item is recognized, a decimal + * number denoting the confidence level between 0 and 1 will be returned. + * + * @param score the score value to set. + * @return the Match object itself. + */ + public Match setScore(double score) { + this.score = score; + return this; + } + + /** + * Get the text property: Entity text as appears in the request. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Set the text property: Entity text as appears in the request. + * + * @param text the text value to set. + * @return the Match object itself. + */ + public Match setText(String text) { + this.text = text; + return this; + } + + /** + * Get the offset property: Start position (in Unicode characters) for the + * entity match text. + * + * @return the offset value. + */ + public int getOffset() { + return this.offset; + } + + /** + * Set the offset property: Start position (in Unicode characters) for the + * entity match text. + * + * @param offset the offset value to set. + * @return the Match object itself. + */ + public Match setOffset(int offset) { + this.offset = offset; + return this; + } + + /** + * Get the length property: Length (in Unicode characters) for the entity + * match text. + * + * @return the length value. + */ + public int getLength() { + return this.length; + } + + /** + * Set the length property: Length (in Unicode characters) for the entity + * match text. + * + * @param length the length value to set. + * @return the Match object itself. + */ + public Match setLength(int length) { + this.length = length; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageBatchInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageBatchInput.java new file mode 100644 index 000000000000..15e031e8696e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageBatchInput.java @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * Contains a set of input documents to be analyzed by the service. + */ +@Fluent +public final class MultiLanguageBatchInput { + /* + * The set of documents to process as part of this batch. + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /** + * Get the documents property: The set of documents to process as part of + * this batch. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: The set of documents to process as part of + * this batch. + * + * @param documents the documents value to set. + * @return the MultiLanguageBatchInput object itself. + */ + public MultiLanguageBatchInput setDocuments(List documents) { + this.documents = documents; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageInput.java new file mode 100644 index 000000000000..3760d680181e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/MultiLanguageInput.java @@ -0,0 +1,98 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Contains an input document to be analyzed by the service. + */ +@Fluent +public final class MultiLanguageInput { + /* + * A unique, non-empty document identifier. + */ + @JsonProperty(value = "id", required = true) + private String id; + + /* + * The input text to process. + */ + @JsonProperty(value = "text", required = true) + private String text; + + /* + * (Optional) This is the 2 letter ISO 639-1 representation of a language. + * For example, use "en" for English; "es" for Spanish etc. If not set, use + * "en" for English as default. + */ + @JsonProperty(value = "language") + private String language; + + /** + * Get the id property: A unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Set the id property: A unique, non-empty document identifier. + * + * @param id the id value to set. + * @return the MultiLanguageInput object itself. + */ + public MultiLanguageInput setId(String id) { + this.id = id; + return this; + } + + /** + * Get the text property: The input text to process. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Set the text property: The input text to process. + * + * @param text the text value to set. + * @return the MultiLanguageInput object itself. + */ + public MultiLanguageInput setText(String text) { + this.text = text; + return this; + } + + /** + * Get the language property: (Optional) This is the 2 letter ISO 639-1 + * representation of a language. For example, use "en" for English; "es" + * for Spanish etc. If not set, use "en" for English as default. + * + * @return the language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Set the language property: (Optional) This is the 2 letter ISO 639-1 + * representation of a language. For example, use "en" for English; "es" + * for Spanish etc. If not set, use "en" for English as default. + * + * @param language the language value to set. + * @return the MultiLanguageInput object itself. + */ + public MultiLanguageInput setLanguage(String language) { + this.language = language; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/RequestStatistics.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/RequestStatistics.java new file mode 100644 index 000000000000..b0934b055ab5 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/RequestStatistics.java @@ -0,0 +1,131 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * if showStats=true was specified in the request this field will contain + * information about the request payload. + */ +@Fluent +public final class RequestStatistics { + /* + * Number of documents submitted in the request. + */ + @JsonProperty(value = "documentsCount", required = true) + private int documentsCount; + + /* + * Number of valid documents. This excludes empty, over-size limit or + * non-supported languages documents. + */ + @JsonProperty(value = "validDocumentsCount", required = true) + private int validDocumentsCount; + + /* + * Number of invalid documents. This includes empty, over-size limit or + * non-supported languages documents. + */ + @JsonProperty(value = "erroneousDocumentsCount", required = true) + private int erroneousDocumentsCount; + + /* + * Number of transactions for the request. + */ + @JsonProperty(value = "transactionsCount", required = true) + private long transactionsCount; + + /** + * Get the documentsCount property: Number of documents submitted in the + * request. + * + * @return the documentsCount value. + */ + public int getDocumentsCount() { + return this.documentsCount; + } + + /** + * Set the documentsCount property: Number of documents submitted in the + * request. + * + * @param documentsCount the documentsCount value to set. + * @return the RequestStatistics object itself. + */ + public RequestStatistics setDocumentsCount(int documentsCount) { + this.documentsCount = documentsCount; + return this; + } + + /** + * Get the validDocumentsCount property: Number of valid documents. This + * excludes empty, over-size limit or non-supported languages documents. + * + * @return the validDocumentsCount value. + */ + public int getValidDocumentsCount() { + return this.validDocumentsCount; + } + + /** + * Set the validDocumentsCount property: Number of valid documents. This + * excludes empty, over-size limit or non-supported languages documents. + * + * @param validDocumentsCount the validDocumentsCount value to set. + * @return the RequestStatistics object itself. + */ + public RequestStatistics setValidDocumentsCount(int validDocumentsCount) { + this.validDocumentsCount = validDocumentsCount; + return this; + } + + /** + * Get the erroneousDocumentsCount property: Number of invalid documents. + * This includes empty, over-size limit or non-supported languages + * documents. + * + * @return the erroneousDocumentsCount value. + */ + public int getErroneousDocumentsCount() { + return this.erroneousDocumentsCount; + } + + /** + * Set the erroneousDocumentsCount property: Number of invalid documents. + * This includes empty, over-size limit or non-supported languages + * documents. + * + * @param erroneousDocumentsCount the erroneousDocumentsCount value to set. + * @return the RequestStatistics object itself. + */ + public RequestStatistics setErroneousDocumentsCount(int erroneousDocumentsCount) { + this.erroneousDocumentsCount = erroneousDocumentsCount; + return this; + } + + /** + * Get the transactionsCount property: Number of transactions for the + * request. + * + * @return the transactionsCount value. + */ + public long getTransactionsCount() { + return this.transactionsCount; + } + + /** + * Set the transactionsCount property: Number of transactions for the + * request. + * + * @param transactionsCount the transactionsCount value to set. + * @return the RequestStatistics object itself. + */ + public RequestStatistics setTransactionsCount(long transactionsCount) { + this.transactionsCount = transactionsCount; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentiment.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentiment.java new file mode 100644 index 000000000000..47a29eb1e207 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentiment.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The SentenceSentiment model. + */ +@Fluent +public final class SentenceSentiment { + /* + * The predicted Sentiment for the sentence. Possible values include: + * 'positive', 'neutral', 'negative' + */ + @JsonProperty(value = "sentiment", required = true) + private SentenceSentimentValue sentiment; + + /* + * The sentiment confidence score between 0 and 1 for the sentence for all + * classes. + */ + @JsonProperty(value = "sentenceScores", required = true) + private SentimentConfidenceScorePerLabel sentenceScores; + + /* + * The sentence offset from the start of the document. + */ + @JsonProperty(value = "offset", required = true) + private int offset; + + /* + * The length of the sentence by Unicode standard. + */ + @JsonProperty(value = "length", required = true) + private int length; + + /* + * The warnings generated for the sentence. + */ + @JsonProperty(value = "warnings") + private List warnings; + + /** + * Get the sentiment property: The predicted Sentiment for the sentence. + * Possible values include: 'positive', 'neutral', 'negative'. + * + * @return the sentiment value. + */ + public SentenceSentimentValue getSentiment() { + return this.sentiment; + } + + /** + * Set the sentiment property: The predicted Sentiment for the sentence. + * Possible values include: 'positive', 'neutral', 'negative'. + * + * @param sentiment the sentiment value to set. + * @return the SentenceSentiment object itself. + */ + public SentenceSentiment setSentiment(SentenceSentimentValue sentiment) { + this.sentiment = sentiment; + return this; + } + + /** + * Get the sentenceScores property: The sentiment confidence score between + * 0 and 1 for the sentence for all classes. + * + * @return the sentenceScores value. + */ + public SentimentConfidenceScorePerLabel getSentenceScores() { + return this.sentenceScores; + } + + /** + * Set the sentenceScores property: The sentiment confidence score between + * 0 and 1 for the sentence for all classes. + * + * @param sentenceScores the sentenceScores value to set. + * @return the SentenceSentiment object itself. + */ + public SentenceSentiment setSentenceScores(SentimentConfidenceScorePerLabel sentenceScores) { + this.sentenceScores = sentenceScores; + return this; + } + + /** + * Get the offset property: The sentence offset from the start of the + * document. + * + * @return the offset value. + */ + public int getOffset() { + return this.offset; + } + + /** + * Set the offset property: The sentence offset from the start of the + * document. + * + * @param offset the offset value to set. + * @return the SentenceSentiment object itself. + */ + public SentenceSentiment setOffset(int offset) { + this.offset = offset; + return this; + } + + /** + * Get the length property: The length of the sentence by Unicode standard. + * + * @return the length value. + */ + public int getLength() { + return this.length; + } + + /** + * Set the length property: The length of the sentence by Unicode standard. + * + * @param length the length value to set. + * @return the SentenceSentiment object itself. + */ + public SentenceSentiment setLength(int length) { + this.length = length; + return this; + } + + /** + * Get the warnings property: The warnings generated for the sentence. + * + * @return the warnings value. + */ + public List getWarnings() { + return this.warnings; + } + + /** + * Set the warnings property: The warnings generated for the sentence. + * + * @param warnings the warnings value to set. + * @return the SentenceSentiment object itself. + */ + public SentenceSentiment setWarnings(List warnings) { + this.warnings = warnings; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentimentValue.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentimentValue.java new file mode 100644 index 000000000000..3a1d6dcb5fee --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentenceSentimentValue.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for SentenceSentimentValue. + */ +public enum SentenceSentimentValue { + /** + * Enum value positive. + */ + POSITIVE("positive"), + + /** + * Enum value neutral. + */ + NEUTRAL("neutral"), + + /** + * Enum value negative. + */ + NEGATIVE("negative"); + + /** + * The actual serialized value for a SentenceSentimentValue instance. + */ + private final String value; + + SentenceSentimentValue(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a SentenceSentimentValue instance. + * + * @param value the serialized value to parse. + * @return the parsed SentenceSentimentValue object, or null if unable to parse. + */ + @JsonCreator + public static SentenceSentimentValue fromString(String value) { + SentenceSentimentValue[] items = SentenceSentimentValue.values(); + for (SentenceSentimentValue item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentConfidenceScorePerLabel.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentConfidenceScorePerLabel.java new file mode 100644 index 000000000000..eea3ba7a45f3 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentConfidenceScorePerLabel.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Represents the confidence scores between 0 and 1 across all sentiment + * classes: positive, neutral, negative. + */ +@Fluent +public final class SentimentConfidenceScorePerLabel { + /* + * The positive property. + */ + @JsonProperty(value = "positive", required = true) + private double positive; + + /* + * The neutral property. + */ + @JsonProperty(value = "neutral", required = true) + private double neutral; + + /* + * The negative property. + */ + @JsonProperty(value = "negative", required = true) + private double negative; + + /** + * Get the positive property: The positive property. + * + * @return the positive value. + */ + public double getPositive() { + return this.positive; + } + + /** + * Set the positive property: The positive property. + * + * @param positive the positive value to set. + * @return the SentimentConfidenceScorePerLabel object itself. + */ + public SentimentConfidenceScorePerLabel setPositive(double positive) { + this.positive = positive; + return this; + } + + /** + * Get the neutral property: The neutral property. + * + * @return the neutral value. + */ + public double getNeutral() { + return this.neutral; + } + + /** + * Set the neutral property: The neutral property. + * + * @param neutral the neutral value to set. + * @return the SentimentConfidenceScorePerLabel object itself. + */ + public SentimentConfidenceScorePerLabel setNeutral(double neutral) { + this.neutral = neutral; + return this; + } + + /** + * Get the negative property: The negative property. + * + * @return the negative value. + */ + public double getNegative() { + return this.negative; + } + + /** + * Set the negative property: The negative property. + * + * @param negative the negative value to set. + * @return the SentimentConfidenceScorePerLabel object itself. + */ + public SentimentConfidenceScorePerLabel setNegative(double negative) { + this.negative = negative; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentResponse.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentResponse.java new file mode 100644 index 000000000000..95a683f7cbb8 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/SentimentResponse.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The SentimentResponse model. + */ +@Fluent +public final class SentimentResponse { + /* + * Sentiment analysis per document. + */ + @JsonProperty(value = "documents", required = true) + private List documents; + + /* + * Errors by document id. + */ + @JsonProperty(value = "errors", required = true) + private List errors; + + /* + * The statistics property. + */ + @JsonProperty(value = "statistics") + private RequestStatistics statistics; + + /* + * This field indicates which model is used for scoring. + */ + @JsonProperty(value = "modelVersion", required = true) + private String modelVersion; + + /** + * Get the documents property: Sentiment analysis per document. + * + * @return the documents value. + */ + public List getDocuments() { + return this.documents; + } + + /** + * Set the documents property: Sentiment analysis per document. + * + * @param documents the documents value to set. + * @return the SentimentResponse object itself. + */ + public SentimentResponse setDocuments(List documents) { + this.documents = documents; + return this; + } + + /** + * Get the errors property: Errors by document id. + * + * @return the errors value. + */ + public List getErrors() { + return this.errors; + } + + /** + * Set the errors property: Errors by document id. + * + * @param errors the errors value to set. + * @return the SentimentResponse object itself. + */ + public SentimentResponse setErrors(List errors) { + this.errors = errors; + return this; + } + + /** + * Get the statistics property: The statistics property. + * + * @return the statistics value. + */ + public RequestStatistics getStatistics() { + return this.statistics; + } + + /** + * Set the statistics property: The statistics property. + * + * @param statistics the statistics value to set. + * @return the SentimentResponse object itself. + */ + public SentimentResponse setStatistics(RequestStatistics statistics) { + this.statistics = statistics; + return this; + } + + /** + * Get the modelVersion property: This field indicates which model is used + * for scoring. + * + * @return the modelVersion value. + */ + public String getModelVersion() { + return this.modelVersion; + } + + /** + * Set the modelVersion property: This field indicates which model is used + * for scoring. + * + * @param modelVersion the modelVersion value to set. + * @return the SentimentResponse object itself. + */ + public SentimentResponse setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsError.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsError.java new file mode 100644 index 000000000000..95cb995ac216 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsError.java @@ -0,0 +1,154 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.annotation.Fluent; +import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; + +/** + * The TextAnalyticsError model. + */ +@Fluent +public final class TextAnalyticsError { + /* + * Error code. Possible values include: 'invalidRequest', + * 'invalidArgument', 'internalServerError', 'serviceUnavailable' + */ + @JsonProperty(value = "code", required = true) + private ErrorCodeValue code; + + /* + * Error message. + */ + @JsonProperty(value = "message", required = true) + private String message; + + /* + * Error target. + */ + @JsonProperty(value = "target") + private String target; + + /* + * Inner error contains more specific information. + */ + @JsonProperty(value = "innerError") + private InnerError innerError; + + /* + * Details about specific errors that led to this reported error. + */ + @JsonProperty(value = "details") + private List details; + + /** + * Get the code property: Error code. Possible values include: + * 'invalidRequest', 'invalidArgument', 'internalServerError', + * 'serviceUnavailable'. + * + * @return the code value. + */ + public ErrorCodeValue getCode() { + return this.code; + } + + /** + * Set the code property: Error code. Possible values include: + * 'invalidRequest', 'invalidArgument', 'internalServerError', + * 'serviceUnavailable'. + * + * @param code the code value to set. + * @return the TextAnalyticsError object itself. + */ + public TextAnalyticsError setCode(ErrorCodeValue code) { + this.code = code; + return this; + } + + /** + * Get the message property: Error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message property: Error message. + * + * @param message the message value to set. + * @return the TextAnalyticsError object itself. + */ + public TextAnalyticsError setMessage(String message) { + this.message = message; + return this; + } + + /** + * Get the target property: Error target. + * + * @return the target value. + */ + public String getTarget() { + return this.target; + } + + /** + * Set the target property: Error target. + * + * @param target the target value to set. + * @return the TextAnalyticsError object itself. + */ + public TextAnalyticsError setTarget(String target) { + this.target = target; + return this; + } + + /** + * Get the innerError property: Inner error contains more specific + * information. + * + * @return the innerError value. + */ + public InnerError getInnerError() { + return this.innerError; + } + + /** + * Set the innerError property: Inner error contains more specific + * information. + * + * @param innerError the innerError value to set. + * @return the TextAnalyticsError object itself. + */ + public TextAnalyticsError setInnerError(InnerError innerError) { + this.innerError = innerError; + return this; + } + + /** + * Get the details property: Details about specific errors that led to this + * reported error. + * + * @return the details value. + */ + public List getDetails() { + return this.details; + } + + /** + * Set the details property: Details about specific errors that led to this + * reported error. + * + * @param details the details value to set. + * @return the TextAnalyticsError object itself. + */ + public TextAnalyticsError setDetails(List details) { + this.details = details; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsErrorException.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsErrorException.java new file mode 100644 index 000000000000..25898ef8f43e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/TextAnalyticsErrorException.java @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.implementation.models; + +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpResponse; + +/** + * Exception thrown for an invalid response with TextAnalyticsError information. + */ +public final class TextAnalyticsErrorException extends HttpResponseException { + /** + * Initializes a new instance of the TextAnalyticsErrorException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + */ + public TextAnalyticsErrorException(String message, HttpResponse response) { + super(message, response); + } + + /** + * Initializes a new instance of the TextAnalyticsErrorException class. + * + * @param message the exception message or the response content if a message is not available. + * @param response the HTTP response. + * @param value the deserialized response value. + */ + public TextAnalyticsErrorException(String message, HttpResponse response, TextAnalyticsError value) { + super(message, response, value); + } + + @Override + public TextAnalyticsError getValue() { + return (TextAnalyticsError) super.getValue(); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/package-info.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/package-info.java new file mode 100644 index 000000000000..3e23bae65d86 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/models/package-info.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the data models for TextAnalyticsClient. + * The Text Analytics API is a suite of text analytics web services built with + * best-in-class Microsoft machine learning algorithms. The API can be used to + * analyze unstructured text for tasks such as sentiment analysis, key phrase + * extraction and language detection. No training data is needed to use this + * API; just bring your text data. This API uses advanced natural language + * processing techniques to deliver best in class predictions. Further + * documentation can be found in + * https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview. + */ +package com.azure.ai.textanalytics.implementation.models; diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/package-info.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/package-info.java new file mode 100644 index 000000000000..14f77f46074d --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/implementation/package-info.java @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing the implementations and inner classes for + * TextAnalyticsClient. + * The Text Analytics API is a suite of text analytics web services built with + * best-in-class Microsoft machine learning algorithms. The API can be used to + * analyze unstructured text for tasks such as sentiment analysis, key phrase + * extraction and language detection. No training data is needed to use this + * API; just bring your text data. This API uses advanced natural language + * processing techniques to deliver best in class predictions. Further + * documentation can be found in + * https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview. + */ +package com.azure.ai.textanalytics.implementation; diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/AnalyzeSentimentResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/AnalyzeSentimentResult.java new file mode 100644 index 000000000000..0439470d1120 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/AnalyzeSentimentResult.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The AnalyzeSentimentResult model. + */ +@Immutable +public final class AnalyzeSentimentResult extends DocumentResult { + private final TextSentiment documentSentiment; + private final List sentenceSentiments; + + /** + * Creates a {@code TextSentimentResult} model that describes analyzed sentiment result + * + * @param id unique, non-empty document identifier + * @param textDocumentStatistics text document statistics + * @param error the document error + * @param documentSentiment the document sentiment + * @param sentenceSentiments a list of sentence sentiments + */ + public AnalyzeSentimentResult(String id, TextDocumentStatistics textDocumentStatistics, TextAnalyticsError error, + TextSentiment documentSentiment, List sentenceSentiments) { + super(id, textDocumentStatistics, error); + this.documentSentiment = documentSentiment; + this.sentenceSentiments = sentenceSentiments == null ? new ArrayList<>() : sentenceSentiments; + } + + /** + * Get the document sentiment. + * + * @return the document sentiment + */ + public TextSentiment getDocumentSentiment() { + return documentSentiment; + } + + /** + * Get a list of sentence sentiments. + * + * @return a list of sentence sentiments + */ + public List getSentenceSentiments() { + return sentenceSentiments; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageInput.java new file mode 100644 index 000000000000..bcb753666b0b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageInput.java @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The DetectLanguageInput model. + */ +@Immutable +public final class DetectLanguageInput { + /* + * Unique, non-empty document identifier. + */ + private final String id; + + /* + * The text property. + */ + private final String text; + + /* + * The countryHint property. + */ + private final String countryHint; + + /** + * Creates an input for detect language that will takes {@code id} and {@code text} as required inputs + * + * @param id unique, non-empty document identifier + * @param text the text property + */ + public DetectLanguageInput(String id, String text) { + this(id, text, null); + } + + /** + * Creates an input for detect language that will takes {@code id}, {@code text} and {@code countryHint} + * + * @param id unique, non-empty document identifier + * @param text the text property + * @param countryHint the country hint + */ + public DetectLanguageInput(String id, String text, String countryHint) { + this.id = id; + this.text = text; + this.countryHint = countryHint; + } + + /** + * Get the id property: Unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Get the text property: The text property. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Get the countryHint property: The countryHint property. + * + * @return the countryHint value. + */ + public String getCountryHint() { + return this.countryHint; + } + + @Override + public String toString() { + return String.format("Text = %s, Id = %s, Country Hint = %s", + this.getText(), this.getId(), this.getCountryHint()); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageResult.java new file mode 100644 index 000000000000..9578e6a214d7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectLanguageResult.java @@ -0,0 +1,51 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The DetectedLanguageResult model. + */ +@Immutable +public final class DetectLanguageResult extends DocumentResult { + private final DetectedLanguage primaryLanguage; + private final List detectedLanguages; + + /** + * Create a {@code DetectedLanguageResult} model that describes detected languages result + * + * @param id Unique, non-empty document identifier. + * @param textDocumentStatistics text document statistics + * @param error the document error. + * @param primaryLanguage the detected primary language + * @param detectedLanguages a list of detected language result + */ + public DetectLanguageResult(String id, TextDocumentStatistics textDocumentStatistics, TextAnalyticsError error, + DetectedLanguage primaryLanguage, List detectedLanguages) { + super(id, textDocumentStatistics, error); + this.primaryLanguage = primaryLanguage; + this.detectedLanguages = detectedLanguages == null ? new ArrayList<>() : detectedLanguages; + } + + /** + * Get the detected primary language + * + * @return the detected language + */ + public DetectedLanguage getPrimaryLanguage() { + return primaryLanguage; + } + + /** + * Get the list of detected languages + * + * @return the list of detected language + */ + public List getDetectedLanguages() { + return detectedLanguages; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectedLanguage.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectedLanguage.java new file mode 100644 index 000000000000..6121f3ced526 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DetectedLanguage.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The DetectedLanguage model. + */ +@Immutable +public final class DetectedLanguage { + /* + * Long name of a detected language (e.g. English, French). + */ + private final String name; + + /* + * A two letter representation of the detected language according to the + * ISO 639-1 standard (e.g. en, fr). + */ + private final String iso6391Name; + + /* + * A confidence score between 0 and 1. Scores close to 1 indicate 100% + * certainty that the identified language is true. + */ + private final double score; + + /** + * Creates a {@code DetectedLanguage} model that describes detected language content. + * + * @param name name of a detected language + * @param iso6391Name a two letter representation of the detected language according to the + * ISO 639-1 standard + * @param score a confidence score between 0 and 1 + */ + public DetectedLanguage(String name, String iso6391Name, double score) { + this.name = name; + this.iso6391Name = iso6391Name; + this.score = score; + } + + /** + * Get the name property: Long name of a detected language (e.g. English, + * French). + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Get the iso6391Name property: A two letter representation of the + * detected language according to the ISO 639-1 standard (e.g. en, fr). + * + * @return the iso6391Name value. + */ + public String getIso6391Name() { + return this.iso6391Name; + } + + /** + * Get the score property: A confidence score between 0 and 1. Scores close + * to 1 indicate 100% certainty that the identified language is true. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResult.java new file mode 100644 index 000000000000..ae5c503ac837 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResult.java @@ -0,0 +1,67 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The DocumentResult model. + */ +@Immutable +public class DocumentResult { + private final String id; + private final TextDocumentStatistics textDocumentStatistics; + private final TextAnalyticsError error; + private final boolean isError; + + /** + * Create a {@code DocumentResult} model that maintains document id, information about the document payload, + * and document error + * + * @param id unique, non-empty document identifier + * @param textDocumentStatistics text document statistics + * @param error the document error. + */ + DocumentResult(String id, TextDocumentStatistics textDocumentStatistics, TextAnalyticsError error) { + this.id = id; + this.error = error; + this.isError = error != null; + this.textDocumentStatistics = textDocumentStatistics; + } + + /** + * Get the document id + * + * @return the document id + */ + public String getId() { + return id; + } + + /** + * Get the statistics of the text document + * + * @return the {@link TextDocumentStatistics} statistics of the text document + */ + public TextDocumentStatistics getStatistics() { + return textDocumentStatistics; + } + + /** + * Get the error of text document + * + * @return the error of text document + */ + public TextAnalyticsError getError() { + return error; + } + + /** + * Get the boolean value indicates if the document result is error or not + * + * @return A boolean indicates if the document result is error or not + */ + public boolean isError() { + return isError; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResultCollection.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResultCollection.java new file mode 100644 index 000000000000..0b3082eb8554 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/DocumentResultCollection.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; +import com.azure.core.util.IterableStream; + +/** + * The DocumentResultCollection model. + * + * @param the type of DocumentResultCollection holds + */ +@Immutable +public final class DocumentResultCollection extends IterableStream { + + private final String modelVersion; + private final TextDocumentBatchStatistics statistics; + + /** + * Create a document result collection + * + * @param iterable a generic iterable that takes type T + * @param modelVersion model version + * @param statistics Text batch statistics + */ + public DocumentResultCollection(Iterable iterable, String modelVersion, TextDocumentBatchStatistics statistics) { + super(iterable); + this.modelVersion = modelVersion; + this.statistics = statistics; + } + + /** + * Get model version + * + * @return model version + */ + public String getModelVersion() { + return modelVersion; + } + + /** + * Get statistics of the batch documents + * + * @return the statistics of the batch documents + */ + public TextDocumentBatchStatistics getStatistics() { + return statistics; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ErrorCodeValue.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ErrorCodeValue.java new file mode 100644 index 000000000000..08bf0130510d --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ErrorCodeValue.java @@ -0,0 +1,71 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for ErrorCodeValue. + */ +public enum ErrorCodeValue { + /** + * Enum value invalidRequest. + */ + INVALID_REQUEST("invalidRequest"), + + /** + * Enum value invalidArgument. + */ + INVALID_ARGUMENT("invalidArgument"), + + /** + * Enum value internalServerError. + */ + INTERNAL_SERVER_ERROR("internalServerError"), + + /** + * Enum value serviceUnavailable. + */ + SERVICE_UNAVAILABLE("serviceUnavailable"); + + /** + * The actual serialized value for a ErrorCodeValue instance. + */ + private final String value; + + /** + * Creates a {@code ErrorCodeValue} model that describes error code value, 'invalidRequest', 'invalidArgument', + * 'internalServerError', or 'serviceUnavailable'. + * + * @param value the enum value for the error code value + */ + ErrorCodeValue(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a ErrorCodeValue instance. + * + * @param value the serialized value to parse. + * @return the parsed ErrorCodeValue object, or null if unable to parse. + */ + @JsonCreator + public static ErrorCodeValue fromString(String value) { + ErrorCodeValue[] items = ErrorCodeValue.values(); + for (ErrorCodeValue item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ExtractKeyPhraseResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ExtractKeyPhraseResult.java new file mode 100644 index 000000000000..74ecf96f63f3 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/ExtractKeyPhraseResult.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The ExtractKeyPhraseResult model. + */ +@Immutable +public final class ExtractKeyPhraseResult extends DocumentResult { + private final List keyPhrases; + + /** + * Create a {@code KeyPhraseResult} model that describes extracted key phrases result + * + * @param id Unique, non-empty document identifier. + * @param textDocumentStatistics text document statistics + * @param error the document error. + * @param keyPhrases a list of key phrases string + */ + public ExtractKeyPhraseResult(String id, TextDocumentStatistics textDocumentStatistics, TextAnalyticsError error, + List keyPhrases) { + super(id, textDocumentStatistics, error); + this.keyPhrases = keyPhrases == null ? new ArrayList<>() : keyPhrases; + } + + /** + * Get a list of key phrase string + * + * @return a list of key phrase string + */ + public List getKeyPhrases() { + return keyPhrases; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/InnerError.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/InnerError.java new file mode 100644 index 000000000000..60f5e7452c3a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/InnerError.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The InnerError model. + */ +@Immutable +public final class InnerError { + /* + * Error code. Possible values include: 'invalidParameterValue', + * 'invalidRequestBodyFormat', 'emptyRequest', 'missingInputRecords', + * 'invalidDocument', 'modelVersionIncorrect', 'invalidDocumentBatch', + * 'unsupportedLanguageCode', 'invalidCountryHint' + */ + private final String code; + + /* + * Error message. + */ + private final String message; + + /* + * Error target. + */ + private final String target; + + /* + * Inner error contains more specific information. + */ + private final InnerError innererror; + + /** + * Creates a {@code InnerError} model that describes inner error information. + * + * @param code error code + * @param message error message + * @param target error target + * @param innerError inner error contains more specific information + */ + public InnerError(String code, String message, String target, InnerError innerError) { + this.code = code; + this.message = message; + this.target = target; + this.innererror = innerError; + } + + /** + * Get the code property: Error code. Possible values include: + * 'invalidParameterValue', 'invalidRequestBodyFormat', 'emptyRequest', + * 'missingInputRecords', 'invalidDocument', 'modelVersionIncorrect', + * 'invalidDocumentBatch', 'unsupportedLanguageCode', 'invalidCountryHint'. + * + * @return the code value. + */ + public String getCode() { + return this.code; + } + + /** + * Get the message property: Error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Get the target property: Error target. + * + * @return the target value. + */ + public String getTarget() { + return this.target; + } + + /** + * Get the innererror property: Inner error contains more specific + * information. + * + * @return the innererror value. + */ + public InnerError getInnererror() { + return this.innererror; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntity.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntity.java new file mode 100644 index 000000000000..dad5bb0a088e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntity.java @@ -0,0 +1,121 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.List; + +/** + * The LinkedEntity model. + */ +@Immutable +public final class LinkedEntity { + /* + * Entity Linking formal name. + */ + private final String name; + + /* + * List of instances this entity appears in the text. + */ + private final List linkedEntityMatches; + + /* + * Language used in the data source. + */ + private final String language; + + /* + * Unique identifier of the recognized entity from the data source. + */ + private final String id; + + /* + * URL for the entity's page from the data source. + */ + private final String url; + + /* + * Data source used to extract entity linking, such as Wiki/Bing etc. + */ + private final String dataSource; + + /** + * Creates a {@code LinkedEntity} model that describes linked entity. + * + * @param name entity Linking formal name + * @param linkedEntityMatches list of instances this entity appears in the text + * @param language language used in the data source + * @param id unique identifier of the recognized entity from the data source + * @param url URL for the entity's page from the data source + * @param dataSource data source used to extract entity linking, such as Wiki/Bing etc + */ + public LinkedEntity(String name, List linkedEntityMatches, String language, String id, + String url, String dataSource) { + this.name = name; + this.linkedEntityMatches = linkedEntityMatches; + this.language = language; + this.id = id; + this.url = url; + this.dataSource = dataSource; + } + + /** + * Get the name property: Entity Linking formal name. + * + * @return the name value. + */ + public String getName() { + return this.name; + } + + /** + * Get the linkedEntityMatches property: List of instances this entity appears in the + * text. + * + * @return the linkedEntityMatches value. + */ + public List getLinkedEntityMatches() { + return this.linkedEntityMatches; + } + + /** + * Get the language property: Language used in the data source. + * + * @return the language value. + */ + public String getLanguage() { + return this.language; + } + + /** + * Get the id property: Unique identifier of the recognized entity from the + * data source. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Get the url property: URL for the entity's page from the data source. + * + * @return the url value. + */ + public String getUrl() { + return this.url; + } + + /** + * Get the dataSource property: Data source used to extract entity linking, + * such as Wiki/Bing etc. + * + * @return the dataSource value. + */ + public String getDataSource() { + return this.dataSource; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntityMatch.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntityMatch.java new file mode 100644 index 000000000000..90b8eaad443a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/LinkedEntityMatch.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The LinkedEntityMatch model. + */ +@Immutable +public final class LinkedEntityMatch { + /* + * If a well-known item is recognized, a decimal number denoting the + * confidence level between 0 and 1 will be returned. + */ + private final double score; + + /* + * Entity text as appears in the request. + */ + private final String text; + + /* + * Start position (in Unicode characters) for the entity match text. + */ + private final int offset; + + /* + * Length (in Unicode characters) for the entity match text. + */ + private final int length; + + /** + * Creates a {@code LinkedEntityMatch} model that describes linked entity match. + * + * @param text entity text as appears in the request + * @param score if a well-known item is recognized, a decimal number denoting the + * confidence level between 0 and 1 will be returned + * @param offset start position (in Unicode characters) for the entity match text + * @param length length (in Unicode characters) for the entity match text + */ + public LinkedEntityMatch(String text, double score, int offset, int length) { + this.text = text; + this.score = score; + this.offset = offset; + this.length = length; + } + + /** + * Get the score property: If a well-known item is recognized, a decimal + * number denoting the confidence level between 0 and 1 will be returned. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } + + /** + * Get the text property: Entity text as appears in the request. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Get the offset property: Start position (in Unicode characters) for the + * entity match text. + * + * @return the offset value. + */ + public int getOffset() { + return this.offset; + } + + /** + * Get the length property: Length (in Unicode characters) for the entity + * match text. + * + * @return the length value. + */ + public int getLength() { + return this.length; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/NamedEntity.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/NamedEntity.java new file mode 100644 index 000000000000..83256c55c788 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/NamedEntity.java @@ -0,0 +1,119 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The NamedEntity model. + */ +@Immutable +public final class NamedEntity { + /* + * NamedEntity text as appears in the request. + */ + private final String text; + + /* + * NamedEntity type, such as Person/Location/Org/SSN etc + */ + private final String type; + + /* + * NamedEntity sub type, such as Age/Year/TimeRange etc + */ + private final String subtype; + + /* + * Start position (in Unicode characters) for the entity text. + */ + private final int offset; + + /* + * Length (in Unicode characters) for the entity text. + */ + private final int length; + + /* + * Confidence score between 0 and 1 of the extracted entity. + */ + private final double score; + + /** + * Creates a {@code NamedEntity} model that describes entity. + * + * @param text namedEntity text as appears in the request + * @param type namedEntity type, such as Person/Location/Org/SSN etc + * @param subtype namedEntity sub type, such as Age/Year/TimeRange etc + * @param offset start position (in Unicode characters) for the entity text + * @param length length (in Unicode characters) for the entity text + * @param score confidence score between 0 and 1 of the extracted entity + */ + public NamedEntity(String text, String type, String subtype, int offset, int length, double score) { + this.text = text; + this.type = type; + this.subtype = subtype; + this.offset = offset; + this.length = length; + this.score = score; + } + + /** + * Get the text property: NamedEntity text as appears in the request. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Get the type property: NamedEntity type, such as Person/Location/Org/SSN etc. + * + * @return the type value. + */ + public String getType() { + return this.type; + } + + /** + * Get the subtype property: NamedEntity sub type, such as Age/Year/TimeRange + * etc. + * + * @return the subtype value. + */ + public String getSubtype() { + return this.subtype; + } + + /** + * Get the offset property: Start position (in Unicode characters) for the + * entity text. + * + * @return the offset value. + */ + public int getOffset() { + return this.offset; + } + + /** + * Get the length property: Length (in Unicode characters) for the entity + * text. + * + * @return the length value. + */ + public int getLength() { + return this.length; + } + + /** + * Get the score property: Confidence score between 0 and 1 of the + * extracted entity. + * + * @return the score value. + */ + public double getScore() { + return this.score; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeEntitiesResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeEntitiesResult.java new file mode 100644 index 000000000000..1821f6b9ce57 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeEntitiesResult.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The RecognizeEntitiesResult model. + */ +@Immutable +public final class RecognizeEntitiesResult extends DocumentResult { + private final List namedEntities; + + /** + * Creates a {@code RecognizeEntitiesResult} model that describes recognized entities result + * + * @param id unique, non-empty document identifier + * @param textDocumentStatistics text document statistics + * @param error the document error + * @param namedEntities a list of {@link NamedEntity} + */ + public RecognizeEntitiesResult(String id, TextDocumentStatistics textDocumentStatistics, TextAnalyticsError error, + List namedEntities) { + super(id, textDocumentStatistics, error); + this.namedEntities = namedEntities == null ? new ArrayList<>() : namedEntities; + } + + /** + * Get a list of named entities string + * + * @return a list of {@link NamedEntity} + */ + public List getNamedEntities() { + return namedEntities; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeLinkedEntitiesResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeLinkedEntitiesResult.java new file mode 100644 index 000000000000..adc71b5ccc87 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizeLinkedEntitiesResult.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The RecognizeLinkedEntitiesResult model. + */ +@Immutable +public final class RecognizeLinkedEntitiesResult extends DocumentResult { + private final List linkedEntities; + + /** + * Creates a {@code RecognizeLinkedEntitiesResult} model that describes recognized linked entities result + * + * @param id unique, non-empty document identifier + * @param textDocumentStatistics text document statistics + * @param error the document error + * @param linkedEntities a list of linked entities + */ + public RecognizeLinkedEntitiesResult(String id, TextDocumentStatistics textDocumentStatistics, + TextAnalyticsError error, List linkedEntities) { + super(id, textDocumentStatistics, error); + this.linkedEntities = linkedEntities == null ? new ArrayList<>() : linkedEntities; + } + + /** + * Get a list of linked entities + * + * @return a list of linked entities. + */ + public List getLinkedEntities() { + return linkedEntities; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizePiiEntitiesResult.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizePiiEntitiesResult.java new file mode 100644 index 000000000000..dc07bcf5edf7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/RecognizePiiEntitiesResult.java @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The RecognizePiiEntitiesResult model. + */ +@Immutable +public final class RecognizePiiEntitiesResult extends DocumentResult { + private final List namedEntities; + + /** + * Creates a {@code RecognizePiiEntitiesResult} model that describes recognized entities result + * + * @param id unique, non-empty document identifier + * @param textDocumentStatistics text document statistics + * @param error the document error + * @param namedEntities a list of {@link NamedEntity} + */ + public RecognizePiiEntitiesResult(String id, TextDocumentStatistics textDocumentStatistics, + TextAnalyticsError error, List namedEntities) { + super(id, textDocumentStatistics, error); + this.namedEntities = namedEntities == null ? new ArrayList<>() : namedEntities; + } + + /** + * Get a list of named entities string + * + * @return a list of {@link NamedEntity} + */ + public List getNamedEntities() { + return namedEntities; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsClientOptions.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsClientOptions.java new file mode 100644 index 000000000000..1c8dd804dc04 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsClientOptions.java @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Fluent; + +/** + * The TextAnalyticsClientOptions model. + */ +@Fluent +public final class TextAnalyticsClientOptions { + private String defaultLanguage; + private String defaultCountryHint; + + /** + * Get the default language. + * + * @return the default language + */ + public String getDefaultLanguage() { + return this.defaultLanguage; + } + + /** + * Set the default language. + * + * @param defaultLanguage the default language + * @return the TextAnalyticsClientOptions object itself + */ + public TextAnalyticsClientOptions setDefaultLanguage(String defaultLanguage) { + this.defaultLanguage = defaultLanguage; + return this; + } + + /** + * Get the default country hint. + * + * @return the default country hint + */ + public String getDefaultCountryHint() { + return this.defaultCountryHint; + } + + /** + * Set the default country hint. + * + * @param defaultCountryHint the default country hint + * @return the TextAnalyticsClientOptions object itself + */ + public TextAnalyticsClientOptions setDefaultCountryHint(String defaultCountryHint) { + this.defaultCountryHint = defaultCountryHint; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsError.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsError.java new file mode 100644 index 000000000000..80e42eedc478 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsError.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +import java.util.ArrayList; +import java.util.List; + +/** + * The TextAnalyticsError model. + */ +@Immutable +public final class TextAnalyticsError { + /* + * Error code. Possible values include: 'invalidRequest', + * 'invalidArgument', 'internalServerError', 'serviceUnavailable' + */ + private final ErrorCodeValue code; + + /* + * Error message. + */ + private final String message; + + /* + * Error target. + */ + private final String target; + + /* + * Details about specific errors that led to this reported error. + */ + private final List details; + + /** + * Creates a {@code TextAnalyticsError} model that describes text analytics error. + * + * @param code error code + * @param message error message + * @param target error target + * @param details details about specific errors that led to this reported error + */ + public TextAnalyticsError(ErrorCodeValue code, String message, String target, List details) { + this.code = code; + this.message = message; + this.target = target; + this.details = details == null ? new ArrayList<>() : details; + } + + /** + * Get the code property: Error code. Possible values include: + * 'invalidRequest', 'invalidArgument', 'internalServerError', + * 'serviceUnavailable'. + * + * @return the code value. + */ + public ErrorCodeValue getCode() { + return this.code; + } + + /** + * Get the message property: Error message. + * + * @return the message value. + */ + public String getMessage() { + return this.message; + } + + /** + * Get the target property: Error target. + * + * @return the target value. + */ + public String getTarget() { + return this.target; + } + + /** + * Get the details property: Details about specific errors that led to this + * reported error. + * + * @return the details value. + */ + public List getDetails() { + return this.details; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsRequestOptions.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsRequestOptions.java new file mode 100644 index 000000000000..3aa07c1c411a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextAnalyticsRequestOptions.java @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Fluent; + +/** + * The TextAnalyticsRequestOptions model. + */ +@Fluent +public final class TextAnalyticsRequestOptions { + private String modelVersion; + private boolean showStatistics; + + /** + * Gets the version of the text analytics model used by this operation. + * + * @return the model version + */ + public String getModelVersion() { + return modelVersion; + } + + /** + * Set the model version. This value indicates which model will be used for scoring, e.g. "latest", "2019-10-01". + * If a model-version is not specified, the API will default to the latest, non-preview version. + * + * @param modelVersion the model version + * @return the TextAnalyticsRequestOptions object itself + */ + public TextAnalyticsRequestOptions setModelVersion(String modelVersion) { + this.modelVersion = modelVersion; + return this; + } + + /** + * Get the value of {@code showStatistics} + * + * @return the value of {@code showStatistics} + */ + public boolean showStatistics() { + return showStatistics; + } + + /** + * Set the value of {@code showStatistics} + * + * @param showStatistics if a boolean value was specified in the request this field will contain + * information about the document payload + * @return the TextAnalyticsRequestOptions object itself + */ + public TextAnalyticsRequestOptions setShowStatistics(boolean showStatistics) { + this.showStatistics = showStatistics; + return this; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentBatchStatistics.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentBatchStatistics.java new file mode 100644 index 000000000000..1c1baa5e27a2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentBatchStatistics.java @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * If {@link TextAnalyticsRequestOptions#showStatistics()} is set to {@code true} this class will will contain + * information about the request payload. + */ +@Immutable +public final class TextDocumentBatchStatistics { + /* + * Number of documents submitted in the request. + */ + private final int documentCount; + + /* + * Number of valid documents. This excludes empty, over-size limit or + * non-supported languages documents. + */ + private final int validDocumentCount; + + /* + * Number of invalid documents. This includes empty, over-size limit or + * non-supported languages documents. + */ + private final int erroneousDocumentCount; + + /* + * Number of transactions for the request. + */ + private final long transactionCount; + + /** + * Creates a {@code TextDocumentBatchStatistics} model that describes the statistics of batch text + * + * @param documentCount number of documents submitted in the request + * @param validDocumentCount number of valid documents. This excludes empty, over-size limit or + * non-supported languages documents + * @param erroneousDocumentCount Number of invalid documents. This includes empty, over-size limit or + * non-supported languages documents + * @param transactionCount number of transactions for the request + */ + public TextDocumentBatchStatistics(int documentCount, int validDocumentCount, int erroneousDocumentCount, + long transactionCount) { + this.documentCount = documentCount; + this.validDocumentCount = validDocumentCount; + this.erroneousDocumentCount = erroneousDocumentCount; + this.transactionCount = transactionCount; + } + + /** + * Get the documentCount property: Number of documents submitted in the + * request. + * + * @return the documentCount value. + */ + public int getDocumentCount() { + return this.documentCount; + } + + /** + * Get the validDocumentCount property: Number of valid documents. This + * excludes empty, over-size limit or non-supported languages documents. + * + * @return the validDocumentCount value. + */ + public int getValidDocumentCount() { + return this.validDocumentCount; + } + + /** + * Get the erroneousDocumentCount property: Number of invalid documents. + * This includes empty, over-size limit or non-supported languages + * documents. + * + * @return the erroneousDocumentCount value. + */ + public int getErroneousDocumentCount() { + return this.erroneousDocumentCount; + } + + /** + * Get the transactionCount property: Number of transactions for the + * request. + * + * @return the transactionCount value. + */ + public long getTransactionCount() { + return this.transactionCount; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentInput.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentInput.java new file mode 100644 index 000000000000..d23b3541b232 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentInput.java @@ -0,0 +1,88 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * Contains an input document to be analyzed by the service. + */ +@Immutable +public final class TextDocumentInput { + + /* + * A unique, non-empty document identifier. + */ + private final String id; + + /* + * The input text to process. + */ + private final String text; + + /* + * (Optional) This is the 2 letter ISO 639-1 representation of a language. + * For example, use "en" for English; "es" for Spanish etc. If not set, use + * "en" for English as default. + */ + private final String language; + + /** + * Creates a {@code TextDocumentInput} model that describes the text inputs. + * + * @param id a unique, non-empty document identifier + * @param text the input text to process + */ + public TextDocumentInput(String id, String text) { + this(id, text, null); + } + + /** + * Creates a {@code TextDocumentInput} model that describes the text inputs. + * + * @param id a unique, non-empty document identifier + * @param text the input text to process + * @param language Optional. This is the 2 letter ISO 639-1 representation of a language + */ + public TextDocumentInput(String id, String text, String language) { + this.id = id; + this.text = text; + this.language = language; + } + + /** + * Get the id property: A unique, non-empty document identifier. + * + * @return the id value. + */ + public String getId() { + return this.id; + } + + /** + * Get the text property: The input text to process. + * + * @return the text value. + */ + public String getText() { + return this.text; + } + + /** + * Get the language property: (Optional) This is the 2 letter ISO 639-1 + * representation of a language. For example, use "en" for English; "es" + * for Spanish etc. If not set, use "en" for English as default. + * + * @return the language value. + */ + public String getLanguage() { + return this.language; + } + + @Override + public String toString() { + return String.format("Text = %s, Id = %s, Language = %s", + this.getText(), this.getId(), this.getLanguage()); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentStatistics.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentStatistics.java new file mode 100644 index 000000000000..4b2a00d37263 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextDocumentStatistics.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * If {@link TextAnalyticsRequestOptions#showStatistics()} is set to {@code true} this class will will contain + * information about the document payload. + */ +@Immutable +public final class TextDocumentStatistics { + /* + * Number of text elements recognized in the document. + */ + private final int characterCount; + + /* + * Number of transactions for the document. + */ + private final int transactionCount; + + /** + * Creates a {@code TextDocumentStatistics} model that describes the statistics of text document. + * + * @param characterCount number of text elements recognized in the document + * @param transactionCount number of transactions for the document + */ + public TextDocumentStatistics(int characterCount, int transactionCount) { + this.characterCount = characterCount; + this.transactionCount = transactionCount; + } + + /** + * Get the charactersCount property: Number of text elements recognized in + * the document. + * + * @return the charactersCount value. + */ + public int getCharacterCount() { + return this.characterCount; + } + + /** + * Get the transactionsCount property: Number of transactions for the + * document. + * + * @return the transactionsCount value. + */ + public int getTransactionCount() { + return this.transactionCount; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentiment.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentiment.java new file mode 100644 index 000000000000..969f615f6487 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentiment.java @@ -0,0 +1,93 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.azure.core.annotation.Immutable; + +/** + * The TextSentiment model. + */ +@Immutable +public final class TextSentiment { + private final double negativeScore; + private final double neutralScore; + private final double positiveScore; + private final int length; + private final int offset; + private final TextSentimentClass textSentimentClass; + + /** + * Creates a {@code TextSentiment} model that describes the sentiment analysis of text + * + * @param textSentimentClass text sentiment class of text + * @param negativeScore negative score value, range in between 0 and 1.0 + * @param neutralScore neutral score value, range in between 0 and 1.0 + * @param positiveScore positive score value, range in between 0 and 1.0 + * @param length length of the text + * @param offset the offset from the start of the document + */ + public TextSentiment(TextSentimentClass textSentimentClass, double negativeScore, double neutralScore, + double positiveScore, int length, int offset) { + this.negativeScore = negativeScore; + this.neutralScore = neutralScore; + this.positiveScore = positiveScore; + this.length = length; + this.offset = offset; + this.textSentimentClass = textSentimentClass; + } + + /** + * Get the length of the text by Unicode standard. + * + * @return the length of the text by Unicode standard + */ + public int getLength() { + return length; + } + + /** + * Get the score of negative sentiment. + * + * @return the score of negative sentiment + */ + public double getNegativeScore() { + return negativeScore; + } + + /** + * Get the score of neutral sentiment. + * + * @return the score of neutral sentiment + */ + public double getNeutralScore() { + return neutralScore; + } + + /** + * Get the score of positive sentiment. + * + * @return the score of positive sentiment + */ + public double getPositiveScore() { + return positiveScore; + } + + /** + * Get the offset of the text sentiment. + * + * @return the offset of text sentiment + */ + public int getOffset() { + return offset; + } + + /** + * Get the text sentiment enum class: POSITIVE, NEGATIVE, NEUTRAL, MIXED. + * + * @return the TextSentimentClass + */ + public TextSentimentClass getTextSentimentClass() { + return textSentimentClass; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentimentClass.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentimentClass.java new file mode 100644 index 000000000000..35b1a5a22c74 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/TextSentimentClass.java @@ -0,0 +1,69 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.models; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Defines values for DocumentSentimentValue. + */ +public enum TextSentimentClass { + /** + * Enum value positive. + */ + POSITIVE("positive"), + + /** + * Enum value neutral. + */ + NEUTRAL("neutral"), + + /** + * Enum value negative. + */ + NEGATIVE("negative"), + + /** + * Enum value mixed. + */ + MIXED("mixed"); + + /** + * The actual serialized value for a DocumentSentimentValue instance. + */ + private final String value; + + /** + * Creates a {@code TextSentimentClass} enum model that describes the sentiment class of text + * + * @param value an enum value, could be positive, neutral, negative, or mixed + */ + TextSentimentClass(String value) { + this.value = value; + } + + /** + * Parses a serialized value to a DocumentSentimentValue instance. + * + * @param value the serialized value to parse. + * @return the parsed DocumentSentimentValue object, or null if unable to parse. + */ + @JsonCreator + public static TextSentimentClass fromString(String value) { + TextSentimentClass[] items = TextSentimentClass.values(); + for (TextSentimentClass item : items) { + if (item.toString().equalsIgnoreCase(value)) { + return item; + } + } + return null; + } + + @JsonValue + @Override + public String toString() { + return this.value; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/package-info.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/package-info.java new file mode 100644 index 000000000000..7e1242b3f2c2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/models/package-info.java @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * Package containing classes for TextAnalyticsClient. + * The Text Analytics API is a suite of text analytics web services built with + * best-in-class Microsoft machine learning algorithms. The API can be used to + * analyze unstructured text for tasks such as sentiment analysis, key phrase + * extraction and language detection. No training data is needed to use this + * API; just bring your text data. This API uses advanced natural language + * processing techniques to deliver best in class predictions. Further + * documentation can be found in + * https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview. + */ +package com.azure.ai.textanalytics.models; diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/package-info.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/package-info.java new file mode 100644 index 000000000000..6a74fe88bbba --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +/** + * Package containing classes for creating a {@link com.azure.ai.textanalytics.TextAnalyticsClient} to + * perform operations on Azure Text Analytics + */ +package com.azure.ai.textanalytics; diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/module-info.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/module-info.java new file mode 100644 index 000000000000..bf8e8945476e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/module-info.java @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +module com.azure.ai.textanalytics { + requires transitive com.azure.core; + requires com.fasterxml.jackson.annotation; + + exports com.azure.ai.textanalytics; + exports com.azure.ai.textanalytics.models; + + opens com.azure.ai.textanalytics.implementation to com.fasterxml.jackson.databind; + opens com.azure.ai.textanalytics.models to com.fasterxml.jackson.databind; + opens com.azure.ai.textanalytics.implementation.models to com.fasterxml.jackson.databind; +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/resources/azure-ai-textanalytics.properties b/sdk/textanalytics/azure-ai-textanalytics/src/main/resources/azure-ai-textanalytics.properties new file mode 100644 index 000000000000..ca812989b4f2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/resources/azure-ai-textanalytics.properties @@ -0,0 +1,2 @@ +name=${project.artifactId} +version=${project.version} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md new file mode 100644 index 000000000000..66f00a95a29c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md @@ -0,0 +1,67 @@ + +## Azure Text Analytics client library for Java Samples + +Azure Text Analytics samples are a set of self-contained Java programs that demonstrate interacting with Azure Text Analytics service +using the client library. Each sample focuses on a specific scenario and can be executed independently. + +## Key concepts +Key concepts are explained in detail [here][SDK_README_KEY_CONCEPTS]. + +# Samples Azure Text Analytics APIs +This document describes how to use samples and what is done in each sample. + +## Getting started +Getting started explained in detail [here][SDK_README_GETTING_STARTED]. + +## Examples +The following sections provide several code snippets covering some of the most common configuration service tasks, including: + +- [Detect language in text][sample_hello_world] +- [Recognize entities in text][sample_entities] +- [Recognize personally identifiable information in text][sample_pii_entities] +- [Recognize linked entities in text][sample_linked_entities] +- [Extract key phrases in text][sample_key_phrases] +- [Analyze sentiment in text.][sample_sentiment] + +Batch Samples: +- [Detect language for a batch of documents][sample_language_batch] +- [Recognize entities in a batch of documents][sample_entities_batch] +- [Recognize personally identifiable information in a batch of documents][sample_pii_entities_batch] +- [Recognize linked entities in a batch of documents][sample_linked_entities_batch] +- [Extract key phrases in a batch of documents][sample_key_phrases_batch] +- [Analyze sentiment in a batch of documents][sample_sentiment_batch] + +## Troubleshooting +Troubleshooting steps can be found [here][SDK_README_TROUBLESHOOTING]. + +## Next steps +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. + + +[KEYS_SDK_README]: ../../README.md +[SDK_README_CONTRIBUTING]: ../../README.md#contributing +[SDK_README_GETTING_STARTED]: ../../README.md#getting-started +[SDK_README_TROUBLESHOOTING]: ../../README.md#troubleshooting +[SDK_README_KEY_CONCEPTS]: ../../README.md#key-concepts +[SDK_README_DEPENDENCY]: ../../README.md#adding-the-package-to-your-product +[SDK_README_NEXT_STEPS]: ../../README.md#next-steps + +[sample_hello_world]: java/com/azure/cs/textanalytics/HelloWorld.java +[sample_entities]: java/com/azure/cs/textanalytics/RecognizeEntities.java +[sample_pii_entities]: java/com/azure/cs/textanalytics/RecognizePII.java +[sample_linked_entities]: java/com/azure/cs/textanalytics/RecognizeLinkedEntities.java +[sample_key_phrases]: java/com/azure/cs/textanalytics/RecognizeKeyPhrases.java +[sample_sentiment]: java/com/azure/cs/textanalytics/DetectSentiment.java + +[sample_language_batch]: java/com/azure/cs/textanalytics/batch/DetectLanguageBatchDocuments.java +[sample_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizeEntitiesBatchDocuments.java +[sample_pii_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizePiiBatchDocuments.java +[sample_linked_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java +[sample_key_phrases_batch]: java/com/azure/cs/textanalytics/batch/RecognizeKeyPhrasesBatchDocuments.java +[sample_sentiment_batch]: java/com/azure/cs/textanalytics/batch/DetectSentimentBatchDocuments.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/java/com/azure/ai/textanalytics/AnalyzeSentiment.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java new file mode 100644 index 000000000000..7273908ac285 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; + +import java.util.List; + +/** + * Sample demonstrate how to analyze sentiment of a text input. + */ +public class AnalyzeSentiment { + /** + * Main method to invoke this demo about how to analyze sentiment of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "The hotel was dark and unclean."; + + final AnalyzeSentimentResult sentimentResult = client.analyzeSentiment(text); + + final TextSentiment documentSentiment = sentimentResult.getDocumentSentiment(); + System.out.printf( + "Recognized TextSentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s.%n", + documentSentiment.getTextSentimentClass(), + documentSentiment.getPositiveScore(), + documentSentiment.getNeutralScore(), + documentSentiment.getNegativeScore()); + + final List sentiments = sentimentResult.getSentenceSentiments(); + for (TextSentiment textSentiment : sentiments) { + System.out.printf( + "Recognized Sentence TextSentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s.%n", + textSentiment.getTextSentimentClass(), + textSentiment.getPositiveScore(), + textSentiment.getNeutralScore(), + textSentiment.getNegativeScore()); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java new file mode 100644 index 000000000000..73c1d6cfcf8e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +/** + * Sample demonstrate how to analyze key phrases of a text input. + */ +public class ExtractKeyPhrases { + /** + * Main method to invoke this demo about how to extract key phrases of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "My cat might need to see a veterinarian."; + + for (String keyPhrase : client.extractKeyPhrases(text).getKeyPhrases()) { + System.out.printf("Recognized Phrases: %s.%n", keyPhrase); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorld.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorld.java new file mode 100644 index 000000000000..84e172062581 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorld.java @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; + +import java.util.List; + +/** + * Sample demonstrate how to detect language of a text input. + */ +public class HelloWorld { + /** + * Main method to invoke this demo about how to detect language of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "hello world"; + + final DetectLanguageResult detectLanguageResult = client.detectLanguage(text, "US"); + final DetectedLanguage detectedDocumentLanguage = detectLanguageResult.getPrimaryLanguage(); + System.out.printf("Detected Primary Language: %s, ISO 6391 Name: %s, Score: %s.%n", + detectedDocumentLanguage.getName(), + detectedDocumentLanguage.getIso6391Name(), + detectedDocumentLanguage.getScore()); + + final List detectedLanguages = detectLanguageResult.getDetectedLanguages(); + for (DetectedLanguage detectedLanguage : detectedLanguages) { + System.out.printf("Other detected languages: %s, ISO 6391 Name: %s, Score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorldAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorldAsync.java new file mode 100644 index 000000000000..dab4ab8b0afc --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/HelloWorldAsync.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectedLanguage; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrate how to detect language of a text input in asynchronously call. + */ +public class HelloWorldAsync { + /** + * Main method to invoke this demo about how to detect language of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "hello world"; + + client.detectLanguage(text).subscribe( + result -> { + final DetectedLanguage primaryLanguage = result.getPrimaryLanguage(); + System.out.printf("Detected Language: %s, ISO 6391 Name: %s, Score: %s.%n", + primaryLanguage.getName(), primaryLanguage.getIso6391Name(), primaryLanguage.getScore()); + }, + error -> System.err.println("There was an error detecting language of the text." + error), + () -> System.out.println("Language detected.")); + + // The .subscribe() creation and assignment is not a blocking call. For the purpose of this example, we sleep + // the thread so the program does not end before the send operation is complete. Using .block() instead of + // .subscribe() will turn this into a synchronous call. + try { + TimeUnit.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java new file mode 100644 index 000000000000..bda25d0026e0 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.NamedEntity; + +/** + * Sample demonstrate how to recognize entities of a text input. + */ +public class RecognizeEntities { + /** + * Main method to invoke this demo about how to recognize entities of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "Satya Nadella is the CEO of Microsoft"; + + for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java new file mode 100644 index 000000000000..20f9f166638f --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java @@ -0,0 +1,35 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.LinkedEntity; + +/** + * Sample demonstrate how to recognize linked entities of a text input. + */ +public class RecognizeLinkedEntities { + /** + * Main method to invoke this demo about how to recognize linked entities of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "Old Faithful is a geyser at Yellowstone Park."; + + for (LinkedEntity linkedEntity : client.recognizeLinkedEntities(text).getLinkedEntities()) { + System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s.%n", + linkedEntity.getName(), + linkedEntity.getUrl(), + linkedEntity.getDataSource()); + } + } + +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java new file mode 100644 index 000000000000..5470ffdc6ef0 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.NamedEntity; + +/** + * Sample demonstrate how to recognize PII(Personally Identifiable Information) entities of a text input. + */ +public class RecognizePii { + /** + * Main method to invoke this demo about how to analyze sentiment of a text input. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "My SSN is 555-55-5555"; + + for (NamedEntity entity : client.recognizePiiEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized PII Entity: %s, Entity Type: %s, Entity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getScore()); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientJavaDocCodeSnippets.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..9be79bf295fc --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientJavaDocCodeSnippets.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +/** + * Code snippet for {@link TextAnalyticsAsyncClient} + */ +public class TextAnalyticsAsyncClientJavaDocCodeSnippets { + private static final String SUBSCRIPTION_KEY = null; + private static final String ENDPOINT = null; + + /** + * Code snippet for creating a {@link TextAnalyticsAsyncClient} + * + * @return The TextAnalyticsAsyncClient object + */ + public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { + // BEGIN: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.instantiation + TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildAsyncClient(); + // END: com.azure.ai.textanalytics.TextAnalyticsAsyncClient.instantiation + return textAnalyticsAsyncClient; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsClientJavaDocCodeSnippets.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsClientJavaDocCodeSnippets.java new file mode 100644 index 000000000000..268575bc9349 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/TextAnalyticsClientJavaDocCodeSnippets.java @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +/** + * Code snippet for {@link TextAnalyticsClient} + */ +public class TextAnalyticsClientJavaDocCodeSnippets { + private static final String SUBSCRIPTION_KEY = null; + private static final String ENDPOINT = null; + + /** + * Code snippet for creating a {@link TextAnalyticsClient} + * + * @return The TextAnalyticsClient object. + */ + public TextAnalyticsClient createTextAnalyticsClient() { + // BEGIN: com.azure.ai.textanalytics.TextAnalyticsClient.instantiation + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + // END: com.azure.ai.textanalytics.TextAnalyticsClient.instantiation + return textAnalyticsClient; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java new file mode 100644 index 000000000000..d6cba7bfbc77 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to analyze sentiment of a batch of text inputs. + */ +public class AnalyzeSentimentBatchDocuments { + /** + * Main method to invoke this demo about how to analyze sentiment of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "en"), + new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.", "en") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + DocumentResultCollection detectedBatchResult = client.analyzeBatchSentimentWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detecting sentiment for each of document from a batch of documents + for (AnalyzeSentimentResult analyzeSentimentResult : detectedBatchResult) { + final TextSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); + System.out.printf("Recognized document sentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s. Length of sentence: %s, Offset of sentence: %s.%n", + documentSentiment.getTextSentimentClass(), + documentSentiment.getPositiveScore(), + documentSentiment.getNeutralScore(), + documentSentiment.getNegativeScore(), + documentSentiment.getLength(), + documentSentiment.getOffset()); + for (TextSentiment sentenceSentiment : analyzeSentimentResult.getSentenceSentiments()) { + System.out.printf("Recognized sentence sentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s. Length of sentence: %s, Offset of sentence: %s.%n", + sentenceSentiment.getTextSentimentClass(), + sentenceSentiment.getPositiveScore(), + sentenceSentiment.getNeutralScore(), + sentenceSentiment.getNegativeScore(), + sentenceSentiment.getLength(), + sentenceSentiment.getOffset()); + } + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java new file mode 100644 index 000000000000..fbf76134e5f7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java @@ -0,0 +1,68 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to detect language of a batch of text inputs. + */ +public class DetectLanguageBatchDocuments { + /** + * Main method to invoke this demo about how to detect language of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new DetectLanguageInput("1", "This is written in English.", "en"), + new DetectLanguageInput("2", "Este es un document escrito en Español.", "es") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + final DocumentResultCollection detectedBatchResult = client.detectBatchLanguagesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("Batch statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detecting languages for a document from a batch of documents + for (DetectLanguageResult detectLanguageResult : detectedBatchResult) { + final DetectedLanguage detectedPrimaryLanguage = detectLanguageResult.getPrimaryLanguage(); + System.out.printf("Detected primary Language for Document: %s, %s, ISO 6391 Name: %s, Score: %s.%n", + detectLanguageResult.getId(), + detectedPrimaryLanguage.getName(), + detectedPrimaryLanguage.getIso6391Name(), + detectedPrimaryLanguage.getScore()); + for (DetectedLanguage detectedLanguage : detectLanguageResult.getDetectedLanguages()) { + System.out.printf("Other detected Languages: %s, ISO 6391 Name: %s, Score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java new file mode 100644 index 000000000000..4ba8ed1233da --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to analyze key phrases of a batch of text inputs. + */ +public class ExtractKeyPhrasesBatchDocuments { + /** + * Main method to invoke this demo about how to extract key phrases of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "My cat might need to see a veterinarian.", "en"), + new TextDocumentInput("2", "The pitot tube is used to measure airspeed.", "en") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + final DocumentResultCollection detectedBatchResult = client.extractBatchKeyPhrasesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detecting key phrase for each of document from a batch of documents + for (ExtractKeyPhraseResult extractKeyPhraseResult : detectedBatchResult) { + for (String keyPhrases : extractKeyPhraseResult.getKeyPhrases()) { + System.out.printf("Recognized Phrases: %s.%n", keyPhrases); + } + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java new file mode 100644 index 000000000000..f9540371aa8b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java @@ -0,0 +1,65 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to recognize entities of a batch of text inputs. + */ +public class RecognizeEntitiesBatchDocuments { + /** + * Main method to invoke this demo about how to recognize entities of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "Satya Nadella is the CEO of Microsoft.", "en"), + new TextDocumentInput("2", "Elon Musk is the CEO of SpaceX and Tesla.", "en") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + final DocumentResultCollection detectedBatchResult = + client.recognizeBatchEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + for (RecognizeEntitiesResult recognizeEntitiesResult : detectedBatchResult) { + for (NamedEntity entity : recognizeEntitiesResult.getNamedEntities()) { + System.out.printf("Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java new file mode 100644 index 000000000000..b072bc018669 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java @@ -0,0 +1,60 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to recognize linked entities of a batch of text inputs. + */ +public class RecognizeLinkedEntitiesBatchDocuments { + /** + * Main method to invoke this demo about how to recognize linked entities of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), + new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + final DocumentResultCollection detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detecting linked entities from a batch of documents + for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : detectedBatchResult) { + for (LinkedEntity linkedEntity : linkedEntityDocumentResult.getLinkedEntities()) { + System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s%n", + linkedEntity.getName(), linkedEntity.getUrl(), linkedEntity.getDataSource()); + } + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java new file mode 100644 index 000000000000..4986f308012e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.core.util.Context; + +import java.util.Arrays; +import java.util.List; + +/** + * Sample demonstrate how to recognize PII(Personally Identifiable Information) entities of a text input. + */ +public class RecognizePiiBatchDocuments { + /** + * Main method to invoke this demo about how to recognize PII entities of a batch of text inputs. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("subscription-key") + .endpoint("https://servicename.cognitiveservices.azure.com/") + .buildClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "My SSN is 555-55-5555", "en"), + new TextDocumentInput("2", "Visa card 4111 1111 1111 1111", "en") + ); + + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + final DocumentResultCollection detectedBatchResult = client.recognizeBatchPiiEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detecting pii entities from a batch of documents + detectedBatchResult.forEach(piiEntityDocumentResult -> + piiEntityDocumentResult.getNamedEntities().forEach(entity -> + System.out.printf("Recognized Personal Identifiable Info NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()))); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java new file mode 100644 index 000000000000..5af526254fbe --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java @@ -0,0 +1,472 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.ErrorCodeValue; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.LinkedEntityMatch; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsError; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.TextSentimentClass; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.util.Context; +import org.junit.jupiter.api.Test; +import reactor.test.StepVerifier; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class TextAnalyticsAsyncClientTest extends TextAnalyticsClientTestBase { + private TextAnalyticsAsyncClient client; + + @Override + protected void beforeTest() { + client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() + .endpoint(getEndpoint()) + .pipeline(httpPipeline) + .buildAsyncClient()); + } + + // Detected Languages + + /** + * Verify that we can get statistics on the collection result when given a batch input with options. + */ + @Test + public void detectLanguagesBatchInputShowStatistics() { + detectLanguageShowStatisticsRunner((inputs, options) -> { + StepVerifier.create(client.detectBatchLanguagesWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)) + .verifyComplete(); + }); + } + + /** + * Test Detect batch input languages. + */ + @Test + public void detectLanguagesBatchInput() { + detectLanguageRunner((inputs) -> { + StepVerifier.create(client.detectBatchLanguages(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)) + .verifyComplete(); + }); + } + + /** + * Test Detect batch languages for List of String input with country Hint. + */ + @Test + public void detectLanguagesBatchListCountryHint() { + detectLanguagesCountryHintRunner((inputs, countryHint) -> { + StepVerifier.create(client.detectLanguagesWithResponse(inputs, countryHint)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)) + .verifyComplete(); + }); + } + + /** + * Test Detect batch languages for List of String input. + */ + @Test + public void detectLanguagesBatchStringInput() { + detectLanguageStringInputRunner((inputs) -> { + StepVerifier.create(client.detectLanguages(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)) + .verifyComplete(); + }); + } + + /** + * Verifies that a single DetectLanguageResult is returned for a text input to detectLanguages. + */ + @Test + public void detectSingleTextLanguage() { + DetectedLanguage primaryLanguage = new DetectedLanguage("English", "en", 1.0); + List expectedLanguageList = Arrays.asList(primaryLanguage); + StepVerifier.create(client.detectLanguage("This is a test English Text")) + .assertNext(response -> validateDetectedLanguages(expectedLanguageList, response.getDetectedLanguages())) + .verifyComplete(); + } + + /** + * Verifies that an error document is returned for a text input with invalid country hint. + *

+ * TODO: update error Model. #6559 + */ + @Test + public void detectLanguageInvalidCountryHint() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid Country Hint.", null, null); + StepVerifier.create(client.detectLanguageWithResponse("Este es un document escrito en Español.", "en")) + .assertNext(response -> validateErrorDocument(expectedError, response.getValue().getError())) + .verifyComplete(); + } + + /** + * Verifies that an error document is returned for a empty text input. + */ + @Test + public void detectLanguageEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.detectLanguage("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())) + .verifyComplete(); + } + + /** + * Verifies that detectLanguage returns an "UNKNOWN" result when faulty text is passed. + */ + @Test + public void detectLanguageFaultyText() { + StepVerifier.create(client.detectLanguage("!@#%%")) + .assertNext(response -> assertEquals(response.getPrimaryLanguage().getIso6391Name(), "(Unknown)")) + .verifyComplete(); + } + + /** + * Verifies that a Bad request exception is returned for input documents with same ids. + */ + @Test + public void detectLanguageDuplicateIdInput() { + detectLanguageDuplicateIdRunner((inputs, options) -> { + StepVerifier.create(client.detectBatchLanguagesWithResponse(inputs, options, Context.NONE)) + .verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 400)); + }); + } + + // Entities + @Test + public void recognizeEntitiesForTextInput() { + NamedEntity namedEntity1 = new NamedEntity("Seattle", "Location", null, 26, 7, 0.80624294281005859); + NamedEntity namedEntity2 = new NamedEntity("last week", "DateTime", "DateRange", 34, 9, 0.8); + RecognizeEntitiesResult recognizeEntitiesResultList = new RecognizeEntitiesResult("0", null, null, Arrays.asList(namedEntity1, namedEntity2)); + StepVerifier.create(client.recognizeEntities("I had a wonderful trip to Seattle last week.")) + .assertNext(response -> validateNamedEntities(recognizeEntitiesResultList.getNamedEntities(), response.getNamedEntities())) + .verifyComplete(); + } + + @Test + public void recognizeEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.recognizeEntities("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())) + .verifyComplete(); + } + + @Override + public void recognizeEntitiesForFaultyText() { + // TODO: (savaity) confirm with service team this returns no error-ed document, no exception but empty documents and error list. + StepVerifier.create(client.recognizeEntities("!@#%%")) + .assertNext(response -> assertEquals(response.getNamedEntities().size(), 0)) + .verifyComplete(); + } + + @Test + public void recognizeEntitiesForBatchInput() { + recognizeBatchNamedEntityRunner((inputs) -> { + StepVerifier.create(client.recognizeBatchEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeEntitiesForBatchInputShowStatistics() { + recognizeBatchNamedEntitiesShowStatsRunner((inputs, options) -> { + StepVerifier.create(client.recognizeBatchEntitiesWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeEntitiesForBatchStringInput() { + recognizeNamedEntityStringInputRunner((inputs) -> { + StepVerifier.create(client.recognizeEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeEntitiesForListLanguageHint() { + recognizeNamedEntitiesLanguageHintRunner((inputs, language) -> { + StepVerifier.create(client.recognizeEntitiesWithResponse(inputs, language)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + // Linked Entities + @Test + public void recognizeLinkedEntitiesForTextInput() { + LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("Seattle", 0.11472424095537814, 7, 26); + LinkedEntity linkedEntity1 = new LinkedEntity("Seattle", Collections.singletonList(linkedEntityMatch1), "en", "Seattle", "https://en.wikipedia.org/wiki/Seattle", "Wikipedia"); + RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResultList = new RecognizeLinkedEntitiesResult("0", null, null, Collections.singletonList(linkedEntity1)); + + StepVerifier.create(client.recognizeLinkedEntities("I had a wonderful trip to Seattle last week.")) + .assertNext(response -> validateLinkedEntities(recognizeLinkedEntitiesResultList.getLinkedEntities(), response.getLinkedEntities())) + .verifyComplete(); + } + + @Test + public void recognizeLinkedEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.recognizeLinkedEntities("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())) + .verifyComplete(); + } + + @Test + public void recognizeLinkedEntitiesForFaultyText() { + StepVerifier.create(client.recognizeLinkedEntities("!@#%%")) + .assertNext(response -> assertEquals(response.getLinkedEntities().size(), 0)) + .verifyComplete(); + } + + @Test + public void recognizeLinkedEntitiesForBatchInput() { + recognizeBatchLinkedEntityRunner((inputs) -> { + StepVerifier.create(client.recognizeBatchLinkedEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeLinkedEntitiesForBatchInputShowStatistics() { + recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> { + StepVerifier.create(client.recognizeBatchLinkedEntitiesWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeLinkedEntitiesForBatchStringInput() { + recognizeLinkedStringInputRunner((inputs) -> { + StepVerifier.create(client.recognizeLinkedEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizeLinkedEntitiesForListLanguageHint() { + recognizeLinkedLanguageHintRunner((inputs, language) -> { + StepVerifier.create(client.recognizeLinkedEntitiesWithResponse(inputs, language)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchLinkedEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + // Pii Entities + @Test + public void recognizePiiEntitiesForTextInput() { + NamedEntity namedEntity1 = new NamedEntity("859-98-0987", "U.S. Social Security Number (SSN)", "", 28, 11, 0.65); + RecognizeEntitiesResult recognizeEntitiesResultList = new RecognizeEntitiesResult("0", null, null, Collections.singletonList(namedEntity1)); + + StepVerifier.create(client.recognizePiiEntities("Microsoft employee with ssn 859-98-0987 is using our awesome API's.")) + .assertNext(response -> validateNamedEntities(recognizeEntitiesResultList.getNamedEntities(), response.getNamedEntities())) + .verifyComplete(); + } + + @Test + public void recognizePiiEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.recognizePiiEntities("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())) + .verifyComplete(); + } + + @Override + public void recognizePiiEntitiesForFaultyText() { + // TODO: (savaity) confirm with service team this returns no error-ed document, no exception but empty documents and error list. + StepVerifier.create(client.recognizePiiEntities("!@#%%")) + .assertNext(response -> assertEquals(response.getNamedEntities().size(), 0)) + .verifyComplete(); + } + + @Test + public void recognizePiiEntitiesForBatchInput() { + recognizeBatchPiiRunner((inputs) -> { + StepVerifier.create(client.recognizeBatchPiiEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizePiiEntitiesForBatchInputShowStatistics() { + recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> { + StepVerifier.create(client.recognizeBatchPiiEntitiesWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizePiiEntitiesForBatchStringInput() { + recognizePiiStringInputRunner((inputs) -> { + StepVerifier.create(client.recognizePiiEntities(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + @Test + public void recognizePiiEntitiesForListLanguageHint() { + recognizePiiLanguageHintRunner((inputs, language) -> { + StepVerifier.create(client.recognizePiiEntitiesWithResponse(inputs, language)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)) + .verifyComplete(); + }); + } + + + // Key Phrases + @Test + public void extractKeyPhrasesForTextInput() { + List keyPhrasesList1 = Arrays.asList("monde"); + StepVerifier.create(client.extractKeyPhrasesWithResponse("Bonjour tout le monde.", "fr")) + .assertNext(response -> validateKeyPhrases(keyPhrasesList1, response.getValue().getKeyPhrases())) + .verifyComplete(); + } + + @Test + public void extractKeyPhrasesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.extractKeyPhrases("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())) + .verifyComplete(); + } + + @Test + public void extractKeyPhrasesForFaultyText() { + StepVerifier.create(client.extractKeyPhrases("!@#%%")) + .assertNext(response -> assertEquals(response.getKeyPhrases().size(), 0)) + .verifyComplete(); + } + + @Test + public void extractKeyPhrasesForBatchInput() { + extractBatchKeyPhrasesRunner((inputs) -> { + StepVerifier.create(client.extractBatchKeyPhrases(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)) + .verifyComplete(); + }); + + } + + @Test + public void extractKeyPhrasesForBatchInputShowStatistics() { + extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> { + StepVerifier.create(client.extractBatchKeyPhrasesWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)) + .verifyComplete(); + }); + } + + @Test + public void extractKeyPhrasesForBatchStringInput() { + extractKeyPhrasesStringInputRunner((inputs) -> { + StepVerifier.create(client.extractKeyPhrases(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)) + .verifyComplete(); + }); + } + + @Test + public void extractKeyPhrasesForListLanguageHint() { + extractKeyPhrasesLanguageHintRunner((inputs, language) -> { + StepVerifier.create(client.extractKeyPhrasesWithResponse(inputs, language)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)) + .verifyComplete(); + }); + } + + // Sentiment + /** + * Test analyzing sentiment for a string input. + */ + @Test + public void analyseSentimentForTextInput() { + final TextSentiment expectedDocumentSentiment = new TextSentiment(TextSentimentClass.MIXED, 0.1, 0.5, 0.4, 66, 0); + final List expectedSentenceSentiments = Arrays.asList( + new TextSentiment(TextSentimentClass.NEGATIVE, 0.99, 0.005, 0.005, 31, 0), + new TextSentiment(TextSentimentClass.POSITIVE, 0.005, 0.005, 0.99, 35, 32)); + + StepVerifier + .create(client.analyzeSentiment("The hotel was dark and unclean. The restaurant had amazing gnocchi.")) + .assertNext(response -> { + validateAnalysedSentiment(expectedDocumentSentiment, response.getDocumentSentiment()); + validateAnalysedSentenceSentiment(expectedSentenceSentiments, response.getSentenceSentiments()); + }).verifyComplete(); + } + + /** + * Verifies that an error document is returned for a empty text input. + */ + @Test + public void analyseSentimentForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + StepVerifier.create(client.analyzeSentiment("")) + .assertNext(response -> validateErrorDocument(expectedError, response.getError())).verifyComplete(); + } + + public void analyseSentimentForFaultyText() { + // TODO (shawn): add this case later + } + + /** + * Test analyzing sentiment for a list of string input. + */ + @Test + public void analyseSentimentForBatchStringInput() { + analyseSentimentStringInputRunner(inputs -> + StepVerifier.create(client.analyzeSentiment(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)) + .verifyComplete()); + } + + /** + * Test analyzing sentiment for a list of string input with language hint. + */ + @Test + public void analyseSentimentForListLanguageHint() { + analyseSentimentLanguageHintRunner((inputs, language) -> + StepVerifier.create(client.analyzeSentimentWithResponse(inputs, language)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)) + .verifyComplete()); + } + + /** + * Test analyzing sentiment for batch input. + */ + @Test + public void analyseSentimentForBatchInput() { + analyseBatchSentimentRunner(inputs -> + StepVerifier.create(client.analyzeBatchSentiment(inputs)) + .assertNext(response -> validateBatchResult(response, getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)) + .verifyComplete()); + } + + /** + * Verify that we can get statistics on the collection result when given a batch input with options. + */ + @Test + public void analyseSentimentForBatchInputShowStatistics() { + analyseBatchSentimentShowStatsRunner((inputs, options) -> + StepVerifier.create(client.analyzeBatchSentimentWithResponse(inputs, options)) + .assertNext(response -> validateBatchResult(response.getValue(), getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)) + .verifyComplete()); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java new file mode 100644 index 000000000000..ff74fe546f81 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java @@ -0,0 +1,392 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.ErrorCodeValue; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.LinkedEntityMatch; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsError; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.util.Context; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { + + private TextAnalyticsClient client; + + @Test + protected void beforeTest() { + client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() + .endpoint(getEndpoint()) + .pipeline(httpPipeline) + .buildClient()); + } + + /** + * Verify that we can get statistics on the collection result when given a batch input with options. + */ + @Test + public void detectLanguagesBatchInputShowStatistics() { + detectLanguageShowStatisticsRunner((inputs, options) -> validateBatchResult( + client.detectBatchLanguagesWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)); + } + + /** + * Test Detect batch input languages. + */ + @Test + public void detectLanguagesBatchInput() { + detectLanguageRunner((inputs) -> validateBatchResult(client.detectBatchLanguages(inputs), + getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)); + } + + /** + * Test Detect batch languages for List of String input with country Hint. + */ + @Test + public void detectLanguagesBatchListCountryHint() { + detectLanguagesCountryHintRunner((inputs, countryHint) -> validateBatchResult( + client.detectLanguagesWithResponse(inputs, countryHint, Context.NONE).getValue(), + getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)); + } + + /** + * Test Detect batch languages for List of String input. + */ + @Test + public void detectLanguagesBatchStringInput() { + detectLanguageStringInputRunner((inputs) -> validateBatchResult(client.detectLanguages(inputs), + getExpectedBatchDetectedLanguages(), TestEndpoint.LANGUAGE)); + } + + /** + * Verifies that a single DetectLanguageResult is returned for a text input to detectLanguages. + */ + @Test + public void detectSingleTextLanguage() { + DetectedLanguage primaryLanguage = new DetectedLanguage("English", "en", 1.0); + List expectedLanguageList = Arrays.asList(primaryLanguage); + validateDetectedLanguages( + client.detectLanguage("This is a test English Text").getDetectedLanguages(), expectedLanguageList); + } + + /** + * Verifies that an exception is thrown when null text is passed. + */ + @Test + public void detectLanguagesNullInput() { + assertThrows(NullPointerException.class, () -> client.detectBatchLanguagesWithResponse(null, null, + Context.NONE).getValue()); + } + + /** + * Verifies that the error result is returned when empty text is passed. + */ + @Test + public void detectLanguageEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + DetectLanguageResult result = client.detectLanguage(""); + assertNotNull(result.getError()); + validateErrorDocument(expectedError, result.getError()); + } + + /** + * Verifies that detectLanguage returns an "UNKNOWN" result when faulty text is passed. + */ + @Test + public void detectLanguageFaultyText() { + DetectLanguageResult result = client.detectLanguage("!@#%%"); + assertEquals(result.getPrimaryLanguage().getIso6391Name(), "(Unknown)"); + } + + /** + * Verifies that an error document is returned for a text input with invalid country hint. + *

+ * TODO: update error Model. #6559 + */ + @Test + public void detectLanguageInvalidCountryHint() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid Country Hint.", null, null); + validateErrorDocument(client.detectLanguage("Este es un document escrito en Español.", "en") + .getError(), expectedError); + } + + /** + * Verifies that a Bad request exception is returned for input documents with same ids. + */ + @Test + public void detectLanguageDuplicateIdInput() { + detectLanguageDuplicateIdRunner((inputs, options) -> { + assertRestException(() -> client.detectBatchLanguagesWithResponse(inputs, options, Context.NONE), + HttpResponseException.class, 400); + }); + } + + @Test + public void recognizeEntitiesForTextInput() { + NamedEntity namedEntity1 = new NamedEntity("Seattle", "Location", null, 26, 7, 0.80624294281005859); + NamedEntity namedEntity2 = new NamedEntity("last week", "DateTime", "DateRange", 34, 9, 0.8); + RecognizeEntitiesResult recognizeEntitiesResultList = new RecognizeEntitiesResult("0", null, null, Arrays.asList(namedEntity1, namedEntity2)); + validateNamedEntities(recognizeEntitiesResultList.getNamedEntities(), + client.recognizeEntities("I had a wonderful trip to Seattle last week.").getNamedEntities()); + } + + @Test + public void recognizeEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + validateErrorDocument(expectedError, client.recognizeEntities("").getError()); + } + + @Test + public void recognizeEntitiesForFaultyText() { + // TODO: (savaity) confirm with service team. + assertEquals(client.recognizeEntities("!@#%%").getNamedEntities().size(), 0); + } + + @Test + public void recognizeEntitiesForBatchInput() { + recognizeBatchNamedEntityRunner((inputs) -> validateBatchResult(client.recognizeBatchEntities(inputs), + getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizeEntitiesForBatchInputShowStatistics() { + recognizeBatchNamedEntitiesShowStatsRunner((inputs, options) -> + validateBatchResult(client.recognizeBatchEntitiesWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizePiiEntitiesForTextInput() { + NamedEntity namedEntity1 = new NamedEntity("859-98-0987", "U.S. Social Security Number (SSN)", "", 28, 11, 0.65); + RecognizeEntitiesResult recognizeEntitiesResultList = new RecognizeEntitiesResult("0", null, null, Collections.singletonList(namedEntity1)); + validateNamedEntities(recognizeEntitiesResultList.getNamedEntities(), + client.recognizePiiEntities("Microsoft employee with ssn 859-98-0987 is using our awesome API's.").getNamedEntities()); + } + + @Test + public void recognizePiiEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + validateErrorDocument(expectedError, client.recognizePiiEntities("").getError()); + } + + @Test + public void recognizePiiEntitiesForFaultyText() { + assertEquals(client.recognizePiiEntities("!@#%%").getNamedEntities().size(), 0); + } + + @Test + public void recognizePiiEntitiesForBatchInput() { + recognizeBatchPiiRunner((inputs) -> + validateBatchResult(client.recognizeBatchPiiEntities(inputs), + getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizePiiEntitiesForBatchInputShowStatistics() { + recognizeBatchPiiEntitiesShowStatsRunner((inputs, options) -> + validateBatchResult(client.recognizeBatchPiiEntitiesWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizePiiEntitiesForBatchStringInput() { + recognizePiiStringInputRunner((inputs) -> + validateBatchResult(client.recognizePiiEntities(inputs), + getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizePiiEntitiesForListLanguageHint() { + recognizePiiLanguageHintRunner((inputs, language) -> + validateBatchResult(client.recognizePiiEntitiesWithResponse(inputs, language, Context.NONE).getValue(), + getExpectedBatchPiiEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizeEntitiesForBatchStringInput() { + recognizeNamedEntityStringInputRunner((inputs) -> + validateBatchResult(client.recognizeEntities(inputs), + getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizeEntitiesForListLanguageHint() { + recognizeNamedEntitiesLanguageHintRunner((inputs, language) -> + validateBatchResult(client.recognizeEntitiesWithResponse(inputs, language, Context.NONE).getValue(), + getExpectedBatchNamedEntities(), TestEndpoint.NAMED_ENTITY)); + } + + @Test + public void recognizeLinkedEntitiesForTextInput() { + LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("Seattle", 0.11472424095537814, 7, 26); + LinkedEntity linkedEntity1 = new LinkedEntity("Seattle", Collections.singletonList(linkedEntityMatch1), "en", "Seattle", "https://en.wikipedia.org/wiki/Seattle", "Wikipedia"); + RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResultList = new RecognizeLinkedEntitiesResult("0", null, null, Collections.singletonList(linkedEntity1)); + + validateLinkedEntities(recognizeLinkedEntitiesResultList.getLinkedEntities(), client.recognizeLinkedEntities("I had a wonderful trip to Seattle last week.").getLinkedEntities()); + } + + @Test + public void recognizeLinkedEntitiesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + validateErrorDocument(expectedError, client.recognizeLinkedEntities("").getError()); + } + + @Test + public void recognizeLinkedEntitiesForFaultyText() { + assertEquals(client.recognizeLinkedEntities("!@#%%").getLinkedEntities().size(), 0); + } + + @Test + public void recognizeLinkedEntitiesForBatchInput() { + recognizeBatchLinkedEntityRunner((inputs) -> + validateBatchResult(client.recognizeBatchLinkedEntities(inputs), + getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)); + } + + @Test + public void recognizeLinkedEntitiesForBatchInputShowStatistics() { + recognizeBatchLinkedEntitiesShowStatsRunner((inputs, options) -> + validateBatchResult(client.recognizeBatchLinkedEntitiesWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)); + } + + @Test + public void recognizeLinkedEntitiesForBatchStringInput() { + recognizeLinkedStringInputRunner((inputs) -> + validateBatchResult(client.recognizeLinkedEntities(inputs), + getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)); + } + + @Test + public void recognizeLinkedEntitiesForListLanguageHint() { + recognizeLinkedLanguageHintRunner((inputs, language) -> + validateBatchResult(client.recognizeLinkedEntitiesWithResponse(inputs, language, Context.NONE).getValue(), + getExpectedBatchLinkedEntities(), TestEndpoint.LINKED_ENTITY)); + } + + @Test + public void extractKeyPhrasesForTextInput() { + List keyPhrasesList1 = Arrays.asList("monde"); + validateKeyPhrases(keyPhrasesList1, + client.extractKeyPhrasesWithResponse("Bonjour tout le monde.", "fr", Context.NONE) + .getValue().getKeyPhrases()); + } + + @Test + public void extractKeyPhrasesForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + validateErrorDocument(expectedError, client.extractKeyPhrases("").getError()); + } + + @Test + public void extractKeyPhrasesForFaultyText() { + assertEquals(client.extractKeyPhrases("!@#%%").getKeyPhrases().size(), 0); + } + + @Test + public void extractKeyPhrasesForBatchInput() { + extractBatchKeyPhrasesRunner((inputs) -> + validateBatchResult(client.extractBatchKeyPhrases(inputs), + getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)); + } + + @Test + public void extractKeyPhrasesForBatchInputShowStatistics() { + extractBatchKeyPhrasesShowStatsRunner((inputs, options) -> + validateBatchResult(client.extractBatchKeyPhrasesWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)); + } + + @Test + public void extractKeyPhrasesForBatchStringInput() { + extractKeyPhrasesStringInputRunner((inputs) -> + validateBatchResult(client.extractKeyPhrases(inputs), + getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)); + } + + @Test + public void extractKeyPhrasesForListLanguageHint() { + extractKeyPhrasesLanguageHintRunner((inputs, language) -> + validateBatchResult(client.extractKeyPhrasesWithResponse(inputs, language, Context.NONE).getValue(), + getExpectedBatchKeyPhrases(), TestEndpoint.KEY_PHRASES)); + } + + // Sentiment + /** + * Test analyzing sentiment for a string input. + */ + @Test + public void analyseSentimentForTextInput() { + analyseBatchSentimentRunner(inputs -> validateBatchResult(client.analyzeBatchSentiment(inputs), + getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)); + } + + /** + * Verifies that an error document is returned for a empty text input. + */ + @Test + public void analyseSentimentForEmptyText() { + TextAnalyticsError expectedError = new TextAnalyticsError(ErrorCodeValue.INVALID_ARGUMENT, "Invalid document in request.", null, null); + validateErrorDocument(expectedError, client.analyzeSentiment("").getError()); + } + + @Test + public void analyseSentimentForFaultyText() { + // TODO (shawn): add this case later + } + + /** + * Test analyzing sentiment for a list of string input. + */ + @Test + public void analyseSentimentForBatchStringInput() { + analyseSentimentStringInputRunner(inputs -> + validateBatchResult(client.analyzeSentiment(inputs), getExpectedBatchTextSentiment(), + TestEndpoint.SENTIMENT)); + } + + /** + * Test analyzing sentiment for a list of string input with language hint. + */ + @Test + public void analyseSentimentForListLanguageHint() { + analyseSentimentLanguageHintRunner((inputs, language) -> + validateBatchResult(client.analyzeSentimentWithResponse(inputs, language, Context.NONE).getValue(), + getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)); + } + + /** + * Test analyzing sentiment for batch input. + */ + @Test + public void analyseSentimentForBatchInput() { + analyseBatchSentimentRunner(inputs -> validateBatchResult(client.analyzeBatchSentiment(inputs), + getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)); + } + + /** + * Verify that we can get statistics on the collection result when given a batch input with options. + */ + @Test + public void analyseSentimentForBatchInputShowStatistics() { + analyseBatchSentimentShowStatsRunner((inputs, options) -> + validateBatchResult(client.analyzeBatchSentimentWithResponse(inputs, options, Context.NONE).getValue(), + getExpectedBatchTextSentiment(), TestEndpoint.SENTIMENT)); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java new file mode 100644 index 000000000000..d8bfd0841a03 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java @@ -0,0 +1,1010 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.LinkedEntityMatch; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsError; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextDocumentStatistics; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.TextSentimentClass; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.core.credential.TokenCredential; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.http.policy.AddDatePolicy; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.HttpPipelinePolicy; +import com.azure.core.http.policy.HttpPolicyProviders; +import com.azure.core.http.policy.RequestIdPolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.policy.UserAgentPolicy; +import com.azure.core.test.TestBase; +import com.azure.core.util.Configuration; +import com.azure.core.util.CoreUtils; +import com.azure.identity.DefaultAzureCredentialBuilder; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +public abstract class TextAnalyticsClientTestBase extends TestBase { + private static final String TEXT_ANALYTICS_PROPERTIES = "azure-ai-textanalytics.properties"; + private static final String NAME = "name"; + private static final String VERSION = "version"; + private static final String DEFAULT_SCOPE = "https://cognitiveservices.azure.com/.default"; + + private final Map properties = CoreUtils.getProperties(TEXT_ANALYTICS_PROPERTIES); + private final String clientName = properties.getOrDefault(NAME, "UnknownName"); + private final String clientVersion = properties.getOrDefault(VERSION, "UnknownVersion"); + private boolean showStatistics = false; + private HttpLogOptions httpLogOptions = new HttpLogOptions(); + + private static final String MODEL_VERSION = "2019-10-01"; + + enum TestEndpoint { + LANGUAGE, NAMED_ENTITY, LINKED_ENTITY, KEY_PHRASES, SENTIMENT + } + + T clientSetup(Function clientBuilder) { + TokenCredential credential = null; + + if (!interceptorManager.isPlaybackMode()) { + credential = new DefaultAzureCredentialBuilder().build(); + } + + HttpClient httpClient; + Configuration buildConfiguration = Configuration.getGlobalConfiguration().clone(); + + // Closest to API goes first, closest to wire goes last. + final List policies = new ArrayList<>(); + policies.add(new UserAgentPolicy(httpLogOptions.getApplicationId(), clientName, clientVersion, buildConfiguration)); + policies.add(new RequestIdPolicy()); + policies.add(new AddDatePolicy()); + + HttpPolicyProviders.addBeforeRetryPolicies(policies); + if (credential != null) { + policies.add(new BearerTokenAuthenticationPolicy(credential, DEFAULT_SCOPE)); + } + policies.add(new RetryPolicy()); + + HttpPolicyProviders.addAfterRetryPolicies(policies); + policies.add(new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))); + + if (interceptorManager.isPlaybackMode()) { + httpClient = interceptorManager.getPlaybackClient(); + } else { + httpClient = new NettyAsyncHttpClientBuilder().wiretap(true).build(); + } + policies.add(interceptorManager.getRecordPolicy()); + + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(policies.toArray(new HttpPipelinePolicy[0])) + .httpClient(httpClient) + .build(); + + T client; + client = clientBuilder.apply(pipeline); + + return Objects.requireNonNull(client); + } + + // Detect Language + @Test + abstract void detectSingleTextLanguage(); + + @Test + abstract void detectLanguageEmptyText(); + + @Test + abstract void detectLanguageFaultyText(); + + @Test + abstract void detectLanguagesBatchInput(); + + @Test + abstract void detectLanguagesBatchInputShowStatistics(); + + @Test + abstract void detectLanguagesBatchStringInput(); + + @Test + abstract void detectLanguagesBatchListCountryHint(); + + // Named Entities + @Test + abstract void recognizeEntitiesForTextInput(); + + @Test + abstract void recognizeEntitiesForEmptyText(); + + @Test + abstract void recognizeEntitiesForFaultyText(); + + @Test + abstract void recognizeEntitiesForBatchInput(); + + @Test + abstract void recognizeEntitiesForBatchInputShowStatistics(); + + @Test + abstract void recognizeEntitiesForBatchStringInput(); + + @Test + abstract void recognizeEntitiesForListLanguageHint(); + + // Pii Entities + @Test + abstract void recognizePiiEntitiesForTextInput(); + + @Test + abstract void recognizePiiEntitiesForEmptyText(); + + @Test + abstract void recognizePiiEntitiesForFaultyText(); + + @Test + abstract void recognizePiiEntitiesForBatchInput(); + + @Test + abstract void recognizePiiEntitiesForBatchInputShowStatistics(); + + @Test + abstract void recognizePiiEntitiesForBatchStringInput(); + + @Test + abstract void recognizePiiEntitiesForListLanguageHint(); + + // Linked Entities + @Test + abstract void recognizeLinkedEntitiesForTextInput(); + + @Test + abstract void recognizeLinkedEntitiesForEmptyText(); + + @Test + abstract void recognizeLinkedEntitiesForFaultyText(); + + @Test + abstract void recognizeLinkedEntitiesForBatchInput(); + + @Test + abstract void recognizeLinkedEntitiesForBatchInputShowStatistics(); + + @Test + abstract void recognizeLinkedEntitiesForBatchStringInput(); + + @Test + abstract void recognizeLinkedEntitiesForListLanguageHint(); + + // Key Phrases + @Test + abstract void extractKeyPhrasesForTextInput(); + + @Test + abstract void extractKeyPhrasesForEmptyText(); + + @Test + abstract void extractKeyPhrasesForFaultyText(); + + @Test + abstract void extractKeyPhrasesForBatchInput(); + + @Test + abstract void extractKeyPhrasesForBatchInputShowStatistics(); + + @Test + abstract void extractKeyPhrasesForBatchStringInput(); + + @Test + abstract void extractKeyPhrasesForListLanguageHint(); + + // Sentiment + @Test + abstract void analyseSentimentForTextInput(); + + @Test + abstract void analyseSentimentForEmptyText(); + + @Test + abstract void analyseSentimentForFaultyText(); + + @Test + abstract void analyseSentimentForBatchInput(); + + @Test + abstract void analyseSentimentForBatchInputShowStatistics(); + + @Test + abstract void analyseSentimentForBatchStringInput(); + + @Test + abstract void analyseSentimentForListLanguageHint(); + + // Detect Language runner + void detectLanguageShowStatisticsRunner(BiConsumer, + TextAnalyticsRequestOptions> testRunner) { + final List detectLanguageInputs = Arrays.asList( + new DetectLanguageInput("0", "This is written in English", "US"), + new DetectLanguageInput("1", "Este es un document escrito en Español."), + new DetectLanguageInput("2", "~@!~:)", "US") + ); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; + + testRunner.accept(detectLanguageInputs, options); + } + + void detectLanguageDuplicateIdRunner(BiConsumer, + TextAnalyticsRequestOptions> testRunner) { + final List detectLanguageInputs = Arrays.asList( + new DetectLanguageInput("0", "This is written in English", "US"), + new DetectLanguageInput("0", "Este es un document escrito en Español.") + ); + + testRunner.accept(detectLanguageInputs, null); + } + + static void detectLanguagesCountryHintRunner(BiConsumer, String> testRunner) { + final List inputs = Arrays.asList( + "This is written in English", "Este es un document escrito en Español.", "~@!~:)"); + + testRunner.accept(inputs, "en"); + } + + static void detectLanguageStringInputRunner(Consumer> testRunner) { + final List inputs = Arrays.asList( + "This is written in English", "Este es un document escrito en Español.", "~@!~:)"); + + testRunner.accept(inputs); + } + + static void detectLanguageRunner(Consumer> testRunner) { + final List detectLanguageInputs = Arrays.asList( + new DetectLanguageInput("0", "This is written in English", "US"), + new DetectLanguageInput("1", "Este es un document escrito en Español."), + new DetectLanguageInput("2", "~@!~:)", "US") + ); + + testRunner.accept(detectLanguageInputs); + } + + // Named Entity runner + static void recognizeNamedEntityStringInputRunner(Consumer> testRunner) { + final List inputs = Arrays.asList( + "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); + + testRunner.accept(inputs); + } + + static void recognizeNamedEntitiesLanguageHintRunner(BiConsumer, String> testRunner) { + final List inputs = Arrays.asList( + "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); + + testRunner.accept(inputs, "en"); + } + + static void recognizeBatchNamedEntityRunner(Consumer> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), + new TextDocumentInput("1", "I work at Microsoft.")); + testRunner.accept(textDocumentInputs); + } + + void recognizeBatchNamedEntitiesShowStatsRunner( + BiConsumer, TextAnalyticsRequestOptions> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), + new TextDocumentInput("1", "I work at Microsoft.")); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; + + testRunner.accept(textDocumentInputs, options); + } + + // Pii Entity runner + static void recognizePiiLanguageHintRunner(BiConsumer, String> testRunner) { + final List inputs = Arrays.asList( + "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", + "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); + + testRunner.accept(inputs, "en"); + } + + static void recognizePiiStringInputRunner(Consumer> testRunner) { + final List inputs = Arrays.asList( + "Microsoft employee with ssn 859-98-0987 is using our awesome API's.", + "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check."); + + testRunner.accept(inputs); + } + + static void recognizeBatchPiiRunner(Consumer> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "Microsoft employee with ssn 859-98-0987 is using our awesome API's."), + new TextDocumentInput("1", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.")); + testRunner.accept(textDocumentInputs); + } + + void recognizeBatchPiiEntitiesShowStatsRunner( + BiConsumer, TextAnalyticsRequestOptions> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "Microsoft employee with ssn 859-98-0987 is using our awesome API's."), + new TextDocumentInput("1", "Your ABA number - 111000025 - is the first 9 digits in the lower left hand corner of your personal check.")); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; + testRunner.accept(textDocumentInputs, options); + } + + // Linked Entity runner + void recognizeBatchLinkedEntitiesShowStatsRunner( + BiConsumer, TextAnalyticsRequestOptions> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), + new TextDocumentInput("1", "I work at Microsoft.")); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; + + testRunner.accept(textDocumentInputs, options); + } + + static void recognizeLinkedLanguageHintRunner(BiConsumer, String> testRunner) { + final List inputs = Arrays.asList( + "I had a wonderful trip to Seattle last week.", + "I work at Microsoft."); + + testRunner.accept(inputs, "en"); + } + + static void recognizeLinkedStringInputRunner(Consumer> testRunner) { + final List inputs = Arrays.asList( + "I had a wonderful trip to Seattle last week.", + "I work at Microsoft."); + + testRunner.accept(inputs); + } + + static void recognizeBatchLinkedEntityRunner(Consumer> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), + new TextDocumentInput("1", "I work at Microsoft.")); + testRunner.accept(textDocumentInputs); + } + + // Key Phrases runner + void extractBatchKeyPhrasesShowStatsRunner( + BiConsumer, TextAnalyticsRequestOptions> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "Hello world. This is some input text that I love."), + new TextDocumentInput("1", "Bonjour tout le monde", "fr")); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; + + testRunner.accept(textDocumentInputs, options); + } + + static void extractKeyPhrasesLanguageHintRunner(BiConsumer, String> testRunner) { + final List inputs = Arrays.asList( + "Hello world. This is some input text that I love.", + "Bonjour tout le monde"); + + testRunner.accept(inputs, "en"); + } + + static void extractKeyPhrasesStringInputRunner(Consumer> testRunner) { + final List inputs = Arrays.asList( + "Hello world. This is some input text that I love.", + "Bonjour tout le monde"); + + testRunner.accept(inputs); + } + + static void extractBatchKeyPhrasesRunner(Consumer> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "Hello world. This is some input text that I love."), + new TextDocumentInput("1", "Bonjour tout le monde")); + testRunner.accept(textDocumentInputs); + } + + // Sentiment Runner + static void analyseSentimentLanguageHintRunner(BiConsumer, String> testRunner) { + testRunner.accept(getSentimentInput(), "en"); + } + + static void analyseSentimentStringInputRunner(Consumer> testRunner) { + testRunner.accept(getSentimentInput()); + } + + static void analyseBatchSentimentRunner(Consumer> testRunner) { + final List sentimentInputs = getSentimentInput(); + testRunner.accept(Arrays.asList( + new TextDocumentInput("0", sentimentInputs.get(0)), + new TextDocumentInput("1", sentimentInputs.get(1)) + )); + } + + void analyseBatchSentimentShowStatsRunner( + BiConsumer, TextAnalyticsRequestOptions> testRunner) { + final List textDocumentInputs = Arrays.asList( + new TextDocumentInput("0", "The hotel was dark and unclean. The restaurant had amazing gnocchi."), + new TextDocumentInput("1", "The restaurant had amazing gnocchi. The hotel was dark and unclean.") + ); + TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + + testRunner.accept(textDocumentInputs, options); + } + + static List getSentimentInput() { + return Arrays.asList("The hotel was dark and unclean. The restaurant had amazing gnocchi.", + "The restaurant had amazing gnocchi. The hotel was dark and unclean."); + } + + String getEndpoint() { + return interceptorManager.isPlaybackMode() + ? "http://localhost:8080" + : Configuration.getGlobalConfiguration().get("AZURE_TEXT_ANALYTICS_ENDPOINT"); + } + + /** + * Helper method to verify batch result. + * + * @param actualResult DocumentResultCollection<> returned by the API. + * @param testApi the API to test. + */ + void validateBatchResult(DocumentResultCollection actualResult, + DocumentResultCollection expectedResult, TestEndpoint testApi) { + // assert batch result + assertEquals(expectedResult.getModelVersion(), actualResult.getModelVersion()); + if (this.showStatistics) { + validateBatchStatistics(expectedResult.getStatistics(), actualResult.getStatistics()); + } + validateDocuments(expectedResult, actualResult, testApi); + } + + /** + * Helper method to verify documents returned in a batch request. + * + * @param expectedResult the expected result collection.. + * @param actualResult the actual result collection returned by the API. + * @param testApi the API to test. + */ + private void validateDocuments(DocumentResultCollection expectedResult, + DocumentResultCollection actualResult, TestEndpoint testApi) { + switch (testApi) { + case LANGUAGE: + final List detectLanguageResults = expectedResult.stream() + .filter(element -> element instanceof DetectLanguageResult) + .map(element -> (DetectLanguageResult) element) + .collect(Collectors.toList()); + + final List actualDetectLanguageResults = actualResult.stream() + .filter(element -> element instanceof DetectLanguageResult) + .map(element -> (DetectLanguageResult) element) + .collect(Collectors.toList()); + assertEquals(detectLanguageResults.size(), actualDetectLanguageResults.size()); + + actualDetectLanguageResults.forEach(actualItem -> { + List expectedItems = detectLanguageResults.stream().filter( + expectedEachItem -> actualItem.getId().equals(expectedEachItem.getId())) + .collect(Collectors.toList()); + assertEquals(expectedItems.size(), 1); + DetectLanguageResult expectedItem = expectedItems.get(0); + if (actualItem.getError() == null) { + if (this.showStatistics) { + validateDocumentStatistics(expectedItem.getStatistics(), actualItem.getStatistics()); + } + validatePrimaryLanguage(expectedItem.getPrimaryLanguage(), actualItem.getPrimaryLanguage()); + validateDetectedLanguages(expectedItem.getDetectedLanguages(), actualItem.getDetectedLanguages()); + } + }); + break; + case NAMED_ENTITY: + final List recognizeEntitiesResults = expectedResult.stream() + .filter(element -> element instanceof RecognizeEntitiesResult) + .map(element -> (RecognizeEntitiesResult) element) + .collect(Collectors.toList()); + + final List actualRecognizeEntitiesResults = actualResult.stream() + .filter(element -> element instanceof RecognizeEntitiesResult) + .map(element -> (RecognizeEntitiesResult) element) + .collect(Collectors.toList()); + assertEquals(recognizeEntitiesResults.size(), actualRecognizeEntitiesResults.size()); + + actualRecognizeEntitiesResults.forEach(actualItem -> { + List expectedItems = recognizeEntitiesResults.stream().filter( + expectedEachItem -> actualItem.getId().equals(expectedEachItem.getId())).collect( + Collectors.toList() + ); + assertEquals(expectedItems.size(), 1); + RecognizeEntitiesResult expectedItem = expectedItems.get(0); + if (actualItem.getError() == null) { + if (this.showStatistics) { + validateDocumentStatistics(expectedItem.getStatistics(), actualItem.getStatistics()); + } + validateNamedEntities(expectedItem.getNamedEntities(), actualItem.getNamedEntities()); + } + }); + break; + case LINKED_ENTITY: + final List recognizeLinkedEntitiesResults = expectedResult.stream() + .filter(element -> element instanceof RecognizeLinkedEntitiesResult) + .map(element -> (RecognizeLinkedEntitiesResult) element) + .collect(Collectors.toList()); + + final List actualRecognizeLinkedEntitiesResults = actualResult.stream() + .filter(element -> element instanceof RecognizeLinkedEntitiesResult) + .map(element -> (RecognizeLinkedEntitiesResult) element) + .collect(Collectors.toList()); + assertEquals(recognizeLinkedEntitiesResults.size(), actualRecognizeLinkedEntitiesResults.size()); + + actualRecognizeLinkedEntitiesResults.forEach(actualItem -> { + List expectedItems = recognizeLinkedEntitiesResults.stream().filter( + expectedEachItem -> actualItem.getId().equals(expectedEachItem.getId())) + .collect(Collectors.toList()); + assertEquals(expectedItems.size(), 1); + RecognizeLinkedEntitiesResult expectedItem = expectedItems.get(0); + if (actualItem.getError() == null) { + if (this.showStatistics) { + validateDocumentStatistics(expectedItem.getStatistics(), actualItem.getStatistics()); + } + validateLinkedEntities(expectedItem.getLinkedEntities(), actualItem.getLinkedEntities()); + } + }); + break; + case KEY_PHRASES: + final List extractKeyPhraseResults = expectedResult.stream() + .filter(element -> element instanceof ExtractKeyPhraseResult) + .map(element -> (ExtractKeyPhraseResult) element) + .collect(Collectors.toList()); + + final List actualExtractKeyPhraseResults = actualResult.stream() + .filter(element -> element instanceof ExtractKeyPhraseResult) + .map(element -> (ExtractKeyPhraseResult) element) + .collect(Collectors.toList()); + assertEquals(extractKeyPhraseResults.size(), actualExtractKeyPhraseResults.size()); + + actualExtractKeyPhraseResults.forEach(actualItem -> { + List expectedItems = extractKeyPhraseResults.stream().filter( + expectedEachItem -> actualItem.getId().equals(expectedEachItem.getId())) + .collect(Collectors.toList()); + assertEquals(expectedItems.size(), 1); + ExtractKeyPhraseResult expectedItem = expectedItems.get(0); + if (actualItem.getError() == null) { + if (this.showStatistics) { + validateDocumentStatistics(expectedItem.getStatistics(), actualItem.getStatistics()); + } + validateKeyPhrases(expectedItem.getKeyPhrases(), actualItem.getKeyPhrases()); + } + }); + break; + case SENTIMENT: + final List expectedSentimentResults = expectedResult.stream() + .filter(element -> element instanceof AnalyzeSentimentResult) + .map(element -> (AnalyzeSentimentResult) element) + .collect(Collectors.toList()); + + final List actualSentimentResults = actualResult.stream() + .filter(element -> element instanceof AnalyzeSentimentResult) + .map(element -> (AnalyzeSentimentResult) element) + .collect(Collectors.toList()); + + expectedSentimentResults.sort(Comparator.comparing(AnalyzeSentimentResult::getId)); + actualSentimentResults.sort(Comparator.comparing(AnalyzeSentimentResult::getId)); + final int actualSize = actualSentimentResults.size(); + final int expectedSize = expectedSentimentResults.size(); + assertEquals(expectedSize, actualSize); + + for (int i = 0; i < actualSize; i++) { + final AnalyzeSentimentResult actualSentimentResult = actualSentimentResults.get(i); + final AnalyzeSentimentResult expectedSentimentResult = expectedSentimentResults.get(i); + + if (actualSentimentResult.getError() == null) { + if (this.showStatistics) { + validateDocumentStatistics(expectedSentimentResult.getStatistics(), actualSentimentResult.getStatistics()); + } + validateAnalysedSentiment(expectedSentimentResult.getDocumentSentiment(), actualSentimentResult.getDocumentSentiment()); + validateAnalysedSentenceSentiment(expectedSentimentResult.getSentenceSentiments(), actualSentimentResult.getSentenceSentiments()); + } else { + validateErrorDocument(actualSentimentResult.getError(), actualSentimentResult.getError()); + } + } + break; + default: + throw new IllegalArgumentException(String.format("Unsupported testApi : '%s'.", testApi)); + } + } + + /** + * Helper method to verify TextBatchStatistics. + * + * @param expectedStatistics the expected value for TextBatchStatistics. + * @param actualStatistics the value returned by API. + */ + private static void validateBatchStatistics(TextDocumentBatchStatistics expectedStatistics, + TextDocumentBatchStatistics actualStatistics) { + assertEquals(expectedStatistics.getDocumentCount(), actualStatistics.getDocumentCount()); + assertEquals(expectedStatistics.getErroneousDocumentCount(), actualStatistics.getErroneousDocumentCount()); + assertEquals(expectedStatistics.getValidDocumentCount(), actualStatistics.getValidDocumentCount()); + assertEquals(expectedStatistics.getTransactionCount(), actualStatistics.getTransactionCount()); + } + + /** + * Helper method to verify TextDocumentStatistics. + * + * @param expected the expected value for TextDocumentStatistics. + * @param actual the value returned by API. + */ + private static void validateDocumentStatistics(TextDocumentStatistics expected, TextDocumentStatistics actual) { + assertEquals(expected.getCharacterCount(), actual.getCharacterCount()); + assertEquals(expected.getTransactionCount(), actual.getTransactionCount()); + } + + /** + * Helper method to verify LinkedEntityMatches. + * + * @param expectedLinkedEntityMatches the expected value for LinkedEntityMatches. + * @param actualLinkedEntityMatches the value returned by API. + */ + private static void validateLinkedEntityMatches(List expectedLinkedEntityMatches, + List actualLinkedEntityMatches) { + assertEquals(expectedLinkedEntityMatches.size(), actualLinkedEntityMatches.size()); + expectedLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText)); + actualLinkedEntityMatches.sort(Comparator.comparing(LinkedEntityMatch::getText)); + + for (int i = 0; i < expectedLinkedEntityMatches.size(); i++) { + LinkedEntityMatch expectedLinkedEntity = expectedLinkedEntityMatches.get(i); + LinkedEntityMatch actualLinkedEntity = actualLinkedEntityMatches.get(i); + assertEquals(expectedLinkedEntity.getLength(), actualLinkedEntity.getLength()); + assertEquals(expectedLinkedEntity.getOffset(), actualLinkedEntity.getOffset()); + assertEquals(expectedLinkedEntity.getScore(), actualLinkedEntity.getScore()); + assertEquals(expectedLinkedEntity.getText(), actualLinkedEntity.getText()); + } + } + + /** + * Helper method to verify the error document. + * @param expectedError the Error returned from the service. + * @param actualError the Error returned from the API. + */ + static void validateErrorDocument(TextAnalyticsError expectedError, TextAnalyticsError actualError) { + assertEquals(expectedError.getCode(), actualError.getCode()); + assertEquals(expectedError.getMessage(), actualError.getMessage()); + assertEquals(expectedError.getTarget(), actualError.getTarget()); + } + + /** + * Helper method to validate a single detected language. + * + * @param expectedLanguage detectedLanguage returned by the service. + * @param actualLanguage detectedLanguage returned by the API. + */ + static void validatePrimaryLanguage(DetectedLanguage expectedLanguage, DetectedLanguage actualLanguage) { + assertEquals(expectedLanguage.getIso6391Name(), actualLanguage.getIso6391Name()); + assertEquals(expectedLanguage.getName(), actualLanguage.getName()); + assertEquals(expectedLanguage.getScore(), actualLanguage.getScore()); + } + + /** + * Helper method to validate the list of detected languages. + * + * @param expectedLanguageList detectedLanguages returned by the service. + * @param actualLanguageList detectedLanguages returned by the API. + */ + static void validateDetectedLanguages(List expectedLanguageList, + List actualLanguageList) { + assertEquals(expectedLanguageList.size(), actualLanguageList.size()); + expectedLanguageList.sort(Comparator.comparing(DetectedLanguage::getName)); + actualLanguageList.sort(Comparator.comparing(DetectedLanguage::getName)); + + for (int i = 0; i < expectedLanguageList.size(); i++) { + DetectedLanguage expectedDetectedLanguage = expectedLanguageList.get(i); + DetectedLanguage actualDetectedLanguage = actualLanguageList.get(i); + validatePrimaryLanguage(expectedDetectedLanguage, actualDetectedLanguage); + } + } + + /** + * Helper method to validate a single named entity. + * + * @param expectedNamedEntity namedEntity returned by the service. + * @param actualNamedEntity namedEntity returned by the API. + */ + static void validateNamedEntity(NamedEntity expectedNamedEntity, NamedEntity actualNamedEntity) { + + assertEquals(expectedNamedEntity.getLength(), actualNamedEntity.getLength()); + assertEquals(expectedNamedEntity.getOffset(), actualNamedEntity.getOffset()); + assertEquals(expectedNamedEntity.getScore(), actualNamedEntity.getScore()); + assertEquals(expectedNamedEntity.getSubtype(), actualNamedEntity.getSubtype()); + assertEquals(expectedNamedEntity.getText(), actualNamedEntity.getText()); + assertEquals(expectedNamedEntity.getType(), actualNamedEntity.getType()); + + } + + /** + * Helper method to validate a single named entity. + * + * @param expectedLinkedEntity namedEntity returned by the service. + * @param actualLinkedEntity namedEntity returned by the API. + */ + static void validateLinkedEntity(LinkedEntity expectedLinkedEntity, LinkedEntity actualLinkedEntity) { + + assertEquals(expectedLinkedEntity.getName(), actualLinkedEntity.getName()); + assertEquals(expectedLinkedEntity.getDataSource(), actualLinkedEntity.getDataSource()); + assertEquals(expectedLinkedEntity.getLanguage(), actualLinkedEntity.getLanguage()); + assertEquals(expectedLinkedEntity.getUrl(), actualLinkedEntity.getUrl()); + assertEquals(expectedLinkedEntity.getId(), actualLinkedEntity.getId()); + validateLinkedEntityMatches(expectedLinkedEntity.getLinkedEntityMatches(), actualLinkedEntity.getLinkedEntityMatches()); + } + + /** + * Helper method to validate a single key phrase. + * + * @param expectedKeyPhrases key phrases returned by the service. + * @param actualKeyPhrases key phrases returned by the API. + */ + void validateKeyPhrases(List expectedKeyPhrases, List actualKeyPhrases) { + assertEquals(expectedKeyPhrases.size(), actualKeyPhrases.size()); + Collections.sort(expectedKeyPhrases); + Collections.sort(actualKeyPhrases); + + for (int i = 0; i < expectedKeyPhrases.size(); i++) { + assertTrue(expectedKeyPhrases.get(i).equals(actualKeyPhrases.get(i))); + } + } + + /** + * Helper method to validate the list of named entities. + * + * @param expectedNamedEntityList namedEntities returned by the service. + * @param actualNamedEntityList namedEntities returned by the API. + */ + static void validateNamedEntities(List expectedNamedEntityList, + List actualNamedEntityList) { + assertEquals(expectedNamedEntityList.size(), actualNamedEntityList.size()); + expectedNamedEntityList.sort(Comparator.comparing(NamedEntity::getText)); + actualNamedEntityList.sort(Comparator.comparing(NamedEntity::getText)); + + for (int i = 0; i < expectedNamedEntityList.size(); i++) { + NamedEntity expectedNamedEntity = expectedNamedEntityList.get(i); + NamedEntity actualNamedEntity = actualNamedEntityList.get(i); + validateNamedEntity(expectedNamedEntity, actualNamedEntity); + } + } + + /** + * Helper method to validate the list of named entities. + * + * @param expectedLinkedEntityList namedEntities returned by the service. + * @param actualLinkedEntityList namedEntities returned by the API. + */ + static void validateLinkedEntities(List expectedLinkedEntityList, + List actualLinkedEntityList) { + assertEquals(expectedLinkedEntityList.size(), actualLinkedEntityList.size()); + expectedLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName)); + actualLinkedEntityList.sort(Comparator.comparing(LinkedEntity::getName)); + + for (int i = 0; i < expectedLinkedEntityList.size(); i++) { + LinkedEntity expectedLinkedEntity = expectedLinkedEntityList.get(i); + LinkedEntity actualLinkedEntity = actualLinkedEntityList.get(i); + validateLinkedEntity(expectedLinkedEntity, actualLinkedEntity); + } + } + + /** + * Helper method to validate the list of sentence sentiment. Can't really validate score numbers because it + * frequently changed by background model computation. + * + * @param expectedSentimentList a list of analyzed sentence sentiment returned by the service. + * @param actualSentimentList a list of analyzed sentence sentiment returned by the API. + */ + static void validateAnalysedSentenceSentiment(List expectedSentimentList, + List actualSentimentList) { + + assertEquals(expectedSentimentList.size(), actualSentimentList.size()); + for (int i = 0; i < expectedSentimentList.size(); i++) { + validateAnalysedSentiment(expectedSentimentList.get(i), actualSentimentList.get(i)); + } + } + + /** + * Helper method to validate one pair of analysed sentiments. Can't really validate score numbers because it + * frequently changed by background model computation. + * + * @param expectedSentiment analyzed document sentiment returned by the service. + * @param actualSentiment analyzed document sentiment returned by the API. + */ + static void validateAnalysedSentiment(TextSentiment expectedSentiment, TextSentiment actualSentiment) { + assertEquals(expectedSentiment.getLength(), actualSentiment.getLength()); + assertEquals(expectedSentiment.getOffset(), actualSentiment.getOffset()); + assertEquals(expectedSentiment.getTextSentimentClass(), actualSentiment.getTextSentimentClass()); + + assertEquals(expectedSentiment.getNegativeScore() > 0, actualSentiment.getNegativeScore() > 0); + assertEquals(expectedSentiment.getNeutralScore() > 0, actualSentiment.getNeutralScore() > 0); + assertEquals(expectedSentiment.getPositiveScore() > 0, actualSentiment.getPositiveScore() > 0); + } + + static void assertRestException(Throwable exception, Class expectedExceptionType, + int expectedStatusCode) { + assertEquals(expectedExceptionType, exception.getClass()); + assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); + } + + static void assertRestException(Runnable exceptionThrower, + Class expectedExceptionType, int expectedStatusCode) { + try { + exceptionThrower.run(); + fail(); + } catch (Throwable ex) { + assertRestException(ex, expectedExceptionType, expectedStatusCode); + } + } + + /** + * Helper method to get the expected Batch Detected Languages + */ + static DocumentResultCollection getExpectedBatchDetectedLanguages() { + DetectedLanguage detectedLanguage1 = new DetectedLanguage("English", "en", 1.0); + DetectedLanguage detectedLanguage2 = new DetectedLanguage("Spanish", "es", 1.0); + DetectedLanguage detectedLanguage3 = new DetectedLanguage("(Unknown)", "(Unknown)", 0.0); + List detectedLanguageList1 = Collections.singletonList(detectedLanguage1); + List detectedLanguageList2 = Collections.singletonList(detectedLanguage2); + List detectedLanguageList3 = Collections.singletonList(detectedLanguage3); + + TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(26, 1); + TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(39, 1); + TextDocumentStatistics textDocumentStatistics3 = new TextDocumentStatistics(6, 1); + + DetectLanguageResult detectLanguageResult1 = new DetectLanguageResult("0", textDocumentStatistics1, null, detectedLanguage1, detectedLanguageList1); + DetectLanguageResult detectLanguageResult2 = new DetectLanguageResult("1", textDocumentStatistics2, null, detectedLanguage2, detectedLanguageList2); + DetectLanguageResult detectLanguageResult3 = new DetectLanguageResult("2", textDocumentStatistics3, null, detectedLanguage3, detectedLanguageList3); + + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 0, 3, 3); + List detectLanguageResultList = Arrays.asList(detectLanguageResult1, detectLanguageResult2, detectLanguageResult3); + + return new DocumentResultCollection<>(detectLanguageResultList, MODEL_VERSION, textDocumentBatchStatistics); + } + + static DocumentResultCollection getExpectedBatchNamedEntities() { + NamedEntity namedEntity1 = new NamedEntity("Seattle", "Location", null, 26, 7, 0.80624294281005859); + NamedEntity namedEntity2 = new NamedEntity("last week", "DateTime", "DateRange", 34, 9, 0.8); + NamedEntity namedEntity3 = new NamedEntity("Microsoft", "Organization", null, 10, 9, 0.99983596801757812); + + List namedEntityList1 = Arrays.asList(namedEntity1, namedEntity2); + List namedEntityList2 = Collections.singletonList(namedEntity3); + + TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); + TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); + + RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, namedEntityList1); + RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, namedEntityList2); + + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + List recognizeEntitiesResultList = Arrays.asList(recognizeEntitiesResult1, recognizeEntitiesResult2); + + return new DocumentResultCollection<>(recognizeEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); + } + + static DocumentResultCollection getExpectedBatchPiiEntities() { + NamedEntity namedEntity1 = new NamedEntity("859-98-0987", "U.S. Social Security Number (SSN)", "", 28, 11, 0.65); + NamedEntity namedEntity2 = new NamedEntity("111000025", "ABA Routing Number", "", 18, 9, 0.75); + + List namedEntityList1 = Collections.singletonList(namedEntity1); + List namedEntityList2 = Collections.singletonList(namedEntity2); + + TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); + TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(105, 1); + + RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, namedEntityList1); + RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, namedEntityList2); + + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + List recognizeEntitiesResultList = Arrays.asList(recognizeEntitiesResult1, recognizeEntitiesResult2); + + return new DocumentResultCollection<>(recognizeEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); + } + + static DocumentResultCollection getExpectedBatchLinkedEntities() { + LinkedEntityMatch linkedEntityMatch1 = new LinkedEntityMatch("Seattle", 0.11472424095537814, 7, 26); + LinkedEntityMatch linkedEntityMatch2 = new LinkedEntityMatch("Microsoft", 0.18693659716732069, 9, 10); + + LinkedEntity linkedEntity1 = new LinkedEntity( + "Seattle", Collections.singletonList(linkedEntityMatch1), + "en", "Seattle", "https://en.wikipedia.org/wiki/Seattle", + "Wikipedia"); + + LinkedEntity linkedEntity2 = new LinkedEntity( + "Microsoft", Collections.singletonList(linkedEntityMatch2), + "en", "Microsoft", "https://en.wikipedia.org/wiki/Microsoft", + "Wikipedia"); + + List linkedEntityList1 = Collections.singletonList(linkedEntity1); + List linkedEntityList2 = Collections.singletonList(linkedEntity2); + + TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(44, 1); + TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(20, 1); + + RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResult1 = new RecognizeLinkedEntitiesResult("0", textDocumentStatistics1, null, linkedEntityList1); + RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResult2 = new RecognizeLinkedEntitiesResult("1", textDocumentStatistics2, null, linkedEntityList2); + + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + List recognizeLinkedEntitiesResultList = Arrays.asList(recognizeLinkedEntitiesResult1, recognizeLinkedEntitiesResult2); + + return new DocumentResultCollection<>(recognizeLinkedEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); + } + + static DocumentResultCollection getExpectedBatchKeyPhrases() { + List keyPhrasesList1 = Arrays.asList("input text", "world"); + List keyPhrasesList2 = Arrays.asList("monde"); + + TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(49, 1); + TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(21, 1); + + ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, keyPhrasesList1); + ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, keyPhrasesList2); + + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + List extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2); + + return new DocumentResultCollection<>(extractKeyPhraseResultList, MODEL_VERSION, textDocumentBatchStatistics); + } + + static DocumentResultCollection getExpectedBatchTextSentiment() { + final TextDocumentStatistics textDocumentStatistics1 = new TextDocumentStatistics(67, 1); + final TextDocumentStatistics textDocumentStatistics2 = new TextDocumentStatistics(67, 1); + + final TextSentiment expectedDocumentSentiment = new TextSentiment(TextSentimentClass.MIXED, + 0.1, 0.5, 0.4, 66, 0); + + final AnalyzeSentimentResult analyzeSentimentResult1 = new AnalyzeSentimentResult("0", textDocumentStatistics1, + null, + expectedDocumentSentiment, + Arrays.asList( + new TextSentiment(TextSentimentClass.NEGATIVE, 0.99, 0.005, 0.005, 31, 0), + new TextSentiment(TextSentimentClass.POSITIVE, 0.005, 0.005, 0.99, 35, 32) + )); + + final AnalyzeSentimentResult analyzeSentimentResult2 = new AnalyzeSentimentResult("1", textDocumentStatistics2, + null, + expectedDocumentSentiment, + Arrays.asList( + new TextSentiment(TextSentimentClass.POSITIVE, 0.005, 0.005, 0.99, 35, 0), + new TextSentiment(TextSentimentClass.NEGATIVE, 0.99, 0.005, 0.005, 31, 36) + )); + + return new DocumentResultCollection<>(Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2), + MODEL_VERSION, + new TextDocumentBatchStatistics(2, 0, 2, 2)); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInput.json new file mode 100644 index 000000000000..93bafb2af6dd --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "bf7faa24-cf2d-48a2-b5a0-4839675aa06d", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "67", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "6ed77caa-7761-4a25-afce-f37f8a60efcf", + "x-aml-ta-request-id" : "87035b65-f78c-40a9-b459-3d016bdeb20a", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":0,\"length\":31},{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":32,\"length\":35}]},{\"id\":\"1\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":0,\"length\":35},{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":36,\"length\":31}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:32 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInputShowStatistics.json new file mode 100644 index 000000000000..1743cd120c65 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "26c1f86c-5406-45ef-8c38-0b88b6a9ee10", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "60", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "6c82ea83-668f-4271-9fa3-0cc085e488cb", + "x-aml-ta-request-id" : "9a184222-e1ba-4b35-800a-0043c3026dd8", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":2,\"validDocumentsCount\":2,\"erroneousDocumentsCount\":0,\"transactionsCount\":2},\"documents\":[{\"id\":\"0\",\"sentiment\":\"mixed\",\"statistics\":{\"charactersCount\":67,\"transactionsCount\":1},\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":0,\"length\":31},{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":32,\"length\":35}]},{\"id\":\"1\",\"sentiment\":\"mixed\",\"statistics\":{\"charactersCount\":67,\"transactionsCount\":1},\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":0,\"length\":35},{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":36,\"length\":31}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:25 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchStringInput.json new file mode 100644 index 000000000000..a7601afb38d0 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "49cc98cd-a9a6-47ab-8436-794c4639fe0a", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "72", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "24cf6a35-734c-4aad-a1be-aa1be6a46518", + "x-aml-ta-request-id" : "f4b4ea38-f3d8-48af-bf43-232e549a6331", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":0,\"length\":31},{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":32,\"length\":35}]},{\"id\":\"1\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":0,\"length\":35},{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":36,\"length\":31}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:30 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForEmptyText.json new file mode 100644 index 000000000000..d1cb1f9abdfc --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForEmptyText.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "2fb51e4d-367e-466c-b23f-69f368e06e61", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "1", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "ab72127f-7d59-4faf-b220-79c937ba79ea", + "x-aml-ta-request-id" : "4595ea83-9cd4-43d5-823c-6ca4260c34ae", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:31 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForFaultyText.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForFaultyText.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForListLanguageHint.json new file mode 100644 index 000000000000..dcff83114c1c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForListLanguageHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "39e2b93d-5a80-47c4-baaa-0222f0ef037c", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "63", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "93a951b1-5086-4eab-b445-ffa38afddeba", + "x-aml-ta-request-id" : "bb3d367a-e339-47f8-9a96-97a1335964be", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":0,\"length\":31},{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":32,\"length\":35}]},{\"id\":\"1\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":0,\"length\":35},{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":36,\"length\":31}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:29 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForTextInput.json new file mode 100644 index 000000000000..ecbd7d0d13fa --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/analyseSentimentForTextInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/sentiment", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "813c1778-0c1a-43f8-861b-8a0be1657d30", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "70", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "1db73d1e-6539-41ea-bf69-f22f7e9bb266", + "x-aml-ta-request-id" : "50bfa3c0-c0b0-491b-a482-1dc62e019a8e", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":0,\"length\":31},{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":32,\"length\":35}]},{\"id\":\"1\",\"sentiment\":\"mixed\",\"documentScores\":{\"positive\":0.49978500604629522,\"neutral\":0.0001903649390442,\"negative\":0.500024676322937},\"sentences\":[{\"sentiment\":\"positive\",\"sentenceScores\":{\"positive\":0.99952912330627441,\"neutral\":0.0003318602975924,\"negative\":0.000139072391903},\"offset\":0,\"length\":35},{\"sentiment\":\"negative\",\"sentenceScores\":{\"positive\":4.08880950999E-05,\"neutral\":4.88695768581E-05,\"negative\":0.99991023540496826},\"offset\":36,\"length\":31}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 20:43:33 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguage.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguage.json new file mode 100644 index 000000000000..3aa910433cce --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguage.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-UnknownName/UnknownVersion (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "dbabcca5-547d-4681-b266-ce49d02ed22e", + "Content-Type" : "application/json" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "4", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "6a49b00e-c7d6-471b-b4ee-8a68a20d2a50", + "x-aml-ta-request-id" : "70e5eede-3999-49e6-afe8-729dfdb48d4e", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Fri, 06 Dec 2019 23:45:12 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json new file mode 100644 index 000000000000..d1947f240b13 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "aabc5399-ae00-4ead-8ead-bca8b1989d7d", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "4", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "54177f2c-6394-44d2-b2eb-a972ad56c0d3", + "x-aml-ta-request-id" : "2eeef4d1-c228-4733-98b2-31b9c2fbbae1", + "retry-after" : "0", + "StatusCode" : "400", + "Body" : "{\"error\":{\"code\":\"InvalidRequest\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Request contains duplicated Ids. Make sure each document has a unique Id.\"},\"message\":\"Invalid document in request.\"}}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json new file mode 100644 index 000000000000..a56c7de41911 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "e4c37fd8-d81c-4ab7-a517-89257f475b92", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=0", + "apim-request-id" : "1854038a-38d2-485c-960e-6ed5820ec990", + "x-aml-ta-request-id" : "5a2557a4-c158-4378-94e7-1b39f8605a62", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:58 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json new file mode 100644 index 000000000000..cd8f1cf32e2e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "d3a5ab6f-88f1-4391-afe9-f45f8ab573e0", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "3", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "453f0d88-f510-421d-b79c-cf95a628e6be", + "x-aml-ta-request-id" : "2afe0f54-c9e9-4c61-96e5-f6b6243f428c", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:41:00 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json new file mode 100644 index 000000000000..753370943c01 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "c628558e-16be-4406-8e3f-c16a5872ccf7", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=0", + "apim-request-id" : "2f848a95-6b34-41bf-9a70-c639559eae87", + "x-aml-ta-request-id" : "240f51c5-2f65-466a-9f7c-8f32e1bee371", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidCountryHint\",\"message\":\"Country hint is not valid. Please specify an ISO 3166-1 alpha-2 two letter country code.\"},\"message\":\"Invalid Country Hint.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageNullText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageNullText.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageNullText.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json new file mode 100644 index 000000000000..e3def4868e7b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "3f29b175-67c1-4323-a35a-de116b207383", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "43b9ec52-c955-4eeb-a1a5-2797a8207890", + "x-aml-ta-request-id" : "d192d264-5fc2-41ab-8bfd-13adfc42d6b1", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}]},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:41:00 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json new file mode 100644 index 000000000000..103dbb27b375 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "e4223261-bd5d-4fe2-9554-e4e5446c56f4", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "6", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "f8999cef-f30b-4ffa-a471-9c8748c9fa47", + "x-aml-ta-request-id" : "25923640-7e6f-4e17-93db-625c1851e727", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":3,\"validDocumentsCount\":3,\"erroneousDocumentsCount\":0,\"transactionsCount\":3},\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}],\"statistics\":{\"charactersCount\":26,\"transactionsCount\":1}},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}],\"statistics\":{\"charactersCount\":39,\"transactionsCount\":1}},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}],\"statistics\":{\"charactersCount\":6,\"transactionsCount\":1}}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json new file mode 100644 index 000000000000..a491422f609c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-UnknownName/UnknownVersion (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "7bbf00ca-d6c7-4e17-9bf4-6bdc587fbdb1", + "Content-Type" : "application/json" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "6", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "0a3819af-a97d-4279-9c1c-30e216082788", + "x-aml-ta-request-id" : "78f53879-b38b-40ec-b441-e47ebc2c5905", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":3,\"validDocumentsCount\":3,\"erroneousDocumentsCount\":0,\"transactionsCount\":3},\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}],\"statistics\":{\"charactersCount\":26,\"transactionsCount\":1}},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}],\"statistics\":{\"charactersCount\":39,\"transactionsCount\":1}},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}],\"statistics\":{\"charactersCount\":6,\"transactionsCount\":1}}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Fri, 06 Dec 2019 23:45:12 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json new file mode 100644 index 000000000000..14ccbb174030 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "de228f54-3435-4075-bbe2-84d568ba00c5", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "ff18a335-ae1e-4041-b7ea-a723e1fe7e1c", + "x-aml-ta-request-id" : "0c8a99c1-0d5e-4e28-9b9d-2e5d54de567a", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}]},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json new file mode 100644 index 000000000000..4cdbceac895f --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "e55e2090-42ea-46ce-8916-c0302d77ef20", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "79cf04cb-21fb-4ca5-9777-03bba3ad58c3", + "x-aml-ta-request-id" : "855d6420-bc78-49fa-853c-3f488453720b", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}]},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:58 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json new file mode 100644 index 000000000000..2359237eb5f5 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-UnknownName/UnknownVersion (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "f2c6afdf-c7d9-4b64-bb47-df7a395fb176", + "Content-Type" : "application/json" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "6", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=3", + "apim-request-id" : "9f374d46-7574-40a3-8f1f-909d785f9bbb", + "x-aml-ta-request-id" : "5927da90-8c7b-4102-916c-b49197615813", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]},{\"id\":\"1\",\"detectedLanguages\":[{\"name\":\"Spanish\",\"iso6391Name\":\"es\",\"score\":1.0}]},{\"id\":\"2\",\"detectedLanguages\":[{\"name\":\"(Unknown)\",\"iso6391Name\":\"(Unknown)\",\"score\":0.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Fri, 06 Dec 2019 23:45:12 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json new file mode 100644 index 000000000000..cb3996213cab --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "fffb67be-78ff-4424-baeb-3889230fdd96", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "7b1a2495-4fab-43d3-ade1-fbd1301ed885", + "x-aml-ta-request-id" : "ba0643bc-a413-42c3-9da2-d852beb22bb9", + "retry-after" : "0", + "StatusCode" : "400", + "Body" : "{\"error\":{\"code\":\"InvalidRequest\",\"innerError\":{\"code\":\"MissingInputRecords\",\"message\":\"Missing input records.\"},\"message\":\"Invalid Request.\"}}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json new file mode 100644 index 000000000000..1796873fc27a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "42c2e666-5591-4307-a822-0e32dd28fde6", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "3", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "bf650aba-ca58-41fe-a7bc-3ee2bb7b85c0", + "x-aml-ta-request-id" : "1fa535eb-5585-4d65-b242-c7686270f6a2", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"detectedLanguages\":[{\"name\":\"English\",\"iso6391Name\":\"en\",\"score\":1.0}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Sun, 15 Dec 2019 18:40:59 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json new file mode 100644 index 000000000000..0bf3e6ef4e5b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "c06ff081-7cd8-4067-9a79-4e4abeb64e19", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "11", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "6d0a7ed6-0460-4828-be82-7e00e73857d4", + "x-aml-ta-request-id" : "8cfb3cb4-c4a9-46b9-aec6-c69e705ca62e", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"keyPhrases\":[\"input text\",\"world\"]},{\"id\":\"1\",\"keyPhrases\":[\"monde\"]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:33:53 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json new file mode 100644 index 000000000000..030a2bab35f4 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "cfeb9641-e809-4708-b37f-88358eaf0312", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "6", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "429897b3-0b7c-4d5c-9203-6eaab27da52f", + "x-aml-ta-request-id" : "c8d65a02-0651-4cf4-917a-f206f6f740c6", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":2,\"validDocumentsCount\":2,\"erroneousDocumentsCount\":0,\"transactionsCount\":2},\"documents\":[{\"id\":\"0\",\"keyPhrases\":[\"input text\",\"world\"],\"statistics\":{\"charactersCount\":49,\"transactionsCount\":1}},{\"id\":\"1\",\"keyPhrases\":[\"monde\"],\"statistics\":{\"charactersCount\":21,\"transactionsCount\":1}}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:43:54 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json new file mode 100644 index 000000000000..610e4628ffe0 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "df579208-6407-49fe-8fef-d54739727c5f", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "10", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "688d17a4-b114-4dc0-b2e8-fdff4de5500e", + "x-aml-ta-request-id" : "1b8e4fea-2ab2-4a3e-a5ab-223d7220aa30", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"keyPhrases\":[\"input text\",\"world\"]},{\"id\":\"1\",\"keyPhrases\":[\"monde\"]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:32:49 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json new file mode 100644 index 000000000000..b3411766fa05 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "47189e17-8ea9-48d4-a991-2bdc3a4ce8a2", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "6", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=0", + "apim-request-id" : "b4f085bb-9cfa-4c4e-be6a-6e9e99419fb0", + "x-aml-ta-request-id" : "f3b8109f-1cca-44bd-ac1c-9d2d1bd66220", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:32:49 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json new file mode 100644 index 000000000000..d74425aee299 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "d825fe65-81b2-4959-8a04-323619abc8ff", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "5ae0d526-c2e7-42e1-b9bb-ff4b5e39e6de", + "x-aml-ta-request-id" : "a1f3e143-7ec6-4976-80c5-7380890ee157", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"keyPhrases\":[]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Mon, 16 Dec 2019 19:27:02 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json new file mode 100644 index 000000000000..85033491096d --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "d6a9fd72-8233-4c03-b4a2-c9c361a8421e", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "11", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "38b9abb6-c8bc-468a-8c0c-91cec945baa0", + "x-aml-ta-request-id" : "ddb68a95-84b6-4aa8-8bac-260a4edbb63c", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"keyPhrases\":[\"input text\",\"world\"]},{\"id\":\"1\",\"keyPhrases\":[\"monde\"]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:32:48 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json new file mode 100644 index 000000000000..b6bc69f4b0f4 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "3be7e42b-301a-4db9-970e-e707d60caeac", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "fb026813-d781-4208-9f69-e23041e738fa", + "x-aml-ta-request-id" : "165e0b26-d158-46ee-a966-5439fd8ed098", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"keyPhrases\":[\"monde\"]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:33:53 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json new file mode 100644 index 000000000000..698d0ae140d4 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "2167dc9e-e029-4b67-85fe-a00d762e9d1c", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "27", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "49d733e3-7dde-4748-952a-41575950a776", + "x-aml-ta-request-id" : "5e28ec93-2366-447a-a4ce-33e0d27cec4b", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"Seattle\",\"type\":\"Location\",\"offset\":26,\"length\":7,\"score\":0.80624294281005859},{\"text\":\"last week\",\"type\":\"DateTime\",\"subtype\":\"DateRange\",\"offset\":34,\"length\":9,\"score\":0.8}]},{\"id\":\"1\",\"entities\":[{\"text\":\"Microsoft\",\"type\":\"Organization\",\"offset\":10,\"length\":9,\"score\":0.99983596801757812}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:31:45 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json new file mode 100644 index 000000000000..b54014e889a2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "4c60a884-a487-4526-a413-1b76f05d11e5", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "28", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "35615485-3f74-48c5-a275-52a832d03c42", + "x-aml-ta-request-id" : "9fcb9f03-2f4d-4863-82bc-162f0ac1a276", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":2,\"validDocumentsCount\":2,\"erroneousDocumentsCount\":0,\"transactionsCount\":2},\"documents\":[{\"id\":\"0\",\"statistics\":{\"charactersCount\":44,\"transactionsCount\":1},\"entities\":[{\"text\":\"Seattle\",\"type\":\"Location\",\"offset\":26,\"length\":7,\"score\":0.80624294281005859},{\"text\":\"last week\",\"type\":\"DateTime\",\"subtype\":\"DateRange\",\"offset\":34,\"length\":9,\"score\":0.8}]},{\"id\":\"1\",\"statistics\":{\"charactersCount\":20,\"transactionsCount\":1},\"entities\":[{\"text\":\"Microsoft\",\"type\":\"Organization\",\"offset\":10,\"length\":9,\"score\":0.99983596801757812}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:36:04 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchListCountryHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchListCountryHint.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchListCountryHint.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json new file mode 100644 index 000000000000..dd5dc375ffa7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "cdf9970f-de45-405a-94e8-45b73808ae92", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "32", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "be5aedfc-5e5e-459f-883c-1b48a1bb845b", + "x-aml-ta-request-id" : "d61bbcb2-4bd0-4930-981a-46b6493ceecf", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"Seattle\",\"type\":\"Location\",\"offset\":26,\"length\":7,\"score\":0.80624294281005859},{\"text\":\"last week\",\"type\":\"DateTime\",\"subtype\":\"DateRange\",\"offset\":34,\"length\":9,\"score\":0.8}]},{\"id\":\"1\",\"entities\":[{\"text\":\"Microsoft\",\"type\":\"Organization\",\"offset\":10,\"length\":9,\"score\":0.99983596801757812}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:31:49 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json new file mode 100644 index 000000000000..1a8ec9d93aad --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "1221c2bb-9541-4201-a2ce-ff119ba77dc9", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "b90ddc69-b691-4008-95d4-8f7ce3029cfa", + "x-aml-ta-request-id" : "fb985580-7eff-4032-bb58-5744906a215a", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:35:00 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json new file mode 100644 index 000000000000..f0eea759ad6c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "34d87319-7ac1-44f2-905a-f7b22515e361", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "20", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "2296fd92-81ee-4490-b426-60a7ec2594db", + "x-aml-ta-request-id" : "6d1cd136-6489-40dd-9a83-e1562a229c7d", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"Seattle\",\"type\":\"Location\",\"offset\":26,\"length\":7,\"score\":0.80624294281005859},{\"text\":\"last week\",\"type\":\"DateTime\",\"subtype\":\"DateRange\",\"offset\":34,\"length\":9,\"score\":0.8}]},{\"id\":\"1\",\"entities\":[{\"text\":\"Microsoft\",\"type\":\"Organization\",\"offset\":10,\"length\":9,\"score\":0.99983596801757812}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:31:48 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForSimpleInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForSimpleInput.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForSimpleInput.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json new file mode 100644 index 000000000000..f6753dd33657 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "9d68d9ec-caee-470e-b90a-e9248e7e112c", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "21", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "3606bada-cdf7-459e-b27f-3076fad38893", + "x-aml-ta-request-id" : "4f5d9ea4-038b-4da3-a865-86edf7104b51", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"Seattle\",\"type\":\"Location\",\"offset\":26,\"length\":7,\"score\":0.80624294281005859},{\"text\":\"last week\",\"type\":\"DateTime\",\"subtype\":\"DateRange\",\"offset\":34,\"length\":9,\"score\":0.8}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:35:06 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json new file mode 100644 index 000000000000..54444d5a507a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "801ab3cf-aa2a-43c7-add5-e1c8e8a2b49d", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "12", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "dd8d437b-aa02-4be1-8a96-bfb6591755ae", + "x-aml-ta-request-id" : "d7bbf941-abd6-44c3-9658-6922a117da0c", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"name\":\"Seattle\",\"matches\":[{\"text\":\"Seattle\",\"offset\":26,\"length\":7,\"score\":0.11472424095537814}],\"language\":\"en\",\"id\":\"Seattle\",\"url\":\"https://en.wikipedia.org/wiki/Seattle\",\"dataSource\":\"Wikipedia\"}]},{\"id\":\"1\",\"entities\":[{\"name\":\"Microsoft\",\"matches\":[{\"text\":\"Microsoft\",\"offset\":10,\"length\":9,\"score\":0.18693659716732069}],\"language\":\"en\",\"id\":\"Microsoft\",\"url\":\"https://en.wikipedia.org/wiki/Microsoft\",\"dataSource\":\"Wikipedia\"}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:32:51 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json new file mode 100644 index 000000000000..8fb51b2fe728 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "17da0fae-061a-4b79-a605-addb46a09b95", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "14", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "56651941-2cb9-4113-8a2c-9b473f517058", + "x-aml-ta-request-id" : "a7782d77-f675-498c-87a5-b4cb7868346d", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":2,\"validDocumentsCount\":2,\"erroneousDocumentsCount\":0,\"transactionsCount\":2},\"documents\":[{\"id\":\"0\",\"statistics\":{\"charactersCount\":44,\"transactionsCount\":1},\"entities\":[{\"name\":\"Seattle\",\"matches\":[{\"text\":\"Seattle\",\"offset\":26,\"length\":7,\"score\":0.11472424095537814}],\"language\":\"en\",\"id\":\"Seattle\",\"url\":\"https://en.wikipedia.org/wiki/Seattle\",\"dataSource\":\"Wikipedia\"}]},{\"id\":\"1\",\"statistics\":{\"charactersCount\":20,\"transactionsCount\":1},\"entities\":[{\"name\":\"Microsoft\",\"matches\":[{\"text\":\"Microsoft\",\"offset\":10,\"length\":9,\"score\":0.18693659716732069}],\"language\":\"en\",\"id\":\"Microsoft\",\"url\":\"https://en.wikipedia.org/wiki/Microsoft\",\"dataSource\":\"Wikipedia\"}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:35:58 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json new file mode 100644 index 000000000000..7411a24a9495 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "10dc1e7a-05e9-489f-8568-b4c8be54790d", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "23", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "20720445-eb4f-4ce7-b89b-43792d6f879f", + "x-aml-ta-request-id" : "1cac6013-2ba1-492d-8395-b91cd2d134e4", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"name\":\"Seattle\",\"matches\":[{\"text\":\"Seattle\",\"offset\":26,\"length\":7,\"score\":0.11472424095537814}],\"language\":\"en\",\"id\":\"Seattle\",\"url\":\"https://en.wikipedia.org/wiki/Seattle\",\"dataSource\":\"Wikipedia\"}]},{\"id\":\"1\",\"entities\":[{\"name\":\"Microsoft\",\"matches\":[{\"text\":\"Microsoft\",\"offset\":10,\"length\":9,\"score\":0.18693659716732069}],\"language\":\"en\",\"id\":\"Microsoft\",\"url\":\"https://en.wikipedia.org/wiki/Microsoft\",\"dataSource\":\"Wikipedia\"}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:25 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json new file mode 100644 index 000000000000..2a0c4ad6b47d --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "9d57fa09-3847-4d14-a9aa-be82464d592b", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "193e013b-5f7d-4597-a924-39739e88b377", + "x-aml-ta-request-id" : "781c87ff-a6a8-4c48-9c96-b4097ac44128", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:26 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json new file mode 100644 index 000000000000..723de16176b1 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "edab5962-f052-40b3-83f3-3a7f11e52d3e", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5017", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "f2d5e5a9-ebf8-49d8-8354-13429b5d7a02", + "x-aml-ta-request-id" : "f6615e24-9bca-481a-b3d9-30a55ffd391f", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:35:00 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json new file mode 100644 index 000000000000..ae7c7a929344 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "9f604d8e-9e35-4fdd-913d-1e2b4b41ad6d", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "15", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "c9959676-d6cb-43ee-8b46-add4ac6273f7", + "x-aml-ta-request-id" : "37d2a4ca-cad6-493f-81f4-6e4b40fbe8c8", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"name\":\"Seattle\",\"matches\":[{\"text\":\"Seattle\",\"offset\":26,\"length\":7,\"score\":0.11472424095537814}],\"language\":\"en\",\"id\":\"Seattle\",\"url\":\"https://en.wikipedia.org/wiki/Seattle\",\"dataSource\":\"Wikipedia\"}]},{\"id\":\"1\",\"entities\":[{\"name\":\"Microsoft\",\"matches\":[{\"text\":\"Microsoft\",\"offset\":10,\"length\":9,\"score\":0.18693659716732069}],\"language\":\"en\",\"id\":\"Microsoft\",\"url\":\"https://en.wikipedia.org/wiki/Microsoft\",\"dataSource\":\"Wikipedia\"}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:25 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json new file mode 100644 index 000000000000..84f5923c78d0 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "c70b3abe-b742-4fe0-99f6-fcfb50a72ac4", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "11", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "0590ca51-9475-4de7-8a58-023ae983eef6", + "x-aml-ta-request-id" : "9df16f76-7828-4be0-9515-bc479fb85195", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"name\":\"Seattle\",\"matches\":[{\"text\":\"Seattle\",\"offset\":26,\"length\":7,\"score\":0.11472424095537814}],\"language\":\"en\",\"id\":\"Seattle\",\"url\":\"https://en.wikipedia.org/wiki/Seattle\",\"dataSource\":\"Wikipedia\"}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:27 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json new file mode 100644 index 000000000000..0566842eeab2 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "f31748d1-e134-4658-9f48-be3468e2e46b", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "18", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "fbc0839b-e714-4d35-82d1-9ed082474088", + "x-aml-ta-request-id" : "4b7f60b8-14a1-4154-8448-71d5584bc6d3", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"859-98-0987\",\"type\":\"U.S. Social Security Number (SSN)\",\"subtype\":\"\",\"offset\":28,\"length\":11,\"score\":0.65}]},{\"id\":\"1\",\"entities\":[{\"text\":\"111000025\",\"type\":\"ABA Routing Number\",\"subtype\":\"\",\"offset\":18,\"length\":9,\"score\":0.75}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:33:55 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json new file mode 100644 index 000000000000..59c29b64abd3 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii?showStats=true", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "52eddf3d-3eab-4f5f-ad18-432783d88f06", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "20", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "38c9a1ae-e3e3-49d9-98b2-77ddd260e7e2", + "x-aml-ta-request-id" : "2fe339d9-8240-4999-910c-e29b1e43ac44", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"statistics\":{\"documentsCount\":2,\"validDocumentsCount\":2,\"erroneousDocumentsCount\":0,\"transactionsCount\":2},\"documents\":[{\"id\":\"0\",\"statistics\":{\"charactersCount\":67,\"transactionsCount\":1},\"entities\":[{\"text\":\"859-98-0987\",\"type\":\"U.S. Social Security Number (SSN)\",\"subtype\":\"\",\"offset\":28,\"length\":11,\"score\":0.65}]},{\"id\":\"1\",\"statistics\":{\"charactersCount\":105,\"transactionsCount\":1},\"entities\":[{\"text\":\"111000025\",\"type\":\"ABA Routing Number\",\"subtype\":\"\",\"offset\":18,\"length\":9,\"score\":0.75}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:26 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json new file mode 100644 index 000000000000..bad174160e98 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "e2ca3edd-e766-4340-ad98-e8f058b51beb", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "23", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "a372d434-7013-485b-a1c8-955804849156", + "x-aml-ta-request-id" : "5778e494-d7ae-459f-92ad-f61e320cc017", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"859-98-0987\",\"type\":\"U.S. Social Security Number (SSN)\",\"subtype\":\"\",\"offset\":28,\"length\":11,\"score\":0.65}]},{\"id\":\"1\",\"entities\":[{\"text\":\"111000025\",\"type\":\"ABA Routing Number\",\"subtype\":\"\",\"offset\":18,\"length\":9,\"score\":0.75}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:31:46 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json new file mode 100644 index 000000000000..209c52bb5bb7 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json @@ -0,0 +1,26 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "08f15ac4-1e65-4f71-ab07-51ba0b33fce5", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "2", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "apim-request-id" : "29e12e69-317e-4039-8725-b17056533036", + "x-aml-ta-request-id" : "dab6d532-4ac9-4666-b00e-33199f5a60e9", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[],\"errors\":[{\"id\":\"0\",\"error\":{\"code\":\"InvalidArgument\",\"innerError\":{\"code\":\"InvalidDocument\",\"message\":\"Document text is empty.\"},\"message\":\"Invalid document in request.\"}}],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:33:56 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json new file mode 100644 index 000000000000..83913ac6f7c5 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "f4838369-e84b-46d4-a921-71b507d889d5", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "17", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=2", + "apim-request-id" : "b4505fcb-d6bb-4c47-9b1e-b26fc1f2fc07", + "x-aml-ta-request-id" : "7b8c578a-9a41-429a-805a-bcaf7f15dfe3", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"859-98-0987\",\"type\":\"U.S. Social Security Number (SSN)\",\"subtype\":\"\",\"offset\":28,\"length\":11,\"score\":0.65}]},{\"id\":\"1\",\"entities\":[{\"text\":\"111000025\",\"type\":\"ABA Routing Number\",\"subtype\":\"\",\"offset\":18,\"length\":9,\"score\":0.75}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:39:28 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForSimpleInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForSimpleInput.json new file mode 100644 index 000000000000..ba5f37f8f855 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForSimpleInput.json @@ -0,0 +1,4 @@ +{ + "networkCallRecords" : [ ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json new file mode 100644 index 000000000000..938a706f0ded --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json @@ -0,0 +1,27 @@ +{ + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "8e84a84c-5f7d-4fc8-85ab-3f0078607bc9", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "5029", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "840b486d-7f42-4515-a062-e2b73d14a1c3", + "x-aml-ta-request-id" : "001e66fa-702e-4184-8d13-0470c9aa7979", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[{\"text\":\"859-98-0987\",\"type\":\"U.S. Social Security Number (SSN)\",\"subtype\":\"\",\"offset\":28,\"length\":11,\"score\":0.65}]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Tue, 17 Dec 2019 22:35:06 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], + "variables" : [ ] +} \ No newline at end of file diff --git a/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md new file mode 100644 index 000000000000..115f9e60af90 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/swagger/README.md @@ -0,0 +1,33 @@ +# Azure Cognitive Service - Text Analytics for Java + +> see https://aka.ms/autorest + +### Setup +```ps +Fork and clone https://github.com/Azure/autorest.java +git checkout v3 +git submodule update --init --recursive +npm install +npm install -g autorest +``` + +### Generation +```ps +cd +autorest --java --use=C:/work/autorest.java +``` + +### Code generation settings +``` yaml +input-file: https://github.com/Azure/azure-rest-api-specs/blob/master/specification/cognitiveservices/data-plane/TextAnalytics/preview/v3.0-preview.1/TextAnalytics.json +java: true +output-folder: ..\ +namespace: com.azure.ai.textanalytics +enable-xml: true +generate-client-interfaces: false +sync-methods: none +license-header: MICROSOFT_MIT_SMALL +add-context-parameter: true +models-subpackage: implementation.models +custom-types-subpackage: models +``` diff --git a/sdk/textanalytics/tests.yml b/sdk/textanalytics/tests.yml new file mode 100644 index 000000000000..a97cc7e5909f --- /dev/null +++ b/sdk/textanalytics/tests.yml @@ -0,0 +1,14 @@ +trigger: none + +jobs: + - template: ../../eng/pipelines/templates/jobs/archetype-sdk-tests.yml + parameters: + ServiceDirectory: textanalytics + EnvVars: + AZURE_TEST_MODE: RECORD + AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY: $(java-textanalytics-test-subscription-key) + AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id) + AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) + AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id) + AZURE_TEXT_ANALYTICS_ENDPOINT: $(java-azure-textanalytics-sdk-endpoint) + AZURE_LOG_LEVEL: 3