Introdução
A AWS oferece um ecossistema completo de serviços de IA que permite implementar soluções inteligentes sem a necessidade de expertise profunda em machine learning. Este guia explora como usar esses serviços para automatizar processos e criar aplicações mais inteligentes.
Serviços de IA da AWS
1. Amazon Comprehend - Análise de Texto
Análise de Sentimento
import boto3
import json
def analyze_sentiment(text):
"""Analisar sentimento de texto usando Comprehend"""
comprehend = boto3.client('comprehend')
response = comprehend.detect_sentiment(
Text=text,
LanguageCode='pt'
)
return {
'sentiment': response['Sentiment'],
'confidence': response['SentimentScore']
}
# Exemplo de uso
text = "Estou muito satisfeito com o atendimento da empresa!"
result = analyze_sentiment(text)
print(f"Sentimento: {result['sentiment']}")
print(f"Confiança: {result['confidence']}")
Extração de Entidades
def extract_entities(text):
"""Extrair entidades nomeadas do texto"""
comprehend = boto3.client('comprehend')
response = comprehend.detect_entities(
Text=text,
LanguageCode='pt'
)
entities = []
for entity in response['Entities']:
entities.append({
'text': entity['Text'],
'type': entity['Type'],
'confidence': entity['Score']
})
return entities
# Exemplo
text = "João Silva trabalha na Amazon em São Paulo desde 2020"
entities = extract_entities(text)
for entity in entities:
print(f"{entity['text']} - {entity['type']} ({entity['confidence']:.2f})")
2. Amazon Rekognition - Análise de Imagens
Detecção de Objetos
def detect_objects_in_image(bucket_name, image_key):
"""Detectar objetos em imagem do S3"""
rekognition = boto3.client('rekognition')
response = rekognition.detect_labels(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_key
}
},
MaxLabels=10,
MinConfidence=80
)
objects = []
for label in response['Labels']:
objects.append({
'name': label['Name'],
'confidence': label['Confidence'],
'instances': len(label.get('Instances', []))
})
return objects
Reconhecimento Facial
def detect_faces(bucket_name, image_key):
"""Detectar faces em imagem"""
rekognition = boto3.client('rekognition')
response = rekognition.detect_faces(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_key
}
},
Attributes=['ALL']
)
faces = []
for face in response['FaceDetails']:
faces.append({
'age_range': face['AgeRange'],
'gender': face['Gender']['Value'],
'emotions': [
{
'type': emotion['Type'],
'confidence': emotion['Confidence']
}
for emotion in face['Emotions']
if emotion['Confidence'] > 50
]
})
return faces
3. Amazon Polly - Text-to-Speech
def text_to_speech(text, output_bucket, output_key):
"""Converter texto em áudio usando Polly"""
polly = boto3.client('polly')
s3 = boto3.client('s3')
# Sintetizar fala
response = polly.synthesize_speech(
Text=text,
OutputFormat='mp3',
VoiceId='Camila', # Voz em português brasileiro
LanguageCode='pt-BR'
)
# Salvar no S3
s3.put_object(
Bucket=output_bucket,
Key=output_key,
Body=response['AudioStream'].read(),
ContentType='audio/mpeg'
)
return f"s3://{output_bucket}/{output_key}"
# Exemplo
audio_url = text_to_speech(
"Olá! Este é um exemplo de síntese de voz usando Amazon Polly.",
"my-audio-bucket",
"speech/example.mp3"
)
Casos de Uso Práticos
1. Análise Automática de Feedback de Clientes
import boto3
from datetime import datetime
import json
class FeedbackAnalyzer:
def __init__(self):
self.comprehend = boto3.client('comprehend')
self.dynamodb = boto3.resource('dynamodb')
self.sns = boto3.client('sns')
self.table = self.dynamodb.Table('customer-feedback')
def process_feedback(self, feedback_text, customer_id):
"""Processar feedback do cliente"""
# Análise de sentimento
sentiment_response = self.comprehend.detect_sentiment(
Text=feedback_text,
LanguageCode='pt'
)
# Extração de tópicos-chave
key_phrases_response = self.comprehend.detect_key_phrases(
Text=feedback_text,
LanguageCode='pt'
)
# Preparar dados para armazenamento
feedback_data = {
'feedback_id': f"{customer_id}_{int(datetime.now().timestamp())}",
'customer_id': customer_id,
'text': feedback_text,
'sentiment': sentiment_response['Sentiment'],
'sentiment_scores': sentiment_response['SentimentScore'],
'key_phrases': [
phrase['Text'] for phrase in key_phrases_response['KeyPhrases']
if phrase['Score'] > 0.8
],
'timestamp': datetime.now().isoformat(),
'processed': True
}
# Salvar no DynamoDB
self.table.put_item(Item=feedback_data)
# Alertar se feedback negativo
if sentiment_response['Sentiment'] == 'NEGATIVE':
self.send_alert(feedback_data)
return feedback_data
def send_alert(self, feedback_data):
"""Enviar alerta para feedback negativo"""
message = {
'alert_type': 'negative_feedback',
'customer_id': feedback_data['customer_id'],
'sentiment_score': feedback_data['sentiment_scores']['Negative'],
'key_issues': feedback_data['key_phrases'][:3],
'timestamp': feedback_data['timestamp']
}
self.sns.publish(
TopicArn='arn:aws:sns:region:account:customer-alerts',
Message=json.dumps(message),
Subject='Feedback Negativo Detectado'
)
# Uso da classe
analyzer = FeedbackAnalyzer()
result = analyzer.process_feedback(
"O produto chegou com defeito e o atendimento foi péssimo!",
"customer_123"
)
2. Moderação Automática de Conteúdo
class ContentModerator:
def __init__(self):
self.rekognition = boto3.client('rekognition')
self.comprehend = boto3.client('comprehend')
self.s3 = boto3.client('s3')
def moderate_image(self, bucket_name, image_key):
"""Moderar conteúdo de imagem"""
# Detectar conteúdo inadequado
moderation_response = self.rekognition.detect_moderation_labels(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_key
}
},
MinConfidence=60
)
inappropriate_content = []
for label in moderation_response['ModerationLabels']:
inappropriate_content.append({
'category': label['Name'],
'confidence': label['Confidence'],
'parent_category': label.get('ParentName', '')
})
# Detectar texto na imagem
text_response = self.rekognition.detect_text(
Image={
'S3Object': {
'Bucket': bucket_name,
'Name': image_key
}
}
)
detected_text = ' '.join([
text['DetectedText']
for text in text_response['TextDetections']
if text['Type'] == 'LINE'
])
# Analisar sentimento do texto detectado
text_sentiment = None
if detected_text:
sentiment_response = self.comprehend.detect_sentiment(
Text=detected_text,
LanguageCode='pt'
)
text_sentiment = sentiment_response['Sentiment']
return {
'image_key': image_key,
'inappropriate_content': inappropriate_content,
'detected_text': detected_text,
'text_sentiment': text_sentiment,
'approved': len(inappropriate_content) == 0,
'confidence_score': min([label['confidence'] for label in inappropriate_content]) if inappropriate_content else 100
}
def moderate_text(self, text_content):
"""Moderar conteúdo de texto"""
# Detectar linguagem tóxica usando Comprehend
sentiment_response = self.comprehend.detect_sentiment(
Text=text_content,
LanguageCode='pt'
)
# Lista de palavras proibidas (exemplo simplificado)
prohibited_words = ['spam', 'golpe', 'fraude']
contains_prohibited = any(
word.lower() in text_content.lower()
for word in prohibited_words
)
return {
'text': text_content,
'sentiment': sentiment_response['Sentiment'],
'sentiment_scores': sentiment_response['SentimentScore'],
'contains_prohibited_words': contains_prohibited,
'approved': not contains_prohibited and sentiment_response['Sentiment'] != 'NEGATIVE'
}
# Exemplo de uso
moderator = ContentModerator()
# Moderar imagem
image_result = moderator.moderate_image('content-bucket', 'user-uploads/image.jpg')
print(f"Imagem aprovada: {image_result['approved']}")
# Moderar texto
text_result = moderator.moderate_text("Este é um comentário normal sobre o produto.")
print(f"Texto aprovado: {text_result['approved']}")
3. Chatbot Inteligente com Lex
class IntelligentChatbot:
def __init__(self):
self.lex = boto3.client('lexv2-runtime')
self.comprehend = boto3.client('comprehend')
self.dynamodb = boto3.resource('dynamodb')
self.conversation_table = self.dynamodb.Table('chatbot-conversations')
def process_message(self, user_id, message, session_id=None):
"""Processar mensagem do usuário"""
if not session_id:
session_id = f"{user_id}_{int(datetime.now().timestamp())}"
# Analisar intenção com Lex
lex_response = self.lex.recognize_text(
botId='your-bot-id',
botAliasId='your-bot-alias-id',
localeId='pt_BR',
sessionId=session_id,
text=message
)
# Analisar sentimento da mensagem
sentiment_response = self.comprehend.detect_sentiment(
Text=message,
LanguageCode='pt'
)
# Preparar resposta baseada na intenção
intent_name = lex_response.get('sessionState', {}).get('intent', {}).get('name', 'Unknown')
bot_response = lex_response.get('messages', [{}])[0].get('content', 'Desculpe, não entendi.')
# Personalizar resposta baseada no sentimento
if sentiment_response['Sentiment'] == 'NEGATIVE':
bot_response = f"Percebo que você está frustrado. {bot_response} Posso transferir você para um atendente humano?"
# Salvar conversa
conversation_data = {
'conversation_id': f"{session_id}_{int(datetime.now().timestamp())}",
'user_id': user_id,
'session_id': session_id,
'user_message': message,
'bot_response': bot_response,
'intent': intent_name,
'sentiment': sentiment_response['Sentiment'],
'confidence': lex_response.get('sessionState', {}).get('intent', {}).get('confirmationState', 'None'),
'timestamp': datetime.now().isoformat()
}
self.conversation_table.put_item(Item=conversation_data)
return {
'response': bot_response,
'intent': intent_name,
'sentiment': sentiment_response['Sentiment'],
'session_id': session_id
}
def get_conversation_analytics(self, user_id):
"""Obter analytics da conversa"""
response = self.conversation_table.query(
IndexName='user-id-index',
KeyConditionExpression='user_id = :user_id',
ExpressionAttributeValues={':user_id': user_id}
)
conversations = response['Items']
# Calcular métricas
total_messages = len(conversations)
sentiments = [conv['sentiment'] for conv in conversations]
intents = [conv['intent'] for conv in conversations]
return {
'total_messages': total_messages,
'sentiment_distribution': {
'positive': sentiments.count('POSITIVE'),
'negative': sentiments.count('NEGATIVE'),
'neutral': sentiments.count('NEUTRAL')
},
'top_intents': list(set(intents)),
'last_interaction': max([conv['timestamp'] for conv in conversations]) if conversations else None
}
# Exemplo de uso
chatbot = IntelligentChatbot()
# Processar mensagem
response = chatbot.process_message(
user_id="user_123",
message="Preciso cancelar meu pedido",
session_id="session_456"
)
print(f"Resposta do bot: {response['response']}")
print(f"Intenção detectada: {response['intent']}")
Automação com Step Functions
Workflow de Processamento de Documentos
{
"Comment": "Workflow de processamento automático de documentos",
"StartAt": "ExtractText",
"States": {
"ExtractText": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:textract:startDocumentTextDetection",
"Parameters": {
"DocumentLocation": {
"S3Object": {
"Bucket.$": "$.bucket",
"Name.$": "$.key"
}
}
},
"Next": "WaitForExtraction"
},
"WaitForExtraction": {
"Type": "Wait",
"Seconds": 10,
"Next": "GetExtractionResults"
},
"GetExtractionResults": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:textract:getDocumentTextDetection",
"Parameters": {
"JobId.$": "$.JobId"
},
"Next": "AnalyzeText"
},
"AnalyzeText": {
"Type": "Task",
"Resource": "arn:aws:states:::lambda:invoke",
"Parameters": {
"FunctionName": "analyze-extracted-text",
"Payload.$": "$"
},
"Next": "ClassifyDocument"
},
"ClassifyDocument": {
"Type": "Task",
"Resource": "arn:aws:states:::aws-sdk:comprehend:detectSentiment",
"Parameters": {
"Text.$": "$.extractedText",
"LanguageCode": "pt"
},
"Next": "StoreResults"
},
"StoreResults": {
"Type": "Task",
"Resource": "arn:aws:states:::dynamodb:putItem",
"Parameters": {
"TableName": "processed-documents",
"Item": {
"documentId": {"S.$": "$.documentId"},
"extractedText": {"S.$": "$.extractedText"},
"sentiment": {"S.$": "$.Sentiment"},
"processedAt": {"S.$": "$$.State.EnteredTime"}
}
},
"End": true
}
}
}
Monitoramento e Otimização
CloudWatch Metrics para IA Services
def monitor_ai_services():
"""Monitorar uso e performance dos serviços de IA"""
cloudwatch = boto3.client('cloudwatch')
# Métricas customizadas
metrics = [
{
'MetricName': 'ComprehendRequests',
'Value': 1,
'Unit': 'Count',
'Dimensions': [
{
'Name': 'Service',
'Value': 'Comprehend'
}
]
},
{
'MetricName': 'RekognitionRequests',
'Value': 1,
'Unit': 'Count',
'Dimensions': [
{
'Name': 'Service',
'Value': 'Rekognition'
}
]
}
]
cloudwatch.put_metric_data(
Namespace='AI/Services',
MetricData=metrics
)
# Dashboard para monitoramento
dashboard_config = {
"widgets": [
{
"type": "metric",
"properties": {
"metrics": [
["AI/Services", "ComprehendRequests"],
["AI/Services", "RekognitionRequests"]
],
"period": 300,
"stat": "Sum",
"region": "us-east-1",
"title": "AI Services Usage"
}
}
]
}
Conclusão
Os serviços de IA da AWS democratizam o acesso à inteligência artificial, permitindo que desenvolvedores implementem soluções sofisticadas sem expertise profunda em ML. As principais vantagens incluem:
- Facilidade de uso - APIs simples e bem documentadas
- Escalabilidade - Processamento de grandes volumes
- Custo-efetivo - Pague apenas pelo que usar
- Integração - Funciona bem com outros serviços AWS
- Precisão - Modelos treinados com grandes datasets
Próximos Passos
- Identificar casos de uso específicos
- Implementar provas de conceito
- Integrar com sistemas existentes
- Monitorar performance e custos
- Otimizar baseado em métricas
Recursos Adicionais: