-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate.ts
252 lines (229 loc) · 7.32 KB
/
generate.ts
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
import { Args, Flags } from '@oclif/core';
import { BaseCommand } from '../../base/BaseCommand.js';
import { join } from 'node:path';
import { downloadImage, fileExists } from '../../utils/file-utils.js';
import { SingleBar } from 'cli-progress';
import writeXlsxFile from 'write-excel-file/node';
import { generateImage, generatePfps, readPfpLayerSpecs } from '../../services/pfp-service.js';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { PfpManifest } from '../../types/pfps.js';
import { confirmPrompt, makeSpinner } from '../../utils/tty-utils.js';
import PfpCoverCommand from './cover.js';
import PfpMosaicCommand from './mosaic.js';
export default class GeneratePfpsCommand extends BaseCommand {
static examples = [
{
command: '<%= config.bin %> <%= command.id %> pfps-specs.xlsx pfps',
description: 'Generates all the pfps defined in the pfps-specs.xlsx file and saves them in the pfps directory.',
},
];
static description = 'Generates the images and attributes for a pfp collection.';
static args = {
input: Args.string({
description: 'Location or google sheets id of the excel file with the pfps definitions.',
required: true,
}),
output: Args.directory({
description: 'Directory where the images will be saved.',
required: true,
}),
};
static flags = {
rootDir: Flags.directory({
char: 'r',
exists: true,
description: 'Directory where the assets are stored.',
}),
resizeWidth: Flags.integer({
char: 'w',
description: 'Width to resize the images to.',
}),
quantity: Flags.integer({
char: 'q',
description: 'Number of pfps to generate.',
required: true,
}),
debug: Flags.boolean({
description: 'Include more information in the pfs excel.',
default: false,
}),
predefined: Flags.string({
description: 'Location or google sheets id of the excel file with the predefined pfps definitions.',
required: false,
}),
};
public async run(): Promise<void> {
const { flags, args } = await this.parse(GeneratePfpsCommand);
const output = args.output;
const rootDir = flags.rootDir || output;
const { quantity, debug, predefined } = flags;
const manifestPath = join(output, 'manifest.json');
const imagesFolder = join(output, 'images');
const excelPath = join(output, 'pfps.xlsx');
const spinner = makeSpinner();
if (existsSync(manifestPath)) {
const overwrite = await confirmPrompt('Manifest file already exists, do you want to overwrite the pfp results?');
if (!overwrite) {
return;
} else {
rmSync(excelPath, { force: true });
rmSync(imagesFolder, { recursive: true, force: true });
}
}
// Save pfps to json file in output directory
if (!fileExists(output)) {
mkdirSync(output, { recursive: true });
}
spinner.start('Reading file...');
const { layerSpecs, forcedPfps, downloadSpecs } = await readPfpLayerSpecs({
filePathOrSheetsId: args.input,
rootDir: args.output,
predefinedFilePathOrSheetsId: predefined,
});
spinner.succeed();
if (downloadSpecs) {
const layersProgressBar = new SingleBar({
format: 'Downloading layers | {bar} | {percentage}% | {value}/{total} layers | ETA: {eta_formatted}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
clearOnComplete: true,
});
const output = downloadSpecs.folder;
const ipfsValues = downloadSpecs.ipfsHashes;
layersProgressBar.start(ipfsValues.length, 0);
for (const ipfs of ipfsValues) {
try {
await downloadImage(ipfs, output);
layersProgressBar.increment();
} catch (error) {
layersProgressBar.stop();
spinner.fail('Failed to generate images');
throw error;
}
}
layersProgressBar.stop();
spinner.succeed(`${ipfsValues.length} layers downloaded`);
}
spinner.start('Mixing pfps...');
const pfps = generatePfps({
quantity,
layerSpecs,
forcedPfps,
});
const manifest: PfpManifest = {
collectionName: '',
uploads: {},
pfps: [],
};
if (existsSync(manifestPath)) {
try {
const currentManifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
manifest.uploads = currentManifest.uploads;
} catch (error) {
const shouldDelete = await confirmPrompt('Manifest file is corrupted, do you want to delete it?');
if (shouldDelete) {
rmSync(manifestPath, { force: true });
} else {
return;
}
}
}
const headerRow = [
{
type: String,
value: 'dna',
},
...(debug
? [
{
type: String,
value: 'imageLayers',
},
]
: []),
...layerSpecs.flatMap((layerSpec) => [
{
type: String,
value: layerSpec.name,
},
...(debug
? [
{
type: String,
value: `${layerSpec.name} id`,
},
]
: []),
]),
];
const excelPfps = pfps.map((pfp) => [
{
type: String,
value: pfp.dna,
},
...(debug
? [
{
type: String,
value: pfp.imageLayers.join('\n'),
},
]
: []),
...layerSpecs.flatMap((layerSpec) => [
{
type: String,
value: pfp.attributes.find(({ name }) => name === layerSpec.name)?.value || '',
},
...(debug
? [
{
type: String,
value: pfp.attributes.find(({ name }) => name === layerSpec.name)?.id || '',
},
]
: []),
]),
]);
for (const pfp of pfps) {
manifest.pfps.push({
dna: pfp.dna,
attributes: pfp.attributes.reduce((acc, { name, value }) => ({ ...acc, [name]: value }), {}),
});
}
const excelData = [headerRow, ...excelPfps];
writeXlsxFile(excelData, { filePath: excelPath });
writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
spinner.succeed('Pfps mixed and saved');
// Generate images for pfps
const imagesProgressBar = new SingleBar({
format: 'Generating images | {bar} | {percentage}% | {value}/{total} pfps | ETA: {eta_formatted}',
barCompleteChar: '\u2588',
barIncompleteChar: '\u2591',
clearOnComplete: true,
});
try {
if (existsSync(imagesFolder)) {
rmSync(imagesFolder, { recursive: true });
}
mkdirSync(imagesFolder, { recursive: true });
imagesProgressBar.start(pfps.length, 0);
for (const pfp of pfps) {
await generateImage({
pfp,
rootDir,
outputFolder: imagesFolder,
resizeWidth: flags.resizeWidth,
});
imagesProgressBar.increment();
}
imagesProgressBar.stop();
spinner.succeed(`Generated ${pfps.length} images`);
} catch (error) {
imagesProgressBar.stop();
spinner.fail('Failed to generate images');
}
await PfpCoverCommand.run([output]);
const mosaicQuantity = Math.min(quantity, 100);
await PfpMosaicCommand.run([output, `--quantity=${mosaicQuantity}`]);
}
}