InvokeAI 2.2.4.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. backend/__init__.py +0 -0
  2. backend/invoke_ai_web_server.py +1724 -0
  3. backend/modules/__init__.py +0 -0
  4. backend/modules/create_cmd_parser.py +55 -0
  5. backend/modules/get_canvas_generation_mode.py +117 -0
  6. backend/modules/parameters.py +71 -0
  7. backend/modules/parse_seed_weights.py +47 -0
  8. configs/INITIAL_MODELS.yaml +80 -0
  9. configs/models.yaml.example +29 -0
  10. configs/sd-concepts.txt +803 -0
  11. configs/stable-diffusion/v1-finetune.yaml +110 -0
  12. configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  13. configs/stable-diffusion/v1-inference.yaml +79 -0
  14. configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  15. configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  16. docs/assets/invoke-web-server-1.png +0 -0
  17. docs/assets/invoke_ai_banner.png +0 -0
  18. invokeai-2.2.4.5.data/data/assets/caution.png +0 -0
  19. invokeai-2.2.4.5.data/data/configs/INITIAL_MODELS.yaml +80 -0
  20. invokeai-2.2.4.5.data/data/configs/models.yaml.example +29 -0
  21. invokeai-2.2.4.5.data/data/configs/sd-concepts.txt +803 -0
  22. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune.yaml +110 -0
  23. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-finetune_style.yaml +103 -0
  24. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inference.yaml +79 -0
  25. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-inpainting-inference.yaml +79 -0
  26. invokeai-2.2.4.5.data/data/configs/stable-diffusion/v1-m1-finetune.yaml +110 -0
  27. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter-Bold.790c108b.ttf +0 -0
  28. invokeai-2.2.4.5.data/data/frontend/dist/assets/Inter.b9a8e5e2.ttf +0 -0
  29. invokeai-2.2.4.5.data/data/frontend/dist/assets/favicon.0d253ced.ico +0 -0
  30. invokeai-2.2.4.5.data/data/frontend/dist/assets/index-legacy-b741077f.js +48 -0
  31. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.0dadf5d0.css +1 -0
  32. invokeai-2.2.4.5.data/data/frontend/dist/assets/index.21ff81eb.js +625 -0
  33. invokeai-2.2.4.5.data/data/frontend/dist/assets/logo.13003d72.png +0 -0
  34. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills-legacy-dde3a68a.js +4 -0
  35. invokeai-2.2.4.5.data/data/frontend/dist/assets/polyfills.1ff60148.js +1 -0
  36. invokeai-2.2.4.5.data/data/frontend/dist/index.html +23 -0
  37. invokeai-2.2.4.5.data/data/scripts/configure_invokeai.py +797 -0
  38. invokeai-2.2.4.5.data/data/scripts/create_root.py +43 -0
  39. invokeai-2.2.4.5.data/data/scripts/dream.py +10 -0
  40. invokeai-2.2.4.5.data/data/scripts/images2prompt.py +30 -0
  41. invokeai-2.2.4.5.data/data/scripts/invoke.py +5 -0
  42. invokeai-2.2.4.5.data/data/scripts/legacy_api.py +681 -0
  43. invokeai-2.2.4.5.data/data/scripts/load_models.py +12 -0
  44. invokeai-2.2.4.5.data/data/scripts/merge_embeddings.py +124 -0
  45. invokeai-2.2.4.5.data/data/scripts/preload_models.py +12 -0
  46. invokeai-2.2.4.5.data/data/scripts/sd-metadata.py +22 -0
  47. invokeai-2.2.4.5.dist-info/LICENSE +21 -0
  48. invokeai-2.2.4.5.dist-info/LICENSE-ModelWeights.txt +294 -0
  49. invokeai-2.2.4.5.dist-info/METADATA +288 -0
  50. invokeai-2.2.4.5.dist-info/RECORD +169 -0
  51. invokeai-2.2.4.5.dist-info/WHEEL +5 -0
  52. invokeai-2.2.4.5.dist-info/entry_points.txt +4 -0
  53. invokeai-2.2.4.5.dist-info/top_level.txt +6 -0
  54. invokeai-2.2.4.5.dist-info/zip-safe +1 -0
  55. ldm/__init__.py +0 -0
  56. ldm/data/__init__.py +0 -0
  57. ldm/data/base.py +31 -0
  58. ldm/data/imagenet.py +466 -0
  59. ldm/data/lsun.py +126 -0
  60. ldm/data/personalized.py +202 -0
  61. ldm/data/personalized_style.py +169 -0
  62. ldm/generate.py +1159 -0
  63. ldm/invoke/CLI.py +960 -0
  64. ldm/invoke/__init__.py +3 -0
  65. ldm/invoke/args.py +1257 -0
  66. ldm/invoke/concepts_lib.py +169 -0
  67. ldm/invoke/conditioning.py +289 -0
  68. ldm/invoke/devices.py +27 -0
  69. ldm/invoke/generator/__init__.py +4 -0
  70. ldm/invoke/generator/base.py +335 -0
  71. ldm/invoke/generator/embiggen.py +501 -0
  72. ldm/invoke/generator/img2img.py +97 -0
  73. ldm/invoke/generator/inpaint.py +358 -0
  74. ldm/invoke/generator/omnibus.py +175 -0
  75. ldm/invoke/generator/txt2img.py +88 -0
  76. ldm/invoke/generator/txt2img2img.py +182 -0
  77. ldm/invoke/globals.py +31 -0
  78. ldm/invoke/image_util.py +70 -0
  79. ldm/invoke/log.py +66 -0
  80. ldm/invoke/model_cache.py +449 -0
  81. ldm/invoke/patchmatch.py +44 -0
  82. ldm/invoke/pngwriter.py +113 -0
  83. ldm/invoke/prompt_parser.py +655 -0
  84. ldm/invoke/readline.py +442 -0
  85. ldm/invoke/restoration/__init__.py +4 -0
  86. ldm/invoke/restoration/base.py +38 -0
  87. ldm/invoke/restoration/codeformer.py +103 -0
  88. ldm/invoke/restoration/codeformer_arch.py +276 -0
  89. ldm/invoke/restoration/gfpgan.py +84 -0
  90. ldm/invoke/restoration/outcrop.py +108 -0
  91. ldm/invoke/restoration/outpaint.py +92 -0
  92. ldm/invoke/restoration/realesrgan.py +90 -0
  93. ldm/invoke/restoration/vqgan_arch.py +435 -0
  94. ldm/invoke/seamless.py +30 -0
  95. ldm/invoke/server.py +282 -0
  96. ldm/invoke/server_legacy.py +246 -0
  97. ldm/invoke/txt2mask.py +136 -0
  98. ldm/lr_scheduler.py +143 -0
  99. ldm/models/__init__.py +0 -0
  100. ldm/models/autoencoder.py +596 -0
  101. ldm/models/diffusion/__init__.py +0 -0
  102. ldm/models/diffusion/classifier.py +355 -0
  103. ldm/models/diffusion/cross_attention_control.py +443 -0
  104. ldm/models/diffusion/cross_attention_map_saving.py +95 -0
  105. ldm/models/diffusion/ddim.py +111 -0
  106. ldm/models/diffusion/ddpm.py +2263 -0
  107. ldm/models/diffusion/ksampler.py +312 -0
  108. ldm/models/diffusion/plms.py +146 -0
  109. ldm/models/diffusion/sampler.py +450 -0
  110. ldm/models/diffusion/shared_invokeai_diffusion.py +244 -0
  111. ldm/modules/__init__.py +0 -0
  112. ldm/modules/attention.py +274 -0
  113. ldm/modules/diffusionmodules/__init__.py +0 -0
  114. ldm/modules/diffusionmodules/model.py +894 -0
  115. ldm/modules/diffusionmodules/openaimodel.py +1036 -0
  116. ldm/modules/diffusionmodules/util.py +314 -0
  117. ldm/modules/distributions/__init__.py +0 -0
  118. ldm/modules/distributions/distributions.py +104 -0
  119. ldm/modules/ema.py +88 -0
  120. ldm/modules/embedding_manager.py +413 -0
  121. ldm/modules/encoders/__init__.py +0 -0
  122. ldm/modules/encoders/modules.py +772 -0
  123. ldm/modules/image_degradation/__init__.py +6 -0
  124. ldm/modules/image_degradation/bsrgan.py +846 -0
  125. ldm/modules/image_degradation/bsrgan_light.py +751 -0
  126. ldm/modules/image_degradation/utils_image.py +1024 -0
  127. ldm/modules/losses/__init__.py +1 -0
  128. ldm/modules/losses/contperceptual.py +175 -0
  129. ldm/modules/losses/vqperceptual.py +240 -0
  130. ldm/modules/x_transformer.py +752 -0
  131. ldm/simplet2i.py +13 -0
  132. ldm/util.py +264 -0
  133. scripts/configure_invokeai.py +797 -0
  134. scripts/create_root.py +43 -0
  135. scripts/dream.py +10 -0
  136. scripts/images2prompt.py +30 -0
  137. scripts/invoke.py +5 -0
  138. scripts/legacy_api.py +681 -0
  139. scripts/load_models.py +12 -0
  140. scripts/merge_embeddings.py +124 -0
  141. scripts/orig_scripts/img2img.py +296 -0
  142. scripts/orig_scripts/inpaint.py +98 -0
  143. scripts/orig_scripts/knn2img.py +397 -0
  144. scripts/orig_scripts/sample_diffusion.py +313 -0
  145. scripts/orig_scripts/train_searcher.py +147 -0
  146. scripts/orig_scripts/txt2img.py +324 -0
  147. scripts/preload_models.py +12 -0
  148. scripts/sd-metadata.py +22 -0
  149. vendored/clip/clip/__init__.py +1 -0
  150. vendored/clip/clip/bpe_simple_vocab_16e6.txt.gz +0 -0
  151. vendored/clip/clip/clip.py +237 -0
  152. vendored/clip/clip/model.py +436 -0
  153. vendored/clip/clip/simple_tokenizer.py +132 -0
  154. vendored/clip/hubconf.py +42 -0
  155. vendored/clip/setup.py +21 -0
  156. vendored/clip/tests/test_consistency.py +25 -0
  157. vendored/clipseg/datasets/coco_wrapper.py +99 -0
  158. vendored/clipseg/datasets/pascal_zeroshot.py +60 -0
  159. vendored/clipseg/datasets/pfe_dataset.py +129 -0
  160. vendored/clipseg/datasets/phrasecut.py +380 -0
  161. vendored/clipseg/datasets/utils.py +68 -0
  162. vendored/clipseg/evaluation_utils.py +292 -0
  163. vendored/clipseg/general_utils.py +272 -0
  164. vendored/clipseg/metrics.py +271 -0
  165. vendored/clipseg/models/clipseg.py +538 -0
  166. vendored/clipseg/models/vitseg.py +286 -0
  167. vendored/clipseg/score.py +453 -0
  168. vendored/clipseg/setup.py +30 -0
  169. vendored/clipseg/training.py +266 -0
