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,797 @@
1
+ #!/usr/bin/env python
2
+ # Copyright (c) 2022 Lincoln D. Stein (https://github.com/lstein)
3
+ # Before running stable-diffusion on an internet-isolated machine,
4
+ # run this script from one with internet connectivity. The
5
+ # two machines must share a common .cache directory.
6
+ #
7
+ # Coauthor: Kevin Turner http://github.com/keturn
8
+ #
9
+ print('Loading Python libraries...\n')
10
+ import argparse
11
+ import sys
12
+ import os
13
+ import io
14
+ import re
15
+ import warnings
16
+ import shutil
17
+ from urllib import request
18
+ from tqdm import tqdm
19
+ from omegaconf import OmegaConf
20
+ from huggingface_hub import HfFolder, hf_hub_url, login as hf_hub_login
21
+ from pathlib import Path
22
+ from typing import Union
23
+ from getpass_asterisk import getpass_asterisk
24
+ from transformers import CLIPTokenizer, CLIPTextModel
25
+ from ldm.invoke.globals import Globals
26
+ from ldm.invoke.readline import generic_completer
27
+
28
+ import traceback
29
+ import requests
30
+ import transformers
31
+ import warnings
32
+ warnings.filterwarnings('ignore')
33
+ import torch
34
+ transformers.logging.set_verbosity_error()
35
+
36
+ #--------------------------globals-----------------------
37
+ Model_dir = 'models'
38
+ Weights_dir = 'ldm/stable-diffusion-v1/'
39
+ Dataset_path = './configs/INITIAL_MODELS.yaml'
40
+ Default_config_file = './configs/models.yaml'
41
+ SD_Configs = './configs/stable-diffusion'
42
+
43
+ assert os.path.exists(Dataset_path),"The configs directory cannot be found. Please run this script from within the invokeai runtime directory."
44
+
45
+ Datasets = OmegaConf.load(Dataset_path)
46
+ completer = generic_completer(['yes','no'])
47
+
48
+ Config_preamble = '''# This file describes the alternative machine learning models
49
+ # available to InvokeAI script.
50
+ #
51
+ # To add a new model, follow the examples below. Each
52
+ # model requires a model config file, a weights file,
53
+ # and the width and height of the images it
54
+ # was trained on.
55
+ '''
56
+
57
+ #---------------------------------------------
58
+ def introduction():
59
+ print(
60
+ '''Welcome to InvokeAI. This script will help download the Stable Diffusion weight files
61
+ and other large models that are needed for text to image generation. At any point you may interrupt
62
+ this program and resume later.\n'''
63
+ )
64
+
65
+ #--------------------------------------------
66
+ def postscript(errors: None):
67
+ if not any(errors):
68
+ message='''
69
+ ** Model Installation Successful **
70
+
71
+ You're all set!
72
+
73
+ If you installed using one of the automated installation scripts,
74
+ execute 'invoke.sh' (Linux/macOS) or 'invoke.bat' (Windows) to
75
+ start InvokeAI.
76
+
77
+ If you installed manually, activate the 'invokeai' environment
78
+ (e.g. 'conda activate invokeai'), then run one of the following
79
+ commands to start InvokeAI.
80
+
81
+ Web UI:
82
+ python scripts/invoke.py --web # (connect to http://localhost:9090)
83
+ Command-line interface:
84
+ python scripts/invoke.py
85
+
86
+ Have fun!
87
+ '''
88
+
89
+ else:
90
+ message=f"\n** There were errors during installation. It is possible some of the models were not fully downloaded.\n"
91
+ for err in errors:
92
+ message += f"\t - {err}\n"
93
+ message += "Please check the logs above and correct any issues."
94
+
95
+ print(message)
96
+
97
+ #---------------------------------------------
98
+ def yes_or_no(prompt:str, default_yes=True):
99
+ completer.set_options(['yes','no'])
100
+ completer.complete_extensions(None) # turn off path-completion mode
101
+ default = "y" if default_yes else 'n'
102
+ response = input(f'{prompt} [{default}] ') or default
103
+ if default_yes:
104
+ return response[0] not in ('n','N')
105
+ else:
106
+ return response[0] in ('y','Y')
107
+
108
+ #---------------------------------------------
109
+ def user_wants_to_download_weights()->str:
110
+ '''
111
+ Returns one of "skip", "recommended" or "customized"
112
+ '''
113
+ print('''You can download and configure the weights files manually or let this
114
+ script do it for you. Manual installation is described at:
115
+
116
+ https://invoke-ai.github.io/InvokeAI/installation/020_INSTALL_MANUAL/
117
+
118
+ You may download the recommended models (about 10GB total), select a customized set, or
119
+ completely skip this step.
120
+ '''
121
+ )
122
+ completer.set_options(['recommended','customized','skip'])
123
+ completer.complete_extensions(None) # turn off path-completion mode
124
+ selection = None
125
+ while selection is None:
126
+ choice = input('Download <r>ecommended models, <a>ll models, <c>ustomized list, or <s>kip this step? [r]: ')
127
+ if choice.startswith(('r','R')) or len(choice)==0:
128
+ selection = 'recommended'
129
+ elif choice.startswith(('c','C')):
130
+ selection = 'customized'
131
+ elif choice.startswith(('a','A')):
132
+ selection = 'all'
133
+ elif choice.startswith(('s','S')):
134
+ selection = 'skip'
135
+ return selection
136
+
137
+ #---------------------------------------------
138
+ def select_datasets(action:str):
139
+ done = False
140
+ while not done:
141
+ datasets = dict()
142
+ dflt = None # the first model selected will be the default; TODO let user change
143
+ counter = 1
144
+
145
+ if action == 'customized':
146
+ print('''
147
+ Choose the weight file(s) you wish to download. Before downloading you
148
+ will be given the option to view and change your selections.
149
+ '''
150
+ )
151
+ for ds in Datasets.keys():
152
+ recommended = '(recommended)' if Datasets[ds]['recommended'] else ''
153
+ print(f'[{counter}] {ds}:\n {Datasets[ds]["description"]} {recommended}')
154
+ if yes_or_no(' Download?',default_yes=Datasets[ds]['recommended']):
155
+ datasets[ds]=counter
156
+ counter += 1
157
+ else:
158
+ for ds in Datasets.keys():
159
+ if Datasets[ds]['recommended']:
160
+ datasets[ds]=counter
161
+ counter += 1
162
+
163
+ print('The following weight files will be downloaded:')
164
+ for ds in datasets:
165
+ dflt = '*' if dflt is None else ''
166
+ print(f' [{datasets[ds]}] {ds}{dflt}')
167
+ print("*default")
168
+ ok_to_download = yes_or_no('Ok to download?')
169
+ if not ok_to_download:
170
+ if yes_or_no('Change your selection?'):
171
+ action = 'customized'
172
+ pass
173
+ else:
174
+ done = True
175
+ else:
176
+ done = True
177
+ return datasets if ok_to_download else None
178
+
179
+ #---------------------------------------------
180
+ def recommended_datasets()->dict:
181
+ datasets = dict()
182
+ for ds in Datasets.keys():
183
+ if Datasets[ds]['recommended']:
184
+ datasets[ds]=True
185
+ return datasets
186
+
187
+ #---------------------------------------------
188
+ def all_datasets()->dict:
189
+ datasets = dict()
190
+ for ds in Datasets.keys():
191
+ datasets[ds]=True
192
+ return datasets
193
+
194
+ #---------------------------------------------
195
+ def HfLogin(access_token) -> str:
196
+ """
197
+ Helper for logging in to Huggingface
198
+ The stdout capture is needed to hide the irrelevant "git credential helper" warning
199
+ """
200
+
201
+ capture = io.StringIO()
202
+ sys.stdout = capture
203
+ try:
204
+ hf_hub_login(token = access_token, add_to_git_credential=False)
205
+ sys.stdout = sys.__stdout__
206
+ except Exception as exc:
207
+ sys.stdout = sys.__stdout__
208
+ print(exc)
209
+ raise exc
210
+
211
+ #-------------------------------Authenticate against Hugging Face
212
+ def authenticate(yes_to_all=False):
213
+ print('** LICENSE AGREEMENT FOR WEIGHT FILES **')
214
+ print("=" * shutil.get_terminal_size()[0])
215
+ print('''
216
+ By downloading the Stable Diffusion weight files from the official Hugging Face
217
+ repository, you agree to have read and accepted the CreativeML Responsible AI License.
218
+ The license terms are located here:
219
+
220
+ https://huggingface.co/spaces/CompVis/stable-diffusion-license
221
+
222
+ ''')
223
+ print("=" * shutil.get_terminal_size()[0])
224
+
225
+ if not yes_to_all:
226
+ accepted = False
227
+ while not accepted:
228
+ accepted = yes_or_no('Accept the above License terms?')
229
+ if not accepted:
230
+ print('Please accept the License or Ctrl+C to exit.')
231
+ else:
232
+ print('Thank you!')
233
+ else:
234
+ print("The program was started with a '--yes' flag, which indicates user's acceptance of the above License terms.")
235
+
236
+ # Authenticate to Huggingface using environment variables.
237
+ # If successful, authentication will persist for either interactive or non-interactive use.
238
+ # Default env var expected by HuggingFace is HUGGING_FACE_HUB_TOKEN.
239
+ print("=" * shutil.get_terminal_size()[0])
240
+ print('Authenticating to Huggingface')
241
+ hf_envvars = [ "HUGGING_FACE_HUB_TOKEN", "HUGGINGFACE_TOKEN" ]
242
+ if not (access_token := HfFolder.get_token()):
243
+ print(f"Huggingface token not found in cache.")
244
+
245
+ for ev in hf_envvars:
246
+ if (access_token := os.getenv(ev)):
247
+ print(f"Token was found in the {ev} environment variable.... Logging in.")
248
+ try:
249
+ HfLogin(access_token)
250
+ continue
251
+ except ValueError:
252
+ print(f"Login failed due to invalid token found in {ev}")
253
+ else:
254
+ print(f"Token was not found in the environment variable {ev}.")
255
+ else:
256
+ print(f"Huggingface token found in cache.")
257
+ try:
258
+ HfLogin(access_token)
259
+ except ValueError:
260
+ print(f"Login failed due to invalid token found in cache")
261
+
262
+ if not yes_to_all:
263
+ print('''
264
+ You may optionally enter your Huggingface token now. InvokeAI *will* work without it, but some functionality may be limited.
265
+ See https://invoke-ai.github.io/InvokeAI/features/CONCEPTS/#using-a-hugging-face-concept for more information.
266
+
267
+ Visit https://huggingface.co/settings/tokens to generate a token. (Sign up for an account if needed).
268
+
269
+ Paste the token below using Ctrl-Shift-V (macOS/Linux) or right-click (Windows), and/or 'Enter' to continue.
270
+ You may re-run the configuration script again in the future if you do not wish to set the token right now.
271
+ ''')
272
+ again = True
273
+ while again:
274
+ try:
275
+ access_token = getpass_asterisk.getpass_asterisk(prompt="HF Token ⮞ ")
276
+ HfLogin(access_token)
277
+ access_token = HfFolder.get_token()
278
+ again = False
279
+ except ValueError:
280
+ again = yes_or_no('Failed to log in to Huggingface. Would you like to try again?')
281
+ if not again:
282
+ print('\nRe-run the configuration script whenever you wish to set the token.')
283
+ print('...Continuing...')
284
+ except EOFError:
285
+ # this happens if the user pressed Enter on the prompt without any input; assume this means they don't want to input a token
286
+ # safety net needed against accidental "Enter"?
287
+ print("None provided - continuing")
288
+ again = False
289
+
290
+ elif access_token is None:
291
+ print()
292
+ print("HuggingFace login did not succeed. Some functionality may be limited; see https://invoke-ai.github.io/InvokeAI/features/CONCEPTS/#using-a-hugging-face-concept for more information")
293
+ print()
294
+ print(f"Re-run the configuration script without '--yes' to set the HuggingFace token interactively, or use one of the environment variables: {', '.join(hf_envvars)}")
295
+
296
+ print("=" * shutil.get_terminal_size()[0])
297
+
298
+ return access_token
299
+
300
+ #---------------------------------------------
301
+ # look for legacy model.ckpt in models directory and offer to
302
+ # normalize its name
303
+ def migrate_models_ckpt():
304
+ model_path = os.path.join(Globals.root,Model_dir,Weights_dir)
305
+ if not os.path.exists(os.path.join(model_path,'model.ckpt')):
306
+ return
307
+ new_name = Datasets['stable-diffusion-1.4']['file']
308
+ print('You seem to have the Stable Diffusion v4.1 "model.ckpt" already installed.')
309
+ rename = yes_or_no(f'Ok to rename it to "{new_name}" for future reference?')
310
+ if rename:
311
+ print(f'model.ckpt => {new_name}')
312
+ os.replace(os.path.join(model_path,'model.ckpt'),os.path.join(model_path,new_name))
313
+
314
+ #---------------------------------------------
315
+ def download_weight_datasets(models:dict, access_token:str):
316
+ migrate_models_ckpt()
317
+ successful = dict()
318
+ for mod in models.keys():
319
+ repo_id = Datasets[mod]['repo_id']
320
+ filename = Datasets[mod]['file']
321
+ dest = os.path.join(Globals.root,Model_dir,Weights_dir)
322
+ success = hf_download_with_resume(
323
+ repo_id=repo_id,
324
+ model_dir=dest,
325
+ model_name=filename,
326
+ access_token=access_token
327
+ )
328
+ if success:
329
+ successful[mod] = True
330
+ if len(successful) < len(models):
331
+ print(f'\n\n** There were errors downloading one or more files. **')
332
+ print('Press any key to try again. Type ^C to quit.\n')
333
+ input()
334
+ return None
335
+
336
+ keys = ', '.join(successful.keys())
337
+ print(f'Successfully installed {keys}')
338
+ return successful
339
+
340
+ #---------------------------------------------
341
+ def hf_download_with_resume(repo_id:str, model_dir:str, model_name:str, access_token:str=None)->bool:
342
+ model_dest = os.path.join(model_dir, model_name)
343
+ os.makedirs(model_dir, exist_ok=True)
344
+
345
+ url = hf_hub_url(repo_id, model_name)
346
+
347
+ header = {"Authorization": f'Bearer {access_token}'} if access_token else {}
348
+ open_mode = 'wb'
349
+ exist_size = 0
350
+
351
+ if os.path.exists(model_dest):
352
+ exist_size = os.path.getsize(model_dest)
353
+ header['Range'] = f'bytes={exist_size}-'
354
+ open_mode = 'ab'
355
+
356
+ resp = requests.get(url, headers=header, stream=True)
357
+ total = int(resp.headers.get('content-length', 0))
358
+
359
+ if resp.status_code==416: # "range not satisfiable", which means nothing to return
360
+ print(f'* {model_name}: complete file found. Skipping.')
361
+ return True
362
+ elif resp.status_code != 200:
363
+ print(f'** An error occurred during downloading {model_name}: {resp.reason}')
364
+ elif exist_size > 0:
365
+ print(f'* {model_name}: partial file found. Resuming...')
366
+ else:
367
+ print(f'* {model_name}: Downloading...')
368
+
369
+ try:
370
+ if total < 2000:
371
+ print(f'*** ERROR DOWNLOADING {model_name}: {resp.text}')
372
+ return False
373
+
374
+ with open(model_dest, open_mode) as file, tqdm(
375
+ desc=model_name,
376
+ initial=exist_size,
377
+ total=total+exist_size,
378
+ unit='iB',
379
+ unit_scale=True,
380
+ unit_divisor=1000,
381
+ ) as bar:
382
+ for data in resp.iter_content(chunk_size=1024):
383
+ size = file.write(data)
384
+ bar.update(size)
385
+ except Exception as e:
386
+ print(f'An error occurred while downloading {model_name}: {str(e)}')
387
+ return False
388
+ return True
389
+
390
+ #---------------------------------------------
391
+ def download_with_progress_bar(model_url:str, model_dest:str, label:str='the'):
392
+ try:
393
+ print(f'Installing {label} model file {model_url}...',end='',file=sys.stderr)
394
+ if not os.path.exists(model_dest):
395
+ os.makedirs(os.path.dirname(model_dest), exist_ok=True)
396
+ print('',file=sys.stderr)
397
+ request.urlretrieve(model_url,model_dest,ProgressBar(os.path.basename(model_dest)))
398
+ print('...downloaded successfully', file=sys.stderr)
399
+ else:
400
+ print('...exists', file=sys.stderr)
401
+ except Exception:
402
+ print('...download failed')
403
+ print(f'Error downloading {label} model')
404
+ print(traceback.format_exc())
405
+
406
+
407
+ #---------------------------------------------
408
+ def update_config_file(successfully_downloaded:dict,opt:dict):
409
+ config_file = opt.config_file or Default_config_file
410
+ config_file = os.path.normpath(os.path.join(Globals.root,config_file))
411
+
412
+ yaml = new_config_file_contents(successfully_downloaded,config_file)
413
+
414
+ try:
415
+ if os.path.exists(config_file):
416
+ print(f'** {config_file} exists. Renaming to {config_file}.orig')
417
+ os.replace(config_file,f'{config_file}.orig')
418
+ tmpfile = os.path.join(os.path.dirname(config_file),'new_config.tmp')
419
+ with open(tmpfile, 'w') as outfile:
420
+ outfile.write(Config_preamble)
421
+ outfile.write(yaml)
422
+ os.replace(tmpfile,config_file)
423
+
424
+ except Exception as e:
425
+ print(f'**Error creating config file {config_file}: {str(e)} **')
426
+ return
427
+
428
+ print(f'Successfully created new configuration file {config_file}')
429
+
430
+
431
+ #---------------------------------------------
432
+ def new_config_file_contents(successfully_downloaded:dict, config_file:str)->str:
433
+ if os.path.exists(config_file):
434
+ conf = OmegaConf.load(config_file)
435
+ else:
436
+ conf = OmegaConf.create()
437
+
438
+ # find the VAE file, if there is one
439
+ vaes = {}
440
+ default_selected = False
441
+
442
+ for model in successfully_downloaded:
443
+ a = Datasets[model]['config'].split('/')
444
+ if a[0] != 'VAE':
445
+ continue
446
+ vae_target = a[1] if len(a)>1 else 'default'
447
+ vaes[vae_target] = Datasets[model]['file']
448
+
449
+ for model in successfully_downloaded:
450
+ if Datasets[model]['config'].startswith('VAE'): # skip VAE entries
451
+ continue
452
+ stanza = conf[model] if model in conf else { }
453
+
454
+ stanza['description'] = Datasets[model]['description']
455
+ stanza['weights'] = os.path.join(Model_dir,Weights_dir,Datasets[model]['file'])
456
+ stanza['config'] = os.path.normpath(os.path.join(SD_Configs, Datasets[model]['config']))
457
+ stanza['width'] = Datasets[model]['width']
458
+ stanza['height'] = Datasets[model]['height']
459
+ stanza.pop('default',None) # this will be set later
460
+ if vaes:
461
+ for target in vaes:
462
+ if re.search(target, model, flags=re.IGNORECASE):
463
+ stanza['vae'] = os.path.normpath(os.path.join(Model_dir,Weights_dir,vaes[target]))
464
+ else:
465
+ stanza['vae'] = os.path.normpath(os.path.join(Model_dir,Weights_dir,vaes['default']))
466
+ # BUG - the first stanza is always the default. User should select.
467
+ if not default_selected:
468
+ stanza['default'] = True
469
+ default_selected = True
470
+ conf[model] = stanza
471
+ return OmegaConf.to_yaml(conf)
472
+
473
+ #---------------------------------------------
474
+ # this will preload the Bert tokenizer fles
475
+ def download_bert():
476
+ print('Installing bert tokenizer (ignore deprecation errors)...', end='',file=sys.stderr)
477
+ with warnings.catch_warnings():
478
+ warnings.filterwarnings('ignore', category=DeprecationWarning)
479
+ from transformers import BertTokenizerFast, AutoFeatureExtractor
480
+ download_from_hf(BertTokenizerFast,'bert-base-uncased')
481
+ print('...success',file=sys.stderr)
482
+
483
+ #---------------------------------------------
484
+ def download_from_hf(model_class:object, model_name:str):
485
+ print('',file=sys.stderr) # to prevent tqdm from overwriting
486
+ return model_class.from_pretrained(model_name,
487
+ cache_dir=os.path.join(Globals.root,Model_dir,model_name),
488
+ resume_download=True
489
+ )
490
+
491
+ #---------------------------------------------
492
+ def download_clip():
493
+ print('Installing CLIP model (ignore deprecation errors)...',file=sys.stderr)
494
+ version = 'openai/clip-vit-large-patch14'
495
+ print('Tokenizer...',file=sys.stderr, end='')
496
+ download_from_hf(CLIPTokenizer,version)
497
+ print('Text model...',file=sys.stderr, end='')
498
+ download_from_hf(CLIPTextModel,version)
499
+ print('...success',file=sys.stderr)
500
+
501
+ #---------------------------------------------
502
+ def download_realesrgan():
503
+ print('Installing models from RealESRGAN...',file=sys.stderr)
504
+ model_url = 'https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth'
505
+ model_dest = os.path.join(Globals.root,'models/realesrgan/realesr-general-x4v3.pth')
506
+ download_with_progress_bar(model_url, model_dest, 'RealESRGAN')
507
+
508
+ def download_gfpgan():
509
+ print('Installing GFPGAN models...',file=sys.stderr)
510
+ for model in (
511
+ [
512
+ 'https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth',
513
+ './models/gfpgan/GFPGANv1.4.pth'
514
+ ],
515
+ [
516
+ 'https://github.com/xinntao/facexlib/releases/download/v0.1.0/detection_Resnet50_Final.pth',
517
+ './models/gfpgan/weights/detection_Resnet50_Final.pth'
518
+ ],
519
+ [
520
+ 'https://github.com/xinntao/facexlib/releases/download/v0.2.2/parsing_parsenet.pth',
521
+ './models/gfpgan/weights/parsing_parsenet.pth'
522
+ ],
523
+ ):
524
+ model_url,model_dest = model[0],os.path.join(Globals.root,model[1])
525
+ download_with_progress_bar(model_url, model_dest, 'GFPGAN weights')
526
+
527
+ #---------------------------------------------
528
+ def download_codeformer():
529
+ print('Installing CodeFormer model file...',file=sys.stderr)
530
+ model_url = 'https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth'
531
+ model_dest = os.path.join(Globals.root,'models/codeformer/codeformer.pth')
532
+ download_with_progress_bar(model_url, model_dest, 'CodeFormer')
533
+
534
+ #---------------------------------------------
535
+ def download_clipseg():
536
+ print('Installing clipseg model for text-based masking...',end='', file=sys.stderr)
537
+ import zipfile
538
+ try:
539
+ model_url = 'https://owncloud.gwdg.de/index.php/s/ioHbRzFx6th32hn/download'
540
+ model_dest = os.path.join(Globals.root,'models/clipseg/clipseg_weights')
541
+ weights_zip = 'models/clipseg/weights.zip'
542
+
543
+ if not os.path.exists(model_dest):
544
+ os.makedirs(os.path.dirname(model_dest), exist_ok=True)
545
+ if not os.path.exists(f'{model_dest}/rd64-uni-refined.pth'):
546
+ dest = os.path.join(Globals.root,weights_zip)
547
+ request.urlretrieve(model_url,dest)
548
+ with zipfile.ZipFile(dest,'r') as zip:
549
+ zip.extractall(os.path.join(Globals.root,'models/clipseg'))
550
+ os.remove(dest)
551
+
552
+ from vendored.clipseg.models.clipseg import CLIPDensePredT
553
+ model = CLIPDensePredT(version='ViT-B/16', reduce_dim=64, )
554
+ model.eval()
555
+ model.load_state_dict(
556
+ torch.load(
557
+ os.path.join(Globals.root,'models/clipseg/clipseg_weights/rd64-uni-refined.pth'),
558
+ map_location=torch.device('cpu')
559
+ ),
560
+ strict=False,
561
+ )
562
+ except Exception:
563
+ print('Error installing clipseg model:')
564
+ print(traceback.format_exc())
565
+ print('...success',file=sys.stderr)
566
+
567
+ #-------------------------------------
568
+ def download_safety_checker():
569
+ print('Installing model for NSFW content detection...',file=sys.stderr)
570
+ try:
571
+ from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
572
+ from transformers import AutoFeatureExtractor
573
+ except ModuleNotFoundError:
574
+ print('Error installing NSFW checker model:')
575
+ print(traceback.format_exc())
576
+ return
577
+ safety_model_id = "CompVis/stable-diffusion-safety-checker"
578
+ print('AutoFeatureExtractor...', end='',file=sys.stderr)
579
+ download_from_hf(AutoFeatureExtractor,safety_model_id)
580
+ print('StableDiffusionSafetyChecker...', end='',file=sys.stderr)
581
+ download_from_hf(StableDiffusionSafetyChecker,safety_model_id)
582
+ print('...success',file=sys.stderr)
583
+
584
+ #-------------------------------------
585
+ def download_weights(opt:dict) -> Union[str, None]:
586
+
587
+ if opt.yes_to_all:
588
+ models = recommended_datasets()
589
+ access_token = authenticate(opt.yes_to_all)
590
+ if len(models)>0:
591
+ successfully_downloaded = download_weight_datasets(models, access_token)
592
+ update_config_file(successfully_downloaded,opt)
593
+ return
594
+
595
+ else:
596
+ choice = user_wants_to_download_weights()
597
+
598
+ if choice == 'recommended':
599
+ models = recommended_datasets()
600
+ elif choice == 'all':
601
+ models = all_datasets()
602
+ elif choice == 'customized':
603
+ models = select_datasets(choice)
604
+ if models is None and yes_or_no('Quit?',default_yes=False):
605
+ sys.exit(0)
606
+ else: # 'skip'
607
+ return
608
+
609
+
610
+ access_token = authenticate()
611
+
612
+ print('\n** DOWNLOADING WEIGHTS **')
613
+ successfully_downloaded = download_weight_datasets(models, access_token)
614
+
615
+ update_config_file(successfully_downloaded,opt)
616
+ if len(successfully_downloaded) < len(models):
617
+ return "some of the model weights downloads were not successful"
618
+
619
+ #-------------------------------------
620
+ def get_root(root:str=None)->str:
621
+ if root:
622
+ return root
623
+ elif os.environ.get('INVOKEAI_ROOT'):
624
+ return os.environ.get('INVOKEAI_ROOT')
625
+ else:
626
+ return Globals.root
627
+
628
+ #-------------------------------------
629
+ def select_root(root:str, yes_to_all:bool=False):
630
+ default = root or os.path.expanduser('~/invokeai')
631
+ if (yes_to_all):
632
+ return default
633
+ completer.set_default_dir(default)
634
+ completer.complete_extensions(())
635
+ completer.set_line(default)
636
+ directory = input(f"Select a directory in which to install InvokeAI's models and configuration files [{default}]: ").strip(' \\')
637
+ return directory or default
638
+
639
+ #-------------------------------------
640
+ def select_outputs(root:str,yes_to_all:bool=False):
641
+ default = os.path.normpath(os.path.join(root,'outputs'))
642
+ if (yes_to_all):
643
+ return default
644
+ completer.set_default_dir(os.path.expanduser('~'))
645
+ completer.complete_extensions(())
646
+ completer.set_line(default)
647
+ directory = input(f'Select the default directory for image outputs [{default}]: ').strip(' \\')
648
+ return directory or default
649
+
650
+ #-------------------------------------
651
+ def initialize_rootdir(root:str,yes_to_all:bool=False):
652
+ assert os.path.exists('./configs'),'Run this script from within the InvokeAI source code directory, "InvokeAI" or the runtime directory "invokeai".'
653
+
654
+ print(f'** INITIALIZING INVOKEAI RUNTIME DIRECTORY **')
655
+ root_selected = False
656
+ while not root_selected:
657
+ outputs = select_outputs(root,yes_to_all)
658
+ outputs = outputs if os.path.isabs(outputs) else os.path.abspath(os.path.join(Globals.root,outputs))
659
+
660
+ print(f'\nInvokeAI image outputs will be placed into "{outputs}".')
661
+ if not yes_to_all:
662
+ root_selected = yes_or_no('Accept this location?')
663
+ else:
664
+ root_selected = True
665
+
666
+ print(f'\nYou may change the chosen output directory at any time by editing the --outdir options in "{Globals.initfile}",')
667
+ print(f'You may also change the runtime directory by setting the environment variable INVOKEAI_ROOT.\n')
668
+
669
+ enable_safety_checker = True
670
+ if not yes_to_all:
671
+ print('The NSFW (not safe for work) checker blurs out images that potentially contain sexual imagery.')
672
+ print('It can be selectively enabled at run time with --nsfw_checker, and disabled with --no-nsfw_checker.')
673
+ print('The following option will set whether the checker is enabled by default. Like other options, you can')
674
+ print(f'change this setting later by editing the file {Globals.initfile}.')
675
+ print(f"This is NOT recommended for systems with less than 6G VRAM because of the checker's memory requirements.")
676
+ enable_safety_checker = yes_or_no('Enable the NSFW checker by default?',enable_safety_checker)
677
+
678
+ safety_checker = '--nsfw_checker' if enable_safety_checker else '--no-nsfw_checker'
679
+
680
+ for name in ('models','configs','embeddings'):
681
+ os.makedirs(os.path.join(root,name), exist_ok=True)
682
+ for src in (['configs']):
683
+ dest = os.path.join(root,src)
684
+ if not os.path.samefile(src,dest):
685
+ shutil.copytree(src,dest,dirs_exist_ok=True)
686
+ os.makedirs(outputs, exist_ok=True)
687
+
688
+ init_file = os.path.join(Globals.root,Globals.initfile)
689
+
690
+ print(f'Creating the initialization file at "{init_file}".\n')
691
+ with open(init_file,'w') as f:
692
+ f.write(f'''# InvokeAI initialization file
693
+ # This is the InvokeAI initialization file, which contains command-line default values.
694
+ # Feel free to edit. If anything goes wrong, you can re-initialize this file by deleting
695
+ # or renaming it and then running configure_invokeai.py again.
696
+
697
+ # the --outdir option controls the default location of image files.
698
+ --outdir="{outputs}"
699
+
700
+ # generation arguments
701
+ {safety_checker}
702
+
703
+ # You may place other frequently-used startup commands here, one or more per line.
704
+ # Examples:
705
+ # --web --host=0.0.0.0
706
+ # --steps=20
707
+ # -Ak_euler_a -C10.0
708
+ #
709
+ ''')
710
+
711
+ #-------------------------------------
712
+ class ProgressBar():
713
+ def __init__(self,model_name='file'):
714
+ self.pbar = None
715
+ self.name = model_name
716
+
717
+ def __call__(self, block_num, block_size, total_size):
718
+ if not self.pbar:
719
+ self.pbar=tqdm(desc=self.name,
720
+ initial=0,
721
+ unit='iB',
722
+ unit_scale=True,
723
+ unit_divisor=1000,
724
+ total=total_size)
725
+ self.pbar.update(block_size)
726
+
727
+ #-------------------------------------
728
+ def main():
729
+ parser = argparse.ArgumentParser(description='InvokeAI model downloader')
730
+ parser.add_argument('--interactive',
731
+ dest='interactive',
732
+ action=argparse.BooleanOptionalAction,
733
+ default=True,
734
+ help='run in interactive mode (default) - DEPRECATED')
735
+ parser.add_argument('--skip-sd-weights',
736
+ dest='skip_sd_weights',
737
+ action=argparse.BooleanOptionalAction,
738
+ default=False,
739
+ help='skip downloading the large Stable Diffusion weight files')
740
+ parser.add_argument('--yes','-y',
741
+ dest='yes_to_all',
742
+ action='store_true',
743
+ help='answer "yes" to all prompts')
744
+ parser.add_argument('--config_file',
745
+ '-c',
746
+ dest='config_file',
747
+ type=str,
748
+ default='./configs/models.yaml',
749
+ help='path to configuration file to create')
750
+ parser.add_argument('--root_dir',
751
+ dest='root',
752
+ type=str,
753
+ default=None,
754
+ help='path to root of install directory')
755
+ opt = parser.parse_args()
756
+
757
+
758
+ # setting a global here
759
+ Globals.root = os.path.expanduser(get_root(opt.root) or '')
760
+
761
+ try:
762
+ introduction()
763
+
764
+ # We check for to see if the runtime directory is correctly initialized.
765
+ if Globals.root == '' \
766
+ or not os.path.exists(os.path.join(Globals.root,'invokeai.init')):
767
+ initialize_rootdir(Globals.root,opt.yes_to_all)
768
+
769
+ # Optimistically try to download all required assets. If any errors occur, add them and proceed anyway.
770
+ errors=set()
771
+
772
+ if not opt.interactive:
773
+ print("WARNING: The --(no)-interactive argument is deprecated and will be removed. Use --skip-sd-weights.")
774
+ opt.skip_sd_weights=True
775
+ if opt.skip_sd_weights:
776
+ print('** SKIPPING DIFFUSION WEIGHTS DOWNLOAD PER USER REQUEST **')
777
+ else:
778
+ print('** DOWNLOADING DIFFUSION WEIGHTS **')
779
+ errors.add(download_weights(opt))
780
+ print('\n** DOWNLOADING SUPPORT MODELS **')
781
+ download_bert()
782
+ download_clip()
783
+ download_realesrgan()
784
+ download_gfpgan()
785
+ download_codeformer()
786
+ download_clipseg()
787
+ download_safety_checker()
788
+ postscript(errors=errors)
789
+ except KeyboardInterrupt:
790
+ print('\nGoodbye! Come back soon.')
791
+ except Exception as e:
792
+ print(f'\nA problem occurred during initialization.\nThe error was: "{str(e)}"')
793
+ print(traceback.format_exc())
794
+
795
+ #-------------------------------------
796
+ if __name__ == '__main__':
797
+ main()