Created
May 14, 2018 05:10
-
-
Save adhorn/af19cfda4195d7aa84bcf1891f3a02e8 to your computer and use it in GitHub Desktop.
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('dynamo_serverless') | |
| 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(feedback_id, sentiment): | |
| response = table.update_item( | |
| Key={ | |
| 'feedback_id': feedback_id | |
| }, | |
| UpdateExpression='set sentiment = :vall', | |
| ExpressionAttributeValues={ | |
| ':vall': sentiment, | |
| } | |
| ) | |
| return response, feedback_id | |
| def handler(event, context): | |
| feedback_id = "" | |
| for record in event['Records']: | |
| if record['eventName'] == "INSERT": | |
| feedback_id = record['dynamodb']['NewImage']['feedback_id']['S'] | |
| if feedback_id is not "": | |
| sentiment = client.detect_sentiment( | |
| Text=record['dynamodb']['NewImage']['session_comment']['S'], | |
| LanguageCode='en' | |
| ) | |
| sent = replace_decimals(remove_key(sentiment, 'ResponseMetadata')) | |
| resp = update_to_dynamo(feedback_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