matrixglitch commited on
Commit
182b634
1 Parent(s): a444299

Upload seamlessmaker512_streamlit.py

Browse files
Files changed (1) hide show
  1. seamlessmaker512_streamlit.py +347 -0
seamlessmaker512_streamlit.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import cv2
3
+ import time
4
+ import os
5
+ import shutil
6
+ from pathlib import Path
7
+ import gradio as gr
8
+ from PIL import Image
9
+ import numpy as np
10
+ from io import BytesIO
11
+ import os
12
+
13
+
14
+ source_img = gr.Image(source="upload", type="filepath", label="init_img | 512*512 px")
15
+ gallery = gr.Gallery(label="Generated images", show_label=False, elem_id="gallery").style(grid=[2], height="auto")
16
+
17
+ doc_path = os.path.expanduser('~\Documents')
18
+ visions_path = os.path.expanduser('~\Documents\\visions of chaos')
19
+
20
+ import subprocess
21
+ import random
22
+ parser = argparse.ArgumentParser()
23
+ #inpaint
24
+ parser.add_argument("--mask", type=str, help="thickness of the mask for seamless inpainting",choices=["thinnest", "thin", "medium", "thick", "thickest"],default="medium")
25
+ parser.add_argument("--input",type=str,nargs="?",default="source_img",help="input image",)
26
+ parser.add_argument("--indir2",type=str,nargs="?",default="tmp360/tiled_image/",help="dir containing image-mask pairs (`example.png` and `example_mask.png`)",)
27
+ parser.add_argument("--outdir2",type=str,nargs="?",default="tmp360/original_image2/",help="temp dir to write results to",)
28
+ parser.add_argument("--steps2",type=int,default=50,help="number of ddim sampling steps",)
29
+ parser.add_argument("--indir3",type=str,nargs="?",default="tmp360/tiled2_image2/",help="dir containing image-mask pairs (`example.png` and `example_mask.png`)",)
30
+ parser.add_argument("--outdir3",type=str,nargs="?",default="outputs/txt2seamlessimg-samples/",help="dir to write results to",)
31
+ parser.add_argument("--steps3",type=int,default=50,help="number of ddim sampling steps",)
32
+
33
+
34
+
35
+
36
+
37
+
38
+ ##first pass of inpainting
39
+ import argparse, os, sys, glob
40
+ from omegaconf import OmegaConf
41
+ from PIL import Image
42
+ from tqdm import tqdm
43
+ import numpy as np
44
+ import torch
45
+ from main import instantiate_from_config
46
+ from ldm.models.diffusion.ddim import DDIMSampler
47
+
48
+
49
+ def make_batch(image, mask, device):
50
+ image = np.array(Image.open(image).convert("RGB"))
51
+ image = image.astype(np.float32)/255.0
52
+ image = image[None].transpose(0,3,1,2)
53
+ image = torch.from_numpy(image)
54
+
55
+ mask = np.array(Image.open(mask).convert("L"))
56
+ mask = mask.astype(np.float32)/255.0
57
+ mask = mask[None,None]
58
+ mask[mask < 0.5] = 0
59
+ mask[mask >= 0.5] = 1
60
+ mask = torch.from_numpy(mask)
61
+
62
+ masked_image = (1-mask)*image
63
+
64
+ batch = {"image": image, "mask": mask, "masked_image": masked_image}
65
+ for k in batch:
66
+ batch[k] = batch[k].to(device=device)
67
+ batch[k] = batch[k]*2.0-1.0
68
+ return batch
69
+
70
+
71
+ if __name__ == "__main__":
72
+
73
+ opt = parser.parse_args()
74
+ inputimg = opt.input
75
+ destination = 'tmp360/original_image/example1.png'
76
+ #shutil.copy(inputimg, destination)
77
+ from PIL import Image
78
+ import PIL
79
+ img = Image.open(inputimg) # image extension *.png,*.jpg
80
+ new_width = 512
81
+ new_height = 512
82
+ img = img.resize((new_width, new_height), PIL.Image.LANCZOS)
83
+ img.save('tmp360/original_image/example.png')
84
+ '''p = subprocess.Popen(['mkdir', 'tmp360'])
85
+ p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
86
+ p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
87
+ p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
88
+ p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
89
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])'''
90
+ # masks = opt.mask
91
+ # thinnest = r'seamless/thinnest/1st_mask.png'
92
+ # thin = r'seamless/thin/1st_mask.png'
93
+ # medium = r'seamless/medium/1st_mask.png'
94
+ # thick = r'seamless/thick/1st_mask.png'
95
+ # thickest = r'seamless/thickest/1st_mask.png'
96
+ #
97
+ # if masks == thinnest:
98
+ # '''p = subprocess.Popen(['mkdir', 'tmp360'])
99
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
100
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
101
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
102
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
103
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])'''
104
+ # print('temporary directories made')
105
+ # print('copying',opt.mask ,'mask to dir')
106
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/medium/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
107
+ # print('thinnest mask copied')
108
+ # elif masks == thin:
109
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
110
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
111
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
112
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
113
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
114
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
115
+ # print('temporary directories made')
116
+ # print('copying',opt.mask ,'mask to dir')
117
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thin/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
118
+ # print(opt.mask, 'mask copied')
119
+ # elif masks == medium:
120
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
121
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
122
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
123
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
124
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
125
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
126
+ # print('temporary directories made')
127
+ # print('copying',opt.mask ,'mask to dir')
128
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/medium/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
129
+ # elif masks == thick:
130
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
131
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
132
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
133
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
134
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
135
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
136
+ # print('temporary directories made')
137
+ # print('copying',opt.mask ,'mask to dir')
138
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thick/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
139
+ # elif masks == thickest:
140
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
141
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
142
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
143
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
144
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
145
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
146
+ # print('temporary directories made')
147
+ # print('copying',opt.mask ,'mask to dir')
148
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thickest/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
149
+ #
150
+ # # outpath = opt.outdir
151
+ # # sample_path = os.path.join(outpath, "samples")
152
+ # output555= "outputs/txt2img-samples/samples/example.png"
153
+
154
+ """##move opt.output to temp directory###
155
+ source = output555
156
+ destination = 'tmp360/original_image/example.png'
157
+ shutil.move(source, destination)"""
158
+
159
+ ##tile the image
160
+ #p = subprocess.Popen(['mogrify', 'convert', '-virtual-pixel', 'tile', '-filter', 'point', '-set', 'option:distort:viewport', '1024x1024', '-distort', 'SRT', '0', '-path', r'tmp360/tiled2_image', r'tmp360/original_image/example.png'])
161
+ #print('image tiled')
162
+ #from PIL import Image # import pillow library (can install with "pip install pillow")
163
+ #im = Image.open('tmp360/tiled2_image/example.png')
164
+ #im = im.crop( (1, 0, 512, 512) ) # previously, image was 826 pixels wide, cropping to 825 pixels wide
165
+ #im.save('tmp360/tiled2_image/example.png') # saves the image
166
+ # im.show() # opens the image
167
+ subprocess.call([r'crop.bat'])
168
+ print('image center cropped')
169
+ masks1 = sorted(glob.glob(os.path.join(opt.indir2, "*_mask.png")))
170
+ images1 = [x.replace("_mask.png", ".png") for x in masks1]
171
+ print(f"Found {len(masks1)} inputs.")
172
+
173
+ config = OmegaConf.load("models/ldm/inpainting_big/config.yaml")
174
+ model = instantiate_from_config(config.model)
175
+ model.load_state_dict(torch.load("C:\deepdream-test\stable\stable-diffusion-2\models\ldm\inpainting_big\last.ckpt")["state_dict"],
176
+ strict=False)
177
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
178
+ model = model.to(device)
179
+ sampler = DDIMSampler(model)
180
+ os.makedirs(opt.outdir2, exist_ok=True)
181
+ with torch.no_grad():
182
+ with model.ema_scope():
183
+ for image, mask in tqdm(zip(images1, masks1)):
184
+ outpath3 = os.path.join(opt.outdir2, os.path.split(image)[1])
185
+ batch = make_batch(image, mask, device=device)
186
+ # encode masked image and concat downsampled mask
187
+ c = model.cond_stage_model.encode(batch["masked_image"])
188
+ cc = torch.nn.functional.interpolate(batch["mask"],
189
+ size=c.shape[-2:])
190
+ c = torch.cat((c, cc), dim=1)
191
+ shape = (c.shape[1]-1,)+c.shape[2:]
192
+ samples_ddim, _ = sampler.sample(S=opt.steps2,
193
+ conditioning=c,
194
+ batch_size=c.shape[0],
195
+ shape=shape,
196
+ verbose=False)
197
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
198
+ image = torch.clamp((batch["image"]+1.0)/2.0,
199
+ min=0.0, max=1.0)
200
+ mask = torch.clamp((batch["mask"]+1.0)/2.0,
201
+ min=0.0, max=1.0)
202
+ predicted_image = torch.clamp((x_samples_ddim+1.0)/2.0,
203
+ min=0.0, max=1.0)
204
+ inpainted = (1-mask)*image+mask*predicted_image
205
+ inpainted = inpainted.cpu().numpy().transpose(0,2,3,1)[0]*255
206
+ Image.fromarray(inpainted.astype(np.uint8)).save(outpath3)
207
+
208
+
209
+ if __name__ == "__main__":
210
+
211
+ #opt = parser.parse_args()
212
+ #inputimg = outpath3
213
+ #destination = 'tmp360/original_image2/example.png'
214
+ #shutil.copy(inputimg, destination)
215
+
216
+ '''p = subprocess.Popen(['mkdir', 'tmp360'])
217
+ p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
218
+ p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
219
+ p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
220
+ p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
221
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])'''
222
+ # masks = opt.mask
223
+ # thinnest = r'seamless/thinnest/1st_mask.png'
224
+ # thin = r'seamless/thin/1st_mask.png'
225
+ # medium = r'seamless/medium/1st_mask.png'
226
+ # thick = r'seamless/thick/1st_mask.png'
227
+ # thickest = r'seamless/thickest/1st_mask.png'
228
+ #
229
+ # if masks == thinnest:
230
+ # '''p = subprocess.Popen(['mkdir', 'tmp360'])
231
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
232
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
233
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
234
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
235
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])'''
236
+ # print('temporary directories made')
237
+ # print('copying',opt.mask ,'mask to dir')
238
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/example_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
239
+ # print('thinnest mask copied')
240
+ # elif masks == thin:
241
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
242
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
243
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
244
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
245
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
246
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
247
+ # print('temporary directories made')
248
+ # print('copying',opt.mask ,'mask to dir')
249
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thin/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
250
+ # print(opt.mask, 'mask copied')
251
+ # elif masks == medium:
252
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
253
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
254
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
255
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
256
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
257
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
258
+ # print('temporary directories made')
259
+ # print('copying',opt.mask ,'mask to dir')
260
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/medium/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
261
+ # elif masks == thick:
262
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
263
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
264
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
265
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
266
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
267
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
268
+ # print('temporary directories made')
269
+ # print('copying',opt.mask ,'mask to dir')
270
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thick/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
271
+ # elif masks == thickest:
272
+ # p = subprocess.Popen(['mkdir', 'tmp360'])
273
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image'])
274
+ # p = subprocess.Popen(['mkdir', 'tmp360/original_image2'])
275
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image'])
276
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled2_image'])
277
+ # p = subprocess.Popen(['mkdir', 'tmp360/tiled_image2'])
278
+ # print('temporary directories made')
279
+ # print('copying',opt.mask ,'mask to dir')
280
+ # shutil.copy('C:/deepdream-test/stable/stable-diffusion-2/seamless/thickest/1st_mask.png', 'C:/deepdream-test/stable/stable-diffusion-2/tmp360/tiled_image/example_mask.png')
281
+
282
+ # outpath = opt.outdir
283
+ # sample_path = os.path.join(outpath, "samples")
284
+ #output555= "outputs/txt2img-samples/samples/example.png"
285
+
286
+ """##move opt.output to temp directory###
287
+ source = output555
288
+ destination = 'tmp360/original_image/example.png'
289
+ shutil.move(source, destination)"""
290
+
291
+ ##tile the image
292
+ #p = subprocess.Popen(['mogrify', 'convert', '-virtual-pixel', 'tile', '-filter', 'point', '-set', 'option:distort:viewport', '1024x1024', '-distort', 'SRT', '0', '-path', r'tmp360/tiled2_image', r'tmp360/original_image/example.png'])
293
+ #print('image tiled')
294
+ #from PIL import Image # import pillow library (can install with "pip install pillow")
295
+ #im = Image.open('tmp360/tiled2_image/example.png')
296
+ #im = im.crop( (1, 0, 512, 512) ) # previously, image was 826 pixels wide, cropping to 825 pixels wide
297
+ #im.save('tmp360/tiled2_image/example.png') # saves the image
298
+ # im.show() # opens the image
299
+ subprocess.call([r'2ndpass.bat'])
300
+ print('image center cropped')
301
+ masks = sorted(glob.glob(os.path.join(opt.indir3, "*_mask.png")))
302
+ images = [x.replace("_mask.png", ".png") for x in masks]
303
+ print(f"Found {len(masks)} inputs.")
304
+
305
+ config = OmegaConf.load("models/ldm/inpainting_big/config.yaml")
306
+ model = instantiate_from_config(config.model)
307
+ model.load_state_dict(torch.load("C:\deepdream-test\stable\stable-diffusion-2\models\ldm\inpainting_big\last.ckpt")["state_dict"],
308
+ strict=False)
309
+ device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
310
+ model = model.to(device)
311
+ sampler = DDIMSampler(model)
312
+ outpath4 = opt.outdir3
313
+ base_count = len(os.listdir(outpath4))
314
+ os.makedirs(opt.outdir3, exist_ok=True)
315
+ with torch.no_grad():
316
+ with model.ema_scope():
317
+ for image, mask in tqdm(zip(images, masks)):
318
+ outpath4 = os.path.join(opt.outdir3, os.path.split(opt.outdir3)[1])
319
+ batch = make_batch(image, mask, device=device)
320
+ # encode masked image and concat downsampled mask
321
+ c = model.cond_stage_model.encode(batch["masked_image"])
322
+ cc = torch.nn.functional.interpolate(batch["mask"],
323
+ size=c.shape[-2:])
324
+ c = torch.cat((c, cc), dim=1)
325
+ shape = (c.shape[1]-1,)+c.shape[2:]
326
+ samples_ddim, _ = sampler.sample(S=opt.steps2,
327
+ conditioning=c,
328
+ batch_size=c.shape[0],
329
+ shape=shape,
330
+ verbose=False)
331
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
332
+ image = torch.clamp((batch["image"]+1.0)/2.0,
333
+ min=0.0, max=1.0)
334
+ mask = torch.clamp((batch["mask"]+1.0)/2.0,
335
+ min=0.0, max=1.0)
336
+ predicted_image = torch.clamp((x_samples_ddim+1.0)/2.0,
337
+ min=0.0, max=1.0)
338
+ inpainted = (1-mask)*image+mask*predicted_image
339
+ inpainted = inpainted.cpu().numpy().transpose(0,2,3,1)[0]*255
340
+ #Image.fromarray(inpainted.astype(np.uint8)).save(outpath4)
341
+ Image.fromarray(inpainted.astype(np.uint8)).save(os.path.join(outpath4, f"{base_count:05}.png"))
342
+ base_count += 1
343
+
344
+ title="make seamless latent diffusion from Stable Diffusion repo"
345
+ description="make seamless Stable Diffusion example"
346
+
347
+ gr.Interface(fn=infer, inputs=[source_img], outputs=gallery,title=title,description=description).launch(enable_queue=True)