你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Foundry 工具

Foundry Tools 可帮助开发人员和组织使用现成的、可自定义的 API 和模型快速创建智能、前沿、市场就绪和负责任的应用程序。

使用 SynapseML 可以基于各种 Spark 数据源生成功能强大且高度可缩放的预测模型和分析模型。 Synapse Spark 提供内置的 SynapseML 库,包括 synapse.ml.services。

重要

从 2023 年 9 月 20 日开始,将无法创建新的异常检测器资源。 异常检测器服务将于 2026 年 10 月 1 日停用。

Azure Synapse Analytics 的先决条件

本教程是 使用 Azure Synapse 中的 Foundry 工具的先决条件,介绍了在 Synapse Analytics 中使用 Foundry 工具之前需要执行的几个步骤。

Foundry Tools 是一套 API、SDK 和服务,开发人员可以使用这些 API、SDK 和服务向其应用程序添加智能功能。 Foundry Tools 即使开发人员没有直接 AI 或数据科学技能或知识,也为开发人员提供支持。 Foundry 工具可帮助开发人员创建应用程序,这些应用程序可以查看、听到、说话、理解,甚至开始推理。 Foundry 工具中的服务目录可分为五个主要支柱:视觉、语音、语言、Web 搜索和决策。

使用情况

视觉

