Created
May 24, 2018 07:05
-
-
Save adhorn/553ca58c5d9938f2dc18bffa6f96aa40 to your computer and use it in GitHub Desktop.
Function to react to DynamoDB stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from __future__ import unicode_literals | |
| import sys | |
| import logging | |
| import os | |
| import json | |
| import decimal | |
| log = logging.getLogger() | |
| log.setLevel(logging.DEBUG) | |
| sys.path.insert(0, './vendored') | |
| import boto3 | |
| client = boto3.client('comprehend') | |
| region = os.environ["AWS_REGION"] | |
| dynamodb = boto3.resource('dynamodb', region_name=region) | |
| table = dynamodb.Table('global2') | |
| def remove_key(d, key): | |
| r = dict(d) | |
| del r[key] | |
| return r | |
| def replace_decimals(obj): | |
| if isinstance(obj, list): | |
| for i in xrange(len(obj)): | |
| obj[i] = replace_decimals(obj[i]) | |
| return obj | |
| elif isinstance(obj, dict): | |
| for k in obj.iterkeys(): | |
| obj[k] = replace_decimals(obj[k]) | |
| return obj | |
| elif isinstance(obj, float): | |
| return decimal.Decimal(obj) | |
| else: | |
| return obj | |
| def update_to_dynamo(item_id, sentiment): | |
| response = table.update_item( | |
| Key={ | |
| 'item_id': item_id | |
| }, | |
| UpdateExpression='set sentiment = :vall', | |
| ExpressionAttributeValues={ | |
| ':vall': sentiment, | |
| } | |
| ) | |
| return response, item_id | |
| def handler(event, context): | |
| item_id = "" | |
| for record in event['Records']: | |
| if record['eventName'] == "INSERT": | |
| # print(record['eventID']) | |
| # print(record['eventName']) | |
| # print(json.dumps(record['dynamodb']['NewImage'])) | |
| item_id = record['dynamodb']['NewImage']['item_id']['S'] | |
| # print("my item id is: {}".format(item_id)) | |
| if item_id: | |
| sentiment = client.detect_sentiment( | |
| Text=record['dynamodb']['NewImage']['session_comment']['S'], | |
| LanguageCode='en' | |
| ) | |
| sent = replace_decimals(remove_key(sentiment, 'ResponseMetadata')) | |
| # print("the sentiment is: {}".format(sentiment)) | |
| resp = update_to_dynamo(item_id, sent) | |
| return True | |
| else: | |
| return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment