Skip to main content
Version: 0.10.2

Cognitive Services

Azure Cognitive Services are a suite of APIs, SDKs, and services available to help developers build intelligent applications without having direct AI or data science skills or knowledge by enabling developers to easily add cognitive features into their applications. The goal of Azure Cognitive Services is to help developers create applications that can see, hear, speak, understand, and even begin to reason. The catalog of services within Azure Cognitive Services can be categorized into five main pillars - Vision, Speech, Language, Web Search, and Decision.



Computer Vision

  • Describe: provides description of an image in human readable language (Scala, Python)
  • Analyze (color, image type, face, adult/racy content): analyzes visual features of an image (Scala, Python)
  • OCR: reads text from an image (Scala, Python)
  • Recognize Text: reads text from an image (Scala, Python)
  • Thumbnail: generates a thumbnail of user-specified size from the image (Scala, Python)
  • Recognize domain-specific content: recognizes domain-specific content (celebrity, landmark) (Scala, Python)
  • Tag: identifies list of words that are relevant to the in0put image (Scala, Python)


  • Detect: detects human faces in an image (Scala, Python)
  • Verify: verifies whether two faces belong to a same person, or a face belongs to a person (Scala, Python)
  • Identify: finds the closest matches of the specific query person face from a person group (Scala, Python)
  • Find similar: finds similar faces to the query face in a face list (Scala, Python)
  • Group: divides a group of faces into disjoint groups based on similarity (Scala, Python)


Speech Services

  • Speech-to-text: transcribes audio streams (Scala, Python)
  • Conversation Transcription: transcribes audio streams into live transcripts with identified speakers. (Scala, Python)
  • Text to Speech: Converts text to realistic audio (Scala, Python)


Text Analytics

  • Language detection: detects language of the input text (Scala, Python)
  • Key phrase extraction: identifies the key talking points in the input text (Scala, Python)
  • Named entity recognition: identifies known entities and general named entities in the input text (Scala, Python)
  • Sentiment analysis: returns a score betwee 0 and 1 indicating the sentiment in the input text (Scala, Python)
  • Healthcare Entity Extraction: Extracts medical entities and relationships from text. (Scala, Python)



  • Translate: Translates text. (Scala, Python)
  • Transliterate: Converts text in one language from one script to another script. (Scala, Python)
  • Detect: Identifies the language of a piece of text. (Scala, Python)
  • BreakSentence: Identifies the positioning of sentence boundaries in a piece of text. (Scala, Python)
  • Dictionary Lookup: Provides alternative translations for a word and a small number of idiomatic phrases. (Scala, Python)
  • Dictionary Examples: Provides examples that show how terms in the dictionary are used in context. (Scala, Python)
  • Document Translation: Translates documents across all supported languages and dialects while preserving document structure and data format. (Scala, Python)

Form Recognizer

Form Recognizer

  • Analyze Layout: Extract text and layout information from a given document. (Scala, Python)
  • Analyze Receipts: Detects and extracts data from receipts using optical character recognition (OCR) and our receipt model, enabling you to easily extract structured data from receipts such as merchant name, merchant phone number, transaction date, transaction total, and more. (Scala, Python)
  • Analyze Business Cards: Detects and extracts data from business cards using optical character recognition (OCR) and our business card model, enabling you to easily extract structured data from business cards such as contact names, company names, phone numbers, emails, and more. (Scala, Python)
  • Analyze Invoices: Detects and extracts data from invoices using optical character recognition (OCR) and our invoice understanding deep learning models, enabling you to easily extract structured data from invoices such as customer, vendor, invoice ID, invoice due date, total, invoice amount due, tax amount, ship to, bill to, line items and more. (Scala, Python)
  • Analyze ID Documents: Detects and extracts data from identification documents using optical character recognition (OCR) and our ID document model, enabling you to easily extract structured data from ID documents such as first name, last name, date of birth, document number, and more. (Scala, Python)
  • Analyze Custom Form: Extracts information from forms (PDFs and images) into structured data based on a model created from a set of representative training forms. (Scala, Python)
  • Get Custom Model: Get detailed information about a custom model. (Scala, Python)
  • List Custom Models: Get information about all custom models. (Scala, Python)


