Posted in: Blog

How to Consume Cognitive Services from a container

Once your Cognitive Services are deployed, applications consume from the containerized Cognitive Services endpoint rather than the default Azure endpoint. Your sample application can be a list of documents representing health worker notes. The application will use the correct Cognitive Services library to consume a prediction from the containerized endpoint. In this case, you will use the text analytics client library. The detected language retrieved from the service will be printed out for each document. Let’s run a sample application that connects through the exposed endpoint of our Kubernetes deployment.

  1. First, set the environment variables we will use to connect, CONTAINER_ENDPOINT and COGNITIVE_SERVICE_KEY (if not already set). Set the environment variables for your session using console window (bash) with the following command.
export CONTAINER_ENDPOINT=https://<EXTERNAL-IP>:5000
export COGNITIVE_SERVICE_KEY=<subscription_key>

Read more: Best web hosting services 2020

Let’s run a sample application that consumes from our language detection container:

Import required libraries.

import os
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient

Set endpoint and subscription key.

service_endpoint = os.environ["CONTAINER_ENDPOINT"] subscription_key = os.environ["COGNITIVE_SERVICE_KEY"]

Initiate the client.

credential = AzureKeyCredential(subscription_key)
text_analytics_client = TextAnalyticsClient(service_endpoint, credential)
client = text_analytics_client

Run language detection example with two documents, one in English and one in Spanish.

try:
    documents = ["The patient has fever, fatigue, and loss of appetite.",
                 "La paciente tiene fiebre y le duele la garganta"]
    response = client.detect_language(documents = documents, country_hint = 'us')

    for document_response in response:
        print("Language used: ", document_response.primary_language.name)

except Exception as err:
    print("Encountered exception. {}".format(err))

Detected languages are printed, one per document submitted.

Language used:  English
Language used:  Spanish

Read More:  Best Managed WordPress Hosting

You have completed all the exercises, but don’t forget to clean up your resources.

If you are not using the resource group for other services, you can remove everything in it by running.
Alternatively, you could remove individual services with the commands.