Crear un API rest de Análisis de sentimiento con SAM y Amazon Comprehend | NLP Series parte 3

Crear un API rest de Análisis de sentimiento con SAM y Amazon Comprehend | NLP Series parte 3

Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 4

📢 Leveleando nuestro guerrero 3 niveles hoy!

Soy Carlos Cortez y bienvenidos a la tercera entrega de estas series, pero, ¿qué me estás contando? Vamos a por 3 niveles más!, hoy aprenderemos las bases de Comprehend y de cómo analizar sentimientos, así como extraer las entidades de los textos, usando un modelo pre entrenado de Amazon Comprehend.

Al mismo tiempo, hago Referencia a unas series en paralelo sobre Serverless, llamadas: Away from Servers, porque hoy también repasamos API rest en AWS y codificaremos una plantilla de AWS SAM, el marco de trabajo de amazon web services para gestionar la configuración de nuestras aplicaciones sin servidor.

Además de estos 4 servicios, aprenderemos más sobre boto3, y Python.

Fuente: Imagen creada por Carlos Cortez, NLP Series parte 3Fuente: Imagen creada por Carlos Cortez, NLP Series parte 3

🧩 Pasar a level 2 es tarea sencilla

Puedes elegir entre, desarrollar el nivel 2, nivel 3 o nivel 4 que veremos más abajo en este episodio, en los 3 lograrás el mismo resultado, que es aprender sobre Amazon Comprehend.

OJO: Siempre es necesario un rol, un permiso, una política cuando creamos un Lambda, en este caso estaremos usando Full Access para Comprehend en IAM.

El nivel 2, trata principalmente de crear una función lambda en la consola de AWS directamente y conectarla con Amazon Comprehend, luego definir un evento de prueba con un JSON y empezar a jugar.

Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 2Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 2

Usemos esta función para darle vida a nuestro Lambda,

import json
import boto3

#Using boto3 to call the Comprehend API
client = boto3.client('comprehend')

#Lambda function to work with Comprehend
def lambda_handler(event, context):

    print("event puro:", event)
    #Accessing data
    puro = json.dumps(event) #intentando cambiar aqui sino vuelvo a la linea 13
    text = puro[0]
    json_object = json.loads(puro)
    print("texto a analizar: ", json_object["body"])
    Body = json.dumps(json_object["body"])
    print("Body:", Body)


    #Sentiment Analysis
    print("iniciando analisis de sentimiento....")
    sentiment = client.detect_sentiment(Text = Body, LanguageCode = 'en') #API call for sentiment analysis
    sentRes = sentiment['Sentiment'] #Positive, Neutral, or Negative
    sentScore = sentiment['SentimentScore'] #Percentage of Positive, Neutral, and Negative
    print(sentRes)
    print(sentScore)

    print("iniciando extraccion de entidades....")
    #Entity Extraction
    entities = client.detect_entities(Text = Body, LanguageCode = 'en') #API call for entity extraction
    entities = entities['Entities'] #all entities
    print(entities)
    textEntities = [dict_item['Text'] for dict_item in entities] #the text that has been identified as entities
    typeEntities = [dict_item['Type'] for dict_item in entities] #the type of entity the text is
    print(textEntities)
    print(typeEntities)


    return {
        'statusCode': 200,
        'body': str(sentiment) + str(entities) #body returned from our function
    }

Explicación:

  1. LÍNEA 12 extraemos el JSON del evento

  2. LÍNEA 20, detectamos el sentimiento sea positivo negativo o neutral

  3. LÍNEA 28: extraemos las entidades detectadas definidas por AWS

Las pruebas aquí son más sencillas, usando la IDE de Cloud9 en Lambda directo en la consola:

Y agregar el evento, es muy rápido, en el level 3 y 4 verán maneras más óptimas de realizar esta prueba. Pueden pasar directo allá.

🧩 Si pasaste el nivel 2, ahora en nivel 3 completamos el Backend

Al adicionar la capa de API rest vamos a darle más cuerpo a nuestra solución. Además como arquitectos de soluciones que somos o queremos ser, tenemos que construir aplicaciones resilientes, escalables y altamente disponibles. Para ello implementamos una capa de API que nos permita escalar. Más adelante nos servirá para agregar seguridad como Cognito, CORS, Caché, custom headers.

Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 3Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 3