Anomaly Detector

  • Anomaly status of latest point: generates a model using preceding points and determines whether the latest point is anomalous (Scala, Python)
  • Find anomalies: generates a model using an entire series and finds anomalies in the series (Scala, Python)


  1. Follow the steps in Getting started to set up your Azure Databricks and Cognitive Services environment. This tutorial shows you how to install SynapseML and how to create your Spark cluster in Databricks.
  2. After you create a new notebook in Azure Databricks, copy the Shared code below and paste into a new cell in your notebook.
  3. Choose a service sample, below, and copy paste it into a second new cell in your notebook.
  4. Replace any of the service subscription key placeholders with your own key.
  5. Choose the run button (triangle icon) in the upper right corner of the cell, then select Run Cell.
  6. View results in a table below the cell.

Shared code

To get started, we'll need to add this code to the project:

from pyspark.sql.functions import udf, col
from import HTTPTransformer, http_udf
from requests import Request
from pyspark.sql.functions import lit
from import PipelineModel
from pyspark.sql.functions import col
import os
from pyspark.sql import SparkSession
from import *

# Bootstrap Spark Session
spark = SparkSession.builder.getOrCreate()

from import materializing_display as display
from import *

# A general Cognitive Services key for Text Analytics, Computer Vision and Form Recognizer (or use separate keys that belong to each service)
service_key = find_secret("cognitive-api-key")
service_loc = "eastus"

# A Bing Search v7 subscription key
bing_search_key = find_secret("bing-search-key")

# An Anomaly Dectector subscription key
anomaly_key = find_secret("anomaly-api-key")
anomaly_loc = "westus2"

# A Translator subscription key
translator_key = find_secret("translator-key")
translator_loc = "eastus"

# An Azure search key
search_key = find_secret("azure-search-key")

Text Analytics sample

The Text Analytics service provides several algorithms for extracting intelligent insights from text. For example, we can find the sentiment of given input text. The service will return a score between 0.0 and 1.0 where low scores indicate negative sentiment and high score indicates positive sentiment. This sample uses three simple sentences and returns the sentiment for each.

