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
ldm/generate.py ADDED
@@ -0,0 +1,1159 @@
1
+ # Copyright (c) 2022 Lincoln D. Stein (https://github.com/lstein)
2
+ import pyparsing
3
+ # Derived from source code carrying the following copyrights
4
+ # Copyright (c) 2022 Machine Vision and Learning Group, LMU Munich
5
+ # Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
6
+
7
+ import torch
8
+ import numpy as np
9
+ import random
10
+ import os
11
+ import time
12
+ import re
13
+ import sys
14
+ import traceback
15
+ import transformers
16
+ import io
17
+ import gc
18
+ import hashlib
19
+ import cv2
20
+ import skimage
21
+
22
+ from omegaconf import OmegaConf
23
+
24
+ import ldm.invoke.conditioning
25
+ from ldm.invoke.generator.base import downsampling
26
+ from PIL import Image, ImageOps
27
+ from torch import nn
28
+ from pytorch_lightning import seed_everything, logging
29
+
30
+ from ldm.invoke.prompt_parser import PromptParser
31
+ from ldm.util import instantiate_from_config
32
+ from ldm.invoke.globals import Globals
33
+ from ldm.models.diffusion.ddim import DDIMSampler
34
+ from ldm.models.diffusion.plms import PLMSSampler
35
+ from ldm.models.diffusion.ksampler import KSampler
36
+ from ldm.invoke.pngwriter import PngWriter
37
+ from ldm.invoke.args import metadata_from_png
38
+ from ldm.invoke.image_util import InitImageResizer
39
+ from ldm.invoke.devices import choose_torch_device, choose_precision
40
+ from ldm.invoke.conditioning import get_uc_and_c_and_ec
41
+ from ldm.invoke.model_cache import ModelCache
42
+ from ldm.invoke.seamless import configure_model_padding
43
+ from ldm.invoke.txt2mask import Txt2Mask, SegmentedGrayscale
44
+ from ldm.invoke.concepts_lib import Concepts
45
+ from ldm.invoke.generator.inpaint import infill_methods
46
+
47
+ def fix_func(orig):
48
+ if hasattr(torch.backends, 'mps') and torch.backends.mps.is_available():
49
+ def new_func(*args, **kw):
50
+ device = kw.get("device", "mps")
51
+ kw["device"]="cpu"
52
+ return orig(*args, **kw).to(device)
53
+ return new_func
54
+ return orig
55
+
56
+ torch.rand = fix_func(torch.rand)
57
+ torch.rand_like = fix_func(torch.rand_like)
58
+ torch.randn = fix_func(torch.randn)
59
+ torch.randn_like = fix_func(torch.randn_like)
60
+ torch.randint = fix_func(torch.randint)
61
+ torch.randint_like = fix_func(torch.randint_like)
62
+ torch.bernoulli = fix_func(torch.bernoulli)
63
+ torch.multinomial = fix_func(torch.multinomial)
64
+
65
+ # this is fallback model in case no default is defined
66
+ FALLBACK_MODEL_NAME='stable-diffusion-1.5'
67
+
68
+ """Simplified text to image API for stable diffusion/latent diffusion
69
+
70
+ Example Usage:
71
+
72
+ from ldm.generate import Generate
73
+
74
+ # Create an object with default values
75
+ gr = Generate('stable-diffusion-1.4')
76
+
77
+ # do the slow model initialization
78
+ gr.load_model()
79
+
80
+ # Do the fast inference & image generation. Any options passed here
81
+ # override the default values assigned during class initialization
82
+ # Will call load_model() if the model was not previously loaded and so
83
+ # may be slow at first.
84
+ # The method returns a list of images. Each row of the list is a sub-list of [filename,seed]
85
+ results = gr.prompt2png(prompt = "an astronaut riding a horse",
86
+ outdir = "./outputs/samples",
87
+ iterations = 3)
88
+
89
+ for row in results:
90
+ print(f'filename={row[0]}')
91
+ print(f'seed ={row[1]}')
92
+
93
+ # Same thing, but using an initial image.
94
+ results = gr.prompt2png(prompt = "an astronaut riding a horse",
95
+ outdir = "./outputs/,
96
+ iterations = 3,
97
+ init_img = "./sketches/horse+rider.png")
98
+
99
+ for row in results:
100
+ print(f'filename={row[0]}')
101
+ print(f'seed ={row[1]}')
102
+
103
+ # Same thing, but we return a series of Image objects, which lets you manipulate them,
104
+ # combine them, and save them under arbitrary names
105
+
106
+ results = gr.prompt2image(prompt = "an astronaut riding a horse"
107
+ outdir = "./outputs/")
108
+ for row in results:
109
+ im = row[0]
110
+ seed = row[1]
111
+ im.save(f'./outputs/samples/an_astronaut_riding_a_horse-{seed}.png')
112
+ im.thumbnail(100,100).save('./outputs/samples/astronaut_thumb.jpg')
113
+
114
+ Note that the old txt2img() and img2img() calls are deprecated but will
115
+ still work.
116
+
117
+ The full list of arguments to Generate() are:
118
+ gr = Generate(
119
+ # these values are set once and shouldn't be changed
120
+ conf:str = path to configuration file ('configs/models.yaml')
121
+ model:str = symbolic name of the model in the configuration file
122
+ precision:float = float precision to be used
123
+ safety_checker:bool = activate safety checker [False]
124
+
125
+ # this value is sticky and maintained between generation calls
126
+ sampler_name:str = ['ddim', 'k_dpm_2_a', 'k_dpm_2', 'k_dpmpp_2', 'k_dpmpp_2_a', 'k_euler_a', 'k_euler', 'k_heun', 'k_lms', 'plms'] // k_lms
127
+
128
+ # these are deprecated - use conf and model instead
129
+ weights = path to model weights ('models/ldm/stable-diffusion-v1/model.ckpt')
130
+ config = path to model configuration ('configs/stable-diffusion/v1-inference.yaml')
131
+ )
132
+
133
+ """
134
+
135
+ class Generate:
136
+ """Generate class
137
+ Stores default values for multiple configuration items
138
+ """
139
+
140
+ def __init__(
141
+ self,
142
+ model = None,
143
+ conf = 'configs/models.yaml',
144
+ embedding_path = None,
145
+ sampler_name = 'k_lms',
146
+ ddim_eta = 0.0, # deterministic
147
+ full_precision = False,
148
+ precision = 'auto',
149
+ outdir = 'outputs/img-samples',
150
+ gfpgan=None,
151
+ codeformer=None,
152
+ esrgan=None,
153
+ free_gpu_mem=False,
154
+ safety_checker:bool=False,
155
+ max_loaded_models:int=2,
156
+ # these are deprecated; if present they override values in the conf file
157
+ weights = None,
158
+ config = None,
159
+ ):
160
+ mconfig = OmegaConf.load(conf)
161
+ self.height = None
162
+ self.width = None
163
+ self.model_cache = None
164
+ self.iterations = 1
165
+ self.steps = 50
166
+ self.cfg_scale = 7.5
167
+ self.sampler_name = sampler_name
168
+ self.ddim_eta = 0.0 # same seed always produces same image
169
+ self.precision = precision
170
+ self.strength = 0.75
171
+ self.seamless = False
172
+ self.seamless_axes = {'x','y'}
173
+ self.hires_fix = False
174
+ self.embedding_path = embedding_path
175
+ self.model = None # empty for now
176
+ self.model_hash = None
177
+ self.sampler = None
178
+ self.device = None
179
+ self.session_peakmem = None
180
+ self.generators = {}
181
+ self.base_generator = None
182
+ self.seed = None
183
+ self.outdir = outdir
184
+ self.gfpgan = gfpgan
185
+ self.codeformer = codeformer
186
+ self.esrgan = esrgan
187
+ self.free_gpu_mem = free_gpu_mem
188
+ self.max_loaded_models = max_loaded_models,
189
+ self.size_matters = True # used to warn once about large image sizes and VRAM
190
+ self.txt2mask = None
191
+ self.safety_checker = None
192
+ self.karras_max = None
193
+ self.infill_method = None
194
+
195
+ # Note that in previous versions, there was an option to pass the
196
+ # device to Generate(). However the device was then ignored, so
197
+ # it wasn't actually doing anything. This logic could be reinstated.
198
+ device_type = choose_torch_device()
199
+ print(f'>> Using device_type {device_type}')
200
+ self.device = torch.device(device_type)
201
+ if full_precision:
202
+ if self.precision != 'auto':
203
+ raise ValueError('Remove --full_precision / -F if using --precision')
204
+ print('Please remove deprecated --full_precision / -F')
205
+ print('If auto config does not work you can use --precision=float32')
206
+ self.precision = 'float32'
207
+ if self.precision == 'auto':
208
+ self.precision = choose_precision(self.device)
209
+
210
+ # model caching system for fast switching
211
+ self.model_cache = ModelCache(mconfig,self.device,self.precision,max_loaded_models=max_loaded_models)
212
+ self.model_name = model or self.model_cache.default_model() or FALLBACK_MODEL_NAME
213
+
214
+ # for VRAM usage statistics
215
+ self.session_peakmem = torch.cuda.max_memory_allocated() if self._has_cuda else None
216
+ transformers.logging.set_verbosity_error()
217
+
218
+ # gets rid of annoying messages about random seed
219
+ logging.getLogger('pytorch_lightning').setLevel(logging.ERROR)
220
+
221
+ # load safety checker if requested
222
+ if safety_checker:
223
+ try:
224
+ print('>> Initializing safety checker')
225
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
226
+ from transformers import AutoFeatureExtractor
227
+ safety_model_id = "CompVis/stable-diffusion-safety-checker"
228
+ safety_model_path = os.path.join(Globals.root,'models',safety_model_id)
229
+ self.safety_checker = StableDiffusionSafetyChecker.from_pretrained(safety_model_id,
230
+ local_files_only=True,
231
+ cache_dir=safety_model_path,
232
+ )
233
+ self.safety_feature_extractor = AutoFeatureExtractor.from_pretrained(safety_model_id,
234
+ local_files_only=True,
235
+ cache_dir=safety_model_path,
236
+ )
237
+ self.safety_checker.to(self.device)
238
+ except Exception:
239
+ print('** An error was encountered while installing the safety checker:')
240
+ print(traceback.format_exc())
241
+
242
+ def prompt2png(self, prompt, outdir, **kwargs):
243
+ """
244
+ Takes a prompt and an output directory, writes out the requested number
245
+ of PNG files, and returns an array of [[filename,seed],[filename,seed]...]
246
+ Optional named arguments are the same as those passed to Generate and prompt2image()
247
+ """
248
+ results = self.prompt2image(prompt, **kwargs)
249
+ pngwriter = PngWriter(outdir)
250
+ prefix = pngwriter.unique_prefix()
251
+ outputs = []
252
+ for image, seed in results:
253
+ name = f'{prefix}.{seed}.png'
254
+ path = pngwriter.save_image_and_prompt_to_png(
255
+ image, dream_prompt=f'{prompt} -S{seed}', name=name)
256
+ outputs.append([path, seed])
257
+ return outputs
258
+
259
+ def txt2img(self, prompt, **kwargs):
260
+ outdir = kwargs.pop('outdir', self.outdir)
261
+ return self.prompt2png(prompt, outdir, **kwargs)
262
+
263
+ def img2img(self, prompt, **kwargs):
264
+ outdir = kwargs.pop('outdir', self.outdir)
265
+ assert (
266
+ 'init_img' in kwargs
267
+ ), 'call to img2img() must include the init_img argument'
268
+ return self.prompt2png(prompt, outdir, **kwargs)
269
+
270
+ def prompt2image(
271
+ self,
272
+ # these are common
273
+ prompt,
274
+ iterations = None,
275
+ steps = None,
276
+ seed = None,
277
+ cfg_scale = None,
278
+ ddim_eta = None,
279
+ skip_normalize = False,
280
+ image_callback = None,
281
+ step_callback = None,
282
+ width = None,
283
+ height = None,
284
+ sampler_name = None,
285
+ seamless = False,
286
+ seamless_axes = {'x','y'},
287
+ log_tokenization = False,
288
+ with_variations = None,
289
+ variation_amount = 0.0,
290
+ threshold = 0.0,
291
+ perlin = 0.0,
292
+ karras_max = None,
293
+ outdir = None,
294
+ # these are specific to img2img and inpaint
295
+ init_img = None,
296
+ init_mask = None,
297
+ text_mask = None,
298
+ invert_mask = False,
299
+ fit = False,
300
+ strength = None,
301
+ init_color = None,
302
+ # these are specific to embiggen (which also relies on img2img args)
303
+ embiggen = None,
304
+ embiggen_tiles = None,
305
+ embiggen_strength = None,
306
+ # these are specific to GFPGAN/ESRGAN
307
+ gfpgan_strength= 0,
308
+ facetool = None,
309
+ facetool_strength = 0,
310
+ codeformer_fidelity = None,
311
+ save_original = False,
312
+ upscale = None,
313
+ # this is specific to inpainting and causes more extreme inpainting
314
+ inpaint_replace = 0.0,
315
+ # This controls the size at which inpaint occurs (scaled up for inpaint, then back down for the result)
316
+ inpaint_width = None,
317
+ inpaint_height = None,
318
+ # This will help match inpainted areas to the original image more smoothly
319
+ mask_blur_radius: int = 8,
320
+ # Set this True to handle KeyboardInterrupt internally
321
+ catch_interrupts = False,
322
+ hires_fix = False,
323
+ use_mps_noise = False,
324
+ # Seam settings for outpainting
325
+ seam_size: int = 0,
326
+ seam_blur: int = 0,
327
+ seam_strength: float = 0.7,
328
+ seam_steps: int = 10,
329
+ tile_size: int = 32,
330
+ infill_method = None,
331
+ force_outpaint: bool = False,
332
+ enable_image_debugging = False,
333
+
334
+ **args,
335
+ ): # eat up additional cruft
336
+ """
337
+ ldm.generate.prompt2image() is the common entry point for txt2img() and img2img()
338
+ It takes the following arguments:
339
+ prompt // prompt string (no default)
340
+ iterations // iterations (1); image count=iterations
341
+ steps // refinement steps per iteration
342
+ seed // seed for random number generator
343
+ width // width of image, in multiples of 64 (512)
344
+ height // height of image, in multiples of 64 (512)
345
+ cfg_scale // how strongly the prompt influences the image (7.5) (must be >1)
346
+ seamless // whether the generated image should tile
347
+ hires_fix // whether the Hires Fix should be applied during generation
348
+ init_img // path to an initial image
349
+ init_mask // path to a mask for the initial image
350
+ text_mask // a text string that will be used to guide clipseg generation of the init_mask
351
+ invert_mask // boolean, if true invert the mask
352
+ strength // strength for noising/unnoising init_img. 0.0 preserves image exactly, 1.0 replaces it completely
353
+ facetool_strength // strength for GFPGAN/CodeFormer. 0.0 preserves image exactly, 1.0 replaces it completely
354
+ ddim_eta // image randomness (eta=0.0 means the same seed always produces the same image)
355
+ step_callback // a function or method that will be called each step
356
+ image_callback // a function or method that will be called each time an image is generated
357
+ with_variations // a weighted list [(seed_1, weight_1), (seed_2, weight_2), ...] of variations which should be applied before doing any generation
358
+ variation_amount // optional 0-1 value to slerp from -S noise to random noise (allows variations on an image)
359
+ threshold // optional value >=0 to add thresholding to latent values for k-diffusion samplers (0 disables)
360
+ perlin // optional 0-1 value to add a percentage of perlin noise to the initial noise
361
+ embiggen // scale factor relative to the size of the --init_img (-I), followed by ESRGAN upscaling strength (0-1.0), followed by minimum amount of overlap between tiles as a decimal ratio (0 - 1.0) or number of pixels
362
+ embiggen_tiles // list of tiles by number in order to process and replace onto the image e.g. `0 2 4`
363
+ embiggen_strength // strength for embiggen. 0.0 preserves image exactly, 1.0 replaces it completely
364
+
365
+ To use the step callback, define a function that receives two arguments:
366
+ - Image GPU data
367
+ - The step number
368
+
369
+ To use the image callback, define a function of method that receives two arguments, an Image object
370
+ and the seed. You can then do whatever you like with the image, including converting it to
371
+ different formats and manipulating it. For example:
372
+
373
+ def process_image(image,seed):
374
+ image.save(f{'images/seed.png'})
375
+
376
+ The code used to save images to a directory can be found in ldm/invoke/pngwriter.py.
377
+ It contains code to create the requested output directory, select a unique informative
378
+ name for each image, and write the prompt into the PNG metadata.
379
+ """
380
+ # TODO: convert this into a getattr() loop
381
+ steps = steps or self.steps
382
+ width = width or self.width
383
+ height = height or self.height
384
+ seamless = seamless or self.seamless
385
+ seamless_axes = seamless_axes or self.seamless_axes
386
+ hires_fix = hires_fix or self.hires_fix
387
+ cfg_scale = cfg_scale or self.cfg_scale
388
+ ddim_eta = ddim_eta or self.ddim_eta
389
+ iterations = iterations or self.iterations
390
+ strength = strength or self.strength
391
+ outdir = outdir or self.outdir
392
+ self.seed = seed
393
+ self.log_tokenization = log_tokenization
394
+ self.step_callback = step_callback
395
+ self.karras_max = karras_max
396
+ self.infill_method = infill_method or infill_methods()[0], # The infill method to use
397
+ with_variations = [] if with_variations is None else with_variations
398
+
399
+ # will instantiate the model or return it from cache
400
+ model = self.set_model(self.model_name)
401
+
402
+ # self.width and self.height are set by set_model()
403
+ # to the width and height of the image training set
404
+ width = width or self.width
405
+ height = height or self.height
406
+
407
+ configure_model_padding(model, seamless, seamless_axes)
408
+
409
+ assert cfg_scale > 1.0, 'CFG_Scale (-C) must be >1.0'
410
+ assert threshold >= 0.0, '--threshold must be >=0.0'
411
+ assert (
412
+ 0.0 < strength < 1.0
413
+ ), 'img2img and inpaint strength can only work with 0.0 < strength < 1.0'
414
+ assert (
415
+ 0.0 <= variation_amount <= 1.0
416
+ ), '-v --variation_amount must be in [0.0, 1.0]'
417
+ assert (
418
+ 0.0 <= perlin <= 1.0
419
+ ), '--perlin must be in [0.0, 1.0]'
420
+ assert (
421
+ (embiggen == None and embiggen_tiles == None) or (
422
+ (embiggen != None or embiggen_tiles != None) and init_img != None)
423
+ ), 'Embiggen requires an init/input image to be specified'
424
+
425
+ if len(with_variations) > 0 or variation_amount > 1.0:
426
+ assert seed is not None,\
427
+ 'seed must be specified when using with_variations'
428
+ if variation_amount == 0.0:
429
+ assert iterations == 1,\
430
+ 'when using --with_variations, multiple iterations are only possible when using --variation_amount'
431
+ assert all(0 <= weight <= 1 for _, weight in with_variations),\
432
+ f'variation weights must be in [0.0, 1.0]: got {[weight for _, weight in with_variations]}'
433
+
434
+ width, height, _ = self._resolution_check(width, height, log=True)
435
+ assert inpaint_replace >=0.0 and inpaint_replace <= 1.0,'inpaint_replace must be between 0.0 and 1.0'
436
+
437
+ if sampler_name and (sampler_name != self.sampler_name):
438
+ self.sampler_name = sampler_name
439
+ self._set_sampler()
440
+
441
+ # apply the concepts library to the prompt
442
+ prompt = self.concept_lib().replace_concepts_with_triggers(prompt, lambda concepts: self.load_concepts(concepts))
443
+
444
+ # bit of a hack to change the cached sampler's karras threshold to
445
+ # whatever the user asked for
446
+ if karras_max is not None and isinstance(self.sampler,KSampler):
447
+ self.sampler.adjust_settings(karras_max=karras_max)
448
+
449
+ tic = time.time()
450
+ if self._has_cuda():
451
+ torch.cuda.reset_peak_memory_stats()
452
+
453
+ results = list()
454
+ init_image = None
455
+ mask_image = None
456
+
457
+
458
+ if self.free_gpu_mem and self.model.cond_stage_model.device != self.model.device:
459
+ self.model.cond_stage_model.device = self.model.device
460
+ self.model.cond_stage_model.to(self.model.device)
461
+
462
+ try:
463
+ uc, c, extra_conditioning_info = get_uc_and_c_and_ec(
464
+ prompt, model =self.model,
465
+ skip_normalize_legacy_blend=skip_normalize,
466
+ log_tokens =self.log_tokenization
467
+ )
468
+
469
+ init_image, mask_image = self._make_images(
470
+ init_img,
471
+ init_mask,
472
+ width,
473
+ height,
474
+ fit=fit,
475
+ text_mask=text_mask,
476
+ invert_mask=invert_mask,
477
+ force_outpaint=force_outpaint,
478
+ )
479
+
480
+ # TODO: Hacky selection of operation to perform. Needs to be refactored.
481
+ generator = self.select_generator(init_image, mask_image, embiggen, hires_fix, force_outpaint)
482
+
483
+ generator.set_variation(
484
+ self.seed, variation_amount, with_variations
485
+ )
486
+ generator.use_mps_noise = use_mps_noise
487
+
488
+ checker = {
489
+ 'checker':self.safety_checker,
490
+ 'extractor':self.safety_feature_extractor
491
+ } if self.safety_checker else None
492
+
493
+ results = generator.generate(
494
+ prompt,
495
+ iterations=iterations,
496
+ seed=self.seed,
497
+ sampler=self.sampler,
498
+ steps=steps,
499
+ cfg_scale=cfg_scale,
500
+ conditioning=(uc, c, extra_conditioning_info),
501
+ ddim_eta=ddim_eta,
502
+ image_callback=image_callback, # called after the final image is generated
503
+ step_callback=step_callback, # called after each intermediate image is generated
504
+ width=width,
505
+ height=height,
506
+ init_img=init_img, # embiggen needs to manipulate from the unmodified init_img
507
+ init_image=init_image, # notice that init_image is different from init_img
508
+ mask_image=mask_image,
509
+ strength=strength,
510
+ threshold=threshold,
511
+ perlin=perlin,
512
+ embiggen=embiggen,
513
+ embiggen_tiles=embiggen_tiles,
514
+ embiggen_strength=embiggen_strength,
515
+ inpaint_replace=inpaint_replace,
516
+ mask_blur_radius=mask_blur_radius,
517
+ safety_checker=checker,
518
+ seam_size = seam_size,
519
+ seam_blur = seam_blur,
520
+ seam_strength = seam_strength,
521
+ seam_steps = seam_steps,
522
+ tile_size = tile_size,
523
+ infill_method = infill_method,
524
+ force_outpaint = force_outpaint,
525
+ inpaint_height = inpaint_height,
526
+ inpaint_width = inpaint_width,
527
+ enable_image_debugging = enable_image_debugging,
528
+ )
529
+
530
+ if init_color:
531
+ self.correct_colors(image_list = results,
532
+ reference_image_path = init_color,
533
+ image_callback = image_callback)
534
+
535
+ if upscale is not None or facetool_strength > 0:
536
+ self.upscale_and_reconstruct(results,
537
+ upscale = upscale,
538
+ facetool = facetool,
539
+ strength = facetool_strength,
540
+ codeformer_fidelity = codeformer_fidelity,
541
+ save_original = save_original,
542
+ image_callback = image_callback)
543
+
544
+ except KeyboardInterrupt:
545
+ if catch_interrupts:
546
+ print('**Interrupted** Partial results will be returned.')
547
+ else:
548
+ raise KeyboardInterrupt
549
+ except RuntimeError as e:
550
+ print(traceback.format_exc(), file=sys.stderr)
551
+ print('>> Could not generate image.')
552
+
553
+ toc = time.time()
554
+ print('>> Usage stats:')
555
+ print(
556
+ f'>> {len(results)} image(s) generated in', '%4.2fs' % (
557
+ toc - tic)
558
+ )
559
+ if self._has_cuda():
560
+ print(
561
+ f'>> Max VRAM used for this generation:',
562
+ '%4.2fG.' % (torch.cuda.max_memory_allocated() / 1e9),
563
+ 'Current VRAM utilization:',
564
+ '%4.2fG' % (torch.cuda.memory_allocated() / 1e9),
565
+ )
566
+
567
+ self.session_peakmem = max(
568
+ self.session_peakmem, torch.cuda.max_memory_allocated()
569
+ )
570
+ print(
571
+ f'>> Max VRAM used since script start: ',
572
+ '%4.2fG' % (self.session_peakmem / 1e9),
573
+ )
574
+ return results
575
+
576
+ # this needs to be generalized to all sorts of postprocessors, which should be wrapped
577
+ # in a nice harmonized call signature. For now we have a bunch of if/elses!
578
+ def apply_postprocessor(
579
+ self,
580
+ image_path,
581
+ tool = 'gfpgan', # one of 'upscale', 'gfpgan', 'codeformer', 'outpaint', or 'embiggen'
582
+ facetool_strength = 0.0,
583
+ codeformer_fidelity = 0.75,
584
+ upscale = None,
585
+ out_direction = None,
586
+ outcrop = [],
587
+ save_original = True, # to get new name
588
+ callback = None,
589
+ opt = None,
590
+ ):
591
+ # retrieve the seed from the image;
592
+ seed = None
593
+ prompt = None
594
+
595
+ args = metadata_from_png(image_path)
596
+ seed = opt.seed or args.seed
597
+ if seed is None or seed < 0:
598
+ seed = random.randrange(0, np.iinfo(np.uint32).max)
599
+
600
+ prompt = opt.prompt or args.prompt or ''
601
+ print(f'>> using seed {seed} and prompt "{prompt}" for {image_path}')
602
+
603
+ # try to reuse the same filename prefix as the original file.
604
+ # we take everything up to the first period
605
+ prefix = None
606
+ m = re.match(r'^([^.]+)\.',os.path.basename(image_path))
607
+ if m:
608
+ prefix = m.groups()[0]
609
+
610
+ # face fixers and esrgan take an Image, but embiggen takes a path
611
+ image = Image.open(image_path)
612
+
613
+ # used by multiple postfixers
614
+ # todo: cross-attention control
615
+ uc, c, extra_conditioning_info = get_uc_and_c_and_ec(
616
+ prompt, model =self.model,
617
+ skip_normalize_legacy_blend=opt.skip_normalize,
618
+ log_tokens =ldm.invoke.conditioning.log_tokenization
619
+ )
620
+
621
+ if tool in ('gfpgan','codeformer','upscale'):
622
+ if tool == 'gfpgan':
623
+ facetool = 'gfpgan'
624
+ elif tool == 'codeformer':
625
+ facetool = 'codeformer'
626
+ elif tool == 'upscale':
627
+ facetool = 'gfpgan' # but won't be run
628
+ facetool_strength = 0
629
+ return self.upscale_and_reconstruct(
630
+ [[image,seed]],
631
+ facetool = facetool,
632
+ strength = facetool_strength,
633
+ codeformer_fidelity = codeformer_fidelity,
634
+ save_original = save_original,
635
+ upscale = upscale,
636
+ image_callback = callback,
637
+ prefix = prefix,
638
+ )
639
+
640
+ elif tool == 'outcrop':
641
+ from ldm.invoke.restoration.outcrop import Outcrop
642
+ extend_instructions = {}
643
+ for direction,pixels in _pairwise(opt.outcrop):
644
+ try:
645
+ extend_instructions[direction]=int(pixels)
646
+ except ValueError:
647
+ print(f'** invalid extension instruction. Use <directions> <pixels>..., as in "top 64 left 128 right 64 bottom 64"')
648
+
649
+ opt.seed = seed
650
+ opt.prompt = prompt
651
+
652
+ if len(extend_instructions) > 0:
653
+ restorer = Outcrop(image,self,)
654
+ return restorer.process (
655
+ extend_instructions,
656
+ opt = opt,
657
+ orig_opt = args,
658
+ image_callback = callback,
659
+ prefix = prefix,
660
+ )
661
+
662
+ elif tool == 'embiggen':
663
+ # fetch the metadata from the image
664
+ generator = self.select_generator(embiggen=True)
665
+ opt.strength = opt.embiggen_strength or 0.40
666
+ print(f'>> Setting img2img strength to {opt.strength} for happy embiggening')
667
+ generator.generate(
668
+ prompt,
669
+ sampler = self.sampler,
670
+ steps = opt.steps,
671
+ cfg_scale = opt.cfg_scale,
672
+ ddim_eta = self.ddim_eta,
673
+ conditioning= (uc, c, extra_conditioning_info),
674
+ init_img = image_path, # not the Image! (sigh)
675
+ init_image = image, # embiggen wants both! (sigh)
676
+ strength = opt.strength,
677
+ width = opt.width,
678
+ height = opt.height,
679
+ embiggen = opt.embiggen,
680
+ embiggen_tiles = opt.embiggen_tiles,
681
+ embiggen_strength = opt.embiggen_strength,
682
+ image_callback = callback,
683
+ )
684
+ elif tool == 'outpaint':
685
+ from ldm.invoke.restoration.outpaint import Outpaint
686
+ restorer = Outpaint(image,self)
687
+ return restorer.process(
688
+ opt,
689
+ args,
690
+ image_callback = callback,
691
+ prefix = prefix
692
+ )
693
+
694
+ elif tool is None:
695
+ print(f'* please provide at least one postprocessing option, such as -G or -U')
696
+ return None
697
+ else:
698
+ print(f'* postprocessing tool {tool} is not yet supported')
699
+ return None
700
+
701
+ def select_generator(
702
+ self,
703
+ init_image:Image.Image=None,
704
+ mask_image:Image.Image=None,
705
+ embiggen:bool=False,
706
+ hires_fix:bool=False,
707
+ force_outpaint:bool=False,
708
+ ):
709
+ inpainting_model_in_use = self.sampler.uses_inpainting_model()
710
+
711
+ if hires_fix:
712
+ return self._make_txt2img2img()
713
+
714
+ if embiggen is not None:
715
+ return self._make_embiggen()
716
+
717
+ if inpainting_model_in_use:
718
+ return self._make_omnibus()
719
+
720
+ if ((init_image is not None) and (mask_image is not None)) or force_outpaint:
721
+ return self._make_inpaint()
722
+
723
+ if init_image is not None:
724
+ return self._make_img2img()
725
+
726
+ return self._make_txt2img()
727
+
728
+ def _make_images(
729
+ self,
730
+ img,
731
+ mask,
732
+ width,
733
+ height,
734
+ fit=False,
735
+ text_mask=None,
736
+ invert_mask=False,
737
+ force_outpaint=False,
738
+ ):
739
+ init_image = None
740
+ init_mask = None
741
+ if not img:
742
+ return None, None
743
+
744
+ image = self._load_img(img)
745
+
746
+ if image.width < self.width and image.height < self.height:
747
+ print(f'>> WARNING: img2img and inpainting may produce unexpected results with initial images smaller than {self.width}x{self.height} in both dimensions')
748
+
749
+ # if image has a transparent area and no mask was provided, then try to generate mask
750
+ if self._has_transparency(image):
751
+ self._transparency_check_and_warning(image, mask, force_outpaint)
752
+ init_mask = self._create_init_mask(image, width, height, fit=fit)
753
+
754
+ if (image.width * image.height) > (self.width * self.height) and self.size_matters:
755
+ print(">> This input is larger than your defaults. If you run out of memory, please use a smaller image.")
756
+ self.size_matters = False
757
+
758
+ init_image = self._create_init_image(image,width,height,fit=fit)
759
+
760
+ if mask:
761
+ mask_image = self._load_img(mask)
762
+ init_mask = self._create_init_mask(mask_image,width,height,fit=fit)
763
+
764
+ elif text_mask:
765
+ init_mask = self._txt2mask(image, text_mask, width, height, fit=fit)
766
+
767
+ if init_mask and invert_mask:
768
+ init_mask = ImageOps.invert(init_mask)
769
+
770
+ return init_image,init_mask
771
+
772
+ # lots o' repeated code here! Turn into a make_func()
773
+ def _make_base(self):
774
+ if not self.generators.get('base'):
775
+ from ldm.invoke.generator import Generator
776
+ self.generators['base'] = Generator(self.model, self.precision)
777
+ return self.generators['base']
778
+
779
+ def _make_img2img(self):
780
+ if not self.generators.get('img2img'):
781
+ from ldm.invoke.generator.img2img import Img2Img
782
+ self.generators['img2img'] = Img2Img(self.model, self.precision)
783
+ self.generators['img2img'].free_gpu_mem = self.free_gpu_mem
784
+ return self.generators['img2img']
785
+
786
+ def _make_embiggen(self):
787
+ if not self.generators.get('embiggen'):
788
+ from ldm.invoke.generator.embiggen import Embiggen
789
+ self.generators['embiggen'] = Embiggen(self.model, self.precision)
790
+ return self.generators['embiggen']
791
+
792
+ def _make_txt2img(self):
793
+ if not self.generators.get('txt2img'):
794
+ from ldm.invoke.generator.txt2img import Txt2Img
795
+ self.generators['txt2img'] = Txt2Img(self.model, self.precision)
796
+ self.generators['txt2img'].free_gpu_mem = self.free_gpu_mem
797
+ return self.generators['txt2img']
798
+
799
+ def _make_txt2img2img(self):
800
+ if not self.generators.get('txt2img2'):
801
+ from ldm.invoke.generator.txt2img2img import Txt2Img2Img
802
+ self.generators['txt2img2'] = Txt2Img2Img(self.model, self.precision)
803
+ self.generators['txt2img2'].free_gpu_mem = self.free_gpu_mem
804
+ return self.generators['txt2img2']
805
+
806
+ def _make_inpaint(self):
807
+ if not self.generators.get('inpaint'):
808
+ from ldm.invoke.generator.inpaint import Inpaint
809
+ self.generators['inpaint'] = Inpaint(self.model, self.precision)
810
+ self.generators['inpaint'].free_gpu_mem = self.free_gpu_mem
811
+ return self.generators['inpaint']
812
+
813
+ # "omnibus" supports the runwayML custom inpainting model, which does
814
+ # txt2img, img2img and inpainting using slight variations on the same code
815
+ def _make_omnibus(self):
816
+ if not self.generators.get('omnibus'):
817
+ from ldm.invoke.generator.omnibus import Omnibus
818
+ self.generators['omnibus'] = Omnibus(self.model, self.precision)
819
+ self.generators['omnibus'].free_gpu_mem = self.free_gpu_mem
820
+ return self.generators['omnibus']
821
+
822
+ def load_model(self):
823
+ '''
824
+ preload model identified in self.model_name
825
+ '''
826
+ self.set_model(self.model_name)
827
+
828
+ def set_model(self,model_name):
829
+ """
830
+ Given the name of a model defined in models.yaml, will load and initialize it
831
+ and return the model object. Previously-used models will be cached.
832
+ """
833
+ if self.model_name == model_name and self.model is not None:
834
+ return self.model
835
+
836
+ # the model cache does the loading and offloading
837
+ cache = self.model_cache
838
+ if not cache.valid_model(model_name):
839
+ print(f'** "{model_name}" is not a known model name. Please check your models.yaml file')
840
+ return self.model
841
+
842
+ cache.print_vram_usage()
843
+
844
+ # have to get rid of all references to model in order
845
+ # to free it from GPU memory
846
+ self.model = None
847
+ self.sampler = None
848
+ self.generators = {}
849
+ gc.collect()
850
+
851
+ model_data = cache.get_model(model_name)
852
+ if model_data is None: # restore previous
853
+ model_data = cache.get_model(self.model_name)
854
+ model_name = self.model_name # addresses Issue #1547
855
+
856
+ self.model = model_data['model']
857
+ self.width = model_data['width']
858
+ self.height= model_data['height']
859
+ self.model_hash = model_data['hash']
860
+
861
+ # uncache generators so they pick up new models
862
+ self.generators = {}
863
+
864
+ seed_everything(random.randrange(0, np.iinfo(np.uint32).max))
865
+ if self.embedding_path is not None:
866
+ self.model.embedding_manager.load(
867
+ self.embedding_path, self.precision == 'float32' or self.precision == 'autocast'
868
+ )
869
+
870
+ self._set_sampler()
871
+ self.model_name = model_name
872
+ return self.model
873
+
874
+ def load_concepts(self,concepts:list[str]):
875
+ self.model.embedding_manager.load_concepts(concepts, self.precision=='float32' or self.precision=='autocast')
876
+
877
+ def concept_lib(self)->Concepts:
878
+ return self.model.embedding_manager.concepts_library
879
+
880
+ def correct_colors(self,
881
+ image_list,
882
+ reference_image_path,
883
+ image_callback = None):
884
+ reference_image = Image.open(reference_image_path)
885
+ correction_target = cv2.cvtColor(np.asarray(reference_image),
886
+ cv2.COLOR_RGB2LAB)
887
+ for r in image_list:
888
+ image, seed = r
889
+ image = cv2.cvtColor(np.asarray(image),
890
+ cv2.COLOR_RGB2LAB)
891
+ image = skimage.exposure.match_histograms(image,
892
+ correction_target,
893
+ channel_axis=2)
894
+ image = Image.fromarray(
895
+ cv2.cvtColor(image, cv2.COLOR_LAB2RGB).astype("uint8")
896
+ )
897
+ if image_callback is not None:
898
+ image_callback(image, seed)
899
+ else:
900
+ r[0] = image
901
+
902
+ def upscale_and_reconstruct(self,
903
+ image_list,
904
+ facetool = 'gfpgan',
905
+ upscale = None,
906
+ strength = 0.0,
907
+ codeformer_fidelity = 0.75,
908
+ save_original = False,
909
+ image_callback = None,
910
+ prefix = None,
911
+ ):
912
+
913
+ for r in image_list:
914
+ image, seed = r
915
+ try:
916
+ if strength > 0:
917
+ if self.gfpgan is not None or self.codeformer is not None:
918
+ if facetool == 'gfpgan':
919
+ if self.gfpgan is None:
920
+ print('>> GFPGAN not found. Face restoration is disabled.')
921
+ else:
922
+ image = self.gfpgan.process(image, strength, seed)
923
+ if facetool == 'codeformer':
924
+ if self.codeformer is None:
925
+ print('>> CodeFormer not found. Face restoration is disabled.')
926
+ else:
927
+ cf_device = 'cpu' if str(self.device) == 'mps' else self.device
928
+ image = self.codeformer.process(image=image, strength=strength, device=cf_device, seed=seed, fidelity=codeformer_fidelity)
929
+ else:
930
+ print(">> Face Restoration is disabled.")
931
+ if upscale is not None:
932
+ if self.esrgan is not None:
933
+ if len(upscale) < 2:
934
+ upscale.append(0.75)
935
+ image = self.esrgan.process(
936
+ image, upscale[1], seed, int(upscale[0]))
937
+ else:
938
+ print(">> ESRGAN is disabled. Image not upscaled.")
939
+ except Exception as e:
940
+ print(
941
+ f'>> Error running RealESRGAN or GFPGAN. Your image was not upscaled.\n{e}'
942
+ )
943
+
944
+ if image_callback is not None:
945
+ image_callback(image, seed, upscaled=True, use_prefix=prefix)
946
+ else:
947
+ r[0] = image
948
+
949
+ def apply_textmask(self, image_path:str, prompt:str, callback, threshold:float=0.5):
950
+ assert os.path.exists(image_path), f'** "{image_path}" not found. Please enter the name of an existing image file to mask **'
951
+ basename,_ = os.path.splitext(os.path.basename(image_path))
952
+ if self.txt2mask is None:
953
+ self.txt2mask = Txt2Mask(device = self.device, refined=True)
954
+ segmented = self.txt2mask.segment(image_path,prompt)
955
+ trans = segmented.to_transparent()
956
+ inverse = segmented.to_transparent(invert=True)
957
+ mask = segmented.to_mask(threshold)
958
+
959
+ path_filter = re.compile(r'[<>:"/\\|?*]')
960
+ safe_prompt = path_filter.sub('_', prompt)[:50].rstrip(' .')
961
+
962
+ callback(trans,f'{safe_prompt}.deselected',use_prefix=basename)
963
+ callback(inverse,f'{safe_prompt}.selected',use_prefix=basename)
964
+ callback(mask,f'{safe_prompt}.masked',use_prefix=basename)
965
+
966
+ # to help WebGUI - front end to generator util function
967
+ def sample_to_image(self, samples):
968
+ return self._make_base().sample_to_image(samples)
969
+
970
+ def sample_to_lowres_estimated_image(self, samples):
971
+ return self._make_base().sample_to_lowres_estimated_image(samples)
972
+
973
+ # very repetitive code - can this be simplified? The KSampler names are
974
+ # consistent, at least
975
+ def _set_sampler(self):
976
+ msg = f'>> Setting Sampler to {self.sampler_name}'
977
+ if self.sampler_name == 'plms':
978
+ self.sampler = PLMSSampler(self.model, device=self.device)
979
+ elif self.sampler_name == 'ddim':
980
+ self.sampler = DDIMSampler(self.model, device=self.device)
981
+ elif self.sampler_name == 'k_dpm_2_a':
982
+ self.sampler = KSampler(self.model, 'dpm_2_ancestral', device=self.device)
983
+ elif self.sampler_name == 'k_dpm_2':
984
+ self.sampler = KSampler(self.model, 'dpm_2', device=self.device)
985
+ elif self.sampler_name == 'k_dpmpp_2_a':
986
+ self.sampler = KSampler(self.model, 'dpmpp_2s_ancestral', device=self.device)
987
+ elif self.sampler_name == 'k_dpmpp_2':
988
+ self.sampler = KSampler(self.model, 'dpmpp_2m', device=self.device)
989
+ elif self.sampler_name == 'k_euler_a':
990
+ self.sampler = KSampler(self.model, 'euler_ancestral', device=self.device)
991
+ elif self.sampler_name == 'k_euler':
992
+ self.sampler = KSampler(self.model, 'euler', device=self.device)
993
+ elif self.sampler_name == 'k_heun':
994
+ self.sampler = KSampler(self.model, 'heun', device=self.device)
995
+ elif self.sampler_name == 'k_lms':
996
+ self.sampler = KSampler(self.model, 'lms', device=self.device)
997
+ else:
998
+ msg = f'>> Unsupported Sampler: {self.sampler_name}, Defaulting to plms'
999
+ self.sampler = PLMSSampler(self.model, device=self.device)
1000
+
1001
+ print(msg)
1002
+
1003
+ def _load_img(self, img)->Image:
1004
+ if isinstance(img, Image.Image):
1005
+ image = img
1006
+ print(
1007
+ f'>> using provided input image of size {image.width}x{image.height}'
1008
+ )
1009
+ elif isinstance(img, str):
1010
+ assert os.path.exists(img), f'>> {img}: File not found'
1011
+
1012
+ image = Image.open(img)
1013
+ print(
1014
+ f'>> loaded input image of size {image.width}x{image.height} from {img}'
1015
+ )
1016
+ else:
1017
+ image = Image.open(img)
1018
+ print(
1019
+ f'>> loaded input image of size {image.width}x{image.height}'
1020
+ )
1021
+ image = ImageOps.exif_transpose(image)
1022
+ return image
1023
+
1024
+ def _create_init_image(self, image: Image.Image, width, height, fit=True):
1025
+ if image.mode != 'RGBA':
1026
+ image = image.convert('RGBA')
1027
+ image = self._fit_image(image, (width, height)) if fit else self._squeeze_image(image)
1028
+ return image
1029
+
1030
+ def _create_init_mask(self, image, width, height, fit=True):
1031
+ # convert into a black/white mask
1032
+ image = self._image_to_mask(image)
1033
+ image = image.convert('RGB')
1034
+ image = self._fit_image(image, (width, height)) if fit else self._squeeze_image(image)
1035
+ return image
1036
+
1037
+ # The mask is expected to have the region to be inpainted
1038
+ # with alpha transparency. It converts it into a black/white
1039
+ # image with the transparent part black.
1040
+ def _image_to_mask(self, mask_image: Image.Image, invert=False) -> Image:
1041
+ # Obtain the mask from the transparency channel
1042
+ if mask_image.mode == 'L':
1043
+ mask = mask_image
1044
+ elif mask_image.mode in ('RGB', 'P'):
1045
+ mask = mask_image.convert('L')
1046
+ else:
1047
+ # Obtain the mask from the transparency channel
1048
+ mask = Image.new(mode="L", size=mask_image.size, color=255)
1049
+ mask.putdata(mask_image.getdata(band=3))
1050
+ if invert:
1051
+ mask = ImageOps.invert(mask)
1052
+ return mask
1053
+
1054
+ def _txt2mask(self, image:Image, text_mask:list, width, height, fit=True) -> Image:
1055
+ prompt = text_mask[0]
1056
+ confidence_level = text_mask[1] if len(text_mask)>1 else 0.5
1057
+ if self.txt2mask is None:
1058
+ self.txt2mask = Txt2Mask(device = self.device)
1059
+
1060
+ segmented = self.txt2mask.segment(image, prompt)
1061
+ mask = segmented.to_mask(float(confidence_level))
1062
+ mask = mask.convert('RGB')
1063
+ mask = self._fit_image(mask, (width, height)) if fit else self._squeeze_image(mask)
1064
+ return mask
1065
+
1066
+ def _has_transparency(self, image):
1067
+ if image.info.get("transparency", None) is not None:
1068
+ return True
1069
+ if image.mode == "P":
1070
+ transparent = image.info.get("transparency", -1)
1071
+ for _, index in image.getcolors():
1072
+ if index == transparent:
1073
+ return True
1074
+ elif image.mode == "RGBA":
1075
+ extrema = image.getextrema()
1076
+ if extrema[3][0] < 255:
1077
+ return True
1078
+ return False
1079
+
1080
+ def _check_for_erasure(self, image:Image.Image)->bool:
1081
+ if image.mode not in ('RGBA','RGB'):
1082
+ return False
1083
+ width, height = image.size
1084
+ pixdata = image.load()
1085
+ colored = 0
1086
+ for y in range(height):
1087
+ for x in range(width):
1088
+ if pixdata[x, y][3] == 0:
1089
+ r, g, b, _ = pixdata[x, y]
1090
+ if (r, g, b) != (0, 0, 0) and \
1091
+ (r, g, b) != (255, 255, 255):
1092
+ colored += 1
1093
+ return colored == 0
1094
+
1095
+ def _transparency_check_and_warning(self,image, mask, force_outpaint=False):
1096
+ if not mask:
1097
+ print(
1098
+ '>> Initial image has transparent areas. Will inpaint in these regions.')
1099
+ if (not force_outpaint) and self._check_for_erasure(image):
1100
+ print(
1101
+ '>> WARNING: Colors underneath the transparent region seem to have been erased.\n',
1102
+ '>> Inpainting will be suboptimal. Please preserve the colors when making\n',
1103
+ '>> a transparency mask, or provide mask explicitly using --init_mask (-M).'
1104
+ )
1105
+
1106
+ def _squeeze_image(self, image):
1107
+ x, y, resize_needed = self._resolution_check(image.width, image.height)
1108
+ if resize_needed:
1109
+ return InitImageResizer(image).resize(x, y)
1110
+ return image
1111
+
1112
+ def _fit_image(self, image, max_dimensions):
1113
+ w, h = max_dimensions
1114
+ print(
1115
+ f'>> image will be resized to fit inside a box {w}x{h} in size.'
1116
+ )
1117
+ # note that InitImageResizer does the multiple of 64 truncation internally
1118
+ image = InitImageResizer(image).resize(width=w, height=h)
1119
+ print(
1120
+ f'>> after adjusting image dimensions to be multiples of 64, init image is {image.width}x{image.height}'
1121
+ )
1122
+ return image
1123
+
1124
+ def _resolution_check(self, width, height, log=False):
1125
+ resize_needed = False
1126
+ w, h = map(
1127
+ lambda x: x - x % 64, (width, height)
1128
+ ) # resize to integer multiple of 64
1129
+ if h != height or w != width:
1130
+ if log:
1131
+ print(
1132
+ f'>> Provided width and height must be multiples of 64. Auto-resizing to {w}x{h}'
1133
+ )
1134
+ height = h
1135
+ width = w
1136
+ resize_needed = True
1137
+ return width, height, resize_needed
1138
+
1139
+
1140
+ def _has_cuda(self):
1141
+ return self.device.type == 'cuda'
1142
+
1143
+ def write_intermediate_images(self,modulus,path):
1144
+ counter = -1
1145
+ if not os.path.exists(path):
1146
+ os.makedirs(path)
1147
+ def callback(img):
1148
+ nonlocal counter
1149
+ counter += 1
1150
+ if counter % modulus != 0:
1151
+ return;
1152
+ image = self.sample_to_image(img)
1153
+ image.save(os.path.join(path,f'{counter:03}.png'),'PNG')
1154
+ return callback
1155
+
1156
+ def _pairwise(iterable):
1157
+ "s -> (s0, s1), (s2, s3), (s4, s5), ..."
1158
+ a = iter(iterable)
1159
+ return zip(a, a)