Skip to content

Commit 641d44f

Browse files
committed
Add uuid for txt2img batches to prevent overwrite
1 parent aa777fd commit 641d44f

File tree

1 file changed

+53
-38
lines changed

1 file changed

+53
-38
lines changed

scripts/stable_txt2img.py

+53-38
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import argparse, os, sys, glob
1+
import argparse, os, sys, glob, uuid
22
import torch
33
import numpy as np
44
from omegaconf import OmegaConf
@@ -50,23 +50,23 @@ def main():
5050
type=str,
5151
nargs="?",
5252
default="a painting of a virus monster playing guitar",
53-
help="the prompt to render"
53+
help="the prompt to render",
5454
)
5555
parser.add_argument(
5656
"--outdir",
5757
type=str,
5858
nargs="?",
5959
help="dir to write results to",
60-
default="outputs/txt2img-samples"
60+
default="outputs/txt2img-samples",
6161
)
6262
parser.add_argument(
6363
"--skip_grid",
64-
action='store_true',
64+
action="store_true",
6565
help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
6666
)
6767
parser.add_argument(
6868
"--skip_save",
69-
action='store_true',
69+
action="store_true",
7070
help="do not save individual samples. For speed measurements.",
7171
)
7272
parser.add_argument(
@@ -77,17 +77,17 @@ def main():
7777
)
7878
parser.add_argument(
7979
"--plms",
80-
action='store_true',
80+
action="store_true",
8181
help="use plms sampling",
8282
)
8383
parser.add_argument(
8484
"--laion400m",
85-
action='store_true',
85+
action="store_true",
8686
help="uses the LAION400M model",
8787
)
8888
parser.add_argument(
8989
"--fixed_code",
90-
action='store_true',
90+
action="store_true",
9191
help="if enabled, uses the same starting code across samples ",
9292
)
9393
parser.add_argument(
@@ -160,7 +160,7 @@ def main():
160160
type=str,
161161
default="models/ldm/stable-diffusion-v1/model.ckpt",
162162
help="path to checkpoint of model",
163-
)
163+
)
164164
parser.add_argument(
165165
"--seed",
166166
type=int,
@@ -172,14 +172,14 @@ def main():
172172
type=str,
173173
help="evaluate at this precision",
174174
choices=["full", "autocast"],
175-
default="autocast"
175+
default="autocast",
176176
)
177177

178-
179178
parser.add_argument(
180-
"--embedding_path",
181-
type=str,
182-
help="Path to a pre-trained embedding manager checkpoint")
179+
"--embedding_path",
180+
type=str,
181+
help="Path to a pre-trained embedding manager checkpoint",
182+
)
183183

184184
opt = parser.parse_args()
185185

@@ -193,7 +193,7 @@ def main():
193193

194194
config = OmegaConf.load(f"{opt.config}")
195195
model = load_model_from_config(config, f"{opt.ckpt}")
196-
#model.embedding_manager.load(opt.embedding_path)
196+
# model.embedding_manager.load(opt.embedding_path)
197197

198198
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
199199
model = model.to(device)
@@ -226,9 +226,11 @@ def main():
226226

227227
start_code = None
228228
if opt.fixed_code:
229-
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)
229+
start_code = torch.randn(
230+
[opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device
231+
)
230232

231-
precision_scope = autocast if opt.precision=="autocast" else nullcontext
233+
precision_scope = autocast if opt.precision == "autocast" else nullcontext
232234
with torch.no_grad():
233235
with precision_scope("cuda"):
234236
with model.ema_scope():
@@ -243,24 +245,31 @@ def main():
243245
prompts = list(prompts)
244246
c = model.get_learned_conditioning(prompts)
245247
shape = [opt.C, opt.H // opt.f, opt.W // opt.f]
246-
samples_ddim, _ = sampler.sample(S=opt.ddim_steps,
247-
conditioning=c,
248-
batch_size=opt.n_samples,
249-
shape=shape,
250-
verbose=False,
251-
unconditional_guidance_scale=opt.scale,
252-
unconditional_conditioning=uc,
253-
eta=opt.ddim_eta,
254-
x_T=start_code)
248+
samples_ddim, _ = sampler.sample(
249+
S=opt.ddim_steps,
250+
conditioning=c,
251+
batch_size=opt.n_samples,
252+
shape=shape,
253+
verbose=False,
254+
unconditional_guidance_scale=opt.scale,
255+
unconditional_conditioning=uc,
256+
eta=opt.ddim_eta,
257+
x_T=start_code,
258+
)
255259

256260
x_samples_ddim = model.decode_first_stage(samples_ddim)
257-
x_samples_ddim = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
261+
x_samples_ddim = torch.clamp(
262+
(x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0
263+
)
258264

259265
if not opt.skip_save:
260266
for x_sample in x_samples_ddim:
261-
x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
267+
x_sample = 255.0 * rearrange(
268+
x_sample.cpu().numpy(), "c h w -> h w c"
269+
)
262270
Image.fromarray(x_sample.astype(np.uint8)).save(
263-
os.path.join(sample_path, f"{base_count:05}.jpg"))
271+
os.path.join(sample_path, f"{base_count:05}.jpg")
272+
)
264273
base_count += 1
265274

266275
if not opt.skip_grid:
@@ -269,23 +278,29 @@ def main():
269278
if not opt.skip_grid:
270279
# additionally, save as grid
271280
grid = torch.stack(all_samples, 0)
272-
grid = rearrange(grid, 'n b c h w -> (n b) c h w')
273-
281+
grid = rearrange(grid, "n b c h w -> (n b) c h w")
282+
283+
batch_uuid = uuid.uuid4()
274284
for i in range(grid.size(0)):
275-
save_image(grid[i, :, :, :], os.path.join(outpath,opt.prompt[:30]+'_{}.png'.format(i)))
285+
file_name = f"{batch_uuid.hex[:10]}_{opt.prompt[:30]}_{i}.png"
286+
save_image(grid[i, :, :, :], os.path.join(outpath, file_name))
276287
grid = make_grid(grid, nrow=n_rows)
277288

278289
# to image
279-
grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
280-
Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'{prompt.replace(" ", "-")[:30]}-{grid_count:04}.jpg'))
290+
grid = 255.0 * rearrange(grid, "c h w -> h w c").cpu().numpy()
291+
Image.fromarray(grid.astype(np.uint8)).save(
292+
os.path.join(
293+
outpath,
294+
f'{batch_uuid.hex[:10]}-{prompt.replace(" ", "-")[:30]}-{grid_count:04}.jpg',
295+
)
296+
)
281297
grid_count += 1
282-
283-
284298

285299
toc = time.time()
286300

287-
print(f"Your samples are ready and waiting for you here: \n{outpath} \n"
288-
f" \nEnjoy.")
301+
print(
302+
f"Your samples are ready and waiting for you here: \n{outpath} \n" f" \nEnjoy."
303+
)
289304

290305

291306
if __name__ == "__main__":

0 commit comments

Comments
 (0)