Cookie Consent by Free Privacy Policy Generator website DALL-E with node.js Seite: 1 u

Portal Nachrichten


➠ DALL-E with node.js

Introduction

over the last few years, we have seen how machine learning and artificial intelligence have improved a lot, and now we are seeing how artificial intelligence is affecting our daily routines and how we interact with the internet. From high-level chatbots to incredible images generators but among those technologies the one I am excited about the most is the possibility of generating images and art through thought and imagination, and this article we shall see how to generate images from inputs also called prompt using DALL-E model, please note that DALL-E is not free after creating your account you will receive free credits that are enough for our min-application and testing purposes.

Create account

Before start building our application we shall start by creating our account and generating an API token that we shall use to access the network
use the following link to create your account if you don't have one yet

after creating your account click on your profile's image and go to view API keys once there you will be prompted to create an API key create one, here is how the screen looks like

Image description

Create a simple node.js application

with all the credentials and information we need for sending our request let us now create our mini node.js application and create some simple images

initialize a node.js application with npm init then install the above dependencies

npm install express nodemon openai body-parser

we shall be using nodemon for reloading our server when we make changes, instead of restarting our application for some small updates. For enabling nodemon go to your package.json file and add the following script "start": "nodemon index.js " don't forget to replace the index.js with your main entry file

create your first image with DALL-E

const express = require("express");
const app = express();
const openai = require('openai');
const bodyparser = require('body-parser');

//body-parser
app.use(bodyparser.json());


app.post('/createImage', async (req, res, next) => {
        try {
        const prompt = req.body.prompt;
        const config = new openai.Configuration({
            apiKey: "your API key",
        });

        const openaiApi = new openai.OpenAIApi(config);
        const createImage = await openaiApi.createImage({
            prompt: prompt,
            n: 1,
            size: "512x512",
        })
        return res.status(201).json({ imageUrl: createImage.data.data[0].url });
    } catch (error) {
        return res.status(500).json({ message: "internal server error" });
    }

})

app.listen(8080, () => {
    console.log('server started on port 3000');
})

let us break down the meaning of that code, the n field represents the number of images that we request, it goes from 1 to 10, and the prompt field
is the text used for creating our image it can be anything like a cat playing on play-station 5😁

please note that not all the sizes are supported here is the list

   "256x256";
   "512x512";
   "1024x1024";

Create image variation

You may also want to create variations of your existing image, which is also possible with DALL-E, please note that your image must respect the following requirements

  1. must be a png image
  2. must be square
  3. must have less than 4mbs
const express = require("express");
const app = express();
const openai = require('openai');
const bodyparser = require('body-parser');
const path = require('path');
const fs = require('fs');

//body-parser
app.use(bodyparser.json());

app.post('/createVariation', async (req, res, next) => {
    const config = new openai.Configuration({
        apiKey: "your API key",
    });
    const openaiApi = new openai.OpenAIApi(config);
    const image = path.join(__dirname, './image.png');
    const file = fs.createReadStream(image);

    try {
        const createVariation = await openaiApi.createImageVariation(
            file,
            2,
            "1024x1024",
        )
        const result = createVariation.data.data;
        return res.status(202).json({ imageUrl: result });

    } catch (error) {
        console.log(error.message);
        return res.status(500).json({ message: error.message, error: error });
    }
})


app.listen(8080, () => {
    console.log('server started on port 8080');
})

In the example above we create two variations of one image which means our response will be an array. Please make sure your image is a square and a valid PNG otherwise this will not work anymore.

Bonus
generating images and creating variations is very amazing and full of fun but what if you want to take the image provided on the URL and write it to your local storage or the storage where your server is running ?🤔 the following functionality does not have anything in relation with openai library this function if fully implemented with nod.js build in functions, this process may take unexpected amount of time since generated images are a bit heavy

  const result = "your image URL";
  const fetchFile = await fetch(result);
  const responseBlob = await fetchFile.blob();
  const arrayBuffer = await responseBlob.arrayBuffer();
  const buffer = Buffer.from(arrayBuffer);
 const filePath = path.join(__dirname, './' + new Date() + ".png");

 const writeFileToDisc = fs.writeFileSync(filePath, buffer);

For this example i use the current date for naming files in a unique fashion please feel free to use any method of your choice.

conclusion
Generating images with DALL-E is very amazing and satisfying but there is another amazing API much more epic and much more creative if this article reaches more than 100 likes I promise to write another article on how to interact with MID-JOURNEY, something that you will like if you liked this article

don't forget to show some love by liking and following for more contents.

...


➦ Programmierung ☆ dev.to

➠ Komplette Nachricht lesen


Zur Startseite

➤ Ähnliche Beiträge für 'DALL-E with node.js'

Introduction to Singly Linked List and Basic Operations in PHP

vom 718.36 Punkte
Table of Contents About Node Singly Linked List Constructor Print all nodes 1. Append 2. Get 3. Set 4. Prepend 5. Insert 6. Pop First 7. Pop Last 8. Remove Time Complexity A singly linked list is a linear data structure that consists of a sequ

Exploring competitive features in Node.js v18 and v19

vom 519.15 Punkte
Written by Stanley Ulili✏️ Node.js has been a popular JavaScript runtime since its release in 2009. But the advent of two new runtimes, Deno and Bun, has brought a lot of hype for the new features they present in contrast to Node. From afar, it may seem like N

What is Node.js? A beginner's introduction to JavaScript runtime