@@ -0,0 +1,124 @@
1
+ from ldm.modules.encoders.modules import FrozenCLIPEmbedder, BERTEmbedder
2
+ from ldm.modules.embedding_manager import EmbeddingManager
3
+ from ldm.invoke.globals import Globals
4
+
5
+ import argparse, os
6
+ from functools import partial
7
+
8
+ import torch
9
+
10
+ def get_placeholder_loop(placeholder_string, embedder, use_bert):
11
+
12
+ new_placeholder = None
13
+
14
+ while True:
15
+ if new_placeholder is None:
16
+ new_placeholder = input(f"Placeholder string {placeholder_string} was already used. Please enter a replacement string: ")
17
+ else:
18
+ new_placeholder = input(f"Placeholder string '{new_placeholder}' maps to more than a single token. Please enter another string: ")
19
+
20
+ token = get_bert_token_for_string(embedder.tknz_fn, new_placeholder) if use_bert else get_clip_token_for_string(embedder.tokenizer, new_placeholder)
21
+
22
+ if token is not None:
23
+ return new_placeholder, token
24
+
25
+ def get_clip_token_for_string(tokenizer, string):
26
+ batch_encoding = tokenizer(
27
+ string,
28
+ truncation=True,
29
+ max_length=77,
30
+ return_length=True,
31
+ return_overflowing_tokens=False,
32
+ padding="max_length",
33
+ return_tensors="pt"
34
+ )
35
+
36
+ tokens = batch_encoding["input_ids"]
37
+
38
+ if torch.count_nonzero(tokens - 49407) == 2:
39
+ return tokens[0, 1]
40
+
41
+ return None
42
+
43
+ def get_bert_token_for_string(tokenizer, string):
44
+ token = tokenizer(string)
45
+ if torch.count_nonzero(token) == 3:
46
+ return token[0, 1]
47
+
48
+ return None
49
+
50
+
51
+ if __name__ == "__main__":
52
+
53
+ parser = argparse.ArgumentParser()
54
+
55
+ parser.add_argument(
56
+ "--root_dir",
57
+ type=str,
58
+ default='.',
59
+ help="Path to the InvokeAI install directory containing 'models', 'outputs' and 'configs'."
60
+ )
61
+
62
+ parser.add_argument(
63
+ "--manager_ckpts",
64
+ type=str,
65
+ nargs="+",
66
+ required=True,
67
+ help="Paths to a set of embedding managers to be merged."
68
+ )
69
+
70
+ parser.add_argument(
71
+ "--output_path",
72
+ type=str,
73
+ required=True,
74
+ help="Output path for the merged manager",
75
+ )
76
+
77
+ parser.add_argument(
78
+ "-sd", "--use_bert",
79
+ action="store_true",
80
+ help="Flag to denote that we are not merging stable diffusion embeddings"
81
+ )
82
+
83
+ args = parser.parse_args()
84
+ Globals.root=args.root_dir
85
+
86
+ if args.use_bert:
87
+ embedder = BERTEmbedder(n_embed=1280, n_layer=32).cuda()
88
+ else:
89
+ embedder = FrozenCLIPEmbedder().cuda()
90
+
91
+ EmbeddingManager = partial(EmbeddingManager, embedder, ["*"])
92
+
93
+ string_to_token_dict = {}
94
+ string_to_param_dict = torch.nn.ParameterDict()
95
+
96
+ placeholder_to_src = {}
97
+
98
+ for manager_ckpt in args.manager_ckpts:
99
+ print(f"Parsing {manager_ckpt}...")
100
+
101
+ manager = EmbeddingManager()
102
+ manager.load(manager_ckpt)
103
+
104
+ for placeholder_string in manager.string_to_token_dict:
105
+ if not placeholder_string in string_to_token_dict:
106
+ string_to_token_dict[placeholder_string] = manager.string_to_token_dict[placeholder_string]
107
+ string_to_param_dict[placeholder_string] = manager.string_to_param_dict[placeholder_string]
108
+
109
+ placeholder_to_src[placeholder_string] = manager_ckpt
110
+ else:
111
+ new_placeholder, new_token = get_placeholder_loop(placeholder_string, embedder, use_bert=args.use_bert)
112
+ string_to_token_dict[new_placeholder] = new_token
113
+ string_to_param_dict[new_placeholder] = manager.string_to_param_dict[placeholder_string]
114
+
115
+ placeholder_to_src[new_placeholder] = manager_ckpt
116
+
117
+ print("Saving combined manager...")
118
+ merged_manager = EmbeddingManager()
119
+ merged_manager.string_to_param_dict = string_to_param_dict
120
+ merged_manager.string_to_token_dict = string_to_token_dict
121
+ merged_manager.save(args.output_path)
122
+
123
+ print("Managers merged. Final list of placeholders: ")
124
+ print(placeholder_to_src)
@@ -0,0 +1,296 @@
1
+ """make variations of input image"""
2
+
3
+ import argparse, os, sys, glob
4
+ import PIL
5
+ import torch
6
+ import numpy as np
7
+ from omegaconf import OmegaConf
8
+ from PIL import Image
9
+ from tqdm import tqdm, trange
10
+ from itertools import islice
11
+ from einops import rearrange, repeat
12
+ from torchvision.utils import make_grid
13
+ from torch import autocast
14
+ from contextlib import nullcontext
15
+ import time
16
+ from pytorch_lightning import seed_everything
17
+
18
+ from ldm.util import instantiate_from_config
19
+ from ldm.models.diffusion.ddim import DDIMSampler
20
+ from ldm.models.diffusion.plms import PLMSSampler
21
+ from ldm.invoke.devices import choose_torch_device
22
+
23
+
24
+ def chunk(it, size):
25
+ it = iter(it)
26
+ return iter(lambda: tuple(islice(it, size)), ())
27
+
28
+
29
+ def load_model_from_config(config, ckpt, verbose=False):
30
+ print(f"Loading model from {ckpt}")
31
+ pl_sd = torch.load(ckpt, map_location="cpu")
32
+ if "global_step" in pl_sd:
33
+ print(f"Global Step: {pl_sd['global_step']}")
34
+ sd = pl_sd["state_dict"]
35
+ model = instantiate_from_config(config.model)
36
+ m, u = model.load_state_dict(sd, strict=False)
37
+ if len(m) > 0 and verbose:
38
+ print("missing keys:")
39
+ print(m)
40
+ if len(u) > 0 and verbose:
41
+ print("unexpected keys:")
42
+ print(u)
43
+
44
+ model.to(choose_torch_device())
45
+ model.eval()
46
+ return model
47
+
48
+
49
+ def load_img(path):
50
+ image = Image.open(path).convert("RGB")
51
+ w, h = image.size
52
+ print(f"loaded input image of size ({w}, {h}) from {path}")
53
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
54
+ image = image.resize((w, h), resample=PIL.Image.LANCZOS)
55
+ image = np.array(image).astype(np.float32) / 255.0
56
+ image = image[None].transpose(0, 3, 1, 2)
57
+ image = torch.from_numpy(image)
58
+ return 2.*image - 1.
59
+
60
+
61
+ def main():
62
+ parser = argparse.ArgumentParser()
63
+
64
+ parser.add_argument(
65
+ "--prompt",
66
+ type=str,
67
+ nargs="?",
68
+ default="a painting of a virus monster playing guitar",
69
+ help="the prompt to render"
70
+ )
71
+
72
+ parser.add_argument(
73
+ "--init-img",
74
+ type=str,
75
+ nargs="?",
76
+ help="path to the input image"
77
+ )
78
+
79
+ parser.add_argument(
80
+ "--outdir",
81
+ type=str,
82
+ nargs="?",
83
+ help="dir to write results to",
84
+ default="outputs/img2img-samples"
85
+ )
86
+
87
+ parser.add_argument(
88
+ "--skip_grid",
89
+ action='store_true',
90
+ help="do not save a grid, only individual samples. Helpful when evaluating lots of samples",
91
+ )
92
+
93
+ parser.add_argument(
94
+ "--skip_save",
95
+ action='store_true',
96
+ help="do not save indiviual samples. For speed measurements.",
97
+ )
98
+
99
+ parser.add_argument(
100
+ "--ddim_steps",
101
+ type=int,
102
+ default=50,
103
+ help="number of ddim sampling steps",
104
+ )
105
+
106
+ parser.add_argument(
107
+ "--plms",
108
+ action='store_true',
109
+ help="use plms sampling",
110
+ )
111
+ parser.add_argument(
112
+ "--fixed_code",
113
+ action='store_true',
114
+ help="if enabled, uses the same starting code across all samples ",
115
+ )
116
+
117
+ parser.add_argument(
118
+ "--ddim_eta",
119
+ type=float,
120
+ default=0.0,
121
+ help="ddim eta (eta=0.0 corresponds to deterministic sampling",
122
+ )
123
+ parser.add_argument(
124
+ "--n_iter",
125
+ type=int,
126
+ default=1,
127
+ help="sample this often",
128
+ )
129
+ parser.add_argument(
130
+ "--C",
131
+ type=int,
132
+ default=4,
133
+ help="latent channels",
134
+ )
135
+ parser.add_argument(
136
+ "--f",
137
+ type=int,
138
+ default=8,
139
+ help="downsampling factor, most often 8 or 16",
140
+ )
141
+ parser.add_argument(
142
+ "--n_samples",
143
+ type=int,
144
+ default=2,
145
+ help="how many samples to produce for each given prompt. A.k.a batch size",
146
+ )
147
+ parser.add_argument(
148
+ "--n_rows",
149
+ type=int,
150
+ default=0,
151
+ help="rows in the grid (default: n_samples)",
152
+ )
153
+ parser.add_argument(
154
+ "--scale",
155
+ type=float,
156
+ default=5.0,
157
+ help="unconditional guidance scale: eps = eps(x, empty) + scale * (eps(x, cond) - eps(x, empty))",
158
+ )
159
+
160
+ parser.add_argument(
161
+ "--strength",
162
+ type=float,
163
+ default=0.75,
164
+ help="strength for noising/unnoising. 1.0 corresponds to full destruction of information in init image",
165
+ )
166
+ parser.add_argument(
167
+ "--from-file",
168
+ type=str,
169
+ help="if specified, load prompts from this file",
170
+ )
171
+ parser.add_argument(
172
+ "--config",
173
+ type=str,
174
+ default="configs/stable-diffusion/v1-inference.yaml",
175
+ help="path to config which constructs model",
176
+ )
177
+ parser.add_argument(
178
+ "--ckpt",
179
+ type=str,
180
+ default="models/ldm/stable-diffusion-v1/model.ckpt",
181
+ help="path to checkpoint of model",
182
+ )
183
+ parser.add_argument(
184
+ "--seed",
185
+ type=int,
186
+ default=42,
187
+ help="the seed (for reproducible sampling)",
188
+ )
189
+ parser.add_argument(
190
+ "--precision",
191
+ type=str,
192
+ help="evaluate at this precision",
193
+ choices=["full", "autocast"],
194
+ default="autocast"
195
+ )
196
+
197
+ opt = parser.parse_args()
198
+ seed_everything(opt.seed)
199
+
200
+ config = OmegaConf.load(f"{opt.config}")
201
+ model = load_model_from_config(config, f"{opt.ckpt}")
202
+
203
+ device = torch.device(choose_torch_device())
204
+ model = model.to(device)
205
+
206
+ if opt.plms:
207
+ raise NotImplementedError("PLMS sampler not (yet) supported")
208
+ sampler = PLMSSampler(model)
209
+ else:
210
+ sampler = DDIMSampler(model)
211
+
212
+ os.makedirs(opt.outdir, exist_ok=True)
213
+ outpath = opt.outdir
214
+
215
+ batch_size = opt.n_samples
216
+ n_rows = opt.n_rows if opt.n_rows > 0 else batch_size
217
+ if not opt.from_file:
218
+ prompt = opt.prompt
219
+ assert prompt is not None
220
+ data = [batch_size * [prompt]]
221
+
222
+ else:
223
+ print(f"reading prompts from {opt.from_file}")
224
+ with open(opt.from_file, "r") as f:
225
+ data = f.read().splitlines()
226
+ data = list(chunk(data, batch_size))
227
+
228
+ sample_path = os.path.join(outpath, "samples")
229
+ os.makedirs(sample_path, exist_ok=True)
230
+ base_count = len(os.listdir(sample_path))
231
+ grid_count = len(os.listdir(outpath)) - 1
232
+
233
+ assert os.path.isfile(opt.init_img)
234
+ init_image = load_img(opt.init_img).to(device)
235
+ init_image = repeat(init_image, '1 ... -> b ...', b=batch_size)
236
+ init_latent = model.get_first_stage_encoding(model.encode_first_stage(init_image)) # move to latent space
237
+
238
+ sampler.make_schedule(ddim_num_steps=opt.ddim_steps, ddim_eta=opt.ddim_eta, verbose=False)
239
+
240
+ assert 0. <= opt.strength <= 1., 'can only work with strength in [0.0, 1.0]'
241
+ t_enc = int(opt.strength * opt.ddim_steps)
242
+ print(f"target t_enc is {t_enc} steps")
243
+
244
+ precision_scope = autocast if opt.precision == "autocast" else nullcontext
245
+ if device.type in ['mps', 'cpu']:
246
+ precision_scope = nullcontext # have to use f32 on mps
247
+ with torch.no_grad():
248
+ with precision_scope(device.type):
249
+ with model.ema_scope():
250
+ tic = time.time()
251
+ all_samples = list()
252
+ for n in trange(opt.n_iter, desc="Sampling"):
253
+ for prompts in tqdm(data, desc="data"):
254
+ uc = None
255
+ if opt.scale != 1.0:
256
+ uc = model.get_learned_conditioning(batch_size * [""])
257
+ if isinstance(prompts, tuple):
258
+ prompts = list(prompts)
259
+ c = model.get_learned_conditioning(prompts)
260
+
261
+ # encode (scaled latent)
262
+ z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device))
263
+ # decode it
264
+ samples = sampler.decode(z_enc, c, t_enc, unconditional_guidance_scale=opt.scale,
265
+ unconditional_conditioning=uc,)
266
+
267
+ x_samples = model.decode_first_stage(samples)
268
+ x_samples = torch.clamp((x_samples + 1.0) / 2.0, min=0.0, max=1.0)
269
+
270
+ if not opt.skip_save:
271
+ for x_sample in x_samples:
272
+ x_sample = 255. * rearrange(x_sample.cpu().numpy(), 'c h w -> h w c')
273
+ Image.fromarray(x_sample.astype(np.uint8)).save(
274
+ os.path.join(sample_path, f"{base_count:05}.png"))
275
+ base_count += 1
276
+ all_samples.append(x_samples)
277
+
278
+ if not opt.skip_grid:
279
+ # additionally, save as grid
280
+ grid = torch.stack(all_samples, 0)
281
+ grid = rearrange(grid, 'n b c h w -> (n b) c h w')
282
+ grid = make_grid(grid, nrow=n_rows)
283
+
284
+ # to image
285
+ grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
286
+ Image.fromarray(grid.astype(np.uint8)).save(os.path.join(outpath, f'grid-{grid_count:04}.png'))
287
+ grid_count += 1
288
+
289
+ toc = time.time()
290
+
291
+ print(f"Your samples are ready and waiting for you here: \n{outpath} \n"
292
+ f" \nEnjoy.")
293
+
294
+
295
+ if __name__ == "__main__":
296
+ main()
@@ -0,0 +1,98 @@
1
+ import argparse, os, sys, glob
2
+ from omegaconf import OmegaConf
3
+ from PIL import Image
4
+ from tqdm import tqdm
5
+ import numpy as np
6
+ import torch
7
+ from main import instantiate_from_config
8
+ from ldm.models.diffusion.ddim import DDIMSampler
9
+ from ldm.invoke.devices import choose_torch_device
10
+
11
+ def make_batch(image, mask, device):
12
+ image = np.array(Image.open(image).convert("RGB"))
13
+ image = image.astype(np.float32)/255.0
14
+ image = image[None].transpose(0,3,1,2)
15
+ image = torch.from_numpy(image)
16
+
17
+ mask = np.array(Image.open(mask).convert("L"))
18
+ mask = mask.astype(np.float32)/255.0
19
+ mask = mask[None,None]
20
+ mask[mask < 0.5] = 0
21
+ mask[mask >= 0.5] = 1
22
+ mask = torch.from_numpy(mask)
23
+
24
+ masked_image = (1-mask)*image
25
+
26
+ batch = {"image": image, "mask": mask, "masked_image": masked_image}
27
+ for k in batch:
28
+ batch[k] = batch[k].to(device=device)
29
+ batch[k] = batch[k]*2.0-1.0
30
+ return batch
31
+
32
+
33
+ if __name__ == "__main__":
34
+ parser = argparse.ArgumentParser()
35
+ parser.add_argument(
36
+ "--indir",
37
+ type=str,
38
+ nargs="?",
39
+ help="dir containing image-mask pairs (`example.png` and `example_mask.png`)",
40
+ )
41
+ parser.add_argument(
42
+ "--outdir",
43
+ type=str,
44
+ nargs="?",
45
+ help="dir to write results to",
46
+ )
47
+ parser.add_argument(
48
+ "--steps",
49
+ type=int,
50
+ default=50,
51
+ help="number of ddim sampling steps",
52
+ )
53
+ opt = parser.parse_args()
54
+
55
+ masks = sorted(glob.glob(os.path.join(opt.indir, "*_mask.png")))
56
+ images = [x.replace("_mask.png", ".png") for x in masks]
57
+ print(f"Found {len(masks)} inputs.")
58
+
59
+ config = OmegaConf.load("models/ldm/inpainting_big/config.yaml")
60
+ model = instantiate_from_config(config.model)
61
+ model.load_state_dict(torch.load("models/ldm/inpainting_big/last.ckpt")["state_dict"],
62
+ strict=False)
63
+
64
+ device = choose_torch_device()
65
+ model = model.to(device)
66
+ sampler = DDIMSampler(model)
67
+
68
+ os.makedirs(opt.outdir, exist_ok=True)
69
+ with torch.no_grad():
70
+ with model.ema_scope():
71
+ for image, mask in tqdm(zip(images, masks)):
72
+ outpath = os.path.join(opt.outdir, os.path.split(image)[1])
73
+ batch = make_batch(image, mask, device=device)
74
+
75
+ # encode masked image and concat downsampled mask
76
+ c = model.cond_stage_model.encode(batch["masked_image"])
77
+ cc = torch.nn.functional.interpolate(batch["mask"],
78
+ size=c.shape[-2:])
79
+ c = torch.cat((c, cc), dim=1)
80
+
81
+ shape = (c.shape[1]-1,)+c.shape[2:]
82
+ samples_ddim, _ = sampler.sample(S=opt.steps,
83
+ conditioning=c,
84
+ batch_size=c.shape[0],
85
+ shape=shape,
86
+ verbose=False)
87
+ x_samples_ddim = model.decode_first_stage(samples_ddim)
88
+
89
+ image = torch.clamp((batch["image"]+1.0)/2.0,
90
+ min=0.0, max=1.0)
91
+ mask = torch.clamp((batch["mask"]+1.0)/2.0,
92
+ min=0.0, max=1.0)
93
+ predicted_image = torch.clamp((x_samples_ddim+1.0)/2.0,
94
+ min=0.0, max=1.0)
95
+
96
+ inpainted = (1-mask)*image+mask*predicted_image
97
+ inpainted = inpainted.cpu().numpy().transpose(0,2,3,1)[0]*255
98
+ Image.fromarray(inpainted.astype(np.uint8)).save(outpath)