Azure AI 서비스는 개발자와 조직이 사용할 준비가 되어 있고 사용자 지정 가능한 API 및 모델을 사용하여 책임 있는 애플리케이션을 빌드하는 데 도움이 됩니다. 이 문서에서는 Azure AI 서비스를 사용하여 텍스트 분석, 번역, 문서 인텔리전스, 비전, 이미지 검색, 음성 텍스트 및 텍스트 음성 변환, 변칙 검색 및 웹 API에서 데이터 추출을 포함하는 작업을 수행합니다.
Azure AI 서비스는 개발자가 보고, 듣고, 말하고, 이해하고, 추론하기 시작하는 애플리케이션을 만드는 데 도움이 됩니다. Azure AI 서비스 카탈로그에는 비전, 음성, 언어, 웹 검색 및 의사 결정의 다섯 가지 핵심 요소가 포함되어 있습니다.
Prerequisites
Microsoft Fabric 구독을 구매합니다. 또는 무료 Microsoft Fabric 평가판에 등록합니다.
Microsoft Fabric에 로그인합니다.
홈 페이지의 왼쪽 아래에 있는 환경 전환기를 사용하여 패브릭으로 전환합니다.
- Notebook을 만듭니다.
- 레이크하우스에 전자 필기장을 첨부합니다. Notebook에서 추가 를 선택하여 기존 레이크하우스를 추가하거나 새 레이크하우스를 만듭니다.
- Azure AI 서비스 키를 가져옵니다. 빠른 시작: Azure AI 서비스에 대한 다중 서비스 리소스를 만듭니다. 아래 코드 샘플에서 사용할 키 값을 복사합니다.
시스템 준비
먼저 필요한 라이브러리를 가져오고 Spark 세션을 초기화합니다.
from pyspark.sql.functions import udf, col, lit
from synapse.ml.io.http import HTTPTransformer, http_udf
from requests import Request
from pyspark.ml import PipelineModel
import os
from pyspark.sql import SparkSession
# Start a Spark session.
spark = SparkSession.builder.getOrCreate()
Azure AI 서비스 라이브러리를 가져옵니다. 다음 코드에서 자리 표시자 텍스트를 <YOUR-KEY-VALUE> 사용자 고유의 키로 바꾸고 각 서비스의 위치 값을 설정합니다.
from synapse.ml.cognitive import *
# A general Azure AI services key for Text Analytics, Vision, and Document Intelligence (or use separate keys for each service).
service_key = "<YOUR-KEY-VALUE>" # Replace `<YOUR-KEY-VALUE>` with your Azure AI services key. See prerequisites for details.
service_loc = "eastus"
# A Bing Search v7 subscription key.
bing_search_key = "<YOUR-KEY-VALUE>" # Replace `<YOUR-KEY-VALUE>` with your Bing Search v7 subscription key. See prerequisites for details.
# An Anomaly Detector subscription key.
anomaly_key = "<YOUR-KEY-VALUE>" # Replace `<YOUR-KEY-VALUE>` with your Anomaly Detector key. See prerequisites for details.
anomaly_loc = "westus2"
# A Translator subscription key.
translator_key = "<YOUR-KEY-VALUE>" # Replace `<YOUR-KEY-VALUE>` with your Translator key. See prerequisites for details.
translator_loc = "eastus"
# An Azure Search key.
search_key = "<YOUR-KEY-VALUE>" # Replace `<YOUR-KEY-VALUE>` with your Azure Search key. See prerequisites for details.
텍스트로 감정 분석
Text Analytics 서비스는 텍스트에서 지능형 인사이트를 추출하기 위한 몇 가지 알고리즘을 제공합니다. 예를 들어 서비스를 사용하여 입력 텍스트의 감정을 분석합니다. 서비스는 0.0에서 1.0 사이의 점수를 반환합니다. 낮은 점수는 부정적인 감정을 나타내고, 높은 점수는 긍정적인 감정을 나타냅니다.
이 코드 샘플은 세 문장에 대한 감정을 반환합니다.
# Create a DataFrame that's tied to its column names
df = spark.createDataFrame(
[
("I am so happy today, it's sunny!", "en-US"),
("I am frustrated by this rush hour traffic", "en-US"),
("The cognitive services on Spark aren't 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 in a table.
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))
텍스트를 다른 언어로 번역
Translator 는 지능형 앱을 빌드하기 위한 인식 API의 Azure AI 서비스 제품군에 속하는 클라우드 기반 기계 번역 서비스입니다. Translator는 앱, 웹 사이트, 도구 및 솔루션에 쉽게 통합됩니다. 90개 언어 및 방언으로 다국어 환경을 추가할 수 있으며 텍스트 번역을 위한 모든 운영 체제에서 작동합니다.
다음 코드 샘플에서는 입력 문장을 대상 언어로 변환합니다.
from pyspark.sql.functions import col, flatten
# Create a DataFrame with the sentences to translate
df = spark.createDataFrame(
[(["Hello, what is your name?", "Bye"],)],
[
"text",
],
)
# Run the Translator service.
translate = (
Translate()
.setSubscriptionKey(translator_key)
.setLocation(translator_loc)
.setTextCol("text")
.setToLanguage(["zh-Hans"])
.setOutputCol("translation")
)
# Show the translation results.
display(
translate.transform(df)
.withColumn("translation", flatten(col("translation.translations")))
.withColumn("translation", col("translation.text"))
.select("translation")
)
문서에서 구조화된 데이터로 정보 추출
Azure AI Document Intelligence 는 Azure AI 서비스의 일부이며 기계 학습을 사용하여 자동화된 데이터 처리 소프트웨어를 빌드할 수 있습니다. Azure AI Document Intelligence를 사용하여 문서에서 텍스트, 키-값 쌍, 선택 표시, 테이블 및 구조를 식별하고 추출합니다. 서비스는 원래 파일의 관계, 경계 상자, 신뢰도 점수 등을 포함하는 구조화된 데이터를 출력합니다.
다음 코드는 명함 이미지를 분석하고 해당 정보를 구조화된 데이터로 추출합니다.
from pyspark.sql.functions import col, explode
# Create a DataFrame with the source files
imageDf = spark.createDataFrame(
[
(
"https://mmlspark.blob.core.windows.net/datasets/FormRecognizer/business_card.jpg",
)
],
[
"source",
],
)
# Run Azure AI Document Intelligence
analyzeBusinessCards = (
AnalyzeBusinessCards()
.setSubscriptionKey(service_key)
.setLocation(service_loc)
.setImageUrlCol("source")
.setOutputCol("businessCards")
)
# Show recognition results.
display(
analyzeBusinessCards.transform(imageDf)
.withColumn(
"documents", explode(col("businessCards.analyzeResult.documentResults.fields"))
)
.select("source", "documents")
)
이미지 분석 및 태그 지정
Azure AI Vision 은 이미지를 분석하여 얼굴, 개체 및 자연어 설명을 식별합니다.
이 코드 샘플은 이미지를 분석하고 태그를 사용하여 레이블 을 지정합니다. 태그는 이미지의 개체, 사람, 풍경 및 작업에 대한 한 단어 설명입니다.
# Create a DataFrame with 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 Azure AI Vision to analyze images and extract information.
analysis = (
AnalyzeImage()
.setLocation(service_loc)
.setSubscriptionKey(service_key)
.setVisualFeatures(
["Categories", "Color", "Description", "Faces", "Objects", "Tags"]
)
.setOutputCol("analysis_results")
.setImageUrlCol("image")
.setErrorCol("error")
)
# Show the description tags.
display(analysis.transform(df).select("image", "analysis_results.description.tags"))
자연어 쿼리와 관련된 이미지 검색
Bing Image Search 는 웹을 검색하여 사용자의 자연어 쿼리와 관련된 이미지를 검색합니다.
이 샘플에서는 텍스트 쿼리를 사용하여 따옴표 이미지를 찾습니다. 쿼리와 관련된 이미지 URL 목록을 출력합니다.
# Number of images Bing returns per query
imgsPerBatch = 10
# List of offsets to page through the search results
offsets = [(i * imgsPerBatch,) for i in range(100)]
# Create a DataFrame of offsets to page through results
bingParameters = spark.createDataFrame(offsets, ["offset"])
# Run Bing Image Search with the text query
bingSearch = (
BingImageSearch()
.setSubscriptionKey(bing_search_key)
.setOffsetCol("offset")
.setQuery("Martin Luther King Jr. quotes")
.setCount(imgsPerBatch)
.setOutputCol("images")
)
# Create a transformer that extracts and flattens the Bing Image Search output into a single URL column
getUrls = BingImageSearch.getUrlTransformer("images", "url")
# Display the full results. Uncomment to use
# display(bingSearch.transform(bingParameters))
# Put both services into a pipeline
pipeline = PipelineModel(stages=[bingSearch, getUrls])
# Show the image URLs returned by the search
display(pipeline.transform(bingParameters))
음성을 텍스트로 변환
Azure AI Speech Service는 음성 오디오 스트림 또는 파일을 텍스트로 변환합니다. 다음 코드 샘플은 하나의 오디오 파일을 전사합니다.
# Create a DataFrame with the audio URL in the 'url' column
df = spark.createDataFrame(
[("https://mmlspark.blob.core.windows.net/datasets/Speech/audio2.wav",)], ["url"]
)
# Run Azure AI Speech to transcribe the audio
speech_to_text = (
SpeechToTextSDK()
.setSubscriptionKey(service_key)
.setLocation(service_loc)
.setOutputCol("text")
.setAudioDataCol("url")
.setLanguage("en-US")
.setProfanity("Masked")
)
# Show the transcription results
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 that there are 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 Anomaly Detector to detect anomalies
anomaly_detector = (
SimpleDetectAnomalies()
.setSubscriptionKey(anomaly_key)
.setLocation(anomaly_loc)
.setTimestampCol("timestamp")
.setValueCol("value")
.setOutputCol("anomalies")
.setGroupbyCol("group")
.setGranularity("monthly")
)
# Show results with anomalies marked as True
display(
anomaly_detector.transform(df).select("timestamp", "value", "anomalies.isAnomaly")
)
임의의 웹 API에서 정보 가져오기
Spark에서 HTTP를 사용하여 큰 파이프라인의 모든 웹 서비스를 사용합니다. 다음 코드 샘플에서는 World Bank API 를 사용하여 전 세계 여러 국가 및 지역에 대한 정보를 가져옵니다.
# Use any request 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 that specifies the countries to get data for.
df = spark.createDataFrame([("br",), ("usa",)], ["country"]).withColumn(
"request", http_udf(world_bank_request)(col("country"))
)
# Improve big data performance by using 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 country details from the response.
display(
client.transform(df).select(
"country", udf(get_response_body)(col("response")).alias("response")
)
)