vom 392.38 Punkte
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a web browser. Node.js is a popular, lightweight web framework for beginners, and it is used by many big companies like Netflix and Uber.

Teaching old labels new tricks in heterogeneous graphs

vom 386.35 Punkte
Posted by Minji Yoon, Research Intern, and Bryan Perozzi, Research Scientist, Google Research, Graph Mining Team Industrial applications of machine learning are commonly composed of various items that have differing data modalities or feature distributions. Heterogeneous graphs (HGs) offer a unified view of these multimodal data systems by defining multiple types of nodes (for each data type) and edges (for the relation between data ite

CVE-2021-27077: Selecting Bitmaps into Mismatched Device Contexts

vom 362.2 Punkte
In March 2021, Microsoft released a patch to correct a vulnerability in the Windows GDI subsystem. The bug could allow an attacker to execute code with escalated privileges. This vulnerability was reported to the ZDI program by security researcher Marc

Machine Learning on Graphs, Part 4

vom 356.16 Punkte
Photo by Clarisse Croset on UnsplashLearning discrete node embeddingsIn this post, I want to present discrete graph node embeddings as part of my series on machine learning on graphs (part 1, part 2, part 3). In particular, it also discusses my last research paper

Venom - A Multi-hop Proxy For Penetration Testers

vom 344.09 Punkte
Venom is a multi-hop proxy tool developed for penetration testers using Go. You can use venom to easily proxy network traffic to a multi-layer intranet, and easily manage intranet nodes.Features network topology multi-hop socks5 proxy multi-hop port forward port r

Algorithms 101: How to use graph algorithms

vom 344.09 Punkte
Algorithms are one of the most common themes in coding interviews. In order to gain an advantage in interviews, it is important to be very familiar with the top algorithms and their implementations. In today’s tutorial, we will be exploring graph alg

Using Node.js for Ecommerce: Pros and Cons

vom 332.02 Punkte
Node.js is a JavaScript runtime environment which developers use to build scalable network applications. You can use it in various software, including ecommerce platforms. To deliver high performance and speed for ecommerce applications, Node.js is one

Backend Delivery - Hands-On Node & Docker 1/2

vom 301.83 Punkte
We’re going to explore how to set yourself up for success - when it comes to exploring Kubernetes and running Dockerized applications. It all starts with understanding whys and hows to deliver your application while being productive in your local dev environment. Why Every time I want to start a new project, I feel like reinventing the wheel. There are so many tutorials that cover Node, Docker, and debugging node… but not how to combine those. While individually each of those is a 5-minute setup, the internet runs short when it comes to an explanation of how to set up the whole thing. So let us follow The twelve factors and start thinking “cloud-first”, and have a project setup that makes sense for both delivery and development. What’s covered In this article: building & running your container. In-depth examples and explanations of how I reason about setting things up. In the follow-up article: in-depth explanation about using containers for “one-command, ready-to-run” projects. Hot-reload, debugger, tests. Delivery-first mentality Say you finished your project and want to deploy it in the wild, so other people can access it. All you have to do is run node src/app.js, right? Right?! Not quite. What were the steps you took on your local environment to run your application? Any prerequisites? Any OS dependencies? etc, etc… The same goes for any server. It needs to have some things installed so that it can run your code. This applies to your friend’s PC and to your mom’s laptop, too. You need to actually install node (and ideally, the same version) so that it runs the same way as it does for you. The problem, if you only do this as a “final” step is that, most likely, your app won’t work anywhere else than on your local machine. Or you are a remember-it-all kind of person, that knows exactly all the steps needed to run the application. And you’re willing and have the time to do that setup manually on multiple machines! The project Just in case you want to follow along, this is the app that we’re going to consider: a simple express application, with cors enabled, and nodemon for local development & hot-reload. // src/app.js import * as dotenv from 'dotenv' dotenv.config() import cors from 'cors' import express from 'express' const app = express() app.use(cors()) app.get('/', (req, res) => { const testDebug = 4; res.send('Hello World!') }) const port = process.env.APP_PORT app.listen(port, () => { console.log(`App listening on port ${port}`) }) // package.json { "scripts": { "dev": "nodemon --inspect=9500 ./src/app.js" }, "dependencies": { "cors": "^2.8.5", "dotenv": "^16.0.3", "express": "^4.18.2" }, "devDependencies": { "nodemon": "^2.0.20" }, "type": "module" } While there are many other things a real project would need, this should suffice for this demo. This is the commit used for this explanation, btw: node-quickstart-local-dev. After cloning/downloading the files, all you have to do is to run a simple npm install; it will fetch all the dependencies defined in the package.json. Running npm run dev will start the nodemon process simulating node --watch and exposing port 9500 for debugging. Or we can run this in “prod” mode by calling node src/app.js. This is all that’s needed to run this project on our local machine. 🤦 No, it’s not, you silly! You also need node to run the app and npm to install the dependencies. To add to that, pr

50 Node JS Interview Questions

vom 277.69 Punkte
Save the story for the Future and crack any Node JS backend interview Under the Hood Well, the story begins when I saw this post about the recession and mass layoffs. I got so many emails/messages for any kind of job opportunity but unfor

Top 6 tools for Node.js monitoring

vom 271.65 Punkte
Written by Pascal Akunne✏️ Node.js monitoring is crucial to helping maintain the stability, dependability, and performance of your applications. You can rapidly spot any problems that might be harming the performance of your app by keeping an eye on

Team Security Diskussion über DALL-E with node.js