Lambda trigger function for S3#

Make sure you place all services in the same region. Paris for example, has no comprehend service. Can take several efforts before that becomes clear. In Europe, use Ireland or London.

  • Set up an S3 Bucket

  • Set up a lambda function and add an S3 trigger and an EventBridge (CloudWatch events) trigger.

  • Add ‘ComprehendFullAccess’ policy to the IAM user that was generated by AWS for the lambda function, and add policies for any other AWS service used.

  • Use the code below for the lambda function:

1raise SystemExit("Stop right there!");
An exception has occurred, use %tb to see the full traceback.

SystemExit: Stop right there!
 1import boto3
 2import json
 3import urllib.parse
 4
 5
 6print("Loading function")
 7
 8s3 = boto3.client("s3")
 9
10
11def lambda_handler(event, context):
12
13    # Getting the object from the event
14    bucket = event["Records"][0]["s3"]["bucket"]["name"]
15    key = urllib.parse.unquote_plus(
16        event["Records"][0]["s3"]["object"]["key"], encoding="utf-8"
17    )
18
19    try:
20        file_object = s3.get_object(Bucket=bucket, Key=key)
21        content = str(file_object["Body"].read())
22
23        # Creating a comprehend object
24        comprehend = boto3.client(service_name="comprehend")
25
26        # Calling detect_sentiment()
27        sentiment_response = comprehend.detect_sentiment(
28            Text=content, LanguageCode="en"
29        )
30        print("sentiment_response: \n", sentiment_response)
31
32        # Calling detect_entities()
33        entity_response = comprehend.detect_entities(
34            Text=content, LanguageCode="en"
35        )
36        print("\n\nentity_response: \n", entity_response)
37
38        # Calling detect_key_phrases()
39        key_phases_response = comprehend.detect_key_phrases(
40            Text=content, LanguageCode="en"
41        )
42        print("\n\nkey_phases_response: \n", key_phases_response)
43
44        return {"statusCode": 200, "body": json.dumps("Hello from Lambda!")}
45    except Exception as e:
46        print(e)
47        print(
48            "Error getting object {} from bucket {}. Make sure "
49            "they exist and your bucket is in the same region as "
50            "the function and other aws services used.".format(key, bucket)
51        )
52        raise e
  • Upload a text or other file to the S3 Bucket

  • Check the results in the Lambda function -> Monitor -> View logs in CloudWatch -> Click the Logstream, and tick the View as text checkbox (just above Filter events)

  • After having played around with the lambda function, delete all of it, including the Role in IAM, to prevent unexpected incurred costs.