Skip to content

Commit 3f90ec9

Browse files
author
Dinesh Sajwan
committed
feat(construct): added review comments
1 parent 2a3e9bf commit 3f90ec9

File tree

4 files changed

+69
-67
lines changed

4 files changed

+69
-67
lines changed

lambda/aws-contentgen-appsync-lambda/src/image_generator.py

+30-58
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
1-
import boto3,os,base64,json
1+
#
2+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
5+
# with the License. A copy of the License is located at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
10+
# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
11+
# and limitations under the License.
12+
#
213
import requests as reqs
3-
from aws_lambda_powertools import Logger, Tracer, Metrics
4-
from requests_aws4auth import AWS4Auth
14+
import boto3,os,base64,json
515
from datetime import datetime
16+
from requests_aws4auth import AWS4Auth
17+
from aws_lambda_powertools import Logger, Tracer, Metrics
618

7-
logger = Logger(service="IMAGE_GENERATION")
8-
tracer = Tracer(service="IMAGE_GENERATION")
9-
metrics = Metrics(namespace="image_generation", service="IMAGE_GENERATION")
19+
logger = Logger(service="CONTENT_GENERATION")
20+
tracer = Tracer(service="CONTENT_GENERATION")
21+
metrics = Metrics(namespace="content_generation", service="CONTENT_GENERATION")
1022

1123

1224
s3 = boto3.resource('s3')
@@ -116,7 +128,7 @@ def generate_image(self,input_params):
116128

117129

118130
input_text=self.input_text
119-
print(f' input_params :: {input_params}')
131+
logger.info(f' input_params :: {input_params}')
120132
# add default negative prompts
121133
if 'negative_prompts' in input_params and input_params['negative_prompts'] is None:
122134
sample_string_bytes = base64.b64decode(input_params['negative_prompts'])
@@ -133,7 +145,6 @@ def generate_image(self,input_params):
133145

134146

135147
body=get_model_payload(model_id,params,input_text,negative_prompts)
136-
print(f' body :: {body}')
137148
try:
138149
return self.bedrock_client.invoke_model(
139150
modelId= model_id,
@@ -228,56 +239,17 @@ def get_model_payload(modelid,params,input_text,negative_prompts):
228239

229240
def get_inference_parameters(model_kwargs):
230241
""" Read inference parameters and set default values"""
231-
if 'seed' in model_kwargs:
232-
seed= model_kwargs['seed']
233-
else:
234-
seed=452345
235-
if 'cfg_scale' in model_kwargs:
236-
cfg_scale= model_kwargs['cfg_scale']
237-
else:
238-
cfg_scale=10
239-
if 'steps' in model_kwargs:
240-
steps= model_kwargs['steps']
241-
else:
242-
steps=10
243-
if 'style_preset' in model_kwargs:
244-
style_preset= model_kwargs['style_preset']
245-
else:
246-
style_preset='photographic'
247-
if 'clip_guidance_preset' in model_kwargs:
248-
clip_guidance_preset= model_kwargs['clip_guidance_preset']
249-
else:
250-
clip_guidance_preset='FAST_GREEN'
251-
if 'width' in model_kwargs:
252-
width= model_kwargs['width']
253-
else:
254-
width=512
255-
if 'height' in model_kwargs:
256-
height= model_kwargs['height']
257-
else:
258-
height=512
259-
if 'sampler' in model_kwargs:
260-
sampler= model_kwargs['sampler']
261-
else:
262-
sampler='K_DPMPP_2S_ANCESTRAL'
263-
if 'numberOfImages' in model_kwargs:
264-
numberOfImages= model_kwargs['numberOfImages']
265-
else:
266-
numberOfImages=1
267-
if 'quality' in model_kwargs:
268-
quality= model_kwargs['quality']
269-
else:
270-
quality="standard"
271242

272243
return {
273-
"cfg_scale": cfg_scale,
274-
"seed": seed,
275-
"steps": steps,
276-
"style_preset": style_preset,
277-
"clip_guidance_preset": clip_guidance_preset,
278-
"sampler": sampler,
279-
"width": width,
280-
"height": height,
281-
"numberOfImages": numberOfImages,
282-
"quality": quality
244+
"cfg_scale": model_kwargs.get('cfg_scale',10),
245+
"seed": model_kwargs.get('seed',452345),
246+
"steps": model_kwargs.get('steps',10),
247+
"style_preset": model_kwargs.get('style_preset','photographic'),
248+
"clip_guidance_preset": model_kwargs.get('clip_guidance_preset','FAST_GREEN'),
249+
"sampler": model_kwargs.get('sampler','K_DPMPP_2S_ANCESTRAL'),
250+
"width": model_kwargs.get('width',512),
251+
"height": model_kwargs.get('height',512),
252+
"numberOfImages": model_kwargs.get('numberOfImages',1),
253+
"quality": model_kwargs.get('quality','standard'),
254+
283255
}

lambda/aws-contentgen-appsync-lambda/src/lambda.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@
2323

2424

2525

26-
logger = Logger(service="IMAGE_GENERATION")
27-
tracer = Tracer(service="IMAGE_GENERATION")
28-
metrics = Metrics(namespace="image_generation", service="IMAGE_GENERATION")
26+
logger = Logger(service="CONTENT_GENERATION")
27+
tracer = Tracer(service="CONTENT_GENERATION")
28+
metrics = Metrics(namespace="content_generation", service="CONTENT_GENERATION")
2929

3030
aws_region = boto3.Session().region_name
3131
bucket = os.environ['OUTPUT_BUCKET']
@@ -87,7 +87,7 @@ def handler(event, context: LambdaContext) -> dict:
8787
else:
8888
num_of_images=0 #if multiple image geneated iterate through all
8989
for image in parsed_reponse['image_generated']:
90-
print(f'num_of_images {num_of_images}')
90+
logger.info(f'num_of_images {num_of_images}')
9191
if model_id=='stability.stable-diffusion-xl' :
9292
imgbase64encoded= parsed_reponse['image_generated'][num_of_images]["base64"]
9393
if model_id=='amazon.titan-image-generator-v1' :
@@ -109,7 +109,7 @@ def handler(event, context: LambdaContext) -> dict:
109109
"jobid":input_params["jobid"],
110110
"message":'Image generated successfully'
111111
}
112-
print (f"response :: {response}")
112+
logger.info (f"response :: {response}")
113113
img.send_job_status(response)
114114

