How to Build a Jasper-like Content Generation Platform Using Node.js

Written by albarqawi | Published 2023/05/05
Tech Story Tags: ai | chatgt | nodejs | javascript | generative-ai | artificial-intelligence | jasper-ai | content-creation

TLDRSimplifying AI Integration for Developers - Discover how to incorporate cutting-edge AI models into your projects for generating text, images, and audio.via the TL;DR App

Integrating state-of-the-art AI models into your projects can be challenging due to the complexities of different AI models and managing numerous dependencies. IntelliNode, an open-source JavaScript library, aims to simplify this process by providing developers with a unified and easy-to-use interface to access the latest AI models. In this blog post, we'll demonstrate how to build a [Jasper ai]-like platform using IntelliNode to generate marketing copy, images, and audio for various products.

Use Case

For this tutorial, let's assume we want to create a content generation platform to generate marketing copy for various products, images, and audio. This platform will help businesses create engaging content for their marketing campaigns without manual work. We'll start by setting up the IntelliNode library, develop the backend functionality, and then connect it to a user interface.

The outcome will be a user-friendly website where users can input a simple prompt and have marketing materials automatically generated for their needs. We will only work a little in frontend styling in this post as our focus is AI integration, but you can add styling to the website, like the screenshots. The code structure can also be adapted to generate a variety of materials, such as blog posts.

Getting Started with IntelliNode

First, add the IntelliNode module to your node.js project by running in an empty folder:

npm init -y
npm i intellinode

Create the following files inside the folder as we will use them in the next steps to fill the code content:

  • index.html: for the frontend html code.
  • app.js: we will add the backend code here.
  • front.js: for the frontend javascript code.

AI model code

Now, let's create an object containing our IntelliNode code to generate text, images, and audio and store it in app.js. The code will call three functions:

  1. get_marketing_desc(prompt, apiKey): This method inputs a prompt and generates marketing text. It requires an API key for the language model.
  2. generate_image_from_desc(prompt, openaiKey, stabilityKey): This method takes a prompt as input and generates an image description used to generate the image. It requires two API keys, one for the language model and another for the image generation model.
  3. generate_speech_synthesis(text, apiKey): generate audio from the input text. It requires an API key for the speech synthesis model.

const {
    Gen
} = require("intellinode");

const intelliCode = {
    async generateText(prompt) {
        const openaiKey = "<openai-key>";
        return await Gen.get_marketing_desc(prompt, apiKey);
    },

    async generateImage(prompt) {
        const openaiKey = "<openai-key>";
        const stabilityKey = "<stability.ai-key>";
        return await Gen.generate_image_from_desc(prompt, openaiKey, stabilityKey);
    },

    async generateAudio(text, base64 = true) {
        const apiKey = "<google-cloud-key>";
        const audioContent = await Gen.generate_speech_synthesis(text, apiKey);
        return base64 ? audioContent : Buffer.from(audioContent, "base64");
    },
};

Backend code

Next, let's create the backend functionality using the intelliCode object we just created.

Let's start by installing express:

npm i express

Add the following backend script to app.js:

const express = require('express');
// .. intelli node import ..

// .. intelli code node here ...

const app = express();
app.use(express.json());
// serve static files
const path = require("path");
app.use(express.static(path.join(__dirname)));

app.post("/generate-content", async (req, res) => {
    const {
        product
    } = req.body;

    const textPrompt = `Write a marketing copy for ${product}`;

    const text = await intelliCode.generateText(textPrompt);

    // const imagePrompt = `Generate an image for ${product}`;
    const imageData = await intelliCode.generateImage(text);

    const audioData = await intelliCode.generateAudio(text);

    res.send({
        text: text,
        imageData: imageData,
        audioData: audioData,
    });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server listening on port ${PORT}`));

Connecting to a User Interface

Now that we have our backend, we can connect it to a simple frontend using HTML, and JavaScript. Add the following content inside index.html file :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jasper-like Content Generation Platform</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container mt-5">
      <h1 class="mb-5 text-center">Jasper-like Content Generation Platform</h1>
      <form id="content-form" class="mb-5">
        <div class="mb-3">
          <label for="product" class="form-label">Product:</label>
          <input type="text" class="form-control" id="product" name="product">
        </div>
        <button type="submit" class="btn btn-primary">Generate Content</button>
      </form>
      <div id="loading" class="text-center d-none">
        <div class="spinner-border" role="status">
          <span class="visually-hidden"></span>
        </div>
      </div>
      <div id="results" class="d-none">
        <h2 class="mb-3">Generated Text:</h2>
        <p id="generated-text"></p>
        <h2 class="mb-3">Generated Image:</h2>
        <img id="generated-image" src="" alt="Generated Image" class="img-fluid">
        <h2 class="mb-3">Generated Audio:</h2>
        <audio id="generated-audio" controls src=""></audio>
      </div>
    </div>
    <script src="front.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>
  </body>
</html>

Lastly, create a front.js file to handle the form submission and display the results:

document.getElementById('content-form').addEventListener('submit', async (e) => {
    e.preventDefault();

    const product = document.getElementById('product').value;

    // Show loading spinner
    document.getElementById('loading').classList.remove('d-none');

    try {
        const response = await fetch('/generate-content', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                product: product
            })
        });
        const data = await response.json();

        // Hide loading spinner and show results
        document.getElementById('loading').classList.add('d-none');
        document.getElementById('results').classList.remove('d-none');

        document.getElementById('generated-text').innerText = data.text;

        // Convert image data to data URL
        const imageDataUrl = `${data.imageData}`;
        document.getElementById('generated-image').src = imageDataUrl;

        // Convert audio data to data URL
        const audioDataUrl = `data:audio/mpeg;base64,${data.audioData}`;
        document.getElementById('generated-audio').src = audioDataUrl;
    } catch (error) {
        // Hide loading spinner and show an error message
        document.getElementById('loading').classList.add('d-none');
        alert('An error occurred while generating content. Please try again.');
    }
});

You can run the server:

node app.js

Open your browser and navigate to http://localhost:3000. You should see the user interface for your content generation platform.

You now have a fully functional platform that integrates with multiple AI models. The response might take some time because the code waits for all models' output before displaying the results. To improve the user experience, consider fetching results from each model separately.

You can find the full code in below sample folder, including the code that fetch each model separately for a faster performance:

[Sample code repo]

In conclusion, developers can utilize multiple AI models with different capabilities to build compelling use cases, and libraries like IntelliNode make it easy to access all the models from one module.


Written by albarqawi | Engineer and data science master at Illinois Urbana-Champaign.
Published by HackerNoon on 2023/05/05