-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsentiment_lambda_function.py
More file actions
50 lines (36 loc) · 2.02 KB
/
Copy pathsentiment_lambda_function.py
File metadata and controls
50 lines (36 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# We need to use the low-level library to interact with SageMaker since the SageMaker API
# is not available natively through Lambda.
import boto3
# And we need the regular expression library to do some of the data processing
import re
REPLACE_NO_SPACE = re.compile("(\.)|(\;)|(\:)|(\!)|(\')|(\?)|(\,)|(\")|(\()|(\))|(\[)|(\])")
REPLACE_WITH_SPACE = re.compile("(<br\s*/><br\s*/>)|(\-)|(\/)")
def review_to_words(review):
words = REPLACE_NO_SPACE.sub("", review.lower())
words = REPLACE_WITH_SPACE.sub(" ", words)
return words
def bow_encoding(words, vocabulary):
bow = [0] * len(vocabulary) # Start by setting the count for each word in the vocabulary to zero.
for word in words.split(): # For each word in the string
if word in vocabulary: # If the word is one that occurs in the vocabulary, increase its count.
bow[vocabulary[word]] += 1
return bow
def lambda_handler(event, context):
vocab = "*** ACTUAL VOCABULARY GOES HERE ***"
words = review_to_words(event['body'])
bow = bow_encoding(words, vocab)
# The SageMaker runtime is what allows us to invoke the endpoint that we've created.
runtime = boto3.Session().client('sagemaker-runtime')
# Now we use the SageMaker runtime to invoke our endpoint, sending the review we were given
response = runtime.invoke_endpoint(EndpointName='***ENDPOINT NAME HERE***', # The name of the endpoint we created
ContentType='text/csv', # The data format that is expected
Body=','.join([str(val) for val in bow]).encode('utf-8')) # The actual review
# The response is an HTTP response whose body contains the result of our inference
result = response['Body'].read().decode('utf-8')
# Round the result so that our web app only gets '1' or '0' as a response.
result = round(float(result))
return {
'statusCode': 200,
'headers': {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': '*'},
'body': str(result)
}