-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_function.py
More file actions
66 lines (57 loc) · 1.99 KB
/
Copy pathlambda_function.py
File metadata and controls
66 lines (57 loc) · 1.99 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import json
import boto3
import datetime
# Initialize AWS clients
comprehend = boto3.client('comprehend')
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MovieReviews')
def lambda_handler(event, context):
# Handle preflight OPTIONS request (CORS)
if event.get('httpMethod') == 'OPTIONS':
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
},
'body': json.dumps('CORS preflight response')
}
try:
# Parse review from request body
body = json.loads(event.get('body', '{}'))
review = body.get('review')
if not review:
raise ValueError("Missing 'review' in request body")
# Analyze sentiment
sentiment = comprehend.detect_sentiment(Text=review, LanguageCode='en')
result = sentiment['Sentiment']
# Save result to DynamoDB
table.put_item(Item={
'review': review,
'sentiment': result,
'timestamp': str(datetime.datetime.now())
})
# Log to CloudWatch
print(f"Review: {review} | Sentiment: {result}")
# Return response with CORS headers
return {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
},
'body': json.dumps({'Sentiment': result})
}
except Exception as e:
print(f"Error: {str(e)}")
return {
'statusCode': 500,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST'
},
'body': json.dumps({'error': str(e)})
}