<jupyter_start><jupyter_text>Sending Events to S3This notebook is pretty simple, just enough code to send events as discrete JSON files to S3 based on user interactions for Amazon Personalize.  Setup<jupyter_code># Imports
import boto3
import json
import numpy as np
import pandas as pd
import time
import uuid<jupyter_output><empty_output><jupyter_text>Be sure to update the Campaign and Dataset ARNs below.<jupyter_code># Setup and Config
# Recommendations from Event data
personalize = boto3.client('personalize')
personalize_runtime = boto3.client('personalize-runtime')

# Campaign ARN
Campaign_ARN = "arn:aws:personalize:us-east-1:059124553121:campaign/personalize-demo-camp"

# Dataset Group Arn:
datasetGroupArn = "arn:aws:personalize:us-east-1:059124553121:dataset-group/personalize-lambda-demo"

# Establish a connection to Personalize's Event Streaming
personalize_events = boto3.client(service_name='personalize-events')


# S3 Configuration
bucket = "personalizedemo9000chris"<jupyter_output><empty_output><jupyter_text>Faking EventsThis code will rely on 3 users that we happen to know exist in the MovieLens dataset:1. 1962. 133. 198They were chosen at random, also we are going to now select 3 movies at random for the user to interact with:1. 2252. 2033. 242Each of these users will interact with each movie, and each interaction will be written to S3 as a distinct JSON file.<jupyter_code>users = ["196", "13", "198"]
items = ["225", "203", "242"]
def write_interaction_to_JSON(user, item):
    # An event needs a user, session, time, type, and a properties dictionary.
    time_of_interaction = int(time.time())
    # This is set for simplification
    session_id = user
    user_id = user
    event_type = "watched"
    properties = {
        'itemId': str(item)
    }
    properties = json.dumps(properties)
    
    event_headers = {
        'userId': user,
        'sessionId': session_id
    }
    
    event_content = {
        'sentAt': time_of_interaction,
        'eventType': event_type,
        'properties': properties
    }
    event_list = [event_content]
    json_struct = [event_headers, event_content]
    json_filename = str(time_of_interaction) + ".json"
    
    with open(json_filename, 'w') as outfile:
        json.dump(json_struct, outfile)
    
    return json_filename

def send_interactions_to_s3():
    for user in users:
        for item in items:
            filename = write_interaction_to_JSON(user, item)
            boto3.Session().resource('s3').Bucket(bucket).Object(filename).upload_file(filename)
            print(filename)
            # Sleep needed to make sure everyone gets a nice new timestamp
            time.sleep(2)
            
send_interactions_to_s3()
# The code below is just to explore what to put in our Lambda:

with open("1568076414.json", 'r') as input_file:
    content = json.loads(input_file.read())
    # assume tracking ID was provided via an environment variable and replace
    trackingId = "a68baf70-f0f2-4c66-af2d-e11047a0372f"
    print(content[0]['userId'])
    
    personalize.put_events(
        trackingId = trackingId,
        userId = content[0]['userId'],
        sessionId = content[0]['sessionId'],
        eventList = [content[1]]
    )<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09132699969353356, 'fraction_numerical': 0.03616304014710389, 'mean_word_length': 3.7859237536656893, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '296104', 'license': 'MIT-0', 'n_tokens_mistral': 1064, 'n_tokens_neox': 997, 'n_words': 293, 'path': 'getting_started/lambda_examples/Sending_Events_to_S3.ipynb', 'repo_name': 'phnascimento/amazon-personalize-samples', 'size': '3263'}