-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathgenerate.mjs
321 lines (252 loc) · 10.6 KB
/
generate.mjs
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import fs from 'fs';
import path from 'path';
import { loadImage, createCanvas } from 'canvas';
import GIFEncoder from 'gifencoder';
import inquirer from 'inquirer';
import config from './config.mjs';
import { execSync } from 'child_process';
import pLimit from 'p-limit';
import printHeader from './workers/bankkroll.mjs';
import printCollectionInfo from "./workers/collectionInfoPrinter.mjs";
import { logSuccess, logError, logRegular } from "./workers/consoleLogger.mjs";
import { extractFrames } from './workers/extractFrames.mjs';
import { generateUniqueTraits, calculateTotalCombinations } from './workers/combinations.mjs';
import ora from 'ora';
import chalk from 'chalk';
// Create a delay
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
//#########################################//
//# #//
//# Main Function #//
//# #//
//#########################################//
async function main() {
try {
// Create the output folder if it does not already exist
fs.mkdirSync(config.outputFolder, { recursive: true });
// Print the header and collection info to the console
printHeader();
await delay(1500);
// Prompt the user to enter the desired processing intensity
const { machineStrength } = await inquirer.prompt({
type: 'list',
name: 'machineStrength',
message: chalk.cyan('What level of processing intensity do you want to run this task with? (Choose a lower level for weaker machines)'),
choices: [
{ name: 'Low (2 - Suitable for low-end machines)', value: 2 },
{ name: 'Medium (4 - Suitable for average hardware)', value: 4 },
{ name: 'High (6 - Suitable for high-end machines)', value: 6 },
{ name: 'Very High (8 - Suitable for very high-end machines)', value: 8 },
{ name: 'Ultra (10 - Suitable for top-tier hardware specs)', value: 10 },
{ name: 'Insane (12 - Only for the most powerful machines)', value: 12 }
]
});
const limit = pLimit(machineStrength);
// Prompt the user to choose between generating GIFs or images
const answer = await inquirer.prompt({
type: 'list',
name: 'choice',
message: chalk.cyan('Do you want to generate GIFs or Images?'),
choices: ['GIFs', 'Images']
});
const choice = answer.choice.charAt(0);
const fileType = choice.toUpperCase() === 'G' ? 'GIFs' : 'Images';
// Calculate the total number of possible combinations of traits
const totalCombinations = calculateTotalCombinations(config);
if (config.numImages > totalCombinations) {
logError(`Requested number of files (${config.numImages}) exceeds the total possible combinations (${totalCombinations}). Please lower the number of files to generate.`);
return;
}
const loadingSpinner = ora({
text: `Reading ${fileType}.`,
color: 'cyan',
spinner: 'dots6'
}).start();
await delay(2000);
loadingSpinner.succeed(chalk.green(`Verified ${fileType}.`));
await delay(500);
printCollectionInfo(config);
const loadingSpinner1 = ora({
text: `Confirming Details.`,
color: 'cyan',
spinner: 'dots6'
}).start();
await delay(2000);
loadingSpinner1.succeed(chalk.green(`Confimred config.js.`));
const loadingSpinner2 = ora({
text: `Thinking please wait....`,
color: 'cyan',
spinner: 'dots6'
}).start();
await delay(2000);
loadingSpinner2.succeed(chalk.green(`Loading traits....`));
const tasks = Array.from({ length: config.numImages }, (_, i) =>
limit(async () => {
if (choice.toUpperCase() === 'G') {
await generateGif(i, config);
} else {
await generateImage(i, config);
}
logSuccess(`Generated ${fileType} #${i + config.startAt}`);
})
);
await Promise.all(tasks);
logSuccess(`All ${fileType} generated successfully!`);
await delay(1000);
// Prompt the user to choose whether to upload to IPFS or not
const ipfsAnswer = await inquirer.prompt({
type: 'list',
name: 'choice',
message: chalk.cyan('Do you want to upload the generated files to IPFS?'),
choices: ['Yes', 'No'],
});
if (ipfsAnswer.choice === 'Yes') {
const folderPath = config.outputFolder;
const cmd = `npx thirdweb@latest upload ${folderPath}`;
execSync(cmd, { stdio: 'inherit' });
} else {
const loadingSpinner = ora({
text: `Skipping IPFS upload.`,
color: 'cyan',
spinner: 'dots6'
}).start();
await delay(1000);
loadingSpinner.succeed(`IPFS upload skipped.`);
}
printHeader();
} catch (err) {
logError(`Failed to generate files: ${err.message}`);
}
}
//#########################################//
//# #//
//# Generate Image #//
//# #//
//#########################################//
async function generateImage(i, config) {
try {
// Generate unique traits
const chosenTraits = await generateUniqueTraits(config.traitFolders, config);
const traits = [];
const canvases = [];
// Loop over all trait folders and use the chosen unique traits
for (let j = 0; j < config.traitFolders.length; j++) {
const traitFolder = config.traitFolders[j];
const traitPath = path.join(config.traitsFolder, traitFolder);
const chosenTrait = chosenTraits[j];
const chosenTraitPath = path.join(traitPath, chosenTrait);
// Load the image
const img = await loadImage(chosenTraitPath);
// Add the trait to the traits array
traits.push({
trait_type: traitFolder,
value: path.basename(chosenTrait, path.extname(chosenTrait)),
});
// Add the image to the canvases array
canvases.push(img);
}
// Combine images from each trait into a single image
const canvas = createCanvas(config.imageWidth, config.imageHeight, 'sRGB');
const ctx = canvas.getContext("2d");
for (let j = 0; j < config.layersNumber; j++) {
const image = canvases[j];
ctx.drawImage(image, 0, 0, config.imageWidth, config.imageHeight);
}
// Save the combined image
const outputPath = path.join(config.outputFolder, `${i + config.startAt}.png`);
const outputBuffer = canvas.toBuffer("image/png");
fs.writeFileSync(outputPath, outputBuffer);
// Create metadata for this generated image and write it to a JSON file
const metadata = {
name: `${config.collectionName} #${i + config.startAt}`,
description: `${config.collectionDescription}`,
image: `${i + config.startAt}.png`,
external_url: `${config.collectionExternal_url}`,
attributes: traits,
};
const outputJsonPath = path.join(config.outputFolder, `${i + config.startAt}.json`);
fs.writeFileSync(outputJsonPath, JSON.stringify(metadata, null, 2));
logRegular(`JSON metadata: ${outputJsonPath}`);
logRegular(`Image file: ${outputPath}`);
} catch (err) {
logError(`Failed to generate image ${i + config.startAt}: ${err.message}`);
}
}
//#########################################//
//# #//
//# Generate Gif #//
//# #//
//#########################################//
async function generateGif(i, config) {
try {
// Generate unique traits
const chosenTraits = await generateUniqueTraits(config.traitFolders, config);
const traits = [];
const traitFrames = [];
// Loop over all trait folders and use the chosen unique traits
for (let j = 0; j < config.traitFolders.length; j++) {
const traitFolder = config.traitFolders[j];
const traitPath = path.join(config.traitsFolder, traitFolder);
const chosenTrait = chosenTraits[j];
const chosenTraitPath = path.join(traitPath, chosenTrait);
// Extract frames from the chosen trait
const frames = await extractFrames(chosenTraitPath);
if (!frames) {
console.error(`Failed to extract frames from file at path: ${chosenTraitPath}`);
return;
}
// Add the trait to the traits array
traits.push({
trait_type: traitFolder,
value: path.basename(chosenTrait, path.extname(chosenTrait)),
});
// Add the frames to the traitFrames array
traitFrames.push(frames);
}
// Calculate max frames for looping
const maxFrames = Math.max(...traitFrames.map(x => x.length));
// Combine frames from each trait into a single image
const frames = [];
for (let frameIndex = 0; frameIndex < maxFrames; frameIndex++) {
const canvas = createCanvas(config.imageWidth, config.imageHeight, 'sRGB');
const ctx = canvas.getContext("2d");
for (let j = 0; j < config.layersNumber; j++) {
const frame = traitFrames[j][frameIndex % traitFrames[j].length];
ctx.drawImage(frame, 0, 0, config.imageWidth, config.imageHeight);
}
frames.push(canvas);
}
// Encode the frames into a GIF
const encoder = new GIFEncoder(config.imageWidth, config.imageHeight);
const outputGifPath = path.join(config.outputFolder, `${i + config.startAt}.gif`);
// Create a write stream to write the GIF file to disk
const outputStream = fs.createWriteStream(outputGifPath);
encoder.createReadStream().pipe(outputStream);
encoder.setRepeat(0);
encoder.setDelay(100);
encoder.setQuality(40);
encoder.start();
// Add each frame to the GIF encoder
for (const frame of frames) {
encoder.addFrame(frame.getContext("2d"));
}
encoder.finish();
// Create metadata for this generated image and write it to a JSON file
const metadata = {
name: `${config.collectionName} #${i + config.startAt}`,
description: `${config.collectionDescription}`,
image: `${i + config.startAt}.gif`,
external_url: `${config.collectionExternal_url}`,
attributes: traits,
};
const outputJsonPath = path.join(config.outputFolder, `${i + config.startAt}.json`);
fs.writeFileSync(outputJsonPath, JSON.stringify(metadata, null, 2));
logRegular(`JSON metadata: ${outputJsonPath}`);
logRegular(`GIF file: ${outputGifPath}`);
} catch (err) {
logError(`Failed to generate GIF ${i + config.startAt}: ${err.message}`);
}
}
main();