如何从OpenAI获取图像并保存到S3存储桶

我想获取在OpenAI/Dall E生成的图像并将其保存到S3存储桶中。

到目前为止,我可以获取图像URL并创建一个缓冲区,如下所示:

const configuration = new Configuration({  apiKey: procEnvVars.OPENAI_API_KEY,});export const openai = new OpenAIApi(configuration);const defaultImageParams: CreateImageRequest = {  n: 1,  prompt: "a bad request message",};interface InputParams extends CreateImageRequest {  prompt: string; // make this mandatory for the function params}// Once we get a URL from the OpenAI API, we want to convert it to a bufferexport async function getBufferFromUrl(openAiUrl: string) {  const axiosResponse = await axios({    url: openAiUrl, //your url    method: "GET",    responseType: "arraybuffer",  });  const data = axiosResponse.data;  if (!(data instanceof Buffer))    throw new Error("Axios response should be of type Buffer");  return data;}export async function getUrlFromOpenAi(inputParams: InputParams) {  const ImageResponse = await openai.createImage({    ...defaultImageParams,    ...inputParams,  });  const dataArray = ImageResponse.data.data;  if (!dataArray || dataArray.length === 0) {    console.error({      error: "We did not return choices from createOpenAiImage()",      data: ImageResponse.data,      datadata: ImageResponse.data.data,    });  }  return dataArray;}

回答:

接下来,我们需要将缓冲区保存到S3中:

// Create service client module using ES6 syntax.import { S3Client } from "@aws-sdk/client-s3";// Set the AWS Region.const REGION = "eu-west-2";// Create an Amazon S3 service client object.const s3Client = new S3Client({ region: REGION });export { s3Client };// Import required AWS SDK clients and commands for Node.js.import { PutObjectCommand } from "@aws-sdk/client-s3";// Set the parameters.export const bucketParams = {  Bucket: "<my s3 bucket name. Can be found in S3 console>",};// Create and upload an object to the S3 bucket.export async function putS3Object(inputParams: { Body: Buffer; Key: string }) {  try {    const data = await s3Client.send(      new PutObjectCommand({        ...bucketParams,        Body: inputParams.Body,        Key: `public/myFolder/${inputParams.Key}`,      })    );    console.log(      "Successfully uploaded object: " +        bucketParams.Bucket +        "/" +        `public/myFolder/${inputParams.Key}`    );    return data; // For unit tests.  } catch (err) {    console.log("Error", err);  }}

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注