-
Notifications
You must be signed in to change notification settings - Fork 0
/
example.js
197 lines (155 loc) · 6.7 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*
Requires Node.js 18.x to be installed.
Create an example.sh file with the following content and execute it from the command line using ./example-js.sh:
USEAPI_SERVER="…" USEAPI_CHANNEL="…" USEAPI_TOKEN="…" USEAPI_DISCORD="…" node ./example.js
*/
const fs = require('fs');
const util = require('util');
const { Readable } = require('stream');
const { finished } = require('stream/promises');
const inputFileName = './prompts.json';
// We will utilize all three available job slots for the Basic or Standard plan.
const maxJobs = 3;
// You can use https://webhook.site or https://ngrok.com if you want to receive results via callback.
const replyUrl = undefined;
// Provide additional prompt params
const withParams = ' --relax'; // --fast or --relax
// Time to pause between calls
const sleepSecs = 5;
// API root url
const rootUrl = 'https://api.useapi.net/v2';
const sleep = (ms = 0) => new Promise(resolve => setTimeout(resolve, ms));
const dateAsString = () => new Date().toISOString();
const loadFromFile = async (filePath) => {
const readFileAsync = util.promisify(fs.readFile);
const data = await readFileAsync(filePath, 'utf8');
if (data)
return JSON.parse(data)
else
throw new Error('Unable to load file:', filePath);
}
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) => {
// Extract filename.png from https://cdn.discordapp.com/attachments/server_id/channed_id/filename.png?ex=
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 main = async () => {
// Load all required parameters from the environment variables
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 prompts = await loadFromFile(inputFileName);
console.log(`${dateAsString()} ⁝ prompts to process`, prompts.length);
const results = [];
let ind = 0;
const startTime = performance.now();
for (const _prompt of prompts) {
const prompt = `${_prompt} ${withParams}`.trim();
ind++;
const data = {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
};
// Detailed documentation at https://useapi.net/docs/api-v2/post-jobs-imagine
data.body = JSON.stringify({
prompt,
discord,
server,
channel,
maxJobs,
replyUrl: replyUrl ? `${replyUrl}?ind=${ind}` : undefined
});
console.log(`${dateAsString()} ⁝ #${ind} prompt`, prompt);
let attempt = 0;
let retry = true;
do {
attempt++;
const apiUrl = `${rootUrl}/jobs/imagine`;
const response = await fetch(apiUrl, data);
const result = await response.json();
console.log(`${dateAsString()} ⁝ attempt #${attempt}, response`, { status: response.status, jobid: result.jobid, job_status: result.status, ind });
switch (response.status) {
case 429: // Query is full
console.log(`${dateAsString()} ⁝ #${ind} attempt #${attempt} sleeping for ${sleepSecs} secs...`);
await sleep(sleepSecs * 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 response.status`, result);
retry = false;
break;
}
} while (retry);
await saveToFile('./result.json', results);
}
console.log(`${dateAsString()} ⁝ downloading generated images`);
ind = 0;
for (const item of results) {
ind++;
const { jobid, status, prompt } = item;
console.log(`${dateAsString()} ⁝ #${ind} jobid`, { jobid, status });
if (status == 422)
console.warn(`moderated prompt`, prompt);
if (status == 200) {
let attempt = 0;
let retry = true;
do {
attempt++;
const apiUrl = `${rootUrl}/jobs/?jobid=${jobid}`;
const response = await fetch(apiUrl, {
headers: {
"Authorization": `Bearer ${token}`,
},
});
const result = await response.json();
console.log(`${dateAsString()} ⁝ 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(`${dateAsString()} ⁝ #${ind} attempt #${attempt} sleeping for ${sleepSecs} secs...`, result.status);
await sleep(sleepSecs * 1000);
} else {
console.error(`Unexpected response.status`, result);
retry = false;
}
break;
default:
console.error(`Unexpected response.status`, result);
retry = false;
break;
}
} while (retry);
}
}
const executionTimeInMilliseconds = performance.now() - startTime;
console.log(`${dateAsString()} ⁝ total elapsed time ${new Date(executionTimeInMilliseconds).toISOString()}`);
}
main();