Executing 10 Midjourney /imagine generations and retrieving results.

JavaScript
# bash 
USEAPI_TOKEN="…" USEAPI_DISCORD="…" USEAPI_SERVER="…" USEAPI_CHANNEL="…" node demo.js
// NodeJs 18.x 
const fs = require('fs');
const { Readable } = require('stream');
const { finished } = require('stream/promises');

const imdb =
    [
        "Tony Stark (Iron Man), The genius billionaire who becomes the armored superhero known as Iron Man, using his technology for good.",
        "Loki, The mischievous and shape-shifting Asgardian god with a complex relationship with his brother Thor.",
        "Princess Leia, A fearless leader in the Rebel Alliance, known for her bravery and role in the Star Wars saga.",
        "The Wicked Witch of the West, The iconic antagonist from 'The Wizard of Oz,' known for her pursuit of Dorothy and her ruby slippers.",
        "John McClane, The tough and resourceful NYPD officer who battles terrorists in the 'Die Hard' series.",
        "The T-800 (Terminator), A relentless and nearly indestructible cyborg assassin from the future.",
        "Katara, A skilled waterbender and member of Team Avatar, known for her role in 'Avatar: The Last Airbender.'",
        "Malekith, The dark elf antagonist from 'Thor: The Dark World,' seeking to unleash darkness upon the Nine Realms.",
        "Hermione Granger, The brilliant and resourceful witch from the 'Harry Potter' series, known for her vast knowledge and loyalty.",
        "The White Witch (Jadis), The evil ruler of Narnia in 'The Chronicles of Narnia,' known for her icy tyranny.",
    ];

const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));

const saveToFile = async (filePath, data) => {
    await fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => {
        if (err)
            console.error('Error writing to file:', err);
    });
}

const getFileNameFromUrl = (url) => {
    const matches = url.match(/\/([^/]+)$/);
    return matches && matches.length > 1 ? matches[1] : null;
}

const downloadFile = async (url, ind) => {
    const { body } = await fetch(url);
    localPath = `./${ind}-${getFileNameFromUrl(url)}`;
    const stream = fs.createWriteStream(localPath);
    await finished(Readable.fromWeb(body).pipe(stream));
};

const exec = async (json_array) => {
    const token = process.env.USEAPI_TOKEN;
    const discord = process.env.USEAPI_DISCORD;
    const server = process.env.USEAPI_SERVER;
    const channel = process.env.USEAPI_CHANNEL;

    const results = [];

    let ind = 0;

    for (const prompt of json_array) {
        ind++;

        const data = {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        };

        data.body = JSON.stringify({ prompt, discord, server, channel });

        console.log(`#${ind} prompt`, prompt);

        let attempt = 0;
        let retry = true;

        do {
            attempt++;

            const apiUrl = "https://api.useapi.net/v2/jobs/imagine";
            const response = await fetch(apiUrl, data);
            const result = await response.json();

            console.log(`attempt #${attempt}, response`, { status: response.status, jobid: result.jobid, job_status: result.status, ind });

            switch (response.status) {
                case 429: // Query is full
                    console.log(`#${ind} attempt #${attempt} sleeping for 10secs...`);
                    await sleep(10 * 1000);
                    break;
                case 200: // OK
                case 422: // Moderated
                    results.push({ status: response.status, jobid: result.jobid, job_status: result.status, ind, prompt });
                    retry = false;
                    break;
                default:
                    console.error(`Unexpected status`, response.status);
                    retry = false;
                    break;
            }
        } while (retry);

        await saveToFile('./result.json', results);
    }

    console.log(`download generated images`, new Date());

    ind = 0;

    for (const item of results) {
        ind++;

        const { jobid, status } = item;
        console.log(`#${ind} jobid`, { jobid, status });

        if (status == 200) {
            let attempt = 0;
            let retry = true;
            do {
                attempt++;

                const apiUrl = `https://api.useapi.net/v2/jobs/?jobid=${jobid}`;
                const response = await fetch(apiUrl, {
                    headers: {
                        "Authorization": `Bearer ${token}`,
                    },
                });
                const result = await response.json();

                console.log(`attempt #${attempt}, response`, { status: response.status, jobid: result.jobid, job_status: result.status, ind });

                switch (response.status) {
                    case 200:
                        if (result.status == 'completed') {
                            if (result.attachments?.length) {
                                downloadFile(result.attachments[0].url, ind);
                            } else {
                                console.error(`#${ind} completed jobid has no attachments`);
                            }
                            retry = false;
                        } else
                            if (result.status == 'started' || result.status == 'progress') {
                                console.log(`#${ind} attempt #${attempt} sleeping for 10secs...`, result.status);
                                await sleep(10 * 1000);
                            } else {
                                console.error(`Unexpected result.status`, result.status);
                                retry = false;
                            }
                        break;
                    default:
                        console.error(`Unexpected status`, response.status);
                        retry = false;
                        break;
                }
            } while (retry);
        }
    }
}

