-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_trigger.py
More file actions
128 lines (111 loc) · 4.11 KB
/
lambda_trigger.py
File metadata and controls
128 lines (111 loc) · 4.11 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import json
import uuid
import base64
import boto3
from datetime import datetime, timezone
from botocore.exceptions import ClientError
REGION = "ap-south-1"
BUCKET = "dev-saarathi-bucket"
JOBS_TABLE = "dev-saarathi-jobs"
USERS_TABLE = "dev-saarathi-users"
PROCESSOR_FUNCTION = "dev-saarathi-processor"
dynamodb = boto3.resource("dynamodb", region_name=REGION)
lambda_client = boto3.client("lambda", region_name=REGION)
s3_client = boto3.client("s3", region_name=REGION)
def lambda_handler(event, context):
# Handle CORS preflight
http_method = event.get('httpMethod') or event.get('requestContext', {}).get('http', {}).get('method', '')
if http_method == 'OPTIONS':
return response(200, {})
try:
body = json.loads(event.get('body', '{}'))
audio_base64 = body.get('audio')
user_id = body.get('user_id', 'anonymous')
code_context = body.get('code_context')
active_filename = body.get('active_filename')
if not audio_base64:
return response(400, {"error": "No audio provided"})
job_id = str(uuid.uuid4())
timestamp = datetime.now(timezone.utc).isoformat()
dynamodb.Table(JOBS_TABLE).put_item(Item={
'job_id': job_id,
'user_id': user_id,
'status': 'PROCESSING',
'timestamp': timestamp,
'query': '',
'response': '',
'intent': '',
'detected_lang': ''
})
try:
dynamodb.Table(USERS_TABLE).put_item(
Item={
'user_id': user_id,
'created_at': timestamp,
'last_seen': timestamp,
'preferred_lang': '',
'total_queries': 0
},
ConditionExpression='attribute_not_exists(user_id)'
)
except ClientError as e:
if e.response['Error']['Code'] != 'ConditionalCheckFailedException':
raise
try:
dynamodb.Table(USERS_TABLE).update_item(
Key={'user_id': user_id},
UpdateExpression='SET last_seen = :ts ADD total_queries :inc',
ExpressionAttributeValues={':ts': timestamp, ':inc': 1}
)
except Exception as e:
print(f"Failed to update user: {e}")
# Upload audio to S3 to avoid Lambda 256KB async payload limit
# Detect actual audio format from header bytes
audio_bytes = base64.b64decode(audio_base64)
header = audio_bytes[:4]
if header[:3] == b'ID3' or header[:2] == b'\\xff\\xfb':
audio_ext = 'mp3'
elif header[:4] == b'OggS':
audio_ext = 'ogg'
elif header[:4] == b'fLaC':
audio_ext = 'flac'
elif header[:4] == b'\\x1aE\\xdf\\xa3':
audio_ext = 'webm'
else:
audio_ext = 'wav'
audio_s3_key = f"audio/{job_id}.{audio_ext}"
s3_client.put_object(
Bucket=BUCKET, Key=audio_s3_key,
Body=audio_bytes
)
payload = {
'job_id': job_id,
'user_id': user_id,
'audio_s3_key': audio_s3_key,
'timestamp': timestamp
}
if code_context:
payload['code_context'] = code_context
if active_filename:
payload['active_filename'] = active_filename
lambda_client.invoke(
FunctionName=PROCESSOR_FUNCTION,
InvocationType='Event',
Payload=json.dumps(payload)
)
print(f"Job created: {job_id} for user: {user_id}")
return response(200, {"job_id": job_id, "status": "PROCESSING"})
except Exception as e:
print(f"Trigger error: {e}")
return response(500, {"error": str(e)})
def response(status_code, body):
return {
"statusCode": status_code,
"headers": {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,Authorization",
"Access-Control-Allow-Methods": "GET,POST,OPTIONS"
},
"body": json.dumps(body)
}