115115
return response
@@ -139,7 +139,8 @@ def parse_response(query_response,model_id):
139139
parsed_reponse['image_generated_status']='Failed'
140140
else:
141141
numiofimages=response_dict['images']
142-
print(f' number of images ::{len(numiofimages)}')
143142
parsed_reponse['image_generated']=response_dict['images']
144143

145144
return parsed_reponse
145+
146+

lambda/aws-contentgen-appsync-lambda/src/requirements.txt

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
aws-lambda-powertools
2-
aws-xray-sdk
3-
fastjsonschema
1+
aws-lambda-powertools=2.34.2
2+
aws-xray-sdk=3.5.4
3+
fastjsonschema=2.19.1
44
boto3>=1.28.69
55
botocore>=1.31.69
66
requests==2.31.0

src/patterns/gen-ai/aws-contentgen-appsync-lambda/README.md

+29
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ AWS Lambda functions provisioned in this construct use [Powertools for AWS Lambd
5959
Here is a minimal deployable pattern definition:
6060

6161
Create a CDK TypeScript project and then update the stack with below configuration.
62+
```cdk init sample-app --language typescript```
6263

6364
``` typescript
6465
import { Construct } from 'constructs';
@@ -76,6 +77,34 @@ const imageGeneration = new emergingTech.ContentGenerationAppsyncLambda(this, 'C
7677

7778
});
7879

80+
```
81+
Create a CDK Python project and then update the stack with below configuration.
82+
```cdk init sample-app --language python```
83+
84+
``` python
85+
from constructs import Construct
86+
from aws_cdk import (
87+
Duration,
88+
Stack,
89+
aws_cognito as cognito,
90+
)
91+
import cdklabs.generative_ai_cdk_constructs as genai
92+
93+
94+
class SampleAppStack(Stack):
95+
96+
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
97+
super().__init__(scope, construct_id, **kwargs)
98+
99+
cognitoPoolId='us-east-1_XXXXX'
100+
userPool = cognito.UserPool.from_user_pool_id(self, 'myuserpool', cognitoPoolId)
101+
102+
img=genai.ContentGenerationAppsyncLambda(self, "ContentGenerationAppsyncLambda",
103+
{
104+
"cognitoUserPool": userPool
105+
})
106+
107+
79108
```
80109

81110

0 commit comments

Comments
 (0)