I have the following code to use the image variant API using an image uploaded to discord:
try {
for (const attachment of message.attachments.values()) {
if (attachment.contentType && attachment.contentType.startsWith('image/')) {
// Use axios to fetch the image buffer
const response = await axios.get(attachment.url, {
responseType: 'arraybuffer'
});
const imageBuffer = Buffer.from(response.data, 'binary');
const image = sharp(imageBuffer);
const metadata = await image.metadata();
if (metadata.width && metadata.height) {
const minDimension = Math.min(metadata.width, metadata.height);
const croppedImageBuffer = await image
.extract({
left: Math.round((metadata.width - minDimension) / 2),
top: Math.round((metadata.height - minDimension) / 2),
width: minDimension,
height: minDimension,
})
.toBuffer();
// Convert the cropped image buffer to a readable stream
const imageStream = Readable.from(croppedImageBuffer);
const openAIResponse = await openai.images.createVariation({
image: imageStream,
n: 1,
});
// Assuming 'openAIResponse' returns an object with a 'data' property containing an array of image URLs
const imageData = openAIResponse.data[0];
if (imageData.url) {
const variationImageBuffer = Buffer.from(imageData.url, 'base64');
const attachment = new AttachmentBuilder(variationImageBuffer, { name: 'variation.jpg' });
await message.reply({ files: [attachment] });
} else {
throw new Error('Invalid OpenAI response: Missing URL.');
}
}
}
}
} catch (error) {
console.error('Error processing image:', error);
await message.reply('There was an error processing your image.');
}
At run time, I get the following error:
Error processing image: TypeError: Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got read() {
this.push(iterable);
this.push(null);
} instead
at addFormValue (/usr/src/tf/node_modules/openai/src/uploads.ts:241:11)
at /usr/src/tf/node_modules/openai/src/uploads.ts:238:51
at Array.map (<anonymous>)
at addFormValue (/usr/src/tf/node_modules/openai/src/uploads.ts:238:29)
at /usr/src/tf/node_modules/openai/src/uploads.ts:205:70
at Array.map (<anonymous>)
at createForm (/usr/src/tf/node_modules/openai/src/uploads.ts:205:48)
at multipartFormRequestOptions (/usr/src/tf/node_modules/openai/src/uploads.ts:199:32)
at Images.createVariation (/usr/src/tf/node_modules/openai/src/resources/images.ts:16:79)
at /usr/src/tf/index.ts:830:60
The error corresponds to the following line from the snippet:
const openAIResponse = await openai.images.createVariation({
Any idea what’s going wrong?