计算机视觉

  • 描述:以用户可读的语言提供图像描述(ScalaPython
  • 分析(颜色、图像类型、人脸、成人/猥亵内容):分析图像的视觉特征(ScalaPython
  • OCR:读取图像中的文本(ScalaPython
  • 识别文本:读取图像中的文本(ScalaPython
  • 缩略图:从图像生成用户指定大小的缩略图(ScalaPython
  • 识别特定于领域的内容:识别特定于领域的内容(名人、地标)(ScalaPython
  • 标记:标识与输入图像相关的单词列表(ScalaPython

人脸

  • 检测:检测图像中的人脸(ScalaPython
  • 验证:验证两张人脸是否属于同一个人,或者一张人脸是否属于某一个人(ScalaPython
  • 识别:在人员组中查找与特定查询人脸最接近的匹配项(ScalaPython
  • 查找相似人脸:在人脸列表中查找与查询人脸相似的人脸(ScalaPython
  • 分组:根据相似性将一组人脸划分成不相交的组(ScalaPython

语音

语音服务

  • 语音转文本:听录音频流(ScalaPython
  • 对话转录:将带有说话人标识的音频流转录为实时转录稿。 (ScalaPython
  • 文本转语音:将文本转换为真实的音频(ScalaPython

语言

AI 语言

  • 语言检测:检测输入文本的语言(ScalaPython
  • 关键短语提取:识别输入文本中的关键论题(ScalaPython
  • 命名实体识别:识别输入文本中的已知实体和常规命名实体(ScalaPython
  • 情绪分析:返回介于 0 和 1 之间的分数,指示输入文本中的情绪(ScalaPython
  • 医疗保健实体提取:从文本中提取医疗实体和关系。 (ScalaPython

翻译

翻译工具

  • 翻译:翻译文本。 (ScalaPython
  • 音译:将一种语言的文本从一个脚本转换为另一个脚本。 (ScalaPython
  • 检测:识别一段文本的语言。 (ScalaPython
  • 断句:识别文本段中的句子边界的位置。 (ScalaPython
  • 字典查找:为某个单词和少量的惯用语提供替代翻译。 (ScalaPython
  • 字典示例:提供示例,说明如何在上下文中使用字典中的术语。 (ScalaPython
  • 文档翻译:翻译所有支持的语言和方言的文档,同时保留文档结构和数据格式。 (ScalaPython

文档智能

文档智能

  • 分析布局:从给定文档中提取文本和布局信息。 (ScalaPython
  • 分析收据:使用光学字符识别 (OCR) 和我们的收据模型从收据中检测和提取数据,这让你可以轻松地从收据中提取结构化数据,例如商店名称、商家电话号码、交易日期、交易总额等。 (ScalaPython
  • 分析名片:使用光学字符识别 (OCR) 和名片模型从名片中检测和提取数据,这让你可以轻松地从名片中提取结构化数据,例如联系人姓名、公司名称、电话号码、电子邮件等。 (ScalaPython
  • 分析发票:使用光学字符识别 (OCR) 以及我们的发票理解深度学习模型从发票中检测和提取数据,这让你可以轻松地从发票中提取结构化数据,例如客户、供应商、发票 ID、发票截止日期、总金额、发票应付金额、税额、发货人、帐单付款、行项等。 (ScalaPython
  • 分析 ID 文档:使用光学字符识别 (OCR) 和我们的 ID 文档模型从标识文档中检测和提取数据,从而轻松从 ID 文档中提取结构化数据,例如名字、姓氏、出生日期、文档编号等。 (ScalaPython
  • 分析自定义表单:根据从一组有代表性的训练表单创建的模型,将表单(PDF 和图像)中的信息提取到结构化数据中。 (ScalaPython
  • 获取自定义模型:获取有关自定义模型的详细信息。 (ScalaPython
  • 列出自定义模型:获取有关所有自定义模型的信息。 (ScalaPython

决策

异常检测器

  • 最新点的异常状态:使用前面的点生成模型,并确定最新点是否有异常(ScalaPython
  • 查找异常:使用整个系列生成模型,并在系列中查找异常(ScalaPython

准备你的系统

首先,导入所需的库并初始化 Spark 会话。

from pyspark.sql.functions import udf, col
from synapse.ml.io.http import HTTPTransformer, http_udf
from requests import Request
from pyspark.sql.functions import lit
from pyspark.ml import PipelineModel
from pyspark.sql.functions import col

导入 Foundry Tools 库,并将以下代码片段中的密钥和位置替换为 Foundry 工具密钥和位置。

from synapse.ml.services import *
from synapse.ml.core.platform import *

# A general Foundry Tools key for Azure Language in Foundry Tools, Computer Vision and Azure Document Intelligence in Foundry Tools (or use separate keys that belong to each service)
service_key = find_secret(
    secret_name="ai-services-api-key", keyvault="mmlspark-build-keys"
)  # Replace the call to find_secret with your key as a python string. e.g. service_key="27snaiw..."
service_loc = "eastus"

# A Bing Search v7 subscription key
bing_search_key = find_secret(
    secret_name="bing-search-key", keyvault="mmlspark-build-keys"
)  # Replace the call to find_secret with your key as a python string.

# An Anomaly Detector subscription key
anomaly_key = find_secret(
    secret_name="anomaly-api-key", keyvault="mmlspark-build-keys"
)  # Replace the call to find_secret with your key as a python string. If you don't have an anomaly detection resource created before Sep 20th 2023, you won't be able to create one.
anomaly_loc = "westus2"

# A Translator subscription key
translator_key = find_secret(
    secret_name="translator-key", keyvault="mmlspark-build-keys"
)  # Replace the call to find_secret with your key as a python string.
translator_loc = "eastus"

# An Azure search key
search_key = find_secret(
    secret_name="azure-search-key", keyvault="mmlspark-build-keys"
)  # Replace the call to find_secret with your key as a python string.

对文本执行情绪分析

AI 语言服务提供了几种从文本中提取智能见解的算法。 例如,我们可以找到给定输入文本的情绪。 服务将返回介于 0.0 和 1.0 之间的分数,其中低分数表示负面情绪,高分表示正面情绪。 此示例使用三个简单的句子,并返回每个句子的情绪。

# 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 Foundry Tools on spark aint bad", "en-US"),
    ],
    ["text", "language"],
)

# Run the Text Analytics service with options
sentiment = (
    AnalyzeText()
    .setKind("SentimentAnalysis")
    .setTextCol("text")
    .setLocation(service_loc)
    .setSubscriptionKey(service_key)
    .setOutputCol("sentiment")
    .setErrorCol("error")
    .setLanguageCol("language")
)

# Show the results of your text query in a table format
display(
    sentiment.transform(df).select(
        "text", col("sentiment.documents.sentiment").alias("sentiment")
    )
)

对健康状况数据执行文本分析

健康服务文本分析从非结构化文本(如医生处方、出院小结、临床文档和电子健康记录)中提取和标记相关的医疗信息。

以下代码示例分析医生笔记中的文本并将其转换为结构化数据。

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

healthcare = (
    AnalyzeHealthText()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setLanguage("en")
    .setOutputCol("response")
)

display(healthcare.transform(df))

将文本翻译成其他语言

Foundry Tools 中的 Azure Translator 是基于云的机器翻译服务,是用于生成智能应用的 Foundry Tools 系列 AI API 的一部分。 “翻译”可以轻松地集成到应用程序、网站、工具和解决方案中。 它可用来在 90 种语言和方言中添加多语言用户体验,并可用来翻译文本,无需托管你自己的算法。

下面的代码示例中,通过提供要翻译的句子和要翻译到的目标语言来执行简单文本翻译。

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"],)],
    [
        "text",
    ],
)

# Run the Translator service with options
translate = (
    Translate()
    .setSubscriptionKey(translator_key)
    .setLocation(translator_loc)
    .setTextCol("text")
    .setToLanguage(["zh-Hans"])
    .setOutputCol("translation")
)

# Show the results of the translation.
display(
    translate.transform(df)
    .withColumn("translation", flatten(col("translation.translations")))
    .withColumn("translation", col("translation.text"))
    .select("translation")
)

将文档中的信息提取到结构化数据中

文档智能 是 Azure 应用 AI 服务的一部分,可让你使用机器学习技术构建自动化数据处理软件。 借助文档智能,可以从文档中识别和提取文本、键/值对、选择标记、表和结构。 该服务会输出结构化数据,其中包含原始文件中的关系、边界框、置信度,等等。

下面的代码示例分析名片图像,并将上面的信息提取到结构化数据中。

from pyspark.sql.functions import col, explode

# Create a dataframe containing the source files
imageDf = spark.createDataFrame(
    [
        (
            "https://mmlspark.blob.core.windows.net/datasets/FormRecognizer/business_card.jpg",
        )
    ],
    [
        "source",
    ],
)

# Run the Form Recognizer service
analyzeBusinessCards = (
    AnalyzeBusinessCards()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setImageUrlCol("source")
    .setOutputCol("businessCards")
)

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

计算机视觉示例

Foundry 工具中的 Azure 视觉 分析图像,以识别人脸、对象和自然语言描述等结构。

以下代码示例分析图像并使用标签标记图像。 标记是对图像中可识别的对象、人物、风景和动作等事物的单个词说明。

# Create a dataframe with the image URLs
base_url = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/"
df = spark.createDataFrame(
    [
        (base_url + "objects.jpg",),
        (base_url + "dog.jpg",),
        (base_url + "house.jpg",),
    ],
    [
        "image",
    ],
)

# Run the Computer Vision service. Analyze Image extracts information from/about the images.
analysis = (
    AnalyzeImage()
    .setLocation(service_loc)
    .setSubscriptionKey(service_key)
    .setVisualFeatures(
        ["Categories", "Color", "Description", "Faces", "Objects", "Tags"]
    )
    .setOutputCol("analysis_results")
    .setImageUrlCol("image")
    .setErrorCol("error")
)

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

必应图像搜索在 Web 中搜索以检索与用户自然语言查询相关的图像。

下面的代码示例使用文本查询来查找带引号的图像。 代码的输出是包含与查询相关的照片的图像 URL 列表。

# 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 = (
    BingImageSearch()
    .setSubscriptionKey(bing_search_key)
    .setOffsetCol("offset")
    .setQuery("Martin Luther King Jr. quotes")
    .setCount(imgsPerBatch)
    .setOutputCol("images")
)

# 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
display(pipeline.transform(bingParameters))

将语音转换为文本

语音转文本服务将语音音频的流或文件转换为文本。 以下代码示例将一个音频文件转录为文本。

# Create a dataframe with our audio URLs, tied to the column called "url"
df = spark.createDataFrame(
    [("https://mmlspark.blob.core.windows.net/datasets/Speech/audio2.wav",)], ["url"]
)

# Run the Speech-to-text service to translate the audio into text
speech_to_text = (
    SpeechToTextSDK()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setOutputCol("text")
    .setAudioDataCol("url")
    .setLanguage("en-US")
    .setProfanity("Masked")
)

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

将文本转换为语音

文本转语音服务允许用户从 119 种语言和变体的 270 多种神经语音中进行选择,以构建讲述自然语言的应用和服务。

下面的代码示例将文本转换为包含文本内容的音频文件。

from synapse.ml.services.speech 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 aka.ms/spark for more information",
            fs + "/output.mp3",
        )
    ],
    ["text", "output_file"],
)

tts = (
    TextToSpeech()
    .setSubscriptionKey(service_key)
    .setTextCol("text")
    .setLocation(service_loc)
    .setVoiceName("en-US-JennyNeural")
    .setOutputFileCol("output_file")
)

# Check to make sure there were no errors during audio creation
display(tts.transform(df))

检测时序数据中存在的异常

如果你在 2023 年 9 月 20 日之前没有创建异常检测资源,你现在将无法创建。 你可能想要跳过此部分。

异常检测器对于检测时间序列数据中的不规则性非常有用。 下面的代码示例使用异常检测器服务来查找某个时序中存在的异常。

# 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
anomaly_detector = (
    SimpleDetectAnomalies()
    .setSubscriptionKey(anomaly_key)
    .setLocation(anomaly_loc)
    .setTimestampCol("timestamp")
    .setValueCol("value")
    .setOutputCol("anomalies")
    .setGroupbyCol("group")
    .setGranularity("monthly")
)

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

从任意 Web API 获取信息

借助 Spark 上的 HTTP,可以在大数据管道中使用任何 Web 服务。 在此示例中,我们使用 World Bank API 获取有关全球各个国家/地区的信息。

# Use any requests from the python requests library

def world_bank_request(country):
    return Request(
        "GET", "http://api.worldbank.org/v2/country/{}?format=json".format(country)
    )

# Create a dataframe with specifies which countries/regions 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 = (
    HTTPTransformer().setConcurrency(3).setInputCol("request").setOutputCol("response")
)

# Get the body of the response

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

# Show the details of the country/region data returned
display(
    client.transform(df).select(
        "country", udf(get_response_body)(col("response")).alias("response")
    )
)

Azure AI 搜索示例

此示例演示如何使用认知技能扩充数据,并使用 SynapseML 写入 Azure 搜索索引。

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

df = spark.createDataFrame(
    [
        (
            "upload",
            "0",
            "https://mmlspark.blob.core.windows.net/datasets/DSIR/test1.jpg",
        ),
        (
            "upload",
            "1",
            "https://mmlspark.blob.core.windows.net/datasets/DSIR/test2.jpg",
        ),
    ],
    ["searchAction", "id", "url"],
)

tdf = (
    AnalyzeImage()
    .setSubscriptionKey(service_key)
    .setLocation(service_loc)
    .setImageUrlCol("url")
    .setOutputCol("analyzed")
    .setErrorCol("errors")
    .setVisualFeatures(
        ["Categories", "Tags", "Description", "Faces", "ImageType", "Color", "Adult"]
    )
    .transform(df)
    .select("*", "analyzed.*")
    .drop("errors", "analyzed")
)

tdf.writeToAzureSearch(
    subscriptionKey=search_key,
    actionCol="searchAction",
    serviceName=search_service,
    indexName=search_index,
    keyCol="id",
)