exec(imdb);
Python
# bash
USEAPI_TOKEN="…" USEAPI_DISCORD="…" USEAPI_SERVER="…" USEAPI_CHANNEL="…" python3 demo.py
# pip install requests

import os
import json
import requests
import time

imdb = [
    "Tony Stark (Iron Man), The genius billionaire who becomes the armored superhero known as Iron Man, using his technology for good.",
    "Loki, The mischievous and shape-shifting Asgardian god with a complex relationship with his brother Thor.",
    "Princess Leia, A fearless leader in the Rebel Alliance, known for her bravery and role in the Star Wars saga.",
    "The Wicked Witch of the West, The iconic antagonist from 'The Wizard of Oz,' known for her pursuit of Dorothy and her ruby slippers.",
    "John McClane, The tough and resourceful NYPD officer who battles terrorists in the 'Die Hard' series.",
    "The T-800 (Terminator), A relentless and nearly indestructible cyborg assassin from the future.",
    "Katara, A skilled waterbender and member of Team Avatar, known for her role in 'Avatar: The Last Airbender.'",
    "Malekith, The dark elf antagonist from 'Thor: The Dark World,' seeking to unleash darkness upon the Nine Realms.",
    "Hermione Granger, The brilliant and resourceful witch from the 'Harry Potter' series, known for her vast knowledge and loyalty.",
    "The White Witch (Jadis), The evil ruler of Narnia in 'The Chronicles of Narnia,' known for her icy tyranny.",
]

def save_to_file(file_path, data):
    with open(file_path, 'w') as file:
        json.dump(data, file, indent=2)

def get_file_name_from_url(url):
    file_name = url.split('/')[-1]
    return file_name

def download_file(url, ind):
    response = requests.get(url, stream=True)
    local_path = f'./{ind}-{get_file_name_from_url(url)}'
    with open(local_path, 'wb') as file:
        for chunk in response.iter_content(chunk_size=8192):
            if chunk:
                file.write(chunk)

def exec(json_array):
    token = os.environ.get('USEAPI_TOKEN')
    discord = os.environ.get('USEAPI_DISCORD')
    server = os.environ.get('USEAPI_SERVER')
    channel = os.environ.get('USEAPI_CHANNEL')

    results = []

    ind = 0

    for prompt in json_array:
        ind += 1

        data = {
            'prompt': prompt,
            'discord': discord,
            'server': server,
            'channel': channel,
        }

        headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json',
        }

        print(f'#{ind} prompt', prompt)

        attempt = 0
        retry = True

        while retry:
            attempt += 1

            api_url = "https://api.useapi.net/v2/jobs/imagine"
            response = requests.post(api_url, headers=headers, json=data)
            result = response.json()

            print(f'attempt #{attempt}, response', {'status': response.status_code, 'jobid': result.get('jobid'), 'job_status': result.get('status'), 'ind': ind})

            if response.status_code == 429:
                print(f'#{ind} attempt #{attempt} sleeping for 10secs...')
                time.sleep(10)
            elif response.status_code == 200 or response.status_code == 422:
                results.append({'status': response.status_code, 'jobid': result.get('jobid'), 'job_status': result.get('status'), 'ind': ind, 'prompt': prompt})
                retry = False
            else:
                print('Unexpected status', response.status_code)
                retry = False

        save_to_file('./result.json', results)

    print('download generated images', time.strftime('%Y-%m-%d %H:%M:%S'))

    ind = 0

    for item in results:
        ind += 1

        job_id = item['jobid']
        status = item['status']

        print(f'#{ind} jobid', {'jobid': job_id, 'status': status})

        if status == 200:
            attempt = 0
            retry = True

            while retry:
                attempt += 1

                api_url = f'https://api.useapi.net/v2/jobs/?jobid={job_id}'
                response = requests.get(api_url, headers={'Authorization': f'Bearer {token}'})
                result = response.json()

                print(f'attempt #{attempt}, response', {'status': response.status_code, 'jobid': result.get('jobid'), 'job_status': result.get('status'), 'ind': ind})

                if response.status_code == 200:
                    if result.get('status') == 'completed':
                        if 'attachments' in result and result.get('attachments'):
                            download_file(result['attachments'][0]['url'], ind)
                        else:
                            print(f'#{ind} completed jobid has no attachments')
                        retry = False
                    elif result.get('status') == 'started' or result.get('status') == 'progress':
                        print(f'#{ind} attempt #{attempt} sleeping for 10secs...', result.get('status'))
                        time.sleep(10)
                    else:
                        print('Unexpected result.status', result.get('status'))
                        retry = False
                else:
                    print('Unexpected status', response.status_code)
                    retry = False

exec(imdb)

Duration: 1min 20sec

YouTube Executing 50 Midjourney /imagine generations and retrieving results, calculating overall execution time vs reported Fast GPU time.