Skip to content

Commit 6dd9550

Browse files
authored
feat: add a generate image sample and test for Imagen (#3861)
* feat: add a generate image sample and test for Imagen * fix lint * trigger build * trigger build
1 parent 023f53b commit 6dd9550

File tree

3 files changed

+141
-1
lines changed

3 files changed

+141
-1
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
'use strict';
18+
19+
const main = async () => {
20+
// [START generativeaionvertexai_imagen_generate_image]
21+
/**
22+
* TODO(developer): Update these variables before running the sample.
23+
*/
24+
const projectId = process.env.CAIP_PROJECT_ID;
25+
const outputFile = 'my-output';
26+
const prompt = 'a dog reading a newspaper'; // The text prompt describing what you want to see
27+
const location = 'us-central1';
28+
29+
const aiplatform = require('@google-cloud/aiplatform');
30+
31+
// Imports the Google Cloud Prediction Service Client library
32+
const {PredictionServiceClient} = aiplatform.v1;
33+
34+
// Import the helper module for converting arbitrary protobuf.Value objects
35+
const {helpers} = aiplatform;
36+
37+
// Specifies the location of the api endpoint
38+
const clientOptions = {
39+
apiEndpoint: `${location}-aiplatform.googleapis.com`,
40+
};
41+
42+
// Instantiates a client
43+
const predictionServiceClient = new PredictionServiceClient(clientOptions);
44+
45+
const fs = require('fs');
46+
const util = require('util');
47+
48+
async function generateImage() {
49+
// Configure the parent resource
50+
const endpoint = `projects/${projectId}/locations/${location}/publishers/google/models/imagen-3.0-generate-001`;
51+
52+
const promptText = {
53+
prompt: prompt,
54+
};
55+
const instanceValue = helpers.toValue(promptText);
56+
const instances = [instanceValue];
57+
58+
const parameter = {
59+
sampleCount: 1,
60+
// You can't use a seed value and watermark at the same time.
61+
// seed: 100,
62+
// addWatermark: false,
63+
aspectRatio: '1:1',
64+
safetyFilterLevel: 'block_some',
65+
personGeneration: 'allow_adult',
66+
};
67+
const parameters = helpers.toValue(parameter);
68+
69+
const request = {
70+
endpoint,
71+
instances,
72+
parameters,
73+
};
74+
75+
// Predict request
76+
const [response] = await predictionServiceClient.predict(request);
77+
const predictions = response.predictions;
78+
if (predictions.length === 0) {
79+
console.log(
80+
'No image was generated. Check the request parameters and prompt.'
81+
);
82+
} else {
83+
let i = 1;
84+
for (const prediction of predictions) {
85+
const buff = Buffer.from(
86+
prediction.structValue.fields.bytesBase64Encoded.stringValue,
87+
'base64'
88+
);
89+
// Write image content to the output file
90+
const writeFile = util.promisify(fs.writeFile);
91+
const filename = `${outputFile}${i}.png`;
92+
await writeFile(filename, buff);
93+
console.log(`Saved image ${filename}`);
94+
i++;
95+
}
96+
}
97+
}
98+
await generateImage();
99+
// [END generativeaionvertexai_imagen_generate_image]
100+
};
101+
102+
// node generateImage.js
103+
main().catch(err => {
104+
console.log(err);
105+
process.exitCode = 1;
106+
});

ai-platform/snippets/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"*.js"
1111
],
1212
"scripts": {
13-
"test": "c8 mocha -p -j 2 --timeout 2400000 test/*.js"
13+
"test": "c8 mocha -p -j 2 --timeout 2400000 test/*.js test/**/*.test.js"
1414
},
1515
"dependencies": {
1616
"@google-cloud/aiplatform": "^3.0.0",
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Copyright 2024 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
'use strict';
18+
19+
const path = require('path');
20+
const {assert} = require('chai');
21+
const {describe, it} = require('mocha');
22+
23+
const cp = require('child_process');
24+
const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
25+
const cwd = path.join(__dirname, '..');
26+
27+
describe('AI platform generate image', () => {
28+
it('should generate an image using the Imagen model', async () => {
29+
const stdout = execSync('node ./imagen/generateImage.js', {
30+
cwd,
31+
});
32+
assert.match(stdout, /Saved image my-output1.png/);
33+
});
34+
});

0 commit comments

Comments
 (0)