No vamos a detallar esta etapa, porque será mucho más genial en nivel 4, pero sí mencionar que probar con API Gateway es mucho más eficiente desde un terminal o una aplicación como Postman. (https://www.postman.com/)

🧩 Nivel 4: ¡Evolucionando a SAM!

Llegó la hora, dejen de ver y pongámonos a trabajar aquí, que esta es la parte más interesante.

Los marcos de trabajo para aplicaciones sin servidor, están tomando un lugar más frecuente en el desarrollo de servicios, AWS SAM llegó algo tarde, y es la opción nativa dentro de los servicios de Amazon Web Services que compite con grandes como Serverless Framework, Chalice, Amplify, pulumi, etc.

No se preocupen, en las series dedicadas a Serverless, nos pelearemos con otros frameworks y veremos qué tan divertido es usarlos! Ahora, me enfocaré en subir a mi nivel 4!

Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 4Fuente: Imagen creada por Carlos Cortez, AWS Warrior Level 4

Cada vez que hago un cambio, se construye toda mi aplicación desde cero. Invierto menos tiempo configurando la consola, que no debería tocarla ni verla más, y me dedico a mejorar el código e integrarlo con más servicios.

🧩 Actualizar sam-cli

Puedes usar una versión más actual si lo prefieres, en este caso:

➜  comprehend-nlp01 brew upgrade aws-sam-cli

Warning: aws/tap/aws-sam-cli 1.13.2 already installed

crear ambiente virtual de python 3.6, (yo tengo múltiples versiones)

➜  comprehend-nlp01 virtualenv -p `which python3.6` nlp01


created virtual environment CPython3.6.5.final.0-64 in 486ms
  creator CPython3Posix(dest=/Users/carlos/repos/cc/nlp/comprehend-nlp01/nlp01, clear=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/Users/carlos/Library/Application Support/virtualenv)
    added seed packages: pip==20.1.1, setuptools==47.3.1, wheel==0.34.2
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator

Iniciamos un template vacío de SAM para Python 3.6

**➜ comprehend-nlp01 source nlp01/bin/activate**

(nlp01)  comprehend-nlp01 python  version

Python 3.6.5

🧩 Inicializamos SAM

(nlp01) ➜ comprehend-nlp01 sam init

Elegimos un template por default:

Which template source would you like to use?

1  AWS Quick Start Templates

2  Custom Template Location

Choice: 1

Which runtime would you like to use?

1  nodejs12.x

2  python3.8

3  ruby2.7

4  go1.x

5  java11

6  dotnetcore3.1

7  nodejs10.x

8  python3.7

9  python3.6

10  python2.7

11  ruby2.5

12  java8

13  dotnetcore2.1

14  dotnetcore2.0

15  dotnetcore1.0

Runtime: 9

Project name [sam-app]: comprehend-01-nlpseries-ep-3

Cloning app templates from https://github.com/awslabs/aws-sam-cli-app-templates.git

AWS quick start application templates:

1  Hello World Example

2  EventBridge Hello World

3  EventBridge App from scratch (100+ Event Schemas)

4  Step Functions Sample App (Stock Trader)

Template selection: 1

            -

Generating application:

            -

Name: comprehend-01-nlpseries-ep-3

Runtime: python3.6

Dependency Manager: pip

Application Template: hello-world

Output Directory: .

Next steps can be found in the README file at ./comprehend-01-nlpseries-ep-3/README.md

Errores de compatibilidad a la hora de crear los templates

Error: Permission denied @ apply2files — /usr/local/lib/node_modules/@aws-amplify/cli/node_modules/extglob/lib/.DS_Store

No debemos darle permisos a todo, salvo lo necesario

Solución:

sudo chown -R ${LOGNAME}:staff /usr/local/lib/node_modules

Aquí vamos a modificar varios archivos,

App.py es el archivo principal, que será el Lambda que usamos, el mismo del nivel 2 y 3!

import json
import boto3

#Using boto3 to call the Comprehend API
client = boto3.client('comprehend')

#Lambda function to work with Comprehend
def lambda_handler(event, context):

    print("event puro:", event)
    #Accessing data
    puro = json.dumps(event) #intentando cambiar aqui sino vuelvo a la linea 13
    text = puro[0]
    json_object = json.loads(puro)
    print("texto a analizar: ", json_object["body"])
    Body = json.dumps(json_object["body"])
    print("Body:", Body)


    #Sentiment Analysis
    print("iniciando analisis de sentimiento....")
    sentiment = client.detect_sentiment(Text = Body, LanguageCode = 'en') #API call for sentiment analysis
    sentRes = sentiment['Sentiment'] #Positive, Neutral, or Negative
    sentScore = sentiment['SentimentScore'] #Percentage of Positive, Neutral, and Negative
    print(sentRes)
    print(sentScore)

    print("iniciando extraccion de entidades....")
    #Entity Extraction
    entities = client.detect_entities(Text = Body, LanguageCode = 'en') #API call for entity extraction
    entities = entities['Entities'] #all entities
    print(entities)
    textEntities = [dict_item['Text'] for dict_item in entities] #the text that has been identified as entities
    typeEntities = [dict_item['Type'] for dict_item in entities] #the type of entity the text is
    print(textEntities)
    print(typeEntities)


    return {
        'statusCode': 200,
        'body': str(sentiment) + str(entities) #body returned from our function
    }

Luego, el template.yaml que es dónde se definirá la estructura de nuestra aplicación serverless con API Gateway y Lambda.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  comprehend-01-nlpseries-ep-3
  Sample SAM Template for comprehend-01-nlpseries-ep-3
Globals:
  Function:
    Timeout: 3

Resources:
  Comprehend01nlpseriesep3Function:
    Type: AWS::Serverless::Function 
    Properties:
      CodeUri: comprehend_01_nlpseries_ep_3/
      Handler: app.lambda_handler
      Runtime: python3.6
      Policies: ComprehendFullAccess
      Events:
        HttpPost:
          Type: Api
          Properties:
            Path: '/sentiment'
            Method: post

Outputs:
  # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
  ComprehendApi:
    Description: "API Gateway endpoint URL for Prod stage for Hello World function"
    Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/sentiment/"
  Comprehend01nlpseriesep3Function:
    Description: "comprehend_01_nlpseries_ep_3 Function ARN"
    Value: !GetAtt Comprehend01nlpseriesep3Function.Arn
  Comprehend01nlpseriesep3FunctionIamRole:
    Description: "Implicit IAM Role created for comprehend_01_nlpseries_ep_3 function"
    Value: !GetAtt Comprehend01nlpseriesep3FunctionRole.Arn

Puedes ir al archivo del repo aquí: ccortezb/comprehend_apirest_sentiment_nlpseries You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com

En este template, creamos el API, los recursos y los métodos, en este caso necesitamos hacer un POST a /sentiment que hará un proxy directo a nuestro Lambda para luego comunicarse con Comprehend

Events:

HttpPost:

   Type: Api

      Properties:

         Path: ‘/sentiment’

         Method: post

🧩 SAM Build:

Ejecutar lo siguiente:

(nlp01) ➜ comprehend-01-nlpseries-ep-3 **sudo sam build**

Resultado:

Building resource ‘Comprehend01nlpseriesep3Function’

Running PythonPipBuilder:ResolveDependencies

Running PythonPipBuilder:CopySource

Build Succeeded

Built Artifacts : .aws-sam/build

Built Template : .aws-sam/build/template.yaml

Commands you can use next

=========================

[*] Invoke Function: sam local invoke

[*] Deploy: sam deploy — guided

🧩 SAM Deploy:

Haremos el Deploy directo desde la consola, para ejecutar nuestro Stack de CloudFormation de manera programática

(nlp01) ➜  comprehend-01-nlpseries-ep-3 sudo sam deploy --guided

Configuring SAM deploy
======================

  Looking for samconfig.toml :  Found
  Reading default arguments  :  Success

  Setting default arguments for 'sam deploy'
  =========================================
  Stack Name [comprehend-01-nlp-03]:
  AWS Region [ca-central-1]:
  #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
  Confirm changes before deploy [Y/n]: Y
  #SAM needs permission to be able to create roles to connect to the resources in your template
  Allow SAM CLI IAM role creation [Y/n]: Y
  Save arguments to samconfig.toml [Y/n]: Y

  Looking for resources needed for deployment: Found!

    Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-18d1u3hw3hac2
    A different default S3 bucket can be set in samconfig.toml

  Saved arguments to config file
  Running 'sam deploy' for future deployments will use the parameters saved above.
  The above parameters can be changed by modifying samconfig.toml
  Learn more about samconfig.toml syntax at
  https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

  Deploying with following values
  ===============================
  Stack name                 : comprehend-01-nlp-03
  Region                     : ca-central-1
  Confirm changeset          : True
  Deployment s3 bucket       : aws-sam-cli-managed-default-samclisourcebucket-18d1u3hw3hac2
  Capabilities               : ["CAPABILITY_IAM"]
  Parameter overrides        : {}

Initiating deployment
=====================

Waiting for changeset to be created..
Error: Failed to create changeset for the stack: comprehend-01-nlp-03, ex: Waiter ChangeSetCreateComplete failed: Waiter encountered a terminal failure state Status: FAILED. Reason: Template error: instance of Fn::GetAtt references undefined resource HelloWorldFunctionRole
(nlp01) ➜  comprehend-01-nlpseries-ep-3 sudo sam deploy --guided

Configuring SAM deploy
======================

  Looking for samconfig.toml :  Found
  Reading default arguments  :  Success

  Setting default arguments for 'sam deploy'
  =========================================
  Stack Name [comprehend-01-nlp-03]:
  AWS Region [ca-central-1]:
  #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
  Confirm changes before deploy [Y/n]: Y
  #SAM needs permission to be able to create roles to connect to the resources in your template
  Allow SAM CLI IAM role creation [Y/n]: Y
  Save arguments to samconfig.toml [Y/n]: Y

  Looking for resources needed for deployment: Found!

    Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-18d1u3hw3hac2
    A different default S3 bucket can be set in samconfig.toml

  Saved arguments to config file
  Running 'sam deploy' for future deployments will use the parameters saved above.
  The above parameters can be changed by modifying samconfig.toml
  Learn more about samconfig.toml syntax at
  https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html

  Deploying with following values
  ===============================
  Stack name                 : comprehend-01-nlp-03
  Region                     : ca-central-1
  Confirm changeset          : True
  Deployment s3 bucket       : aws-sam-cli-managed-default-samclisourcebucket-18d1u3hw3hac2
  Capabilities               : ["CAPABILITY_IAM"]
  Parameter overrides        : {}

Initiating deployment
=====================
Uploading to comprehend-01-nlp-03/eff52ec0ae2140c2154eb8486ef244aa.template  1286 / 1286.0  (100.00%)

Waiting for changeset to be created..

CloudFormation stack changeset
------------------------------------------------------------------------------------------------------------------------------------------------
Operation                                        LogicalResourceId                                ResourceType
------------------------------------------------------------------------------------------------------------------------------------------------
+ Add                                            Comprehend01nlpseriesep3FunctionHttpPostPermis   AWS::Lambda::Permission
                                                 sionProd
+ Add                                            Comprehend01nlpseriesep3FunctionRole             AWS::IAM::Role
+ Add                                            Comprehend01nlpseriesep3Function                 AWS::Lambda::Function
+ Add                                            ServerlessRestApiDeployment1449b782f7            AWS::ApiGateway::Deployment
+ Add                                            ServerlessRestApiProdStage                       AWS::ApiGateway::Stage
+ Add                                            ServerlessRestApi                                AWS::ApiGateway::RestApi
------------------------------------------------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:ca-central-1:[aws_account_number]:changeSet/samcli-deploy1617735990/54bf479f-01a3-49ac-a71f-30219a23f2ba


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2021-04-06 14:06:44 - Waiting for stack create/update to complete

CloudFormation events from changeset
-------------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                       ResourceType                         LogicalResourceId                    ResourceStatusReason
-------------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                   AWS::IAM::Role                       Comprehend01nlpseriesep3FunctionRo   -
                                                                          le
CREATE_IN_PROGRESS                   AWS::IAM::Role                       Comprehend01nlpseriesep3FunctionRo   Resource creation Initiated
                                                                          le
CREATE_COMPLETE                      AWS::IAM::Role                       Comprehend01nlpseriesep3FunctionRo   -
                                                                          le
CREATE_IN_PROGRESS                   AWS::Lambda::Function                Comprehend01nlpseriesep3Function     Resource creation Initiated
CREATE_IN_PROGRESS                   AWS::Lambda::Function                Comprehend01nlpseriesep3Function     -
CREATE_COMPLETE                      AWS::Lambda::Function                Comprehend01nlpseriesep3Function     -
CREATE_IN_PROGRESS                   AWS::ApiGateway::RestApi             ServerlessRestApi                    -
CREATE_COMPLETE                      AWS::ApiGateway::RestApi             ServerlessRestApi                    -
CREATE_IN_PROGRESS                   AWS::ApiGateway::RestApi             ServerlessRestApi                    Resource creation Initiated
CREATE_IN_PROGRESS                   AWS::Lambda::Permission              Comprehend01nlpseriesep3FunctionHt   -
                                                                          tpPostPermissionProd
CREATE_IN_PROGRESS                   AWS::ApiGateway::Deployment          ServerlessRestApiDeployment1449b78   -
                                                                          2f7
CREATE_COMPLETE                      AWS::ApiGateway::Deployment          ServerlessRestApiDeployment1449b78   -
                                                                          2f7
CREATE_IN_PROGRESS                   AWS::ApiGateway::Deployment          ServerlessRestApiDeployment1449b78   Resource creation Initiated
                                                                          2f7
CREATE_IN_PROGRESS                   AWS::Lambda::Permission              Comprehend01nlpseriesep3FunctionHt   Resource creation Initiated
                                                                          tpPostPermissionProd
CREATE_IN_PROGRESS                   AWS::ApiGateway::Stage               ServerlessRestApiProdStage           -
CREATE_COMPLETE                      AWS::ApiGateway::Stage               ServerlessRestApiProdStage           -
CREATE_IN_PROGRESS                   AWS::ApiGateway::Stage               ServerlessRestApiProdStage           Resource creation Initiated
CREATE_COMPLETE                      AWS::Lambda::Permission              Comprehend01nlpseriesep3FunctionHt   -
                                                                          tpPostPermissionProd
CREATE_COMPLETE                      AWS::CloudFormation::Stack           comprehend-01-nlp-03                 -
-------------------------------------------------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
-------------------------------------------------------------------------------------------------------------------------------------------------
Outputs
-------------------------------------------------------------------------------------------------------------------------------------------------
Key                 ComprehendApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://[api_id].execute-api.ca-central-1.amazonaws.com/Prod/sentiment/

Key                 Comprehend01nlpseriesep3FunctionIamRole
Description         Implicit IAM Role created for comprehend_01_nlpseries_ep_3 function
Value               arn:aws:iam::[aws_account_number]:role/comprehend-01-nlp-03-Comprehend01nlpseriesep3Funct-1363JG49IXNQG

Key                 Comprehend01nlpseriesep3Function
Description         comprehend_01_nlpseries_ep_3 Function ARN
Value               arn:aws:lambda:ca-central-1:[aws_account_number]:function:comprehend-01-nlp-03-Comprehend01nlpseriesep3Funct-BFO9E0QBGG47
-------------------------------------------------------------------------------------------------------------------------------------------------

Successfully created/updated stack - comprehend-01-nlp-03 in ca-central-1

Una vez esté 100% desplegado, si nos fijamos en los Outputs, tendremos todos los valores necesarios para empezar a testar.

CloudFormation outputs from deployed stack

 — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — 

Outputs

 — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — 

Key ComprehendApi

Description API Gateway endpoint URL for Prod stage for your function

Value https://{api}.execute-api.ca-central-1.amazonaws.com/Prod/sentiment/

Key Comprehend01nlpseriesep3FunctionIamRole

Description Implicit IAM Role created for comprehend_01_nlpseries_ep_3 function

Value arn:aws:iam::cuenta_aws:role/comprehend-01-nlp-03-Comprehend01nlpseriesep3Funct-1363JG49IXNQG

Key Comprehend01nlpseriesep3Function

Description comprehend_01_nlpseries_ep_3 Function ARN

Value arn:aws:lambda:ca-central-1:cuenta_aws:function:comprehend-01-nlp-03-Comprehend01nlpseriesep3Funct-BFO9E0QBGG47

🧩 Pruebas con API rest:

Vamos a probar con un simple request nuestra nueva API vía CuRL:

{“body”: “Hola a todos, estamos aprendiendo cómo usar servicios de inteligencia artificial en AWS para el entendimiento del lenguaje natural así que pongamos mucha atención”}

curl -X POST \
  https://d5601zkukf.execute-api.ca-central-1.amazonaws.com/Prod/sentiment \
  -H 'cache-control: no-cache' \
  -H 'content-type: application/json' \
  -H 'postman-token: ea059b31-e081-24e6-8911-c179362ee99c' \
  -d '{"body": "{\"Body\":\"estoy de humor bueno\"}"}'

y por qué no también por Postman, más interactivo:

Imagen: request desde PostmanImagen: request desde Postman

{
  'Sentiment': 'NEUTRAL',
  'SentimentScore': {
    'Positive': 0.019190235063433647,
    'Negative': 0.027914147824048996,
    'Neutral': 0.937386691570282,
    'Mixed': 0.015508887358009815
  },
  'ResponseMetadata': {
    'RequestId': 'c45999f3-3021-4e4d-95e8-bd8763d54337',
    'HTTPStatusCode': 200,
    'HTTPHeaders': {
      'x-amzn-requestid': 'c45999f3-3021-4e4d-95e8-bd8763d54337',
      'content-type': 'application/x-amz-json-1.1',
      'content-length': '163',
      'date': 'Wed, 07 Apr 2021 00:12:21 GMT'
    },
    'RetryAttempts': 0
  }
}

Otro ejemplo:

{
 “body”: “Me encanta aprender cosas nuevas, más aún si es sobre Ai o ML, la verdad es un tema muy interesante y lo explicas de manera entretenida”
}

Resultado a prueba de análisis de sentimiento

‘Sentiment’: ‘POSITIVE’, ‘SentimentScore’: {‘Positive’: 0.9948458671569824, ‘Negative’: 9.346976730739698e-05, ‘Neutral’

Mientras más se acerca a 1, la probabilidad de que sea positivo es mayor. así como mientras más se acerca a 0, la probabilidad de que NO lo sea, es casi nula.

Probemos de nuevo cambiando algunos términos, porque no obtuvimos ningún ENTITY reconocido por el API de Amazon Comprehend usando el lenguaje ‘es’, así que veamos:

{
 “body”: “Hola, Soy Carlos y me encanta aprender lenguajes nuevos en internet, más aún si es sobre AI o ML, la verdad es un tema muy interesante y lo explicas de manera entretenida en tu web. visitalo en cortez.cloud a las 8pm de lunes a domingo y en youtube también. ¡ya tiene más de 30 suscriptores! que bueno”
}

Resultado a prueba para extracción de entidades:

[‘Carlos’, ‘AI’, ‘ML’, ‘8pm’, ‘lunes’, ‘domingo’, ‘youtube’, ’30 suscriptores’]
[‘PERSON’, ‘OTHER’, ‘OTHER’, ‘DATE’, ‘DATE’, ‘DATE’, ‘TITLE’, ‘QUANTITY’]

🧩 Conclusión

Estamos en la punta del iceberg, recién entendiendo NLP usando servicios auto administrados, lo cual nos da resultados aceptables y discutibles. Pero espera!Recién estamos empezando con Comprehend, y además también vamos a aprender librerías propias open source para poder compararlo y llevarlo a AWS Sagemaker luego. Eso ya suena como level 10 o 15 no? Vamos con calma y a paso seguro.

¡Estamos en la nube podemos romperlo todo y no pasa nada. (en desarrollo…)

Puedes revisar todo el código aquí en mi github: ccortezb/comprehend_apirest_sentiment_nlpseries estos son los 3 archvos que necesitas editar si empieazas desde cero un repo de SAM de Hello World.github.com

Siguiente post: (Al Aire el 12 de Abril)

Parte 2: https://ccortezb.medium.com/ingestando-noticias-de-mi-propia-web-text-analytics-basics-nlp-series-parte-2-por-carlos-7899bedd0995

Parte 1: https://ccortezb.medium.com/empezando-con-nlp-en-aws-desde-cero-nlp-series-parte-1-por-carlos-cortez-breaking-the-cloud-13da2adc0151

Si te gustó este post, dale un like, comparte y comenta.

Estas series son parte de una nueva sección llamada AI for Mortals, donde me incluyo con ustedes para enseñarles lo que voy aprendiendo.

Visitar AI for Mortals: (https://aiformortals.cortez.cloud)

☢ Rompiendo se aprende

Suscríbete a mi canal, Breaking the Cloud y Al día con AWS en https://cortez.cloud

⭐Suscríbete a mi canal : http://bit.ly/aldiaconaws

videos, noticas de AWS, análisis, demos, workshops

🔥🔥 Sígueme en mis redes 🔥🔥

follow <- me()

🦜 Mi Twitter: https://twitter.com/ccortezb

📺 Youtube Channel: http://bit.ly/aldiaconaws

📺 AWSUGPerú: https://www.youtube.com/awsusergroupperuoficial

📟 Mi Facebook: https://www.facebook.com/ccortezb/

🤳 Mi Instagram: ccortezbazan

📜 Mis cursos de AWS: https://cennticloud.thinkific.com

🕮 Mi blog — cortez.cloud

Muchas gracias, espero nos volvamos a ver

🔥🔥 Acerca de mí 🔥🔥

Cortez.Cloud/whoami

Les presento mi pequeña web personal https://www.Cortez.Cloud llamado “Breaking the Cloud”.

Seguiré creando contenido cada semana de AWS sobre Al/ML, Serverless, Security y como romper las reglas!

También mis próximas iniciativas, talleres, cursos, videos gratuitos, awsugperu y más.