Microsoft Fabric에서 SynapseML과 함께 Azure AI 서비스 사용
Azure AI 서비스는 개발자와 조직이 즉시 사용 가능하고 사전 빌드되었으며 사용자 지정 가능한 API 및 모델을 사용하여 시장에 출시할 수 있는 지능적이고 최첨단의 책임감 있는 애플리케이션을 신속하게 만들 수 있도록 지원합니다. 이 문서에서는 Azure AI 서비스에서 사용할 수 있는 다양한 서비스를 사용하여 텍스트 분석, 번역, 문서 인텔리전스, 비전, 이미지 검색, 음성 텍스트 변환 및 텍스트 음성 변환, 이상 탐지 및 웹 API에서 데이터 추출을 포함하는 작업을 수행합니다.
Azure AI 서비스의 목표는 개발자가 보고, 듣고, 말하고, 이해하고, 추론까지 할 수 있는 애플리케이션을 만들도록 지원하는 것입니다. Azure AI 서비스 내의 서비스 카탈로그는 5가지 주요 핵심 요소인 비전, 음성, 언어, 웹 검색 및 결정으로 분류될 수 있습니다.
필수 조건
Microsoft Fabric 구독을 구매합니다. 또는 무료 Microsoft Fabric 평가판에 등록합니다.
Microsoft Fabric에 로그인합니다.
홈페이지 왼쪽 아래에 있는 환경 전환기를 사용하여 패브릭으로 전환합니다.
- 새 Notebook을 만듭니다.
- 레이크하우스에 Notebook을 첨부합니다. Notebook 왼쪽에서 추가를 선택하여 기존 레이크하우스를 추가하거나 새 레이크하우스를 만듭니다.
- 빠른 시작: Azure AI 서비스에 대한 다중 서비스 리소스 만들기를 통해 Azure AI 서비스 키를 가져옵니다. 아래 코드 샘플에서 사용할 키 값을 복사합니다.
시스템 준비
시작하려면 필수 라이브러리를 가져오고 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
import os
from pyspark.sql import SparkSession
from synapse.ml.core.platform import *
# Bootstrap Spark Session
spark = SparkSession.builder.getOrCreate()
Azure AI 서비스 라이브러리를 가져오고 다음 코드 조각의 키와 위치를 Azure AI 서비스 키 및 위치로 바꿉니다.
from synapse.ml.cognitive import *
# A general Azure AI services key for Text Analytics, Vision and Document Intelligence (or use separate keys that belong to each service)
service_key = "<YOUR-KEY-VALUE>" # Replace <YOUR-KEY-VALUE> with your Azure AI service key, check prerequisites for more details
service_loc = "eastus"
# A Bing Search v7 subscription key
bing_search_key = "<YOUR-KEY-VALUE>" # Replace <YOUR-KEY-VALUE> with your Bing v7 subscription key, check prerequisites for more details
# An Anomaly Detector subscription key
anomaly_key = <"YOUR-KEY-VALUE"> # Replace <YOUR-KEY-VALUE> with your anomaly service key, check prerequisites for more details
anomaly_loc = "westus2"
# A Translator subscription key
translator_key = "<YOUR-KEY-VALUE>" # Replace <YOUR-KEY-VALUE> with your translator service key, check prerequisites for more details
translator_loc = "eastus"
# An Azure search key
search_key = "<YOUR-KEY-VALUE>" # Replace <YOUR-KEY-VALUE> with your search key, check prerequisites for more details
텍스트에 대한 감정 분석 수행
Text Analytics 서비스는 텍스트에서 인텔리전트 인사이트를 추출하기 위한 몇 가지 알고리즘을 제공합니다. 예를 들어 서비스를 사용하여 일부 입력 텍스트의 감정을 찾을 수 있습니다. 이 서비스는 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 cognitive services on spark aint bad", "en-US"),
],
["text", "language"],
)
# Run the Text Analytics service with options
sentiment = (
TextSentiment()
.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.document.sentiment").alias("sentiment")
)
)
상태 데이터에 대한 텍스트 분석 수행
의료 분야 Text Analytics는 의사의 메모, 퇴원 요약, 임상 문서 및 전자 의료 레코드 같은 비정형 텍스트에서 관련 의료 정보를 추출하고 레이블을 지정합니다.
다음 코드 샘플은 의사 메모의 텍스트를 분석하고 구조화된 데이터로 변환합니다.
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))
다른 언어로 텍스트 번역
번역기는 클라우드 기반 기계 번역 서비스이며 지능형 앱을 빌드하는 데 사용되는 Azure AI 서비스의 인지 API 제품군의 일부입니다. Translator는 애플리케이션, 웹 사이트, 도구 및 솔루션에 쉽게 통합할 수 있습니다. 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 문서 인텔리전스는 기계 학습 기술을 사용하여 자동화된 데이터 처리 소프트웨어를 빌드할 수 있는 Azure AI 서비스의 일부입니다. 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")
)
태그 이미지 분석
Computer Vision은 이미지를 분석하여 얼굴, 개체 및 자연어 설명과 같은 구조를 식별합니다.
다음 코드 샘플은 이미지를 분석하고 태그로 레이블을 지정합니다. 태그는 인식할 수 있는 개체, 사람, 풍경, 작업 등 이미지의 대상에 대한 한 단어 설명입니다.
# 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"))
자연어 쿼리와 관련된 이미지 쿼리
Bing Image Search는 웹을 검색하여 사용자의 자연어 쿼리와 관련된 이미지를 검색합니다.
다음 코드 샘플은 따옴표가 있는 이미지를 찾는 텍스트 쿼리를 사용합니다. 코드의 출력은 쿼리와 관련된 사진이 포함된 이미지 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.cognitive 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))
시계열 데이터의 변칙 징후 검색
Anomaly Detector는 시계열 데이터의 변칙을 감지하는 데 유용합니다. 다음 코드 샘플은 Anomaly Detector 서비스를 사용하여 전체 시계열에서 변칙을 찾습니다.
# 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 = (
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(
anamoly_detector.transform(df).select("timestamp", "value", "anomalies.isAnomaly")
)
임의의 웹 API에서 정보 가져오기
HTTP on Spark를 사용하면 빅 데이터 파이프라인에서 모든 웹 서비스를 사용할 수 있습니다. 다음 코드 샘플은세계 은행 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 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 data returned
display(
client.transform(df).select(
"country", udf(get_response_body)(col("response")).alias("response")
)
)