Compartir a través de


Uso de servicios de Azure AI con SynapseML en Microsoft Fabric

los servicios de Azure AI ayudan a los desarrolladores y a las organizaciones a crear rápidamente aplicaciones inteligentes, avanzadas, listas para el mercado y responsables con api y modelos precompilados y personalizables. En este artículo, usará los distintos servicios disponibles en los servicios de Azure AI para realizar tareas que incluyen: análisis de texto, traducción, inteligencia de documentos, visión, búsqueda de imágenes, conversión de voz a texto y conversión de texto a voz, detección de anomalías y extracción de datos de las API web.

El objetivo de los servicios de Azure AI es ayudar a los desarrolladores a crear aplicaciones que puedan ver, escuchar, hablar, comprender e incluso empezar a razonar. El catálogo de servicios dentro de los servicios de Azure AI se puede clasificar en cinco pilares principales: Vision, Speech, Language, Web searchy Decision.

Prerrequisitos

Prepare su sistema

Para empezar, importe las bibliotecas necesarias e inicialice la sesión de 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()

Importe las bibliotecas de servicios de Azure AI y reemplace las claves y ubicaciones del siguiente fragmento de código por la clave y la ubicación de los servicios de 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

Realizar análisis de sentimiento en texto

El servicio Text Analytics proporciona varios algoritmos para extraer información inteligente del texto. Por ejemplo, puede usar el servicio para buscar la opinión de algún texto de entrada. El servicio devolverá una puntuación entre 0,0 y 1,0, donde las puntuaciones bajas indican opiniones negativas y puntuaciones altas indican opiniones positivas.

El ejemplo de código siguiente devuelve la opinión de tres oraciones simples.

# 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")
    )
)

Realizar análisis de texto para datos de salud

El Text Analytics for Health Service extrae y etiqueta información médica relevante de texto no estructurado, como notas del médico, resúmenes de alta, documentos clínicos y registros sanitarios electrónicos.

En el ejemplo de código siguiente se analiza y transforma el texto de las notas de los médicos en datos estructurados.

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))

Traducción de texto a otro idioma

Translator es un servicio de traducción automática basado en la nube y forma parte de la familia de servicios de Inteligencia Artificial de Azure que se usan para crear aplicaciones inteligentes. Translator es fácil de integrar en sus aplicaciones, sitios web, herramientas y soluciones. Permite agregar experiencias de usuario de varios idiomas en 90 idiomas y dialectos y se puede usar para la traducción de texto con cualquier sistema operativo.

En el ejemplo de código siguiente se realiza una traducción de texto simple proporcionando las oraciones a las que desea traducir e idiomas de destino a los que desea traducirlos.

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")
)

Extracción de información de un documento en datos estructurados

azure AI Document Intelligence forma parte de los servicios de Azure AI que le permiten crear software de procesamiento de datos automatizado mediante la tecnología de aprendizaje automático. Con La inteligencia de documentos de Azure AI, puede identificar y extraer texto, pares clave-valor, marcas de selección, tablas y estructura de los documentos. El servicio genera datos estructurados que incluyen las relaciones en el archivo original, los cuadros de límite, la confianza y mucho más.

En el ejemplo de código siguiente se analiza una imagen de tarjeta de presentación y se extrae su información en datos estructurados.

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")
)

Análisis e etiquetado de imágenes

Computer Vision analiza imágenes para identificar estructuras como caras, objetos y descripciones de lenguaje natural.

En el ejemplo de código siguiente se analizan imágenes y se etiquetan con etiquetas . Las etiquetas son descripciones únicas de las cosas de la imagen, como objetos reconocibles, personas, paisajes y acciones.

# 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 busca en la web para recuperar imágenes relacionadas con la consulta de lenguaje natural de un usuario.

En el ejemplo de código siguiente se usa una consulta de texto que busca imágenes con comillas. La salida del código es una lista de direcciones URL de imagen que contienen fotos relacionadas con la consulta.

# 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))

Transformación de voz en texto

El servicio de conversión de voz en texto convierte secuencias o archivos de audio hablado en texto. En el ejemplo de código siguiente se transcribe un archivo de audio al texto.

# 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"))

Transformación de texto a voz

texto a voz es un servicio que permite crear aplicaciones y servicios que hablan naturalmente, eligiendo entre más de 270 voces neuronales en 119 idiomas y variantes.

El ejemplo de código siguiente transforma el texto en un archivo de audio que contiene el contenido del texto.

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))

Detección de anomalías en los datos de series temporales

Anomaly Detector es excelente para detectar irregularidades en series temporales de datos. En el ejemplo de código siguiente se usa el servicio Anomaly Detector para buscar anomalías en datos completos de series temporales.

# 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")
)

Obtención de información de API web arbitrarias

Con HTTP en Spark, puede usar cualquier servicio web en la canalización de macrodatos. En el ejemplo de código siguiente se usa el api de Banco Mundial para obtener información sobre varios países de todo el mundo.

# 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")
    )
)