# Create a dataframe that's tied to it's column names
df = spark.createDataFrame(
("I am so happy today, its sunny!", "en-US"),
("I am frustrated by this rush hour traffic", "en-US"),
("The cognitive services on spark aint bad", "en-US"),
["text", "language"],

# Run the Text Analytics service with options
sentiment = (

# Show the results of your text query in a table format
"text", col("sentiment.document.sentiment").alias("sentiment")

Text Analytics for Health Sample

The Text Analytics for Heatlth Service extracts and labels relevant medical information from unstructured texts such as doctor's notes, discharge summaries, clinical documents, and electronic health records.

df = spark.createDataFrame(
("20mg of ibuprofen twice a day",),
("1tsp of Tylenol every 4 hours",),
("6-drops of Vitamin B-12 every evening",),

healthcare = (


Translator sample

Translator is a cloud-based machine translation service and is part of the Azure Cognitive Services family of cognitive APIs used to build intelligent apps. Translator is easy to integrate in your applications, websites, tools, and solutions. It allows you to add multi-language user experiences in 90 languages and dialects and can be used for text translation with any operating system. In this sample, we do a simple text translation by providing the sentences you want to translate and target languages you want to translate to.

from pyspark.sql.functions import col, flatten

# Create a dataframe including sentences you want to translate
df = spark.createDataFrame(
[(["Hello, what is your name?", "Bye"],)],

# Run the Translator service with options
translate = (

# Show the results of the translation.
.withColumn("translation", flatten(col("translation.translations")))
.withColumn("translation", col("translation.text"))

Form Recognizer sample

Form Recognizer is a part of Azure Applied AI Services that lets you build automated data processing software using machine learning technology. Identify and extract text, key/value pairs, selection marks, tables, and structure from your documents—the service outputs structured data that includes the relationships in the original file, bounding boxes, confidence and more. In this sample, we analyze a business card image and extract its information into structured data.

from pyspark.sql.functions import col, explode

# Create a dataframe containing the source files
imageDf = spark.createDataFrame(

# Run the Form Recognizer service
analyzeBusinessCards = (

# Show the results of recognition.
"documents", explode(col("businessCards.analyzeResult.documentResults.fields"))
.select("source", "documents")

Computer Vision sample

Computer Vision analyzes images to identify structure such as faces, objects, and natural-language descriptions. In this sample, we tag a list of images. Tags are one-word descriptions of things in the image like recognizable objects, people, scenery, and actions.

# Create a dataframe with the image URLs
base_url = ""
df = spark.createDataFrame(
(base_url + "objects.jpg",),
(base_url + "dog.jpg",),
(base_url + "house.jpg",),

# Run the Computer Vision service. Analyze Image extracts infortmation from/about the images.
analysis = (
["Categories", "Color", "Description", "Faces", "Objects", "Tags"]

# Show the results of what you wanted to pull out of the images.
display(analysis.transform(df).select("image", "analysis_results.description.tags"))

Bing Image Search sample

Bing Image Search searches the web to retrieve images related to a user's natural language query. In this sample, we use a text query that looks for images with quotes. It returns a list of image URLs that contain photos related to our query.

# Number of images Bing will return per query
imgsPerBatch = 10
# A list of offsets, used to page into the search results
offsets = [(i * imgsPerBatch,) for i in range(100)]
# Since web content is our data, we create a dataframe with options on that data: offsets
bingParameters = spark.createDataFrame(offsets, ["offset"])

# Run the Bing Image Search service with our text query
bingSearch = (
.setQuery("Martin Luther King Jr. quotes")

# Transformer that extracts and flattens the richly structured output of Bing Image Search into a simple URL column
getUrls = BingImageSearch.getUrlTransformer("images", "url")

# This displays the full results returned, uncomment to use
# display(bingSearch.transform(bingParameters))

# Since we have two services, they are put into a pipeline
pipeline = PipelineModel(stages=[bingSearch, getUrls])

# Show the results of your search: image URLs

Speech-to-Text sample

The Speech-to-text service converts streams or files of spoken audio to text. In this sample, we transcribe one audio file.

# Create a dataframe with our audio URLs, tied to the column called "url"
df = spark.createDataFrame(
[("",)], ["url"]

# Run the Speech-to-text service to translate the audio into text
speech_to_text = (

# Show the results of the translation
display(speech_to_text.transform(df).select("url", "text.DisplayText"))

Text-to-Speech sample

Text to speech is a service that allows one to build apps and services that speak naturally, choosing from more than 270 neural voices across 119 languages and variants.

from import TextToSpeech

fs = ""
if running_on_databricks():
fs = "dbfs:"
elif running_on_synapse_internal():
fs = "Files"

# Create a dataframe with text and an output file location
df = spark.createDataFrame(
"Reading out loud is fun! Check out for more information",
fs + "/output.mp3",
["text", "output_file"],

tts = (

# Check to make sure there were no errors during audio creation

Anomaly Detector sample

Anomaly Detector is great for detecting irregularities in your time series data. In this sample, we use the service to find anomalies in the entire time series.

# Create a dataframe with the point data that Anomaly Detector requires
df = spark.createDataFrame(
("1972-01-01T00:00:00Z", 826.0),
("1972-02-01T00:00:00Z", 799.0),
("1972-03-01T00:00:00Z", 890.0),
("1972-04-01T00:00:00Z", 900.0),
("1972-05-01T00:00:00Z", 766.0),
("1972-06-01T00:00:00Z", 805.0),
("1972-07-01T00:00:00Z", 821.0),
("1972-08-01T00:00:00Z", 20000.0),
("1972-09-01T00:00:00Z", 883.0),
("1972-10-01T00:00:00Z", 898.0),
("1972-11-01T00:00:00Z", 957.0),
("1972-12-01T00:00:00Z", 924.0),
("1973-01-01T00:00:00Z", 881.0),
("1973-02-01T00:00:00Z", 837.0),
("1973-03-01T00:00:00Z", 9000.0),
["timestamp", "value"],
).withColumn("group", lit("series1"))

# Run the Anomaly Detector service to look for irregular data
anamoly_detector = (

# Show the full results of the analysis with the anomalies marked as "True"
anamoly_detector.transform(df).select("timestamp", "value", "anomalies.isAnomaly")

Arbitrary web APIs

With HTTP on Spark, any web service can be used in your big data pipeline. In this example, we use the World Bank API to get information about various countries around the world.

# Use any requests from the python requests library

def world_bank_request(country):
return Request(
"GET", "{}?format=json".format(country)

# Create a dataframe with spcificies which countries we want data on
df = spark.createDataFrame([("br",), ("usa",)], ["country"]).withColumn(
"request", http_udf(world_bank_request)(col("country"))

# Much faster for big data because of the concurrency :)
client = (

# Get the body of the response

def get_response_body(resp):
return resp.entity.content.decode()

# Show the details of the country data returned
"country", udf(get_response_body)(col("response")).alias("response")

Azure Cognitive search sample

In this example, we show how you can enrich data using Cognitive Skills and write to an Azure Search Index using SynapseML.

search_service = "mmlspark-azure-search"
search_index = "test-33467690"

df = spark.createDataFrame(
["searchAction", "id", "url"],

tdf = (
["Categories", "Tags", "Description", "Faces", "ImageType", "Color", "Adult"]
.select("*", "analyzed.*")
.drop("errors", "analyzed")