johnslegers commited on
Commit
9643009
1 Parent(s): 121f6d3
models/stable-diffusion/Put your custom ckpt files here.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
modules/app.py CHANGED
@@ -1,55 +1,329 @@
1
- import os
2
- import requests
3
  import json
4
- from io import BytesIO
 
 
 
 
 
 
5
 
6
- from fastapi import FastAPI
 
 
 
 
 
 
 
 
7
  from fastapi.staticfiles import StaticFiles
8
- from fastapi.responses import FileResponse, StreamingResponse
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- from modules.inference import infer_t5
11
- from modules.dataset import query_emotion
12
 
13
- # https://huggingface.co/settings/tokens
14
- # https://huggingface.co/spaces/{username}/{space}/settings
15
- API_TOKEN = os.getenv("AUTH_TOKEN")
16
- if not API_TOKEN:
17
- with open('/root/.huggingface/token') as f:
18
- lines = f.readlines()
19
- API_TOKEN = lines[0]
20
 
21
- app = FastAPI(docs_url=None, redoc_url=None)
 
 
22
 
23
- app.mount("/static", StaticFiles(directory="static"), name="static")
 
 
 
24
 
 
 
 
 
 
 
 
 
 
 
25
 
26
- @app.head("/")
27
- @app.get("/")
28
- def index() -> FileResponse:
29
- return FileResponse(path="static/index.html", media_type="text/html")
 
 
30
 
 
 
 
 
 
31
 
32
- @app.get("/infer_biggan")
33
- def biggan(input):
34
- output = requests.request(
35
- "POST",
36
- "https://api-inference.huggingface.co/models/osanseviero/BigGAN-deep-128",
37
- headers={"Authorization": f"Bearer {API_TOKEN}"},
38
- data=json.dumps(input),
39
- )
40
- #return json.dumps(output)
41
- return StreamingResponse(BytesIO(output.content), media_type="image/png")
42
 
 
43
 
44
- @app.get("/infer_t5")
45
- def t5(input):
46
- output = infer_t5(input)
 
47
 
48
- return {"output": output}
 
 
49
 
 
 
 
 
 
 
 
50
 
51
- @app.get("/query_emotion")
52
- def emotion(start, end):
53
- output = query_emotion(int(start), int(end))
54
 
55
- return {"output": output}
 
 
 
1
  import json
2
+ import traceback
3
+
4
+ import sys
5
+ import os
6
+
7
+ SD_DIR = os.getcwd()
8
+ print('started in ', SD_DIR)
9
 
10
+ SD_UI_DIR = './ui'
11
+ sys.path.append(os.path.dirname(SD_UI_DIR))
12
+
13
+ CONFIG_DIR = os.path.abspath(os.path.join(SD_UI_DIR, '..', 'scripts'))
14
+ MODELS_DIR = os.path.abspath(os.path.join(SD_DIR, '..', 'models'))
15
+
16
+ OUTPUT_DIRNAME = "Stable Diffusion UI" # in the user's home folder
17
+
18
+ from fastapi import FastAPI, HTTPException
19
  from fastapi.staticfiles import StaticFiles
20
+ from starlette.responses import FileResponse, StreamingResponse
21
+ from pydantic import BaseModel
22
+ import logging
23
+
24
+ from sd_internal import Request, Response
25
+
26
+ app = FastAPI()
27
+
28
+ model_loaded = False
29
+ model_is_loading = False
30
+
31
+ modifiers_cache = None
32
+ outpath = os.path.join(os.path.expanduser("~"), OUTPUT_DIRNAME)
33
+
34
+ # don't show access log entries for URLs that start with the given prefix
35
+ ACCESS_LOG_SUPPRESS_PATH_PREFIXES = ['/ping', '/modifier-thumbnails']
36
+
37
+ app.mount('/media', StaticFiles(directory=os.path.join(SD_UI_DIR, 'media/')), name="media")
38
+
39
+ # defaults from https://huggingface.co/blog/stable_diffusion
40
+ class ImageRequest(BaseModel):
41
+ session_id: str = "session"
42
+ prompt: str = ""
43
+ negative_prompt: str = ""
44
+ init_image: str = None # base64
45
+ mask: str = None # base64
46
+ num_outputs: int = 1
47
+ num_inference_steps: int = 50
48
+ guidance_scale: float = 7.5
49
+ width: int = 512
50
+ height: int = 512
51
+ seed: int = 42
52
+ prompt_strength: float = 0.8
53
+ sampler: str = None # "ddim", "plms", "heun", "euler", "euler_a", "dpm2", "dpm2_a", "lms"
54
+ # allow_nsfw: bool = False
55
+ save_to_disk_path: str = None
56
+ turbo: bool = True
57
+ use_cpu: bool = False
58
+ use_full_precision: bool = False
59
+ use_face_correction: str = None # or "GFPGANv1.3"
60
+ use_upscale: str = None # or "RealESRGAN_x4plus" or "RealESRGAN_x4plus_anime_6B"
61
+ use_stable_diffusion_model: str = "sd-v1-4"
62
+ show_only_filtered_image: bool = False
63
+ output_format: str = "jpeg" # or "png"
64
+
65
+ stream_progress_updates: bool = False
66
+ stream_image_progress: bool = False
67
+
68
+ class SetAppConfigRequest(BaseModel):
69
+ update_branch: str = "main"
70
+
71
+ @app.get('/')
72
+ def read_root():
73
+ headers = {"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0"}
74
+ return FileResponse(os.path.join(SD_UI_DIR, 'index.html'), headers=headers)
75
+
76
+ @app.get('/ping')
77
+ async def ping():
78
+ global model_loaded, model_is_loading
79
+
80
+ try:
81
+ if model_loaded:
82
+ return {'OK'}
83
+
84
+ if model_is_loading:
85
+ return {'ERROR'}
86
+
87
+ model_is_loading = True
88
+
89
+ import runtime
90
+
91
+ runtime.load_model_ckpt(ckpt_to_use=get_initial_model_to_load())
92
+
93
+ model_loaded = True
94
+ model_is_loading = False
95
+
96
+ return {'OK'}
97
+ except Exception as e:
98
+ print(traceback.format_exc())
99
+ return HTTPException(status_code=500, detail=str(e))
100
+
101
+ # needs to support the legacy installations
102
+ def get_initial_model_to_load():
103
+ custom_weight_path = os.path.join(SD_DIR, 'custom-model.ckpt')
104
+ ckpt_to_use = "sd-v1-4" if not os.path.exists(custom_weight_path) else "custom-model"
105
+
106
+ ckpt_to_use = os.path.join(SD_DIR, ckpt_to_use)
107
+
108
+ config = getConfig()
109
+ if 'model' in config and 'stable-diffusion' in config['model']:
110
+ model_name = config['model']['stable-diffusion']
111
+ model_path = resolve_model_to_use(model_name)
112
+
113
+ if os.path.exists(model_path + '.ckpt'):
114
+ ckpt_to_use = model_path
115
+ else:
116
+ print('Could not find the configured custom model at:', model_path + '.ckpt', '. Using the default one:', ckpt_to_use + '.ckpt')
117
+
118
+ return ckpt_to_use
119
+
120
+ def resolve_model_to_use(model_name):
121
+ if model_name in ('sd-v1-4', 'custom-model'):
122
+ model_path = os.path.join(MODELS_DIR, 'stable-diffusion', model_name)
123
+
124
+ legacy_model_path = os.path.join(SD_DIR, model_name)
125
+ if not os.path.exists(model_path + '.ckpt') and os.path.exists(legacy_model_path + '.ckpt'):
126
+ model_path = legacy_model_path
127
+ else:
128
+ model_path = os.path.join(MODELS_DIR, 'stable-diffusion', model_name)
129
+
130
+ return model_path
131
+
132
+ def save_model_to_config(model_name):
133
+ config = getConfig()
134
+ if 'model' not in config:
135
+ config['model'] = {}
136
+
137
+ config['model']['stable-diffusion'] = model_name
138
+
139
+ setConfig(config)
140
+
141
+ @app.post('/image')
142
+ def image(req : ImageRequest):
143
+ import runtime
144
+
145
+ r = Request()
146
+ r.session_id = req.session_id
147
+ r.prompt = req.prompt
148
+ r.negative_prompt = req.negative_prompt
149
+ r.init_image = req.init_image
150
+ r.mask = req.mask
151
+ r.num_outputs = req.num_outputs
152
+ r.num_inference_steps = req.num_inference_steps
153
+ r.guidance_scale = req.guidance_scale
154
+ r.width = req.width
155
+ r.height = req.height
156
+ r.seed = req.seed
157
+ r.prompt_strength = req.prompt_strength
158
+ r.sampler = req.sampler
159
+ # r.allow_nsfw = req.allow_nsfw
160
+ r.turbo = req.turbo
161
+ r.use_cpu = req.use_cpu
162
+ r.use_full_precision = req.use_full_precision
163
+ r.save_to_disk_path = req.save_to_disk_path
164
+ r.use_upscale: str = req.use_upscale
165
+ r.use_face_correction = req.use_face_correction
166
+ r.show_only_filtered_image = req.show_only_filtered_image
167
+ r.output_format = req.output_format
168
+
169
+ r.stream_progress_updates = True # the underlying implementation only supports streaming
170
+ r.stream_image_progress = req.stream_image_progress
171
+
172
+ r.use_stable_diffusion_model = resolve_model_to_use(req.use_stable_diffusion_model)
173
+
174
+ save_model_to_config(req.use_stable_diffusion_model)
175
+
176
+ try:
177
+ if not req.stream_progress_updates:
178
+ r.stream_image_progress = False
179
+
180
+ res = runtime.mk_img(r)
181
+
182
+ if req.stream_progress_updates:
183
+ return StreamingResponse(res, media_type='application/json')
184
+ else: # compatibility mode: buffer the streaming responses, and return the last one
185
+ last_result = None
186
+
187
+ for result in res:
188
+ last_result = result
189
+
190
+ return json.loads(last_result)
191
+ except Exception as e:
192
+ print(traceback.format_exc())
193
+ return HTTPException(status_code=500, detail=str(e))
194
+
195
+ @app.get('/image/stop')
196
+ def stop():
197
+ try:
198
+ if model_is_loading:
199
+ return {'ERROR'}
200
+
201
+ import runtime
202
+ runtime.stop_processing = True
203
+
204
+ return {'OK'}
205
+ except Exception as e:
206
+ print(traceback.format_exc())
207
+ return HTTPException(status_code=500, detail=str(e))
208
+
209
+ @app.get('/image/tmp/{session_id}/{img_id}')
210
+ def get_image(session_id, img_id):
211
+ import runtime
212
+ buf = runtime.temp_images[session_id + '/' + img_id]
213
+ buf.seek(0)
214
+ return StreamingResponse(buf, media_type='image/jpeg')
215
+
216
+ @app.post('/app_config')
217
+ async def setAppConfig(req : SetAppConfigRequest):
218
+ try:
219
+ config = {
220
+ 'update_branch': req.update_branch
221
+ }
222
+
223
+ config_json_str = json.dumps(config)
224
+ config_bat_str = f'@set update_branch={req.update_branch}'
225
+ config_sh_str = f'export update_branch={req.update_branch}'
226
+
227
+ config_json_path = os.path.join(CONFIG_DIR, 'config.json')
228
+ config_bat_path = os.path.join(CONFIG_DIR, 'config.bat')
229
+ config_sh_path = os.path.join(CONFIG_DIR, 'config.sh')
230
+
231
+ with open(config_json_path, 'w') as f:
232
+ f.write(config_json_str)
233
+
234
+ with open(config_bat_path, 'w') as f:
235
+ f.write(config_bat_str)
236
+
237
+ with open(config_sh_path, 'w') as f:
238
+ f.write(config_sh_str)
239
+
240
+ return {'OK'}
241
+ except Exception as e:
242
+ print(traceback.format_exc())
243
+ return HTTPException(status_code=500, detail=str(e))
244
+
245
+ @app.get('/app_config')
246
+ def getAppConfig():
247
+ try:
248
+ config_json_path = os.path.join(CONFIG_DIR, 'config.json')
249
+
250
+ if not os.path.exists(config_json_path):
251
+ return HTTPException(status_code=500, detail="No config file")
252
+
253
+ with open(config_json_path, 'r') as f:
254
+ return json.load(f)
255
+ except Exception as e:
256
+ print(traceback.format_exc())
257
+ return HTTPException(status_code=500, detail=str(e))
258
+
259
+ def getConfig():
260
+ try:
261
+ config_json_path = os.path.join(CONFIG_DIR, 'config.json')
262
 
263
+ if not os.path.exists(config_json_path):
264
+ return {}
265
 
266
+ with open(config_json_path, 'r') as f:
267
+ return json.load(f)
268
+ except Exception as e:
269
+ return {}
 
 
 
270
 
271
+ def setConfig(config):
272
+ try:
273
+ config_json_path = os.path.join(CONFIG_DIR, 'config.json')
274
 
275
+ with open(config_json_path, 'w') as f:
276
+ return json.dump(config, f)
277
+ except:
278
+ print(traceback.format_exc())
279
 
280
+ @app.get('/models')
281
+ def getModels():
282
+ models = {
283
+ 'active': {
284
+ 'stable-diffusion': 'sd-v1-4',
285
+ },
286
+ 'options': {
287
+ 'stable-diffusion': ['sd-v1-4'],
288
+ },
289
+ }
290
 
291
+ # custom models
292
+ sd_models_dir = os.path.join(MODELS_DIR, 'stable-diffusion')
293
+ for file in os.listdir(sd_models_dir):
294
+ if file.endswith('.ckpt'):
295
+ model_name = os.path.splitext(file)[0]
296
+ models['options']['stable-diffusion'].append(model_name)
297
 
298
+ # legacy
299
+ custom_weight_path = os.path.join(SD_DIR, 'custom-model.ckpt')
300
+ if os.path.exists(custom_weight_path):
301
+ models['active']['stable-diffusion'] = 'custom-model'
302
+ models['options']['stable-diffusion'].append('custom-model')
303
 
304
+ config = getConfig()
305
+ if 'model' in config and 'stable-diffusion' in config['model']:
306
+ models['active']['stable-diffusion'] = config['model']['stable-diffusion']
 
 
 
 
 
 
 
307
 
308
+ return models
309
 
310
+ @app.get('/modifiers.json')
311
+ def read_modifiers():
312
+ headers = {"Cache-Control": "no-cache, no-store, must-revalidate", "Pragma": "no-cache", "Expires": "0"}
313
+ return FileResponse(os.path.join(SD_UI_DIR, 'modifiers.json'), headers=headers)
314
 
315
+ @app.get('/output_dir')
316
+ def read_home_dir():
317
+ return {outpath}
318
 
319
+ # don't log certain requests
320
+ class LogSuppressFilter(logging.Filter):
321
+ def filter(self, record: logging.LogRecord) -> bool:
322
+ path = record.getMessage()
323
+ for prefix in ACCESS_LOG_SUPPRESS_PATH_PREFIXES:
324
+ if path.find(prefix) != -1:
325
+ return False
326
 
327
+ return True
 
 
328
 
329
+ logging.getLogger('uvicorn.access').addFilter(LogSuppressFilter())
modules/dataset.py DELETED
@@ -1,19 +0,0 @@
1
- from datasets import load_dataset
2
-
3
- dataset = load_dataset("emotion", split="train")
4
-
5
- emotions = dataset.info.features["label"].names
6
-
7
- def query_emotion(start, end):
8
- rows = dataset[start:end]
9
- texts, labels = [rows[k] for k in rows.keys()]
10
-
11
- observations = []
12
-
13
- for i, text in enumerate(texts):
14
- observations.append({
15
- "text": text,
16
- "emotion": emotions[labels[i]],
17
- })
18
-
19
- return observations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
modules/inference.py DELETED
@@ -1,11 +0,0 @@
1
- from transformers import T5Tokenizer, T5ForConditionalGeneration
2
-
3
- tokenizer = T5Tokenizer.from_pretrained("t5-small")
4
- model = T5ForConditionalGeneration.from_pretrained("t5-small")
5
-
6
-
7
- def infer_t5(input):
8
- input_ids = tokenizer(input, return_tensors="pt").input_ids
9
- outputs = model.generate(input_ids)
10
-
11
- return tokenizer.decode(outputs[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
 
 
 
 
modules/runtime.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os, re
3
+ import traceback
4
+ import torch
5
+ import numpy as np
6
+ from omegaconf import OmegaConf
7
+ from PIL import Image, ImageOps
8
+ from tqdm import tqdm, trange
9
+ from itertools import islice
10
+ from einops import rearrange
11
+ import time
12
+ from pytorch_lightning import seed_everything
13
+ from torch import autocast
14
+ from contextlib import nullcontext
15
+ from einops import rearrange, repeat
16
+ from ldmlib.util import instantiate_from_config
17
+ from optimizedSD.optimUtils import split_weighted_subprompts
18
+ from transformers import logging
19
+
20
+ from gfpgan import GFPGANer
21
+ from basicsr.archs.rrdbnet_arch import RRDBNet
22
+ from realesrgan import RealESRGANer
23
+
24
+ import uuid
25
+
26
+ logging.set_verbosity_error()
27
+
28
+ # consts
29
+ config_yaml = "optimizedSD/v1-inference.yaml"
30
+ filename_regex = re.compile('[^a-zA-Z0-9]')
31
+
32
+ # api stuff
33
+ from sd_internal import Request, Response, Image as ResponseImage
34
+ import base64
35
+ from io import BytesIO
36
+ #from colorama import Fore
37
+
38
+ # local
39
+ stop_processing = False
40
+ temp_images = {}
41
+
42
+ ckpt_file = None
43
+ gfpgan_file = None
44
+ real_esrgan_file = None
45
+
46
+ model = None
47
+ modelCS = None
48
+ modelFS = None
49
+ model_gfpgan = None
50
+ model_real_esrgan = None
51
+
52
+ model_is_half = False
53
+ model_fs_is_half = False
54
+ device = None
55
+ unet_bs = 1
56
+ precision = 'autocast'
57
+ sampler_plms = None
58
+ sampler_ddim = None
59
+
60
+ has_valid_gpu = False
61
+ force_full_precision = False
62
+ try:
63
+ gpu = torch.cuda.current_device()
64
+ gpu_name = torch.cuda.get_device_name(gpu)
65
+ print('GPU detected: ', gpu_name)
66
+
67
+ force_full_precision = ('nvidia' in gpu_name.lower() or 'geforce' in gpu_name.lower()) and (' 1660' in gpu_name or ' 1650' in gpu_name) # otherwise these NVIDIA cards create green images
68
+ if force_full_precision:
69
+ print('forcing full precision on NVIDIA 16xx cards, to avoid green images. GPU detected: ', gpu_name)
70
+
71
+ mem_free, mem_total = torch.cuda.mem_get_info(gpu)
72
+ mem_total /= float(10**9)
73
+ if mem_total < 3.0:
74
+ print("GPUs with less than 3 GB of VRAM are not compatible with Stable Diffusion")
75
+ raise Exception()
76
+
77
+ has_valid_gpu = True
78
+ except:
79
+ print('WARNING: No compatible GPU found. Using the CPU, but this will be very slow!')
80
+ pass
81
+
82
+ def load_model_ckpt(ckpt_to_use, device_to_use='cuda', turbo=False, unet_bs_to_use=1, precision_to_use='autocast'):
83
+ global ckpt_file, model, modelCS, modelFS, model_is_half, device, unet_bs, precision, model_fs_is_half
84
+
85
+ device = device_to_use if has_valid_gpu else 'cpu'
86
+ precision = precision_to_use if not force_full_precision else 'full'
87
+ unet_bs = unet_bs_to_use
88
+
89
+ unload_model()
90
+
91
+ if device == 'cpu':
92
+ precision = 'full'
93
+
94
+ sd = load_model_from_config(f"{ckpt_to_use}.ckpt")
95
+ li, lo = [], []
96
+ for key, value in sd.items():
97
+ sp = key.split(".")
98
+ if (sp[0]) == "model":
99
+ if "input_blocks" in sp:
100
+ li.append(key)
101
+ elif "middle_block" in sp:
102
+ li.append(key)
103
+ elif "time_embed" in sp:
104
+ li.append(key)
105
+ else:
106
+ lo.append(key)
107
+ for key in li:
108
+ sd["model1." + key[6:]] = sd.pop(key)
109
+ for key in lo:
110
+ sd["model2." + key[6:]] = sd.pop(key)
111
+
112
+ config = OmegaConf.load(f"{config_yaml}")
113
+
114
+ model = instantiate_from_config(config.modelUNet)
115
+ _, _ = model.load_state_dict(sd, strict=False)
116
+ model.eval()
117
+ model.cdevice = device
118
+ model.unet_bs = unet_bs
119
+ model.turbo = turbo
120
+
121
+ modelCS = instantiate_from_config(config.modelCondStage)
122
+ _, _ = modelCS.load_state_dict(sd, strict=False)
123
+ modelCS.eval()
124
+ modelCS.cond_stage_model.device = device
125
+
126
+ modelFS = instantiate_from_config(config.modelFirstStage)
127
+ _, _ = modelFS.load_state_dict(sd, strict=False)
128
+ modelFS.eval()
129
+ del sd
130
+
131
+ if device != "cpu" and precision == "autocast":
132
+ model.half()
133
+ modelCS.half()
134
+ modelFS.half()
135
+ model_is_half = True
136
+ model_fs_is_half = True
137
+ else:
138
+ model_is_half = False
139
+ model_fs_is_half = False
140
+
141
+ ckpt_file = ckpt_to_use
142
+
143
+ print('loaded ', ckpt_file, 'to', device, 'precision', precision)
144
+
145
+ def unload_model():
146
+ global model, modelCS, modelFS
147
+
148
+ if model is not None:
149
+ del model
150
+ del modelCS
151
+ del modelFS
152
+
153
+ model = None
154
+ modelCS = None
155
+ modelFS = None
156
+
157
+ def load_model_gfpgan(gfpgan_to_use):
158
+ global gfpgan_file, model_gfpgan
159
+
160
+ if gfpgan_to_use is None:
161
+ return
162
+
163
+ gfpgan_file = gfpgan_to_use
164
+ model_path = gfpgan_to_use + ".pth"
165
+
166
+ if device == 'cpu':
167
+ model_gfpgan = GFPGANer(model_path=model_path, upscale=1, arch='clean', channel_multiplier=2, bg_upsampler=None, device=torch.device('cpu'))
168
+ else:
169
+ model_gfpgan = GFPGANer(model_path=model_path, upscale=1, arch='clean', channel_multiplier=2, bg_upsampler=None, device=torch.device('cuda'))
170
+
171
+ print('loaded ', gfpgan_to_use, 'to', device, 'precision', precision)
172
+
173
+ def load_model_real_esrgan(real_esrgan_to_use):
174
+ global real_esrgan_file, model_real_esrgan
175
+
176
+ if real_esrgan_to_use is None:
177
+ return
178
+
179
+ real_esrgan_file = real_esrgan_to_use
180
+ model_path = real_esrgan_to_use + ".pth"
181
+
182
+ RealESRGAN_models = {
183
+ 'RealESRGAN_x4plus': RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4),
184
+ 'RealESRGAN_x4plus_anime_6B': RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=6, num_grow_ch=32, scale=4)
185
+ }
186
+
187
+ model_to_use = RealESRGAN_models[real_esrgan_to_use]
188
+
189
+ if device == 'cpu':
190
+ model_real_esrgan = RealESRGANer(scale=2, model_path=model_path, model=model_to_use, pre_pad=0, half=False) # cpu does not support half
191
+ model_real_esrgan.device = torch.device('cpu')
192
+ model_real_esrgan.model.to('cpu')
193
+ else:
194
+ model_real_esrgan = RealESRGANer(scale=2, model_path=model_path, model=model_to_use, pre_pad=0, half=model_is_half)
195
+
196
+ model_real_esrgan.model.name = real_esrgan_to_use
197
+
198
+ print('loaded ', real_esrgan_to_use, 'to', device, 'precision', precision)
199
+
200
+ def mk_img(req: Request):
201
+ try:
202
+ yield from do_mk_img(req)
203
+ except Exception as e:
204
+ print(traceback.format_exc())
205
+
206
+ gc()
207
+
208
+ if device != "cpu":
209
+ modelFS.to("cpu")
210
+ modelCS.to("cpu")
211
+
212
+ model.model1.to("cpu")
213
+ model.model2.to("cpu")
214
+
215
+ gc()
216
+
217
+ yield json.dumps({
218
+ "status": 'failed',
219
+ "detail": str(e)
220
+ })
221
+
222
+ def do_mk_img(req: Request):
223
+ global ckpt_file
224
+ global model, modelCS, modelFS, device
225
+ global model_gfpgan, model_real_esrgan
226
+ global stop_processing
227
+
228
+ stop_processing = False
229
+
230
+ res = Response()
231
+ res.request = req
232
+ res.images = []
233
+
234
+ temp_images.clear()
235
+
236
+ # custom model support:
237
+ # the req.use_stable_diffusion_model needs to be a valid path
238
+ # to the ckpt file (without the extension).
239
+
240
+ needs_model_reload = False
241
+ ckpt_to_use = ckpt_file
242
+ if ckpt_to_use != req.use_stable_diffusion_model:
243
+ ckpt_to_use = req.use_stable_diffusion_model
244
+ needs_model_reload = True
245
+
246
+ model.turbo = req.turbo
247
+ if req.use_cpu:
248
+ if device != 'cpu':
249
+ device = 'cpu'
250
+
251
+ if model_is_half:
252
+ load_model_ckpt(ckpt_to_use, device)
253
+ needs_model_reload = False
254
+
255
+ load_model_gfpgan(gfpgan_file)
256
+ load_model_real_esrgan(real_esrgan_file)
257
+ else:
258
+ if has_valid_gpu:
259
+ prev_device = device
260
+ device = 'cuda'
261
+
262
+ if (precision == 'autocast' and (req.use_full_precision or not model_is_half)) or \
263
+ (precision == 'full' and not req.use_full_precision and not force_full_precision):
264
+
265
+ load_model_ckpt(ckpt_to_use, device, req.turbo, unet_bs, ('full' if req.use_full_precision else 'autocast'))
266
+ needs_model_reload = False
267
+
268
+ if prev_device != device:
269
+ load_model_gfpgan(gfpgan_file)
270
+ load_model_real_esrgan(real_esrgan_file)
271
+
272
+ if needs_model_reload:
273
+ load_model_ckpt(ckpt_to_use, device, req.turbo, unet_bs, precision)
274
+
275
+ if req.use_face_correction != gfpgan_file:
276
+ load_model_gfpgan(req.use_face_correction)
277
+
278
+ if req.use_upscale != real_esrgan_file:
279
+ load_model_real_esrgan(req.use_upscale)
280
+
281
+ model.cdevice = device
282
+ modelCS.cond_stage_model.device = device
283
+
284
+ opt_prompt = req.prompt
285
+ opt_seed = req.seed
286
+ opt_n_samples = req.num_outputs
287
+ opt_n_iter = 1
288
+ opt_scale = req.guidance_scale
289
+ opt_C = 4
290
+ opt_H = req.height
291
+ opt_W = req.width
292
+ opt_f = 8
293
+ opt_ddim_steps = req.num_inference_steps
294
+ opt_ddim_eta = 0.0
295
+ opt_strength = req.prompt_strength
296
+ opt_save_to_disk_path = req.save_to_disk_path
297
+ opt_init_img = req.init_image
298
+ opt_use_face_correction = req.use_face_correction
299
+ opt_use_upscale = req.use_upscale
300
+ opt_show_only_filtered = req.show_only_filtered_image
301
+ opt_format = req.output_format
302
+ opt_sampler_name = req.sampler
303
+
304
+ print(req.to_string(), '\n device', device)
305
+
306
+ print('\n\n Using precision:', precision)
307
+
308
+ seed_everything(opt_seed)
309
+
310
+ batch_size = opt_n_samples
311
+ prompt = opt_prompt
312
+ assert prompt is not None
313
+ data = [batch_size * [prompt]]
314
+
315
+ if precision == "autocast" and device != "cpu":
316
+ precision_scope = autocast
317
+ else:
318
+ precision_scope = nullcontext
319
+
320
+ mask = None
321
+
322
+ if req.init_image is None:
323
+ handler = _txt2img
324
+
325
+ init_latent = None
326
+ t_enc = None
327
+ else:
328
+ handler = _img2img
329
+
330
+ init_image = load_img(req.init_image, opt_W, opt_H)
331
+ init_image = init_image.to(device)
332
+
333
+ if device != "cpu" and precision == "autocast":
334
+ init_image = init_image.half()
335
+
336
+ modelFS.to(device)
337
+
338
+ init_image = repeat(init_image, '1 ... -> b ...', b=batch_size)
339
+ init_latent = modelFS.get_first_stage_encoding(modelFS.encode_first_stage(init_image)) # move to latent space
340
+
341
+ if req.mask is not None:
342
+ mask = load_mask(req.mask, opt_W, opt_H, init_latent.shape[2], init_latent.shape[3], True).to(device)
343
+ mask = mask[0][0].unsqueeze(0).repeat(4, 1, 1).unsqueeze(0)
344
+ mask = repeat(mask, '1 ... -> b ...', b=batch_size)
345
+
346
+ if device != "cpu" and precision == "autocast":
347
+ mask = mask.half()
348
+
349
+ move_fs_to_cpu()
350
+
351
+ assert 0. <= opt_strength <= 1., 'can only work with strength in [0.0, 1.0]'
352
+ t_enc = int(opt_strength * opt_ddim_steps)
353
+ print(f"target t_enc is {t_enc} steps")
354
+
355
+ if opt_save_to_disk_path is not None:
356
+ session_out_path = os.path.join(opt_save_to_disk_path, req.session_id)
357
+ os.makedirs(session_out_path, exist_ok=True)
358
+ else:
359
+ session_out_path = None
360
+
361
+ seeds = ""
362
+ with torch.no_grad():
363
+ for n in trange(opt_n_iter, desc="Sampling"):
364
+ for prompts in tqdm(data, desc="data"):
365
+
366
+ with precision_scope("cuda"):
367
+ modelCS.to(device)
368
+ uc = None
369
+ if opt_scale != 1.0:
370
+ uc = modelCS.get_learned_conditioning(batch_size * [req.negative_prompt])
371
+ if isinstance(prompts, tuple):
372
+ prompts = list(prompts)
373
+
374
+ subprompts, weights = split_weighted_subprompts(prompts[0])
375
+ if len(subprompts) > 1:
376
+ c = torch.zeros_like(uc)
377
+ totalWeight = sum(weights)
378
+ # normalize each "sub prompt" and add it
379
+ for i in range(len(subprompts)):
380
+ weight = weights[i]
381
+ # if not skip_normalize:
382
+ weight = weight / totalWeight
383
+ c = torch.add(c, modelCS.get_learned_conditioning(subprompts[i]), alpha=weight)
384
+ else:
385
+ c = modelCS.get_learned_conditioning(prompts)
386
+
387
+ modelFS.to(device)
388
+
389
+ partial_x_samples = None
390
+ def img_callback(x_samples, i):
391
+ nonlocal partial_x_samples
392
+
393
+ partial_x_samples = x_samples
394
+
395
+ if req.stream_progress_updates:
396
+ n_steps = opt_ddim_steps if req.init_image is None else t_enc
397
+ progress = {"step": i, "total_steps": n_steps}
398
+
399
+ if req.stream_image_progress and i % 5 == 0:
400
+ partial_images = []
401
+
402
+ for i in range(batch_size):
403
+ x_samples_ddim = modelFS.decode_first_stage(x_samples[i].unsqueeze(0))
404
+ x_sample = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
405
+ x_sample = 255.0 * rearrange(x_sample[0].cpu().numpy(), "c h w -> h w c")
406
+ x_sample = x_sample.astype(np.uint8)
407
+ img = Image.fromarray(x_sample)
408
+ buf = BytesIO()
409
+ img.save(buf, format='JPEG')
410
+ buf.seek(0)
411
+
412
+ del img, x_sample, x_samples_ddim
413
+ # don't delete x_samples, it is used in the code that called this callback
414
+
415
+ temp_images[str(req.session_id) + '/' + str(i)] = buf
416
+ partial_images.append({'path': f'/image/tmp/{req.session_id}/{i}'})
417
+
418
+ progress['output'] = partial_images
419
+
420
+ yield json.dumps(progress)
421
+
422
+ if stop_processing:
423
+ raise UserInitiatedStop("User requested that we stop processing")
424
+
425
+ # run the handler
426
+ try:
427
+ if handler == _txt2img:
428
+ x_samples = _txt2img(opt_W, opt_H, opt_n_samples, opt_ddim_steps, opt_scale, None, opt_C, opt_f, opt_ddim_eta, c, uc, opt_seed, img_callback, mask, opt_sampler_name)
429
+ else:
430
+ x_samples = _img2img(init_latent, t_enc, batch_size, opt_scale, c, uc, opt_ddim_steps, opt_ddim_eta, opt_seed, img_callback, mask)
431
+
432
+ yield from x_samples
433
+
434
+ x_samples = partial_x_samples
435
+ except UserInitiatedStop:
436
+ if partial_x_samples is None:
437
+ continue
438
+
439
+ x_samples = partial_x_samples
440
+
441
+ print("saving images")
442
+ for i in range(batch_size):
443
+
444
+ x_samples_ddim = modelFS.decode_first_stage(x_samples[i].unsqueeze(0))
445
+ x_sample = torch.clamp((x_samples_ddim + 1.0) / 2.0, min=0.0, max=1.0)
446
+ x_sample = 255.0 * rearrange(x_sample[0].cpu().numpy(), "c h w -> h w c")
447
+ x_sample = x_sample.astype(np.uint8)
448
+ img = Image.fromarray(x_sample)
449
+
450
+ has_filters = (opt_use_face_correction is not None and opt_use_face_correction.startswith('GFPGAN')) or \
451
+ (opt_use_upscale is not None and opt_use_upscale.startswith('RealESRGAN'))
452
+
453
+ return_orig_img = not has_filters or not opt_show_only_filtered
454
+
455
+ if stop_processing:
456
+ return_orig_img = True
457
+
458
+ if opt_save_to_disk_path is not None:
459
+ prompt_flattened = filename_regex.sub('_', prompts[0])
460
+ prompt_flattened = prompt_flattened[:50]
461
+
462
+ img_id = str(uuid.uuid4())[-8:]
463
+
464
+ file_path = f"{prompt_flattened}_{img_id}"
465
+ img_out_path = os.path.join(session_out_path, f"{file_path}.{opt_format}")
466
+ meta_out_path = os.path.join(session_out_path, f"{file_path}.txt")
467
+
468
+ if return_orig_img:
469
+ save_image(img, img_out_path)
470
+
471
+ save_metadata(meta_out_path, prompts, opt_seed, opt_W, opt_H, opt_ddim_steps, opt_scale, opt_strength, opt_use_face_correction, opt_use_upscale, opt_sampler_name, req.negative_prompt, ckpt_file)
472
+
473
+ if return_orig_img:
474
+ img_data = img_to_base64_str(img, opt_format)
475
+ res_image_orig = ResponseImage(data=img_data, seed=opt_seed)
476
+ res.images.append(res_image_orig)
477
+
478
+ if opt_save_to_disk_path is not None:
479
+ res_image_orig.path_abs = img_out_path
480
+
481
+ del img
482
+
483
+ if has_filters and not stop_processing:
484
+ print('Applying filters..')
485
+
486
+ gc()
487
+ filters_applied = []
488
+
489
+ if opt_use_face_correction:
490
+ _, _, output = model_gfpgan.enhance(x_sample[:,:,::-1], has_aligned=False, only_center_face=False, paste_back=True)
491
+ x_sample = output[:,:,::-1]
492
+ filters_applied.append(opt_use_face_correction)
493
+
494
+ if opt_use_upscale:
495
+ output, _ = model_real_esrgan.enhance(x_sample[:,:,::-1])
496
+ x_sample = output[:,:,::-1]
497
+ filters_applied.append(opt_use_upscale)
498
+
499
+ filtered_image = Image.fromarray(x_sample)
500
+
501
+ filtered_img_data = img_to_base64_str(filtered_image, opt_format)
502
+ res_image_filtered = ResponseImage(data=filtered_img_data, seed=opt_seed)
503
+ res.images.append(res_image_filtered)
504
+
505
+ filters_applied = "_".join(filters_applied)
506
+
507
+ if opt_save_to_disk_path is not None:
508
+ filtered_img_out_path = os.path.join(session_out_path, f"{file_path}_{filters_applied}.{opt_format}")
509
+ save_image(filtered_image, filtered_img_out_path)
510
+ res_image_filtered.path_abs = filtered_img_out_path
511
+
512
+ del filtered_image
513
+
514
+ seeds += str(opt_seed) + ","
515
+ opt_seed += 1
516
+
517
+ move_fs_to_cpu()
518
+ gc()
519
+ del x_samples, x_samples_ddim, x_sample
520
+ print("memory_final = ", torch.cuda.memory_allocated() / 1e6)
521
+
522
+ print('Task completed')
523
+
524
+ yield json.dumps(res.json())
525
+
526
+ def save_image(img, img_out_path):
527
+ try:
528
+ img.save(img_out_path)
529
+ except:
530
+ print('could not save the file', traceback.format_exc())
531
+
532
+ def save_metadata(meta_out_path, prompts, opt_seed, opt_W, opt_H, opt_ddim_steps, opt_scale, opt_prompt_strength, opt_correct_face, opt_upscale, sampler_name, negative_prompt, ckpt_file):
533
+ metadata = f"{prompts[0]}\nWidth: {opt_W}\nHeight: {opt_H}\nSeed: {opt_seed}\nSteps: {opt_ddim_steps}\nGuidance Scale: {opt_scale}\nPrompt Strength: {opt_prompt_strength}\nUse Face Correction: {opt_correct_face}\nUse Upscaling: {opt_upscale}\nSampler: {sampler_name}\nNegative Prompt: {negative_prompt}\nStable Diffusion Model: {ckpt_file + '.ckpt'}"
534
+
535
+ try:
536
+ with open(meta_out_path, 'w') as f:
537
+ f.write(metadata)
538
+ except:
539
+ print('could not save the file', traceback.format_exc())
540
+
541
+ def _txt2img(opt_W, opt_H, opt_n_samples, opt_ddim_steps, opt_scale, start_code, opt_C, opt_f, opt_ddim_eta, c, uc, opt_seed, img_callback, mask, sampler_name):
542
+ shape = [opt_n_samples, opt_C, opt_H // opt_f, opt_W // opt_f]
543
+
544
+ if device != "cpu":
545
+ mem = torch.cuda.memory_allocated() / 1e6
546
+ modelCS.to("cpu")
547
+ while torch.cuda.memory_allocated() / 1e6 >= mem:
548
+ time.sleep(1)
549
+
550
+ if sampler_name == 'ddim':
551
+ model.make_schedule(ddim_num_steps=opt_ddim_steps, ddim_eta=opt_ddim_eta, verbose=False)
552
+
553
+ samples_ddim = model.sample(
554
+ S=opt_ddim_steps,
555
+ conditioning=c,
556
+ seed=opt_seed,
557
+ shape=shape,
558
+ verbose=False,
559
+ unconditional_guidance_scale=opt_scale,
560
+ unconditional_conditioning=uc,
561
+ eta=opt_ddim_eta,
562
+ x_T=start_code,
563
+ img_callback=img_callback,
564
+ mask=mask,
565
+ sampler = sampler_name,
566
+ )
567
+
568
+ yield from samples_ddim
569
+
570
+ def _img2img(init_latent, t_enc, batch_size, opt_scale, c, uc, opt_ddim_steps, opt_ddim_eta, opt_seed, img_callback, mask):
571
+ # encode (scaled latent)
572
+ z_enc = model.stochastic_encode(
573
+ init_latent,
574
+ torch.tensor([t_enc] * batch_size).to(device),
575
+ opt_seed,
576
+ opt_ddim_eta,
577
+ opt_ddim_steps,
578
+ )
579
+ x_T = None if mask is None else init_latent
580
+
581
+ # decode it
582
+ samples_ddim = model.sample(
583
+ t_enc,
584
+ c,
585
+ z_enc,
586
+ unconditional_guidance_scale=opt_scale,
587
+ unconditional_conditioning=uc,
588
+ img_callback=img_callback,
589
+ mask=mask,
590
+ x_T=x_T,
591
+ sampler = 'ddim'
592
+ )
593
+
594
+ yield from samples_ddim
595
+
596
+ def move_fs_to_cpu():
597
+ if device != "cpu":
598
+ mem = torch.cuda.memory_allocated() / 1e6
599
+ modelFS.to("cpu")
600
+ while torch.cuda.memory_allocated() / 1e6 >= mem:
601
+ time.sleep(1)
602
+
603
+ def gc():
604
+ if device == 'cpu':
605
+ return
606
+
607
+ torch.cuda.empty_cache()
608
+ torch.cuda.ipc_collect()
609
+
610
+ # internal
611
+
612
+ def chunk(it, size):
613
+ it = iter(it)
614
+ return iter(lambda: tuple(islice(it, size)), ())
615
+
616
+
617
+ def load_model_from_config(ckpt, verbose=False):
618
+ print(f"Loading model from {ckpt}")
619
+ pl_sd = torch.load(ckpt, map_location="cpu")
620
+ if "global_step" in pl_sd:
621
+ print(f"Global Step: {pl_sd['global_step']}")
622
+ sd = pl_sd["state_dict"]
623
+ return sd
624
+
625
+ # utils
626
+ class UserInitiatedStop(Exception):
627
+ pass
628
+
629
+ def load_img(img_str, w0, h0):
630
+ image = base64_str_to_img(img_str).convert("RGB")
631
+ w, h = image.size
632
+ print(f"loaded input image of size ({w}, {h}) from base64")
633
+ if h0 is not None and w0 is not None:
634
+ h, w = h0, w0
635
+
636
+ w, h = map(lambda x: x - x % 64, (w, h)) # resize to integer multiple of 64
637
+ image = image.resize((w, h), resample=Image.Resampling.LANCZOS)
638
+ image = np.array(image).astype(np.float32) / 255.0
639
+ image = image[None].transpose(0, 3, 1, 2)
640
+ image = torch.from_numpy(image)
641
+ return 2.*image - 1.
642
+
643
+ def load_mask(mask_str, h0, w0, newH, newW, invert=False):
644
+ image = base64_str_to_img(mask_str).convert("RGB")
645
+ w, h = image.size
646
+ print(f"loaded input mask of size ({w}, {h})")
647
+
648
+ if invert:
649
+ print("inverted")
650
+ image = ImageOps.invert(image)
651
+ # where_0, where_1 = np.where(image == 0), np.where(image == 255)
652
+ # image[where_0], image[where_1] = 255, 0
653
+
654
+ if h0 is not None and w0 is not None:
655
+ h, w = h0, w0
656
+
657
+ w, h = map(lambda x: x - x % 64, (w, h)) # resize to integer multiple of 64
658
+
659
+ print(f"New mask size ({w}, {h})")
660
+ image = image.resize((newW, newH), resample=Image.Resampling.LANCZOS)
661
+ image = np.array(image)
662
+
663
+ image = image.astype(np.float32) / 255.0
664
+ image = image[None].transpose(0, 3, 1, 2)
665
+ image = torch.from_numpy(image)
666
+ return image
667
+
668
+ # https://stackoverflow.com/a/61114178
669
+ def img_to_base64_str(img, output_format="PNG"):
670
+ buffered = BytesIO()
671
+ img.save(buffered, format=output_format)
672
+ buffered.seek(0)
673
+ img_byte = buffered.getvalue()
674
+ img_str = "data:image/png;base64," + base64.b64encode(img_byte).decode()
675
+ return img_str
676
+
677
+ def base64_str_to_img(img_str):
678
+ img_str = img_str[len("data:image/png;base64,"):]
679
+ data = base64.b64decode(img_str)
680
+ buffered = BytesIO(data)
681
+ img = Image.open(buffered)
682
+ return img
ui/scripts/Developer Console.cmd ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ echo "Opening Stable Diffusion UI - Developer Console.." & echo.
4
+
5
+ @call installer\Scripts\activate.bat
6
+
7
+ @call conda-unpack
8
+
9
+ @call conda --version
10
+ @call git --version
11
+
12
+ @call conda activate .\stable-diffusion\env
13
+
14
+ cmd /k
ui/scripts/Start Stable Diffusion UI.cmd ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ @REM Delete the post-activate hook from the old installer
4
+ if exist "installer\etc\conda\activate.d\post_activate.bat" (
5
+ echo. > installer\etc\conda\activate.d\post_activate.bat
6
+ )
7
+
8
+ @call installer\Scripts\activate.bat
9
+
10
+ @call conda-unpack
11
+
12
+ @call conda --version
13
+ @call git --version
14
+
15
+ @cd installer
16
+
17
+ @call ..\scripts\on_env_start.bat
18
+
19
+ @pause
ui/scripts/developer_console.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ if [ "$0" == "bash" ]; then
4
+ echo "Opening Stable Diffusion UI - Developer Console.."
5
+ echo ""
6
+
7
+ source installer/bin/activate
8
+
9
+ conda-unpack
10
+
11
+ conda --version
12
+ git --version
13
+
14
+ conda activate ./stable-diffusion/env
15
+ else
16
+ bash --init-file developer_console.sh
17
+ fi
ui/scripts/on_env_start.bat ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ @echo. & echo "Stable Diffusion UI - v2" & echo.
4
+
5
+ set PATH=C:\Windows\System32;%PATH%
6
+
7
+ @cd ..
8
+
9
+ if exist "scripts\config.bat" (
10
+ @call scripts\config.bat
11
+ )
12
+
13
+ if "%update_branch%"=="" (
14
+ set update_branch=main
15
+ )
16
+
17
+ @>nul grep -c "conda_sd_ui_deps_installed" scripts\install_status.txt
18
+ @if "%ERRORLEVEL%" NEQ "0" (
19
+ for /f "tokens=*" %%a in ('python -c "import os; parts = os.getcwd().split(os.path.sep); print(len(parts))"') do if "%%a" NEQ "2" (
20
+ echo. & echo "!!!! WARNING !!!!" & echo.
21
+ echo "Your 'stable-diffusion-ui' folder is at %cd%" & echo.
22
+ echo "The 'stable-diffusion-ui' folder needs to be at the top of your drive, for e.g. 'C:\stable-diffusion-ui' or 'D:\stable-diffusion-ui' etc."
23
+ echo "Not placing this folder at the top of a drive can cause errors on some computers."
24
+ echo. & echo "Recommended: Please close this window and move the 'stable-diffusion-ui' folder to the top of a drive. For e.g. 'C:\stable-diffusion-ui'. Then run the installer again." & echo.
25
+ echo "Not Recommended: If you're sure that you want to install at the current location, please press any key to continue." & echo.
26
+
27
+ pause
28
+ )
29
+ )
30
+
31
+ @>nul grep -c "sd_ui_git_cloned" scripts\install_status.txt
32
+ @if "%ERRORLEVEL%" EQU "0" (
33
+ @echo "Stable Diffusion UI's git repository was already installed. Updating from %update_branch%.."
34
+
35
+ @cd sd-ui-files
36
+
37
+ @call git reset --hard
38
+ @call git checkout "%update_branch%"
39
+ @call git pull
40
+
41
+ @cd ..
42
+ ) else (
43
+ @echo. & echo "Downloading Stable Diffusion UI.." & echo.
44
+ @echo "Using the %update_branch% channel" & echo.
45
+
46
+ @call git clone -b "%update_branch%" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files && (
47
+ @echo sd_ui_git_cloned >> scripts\install_status.txt
48
+ ) || (
49
+ @echo "Error downloading Stable Diffusion UI. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!"
50
+ pause
51
+ @exit /b
52
+ )
53
+ )
54
+
55
+ @xcopy sd-ui-files\ui ui /s /i /Y
56
+ @copy sd-ui-files\scripts\on_sd_start.bat scripts\ /Y
57
+ @copy "sd-ui-files\scripts\Start Stable Diffusion UI.cmd" . /Y
58
+ @copy "sd-ui-files\scripts\Developer Console.cmd" . /Y
59
+
60
+ @call scripts\on_sd_start.bat
61
+
62
+ @pause
ui/scripts/on_env_start.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ printf "\n\nStable Diffusion UI\n\n"
4
+
5
+ if [ -f "scripts/config.sh" ]; then
6
+ source scripts/config.sh
7
+ fi
8
+
9
+ if [ "$update_branch" == "" ]; then
10
+ export update_branch="main"
11
+ fi
12
+
13
+ if [ -f "scripts/install_status.txt" ] && [ `grep -c sd_ui_git_cloned scripts/install_status.txt` -gt "0" ]; then
14
+ echo "Stable Diffusion UI's git repository was already installed. Updating from $update_branch.."
15
+
16
+ cd sd-ui-files
17
+
18
+ git reset --hard
19
+ git checkout "$update_branch"
20
+ git pull
21
+
22
+ cd ..
23
+ else
24
+ printf "\n\nDownloading Stable Diffusion UI..\n\n"
25
+ printf "Using the $update_branch channel\n\n"
26
+
27
+ if git clone -b "$update_branch" https://github.com/cmdr2/stable-diffusion-ui.git sd-ui-files ; then
28
+ echo sd_ui_git_cloned >> scripts/install_status.txt
29
+ else
30
+ printf "\n\nError downloading Stable Diffusion UI. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
31
+ read -p "Press any key to continue"
32
+ exit
33
+ fi
34
+ fi
35
+
36
+ rm -rf ui
37
+ cp -Rf sd-ui-files/ui .
38
+ cp sd-ui-files/scripts/on_sd_start.sh scripts/
39
+ cp sd-ui-files/scripts/start.sh .
40
+ cp sd-ui-files/scripts/developer_console.sh .
41
+
42
+ ./scripts/on_sd_start.sh
43
+
44
+ read -p "Press any key to continue"
ui/scripts/on_sd_start.bat ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+
3
+ @copy sd-ui-files\scripts\on_env_start.bat scripts\ /Y
4
+
5
+ @REM Caution, this file will make your eyes and brain bleed. It's such an unholy mess.
6
+ @REM Note to self: Please rewrite this in Python. For the sake of your own sanity.
7
+
8
+ @copy "sd-ui-files\scripts\Developer Console.cmd" . /Y
9
+ if exist "Open Developer Console.cmd" del "Open Developer Console.cmd"
10
+
11
+ @call python -c "import os; import shutil; frm = 'sd-ui-files\\ui\\hotfix\\9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'; dst = os.path.join(os.path.expanduser('~'), '.cache', 'huggingface', 'transformers', '9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'); shutil.copyfile(frm, dst) if os.path.exists(dst) else print(''); print('Hotfixed broken JSON file from OpenAI');"
12
+
13
+ @>nul grep -c "sd_git_cloned" scripts\install_status.txt
14
+ @if "%ERRORLEVEL%" EQU "0" (
15
+ @echo "Stable Diffusion's git repository was already installed. Updating.."
16
+
17
+ @cd stable-diffusion
18
+
19
+ @call git reset --hard
20
+ @call git pull
21
+ @call git checkout f6cfebffa752ee11a7b07497b8529d5971de916c
22
+
23
+ @call git apply ..\ui\sd_internal\ddim_callback.patch
24
+ @call git apply ..\ui\sd_internal\env_yaml.patch
25
+
26
+ @cd ..
27
+ ) else (
28
+ @echo. & echo "Downloading Stable Diffusion.." & echo.
29
+
30
+ @call git clone https://github.com/basujindal/stable-diffusion.git && (
31
+ @echo sd_git_cloned >> scripts\install_status.txt
32
+ ) || (
33
+ @echo "Error downloading Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!"
34
+ pause
35
+ @exit /b
36
+ )
37
+
38
+ @cd stable-diffusion
39
+ @call git checkout f6cfebffa752ee11a7b07497b8529d5971de916c
40
+
41
+ @call git apply ..\ui\sd_internal\ddim_callback.patch
42
+ @call git apply ..\ui\sd_internal\env_yaml.patch
43
+
44
+ @cd ..
45
+ )
46
+
47
+ @cd stable-diffusion
48
+
49
+ @>nul grep -c "conda_sd_env_created" ..\scripts\install_status.txt
50
+ @if "%ERRORLEVEL%" EQU "0" (
51
+ @echo "Packages necessary for Stable Diffusion were already installed"
52
+
53
+ @call conda activate .\env
54
+ ) else (
55
+ @echo. & echo "Downloading packages necessary for Stable Diffusion.." & echo. & echo "***** This will take some time (depending on the speed of the Internet connection) and may appear to be stuck, but please be patient ***** .." & echo.
56
+
57
+ @rmdir /s /q .\env
58
+
59
+ @REM prevent conda from using packages from the user's home directory, to avoid conflicts
60
+ @set PYTHONNOUSERSITE=1
61
+
62
+ set TMP=%cd%\tmp
63
+ set TEMP=%cd%\tmp
64
+
65
+ @call conda env create --prefix env -f environment.yaml || (
66
+ @echo. & echo "Error installing the packages necessary for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
67
+ pause
68
+ exit /b
69
+ )
70
+
71
+ @call conda activate .\env
72
+
73
+ @call conda install -c conda-forge -y --prefix env antlr4-python3-runtime=4.8 || (
74
+ @echo. & echo "Error installing antlr4-python3-runtime for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
75
+ pause
76
+ exit /b
77
+ )
78
+
79
+ for /f "tokens=*" %%a in ('python -c "import torch; import ldm; import transformers; import numpy; import antlr4; print(42)"') do if "%%a" NEQ "42" (
80
+ @echo. & echo "Dependency test failed! Error installing the packages necessary for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
81
+ pause
82
+ exit /b
83
+ )
84
+
85
+ @echo conda_sd_env_created >> ..\scripts\install_status.txt
86
+ )
87
+
88
+ set PATH=C:\Windows\System32;%PATH%
89
+
90
+ @>nul grep -c "conda_sd_gfpgan_deps_installed" ..\scripts\install_status.txt
91
+ @if "%ERRORLEVEL%" EQU "0" (
92
+ @echo "Packages necessary for GFPGAN (Face Correction) were already installed"
93
+ ) else (
94
+ @echo. & echo "Downloading packages necessary for GFPGAN (Face Correction).." & echo.
95
+
96
+ @set PYTHONNOUSERSITE=1
97
+
98
+ set TMP=%cd%\tmp
99
+ set TEMP=%cd%\tmp
100
+
101
+ @call pip install -e git+https://github.com/TencentARC/GFPGAN#egg=GFPGAN || (
102
+ @echo. & echo "Error installing the packages necessary for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
103
+ pause
104
+ exit /b
105
+ )
106
+
107
+ @call pip install basicsr==1.4.2 || (
108
+ @echo. & echo "Error installing the basicsr package necessary for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
109
+ pause
110
+ exit /b
111
+ )
112
+
113
+ for /f "tokens=*" %%a in ('python -c "from gfpgan import GFPGANer; print(42)"') do if "%%a" NEQ "42" (
114
+ @echo. & echo "Dependency test failed! Error installing the packages necessary for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
115
+ pause
116
+ exit /b
117
+ )
118
+
119
+ @echo conda_sd_gfpgan_deps_installed >> ..\scripts\install_status.txt
120
+ )
121
+
122
+ @>nul grep -c "conda_sd_esrgan_deps_installed" ..\scripts\install_status.txt
123
+ @if "%ERRORLEVEL%" EQU "0" (
124
+ @echo "Packages necessary for ESRGAN (Resolution Upscaling) were already installed"
125
+ ) else (
126
+ @echo. & echo "Downloading packages necessary for ESRGAN (Resolution Upscaling).." & echo.
127
+
128
+ @set PYTHONNOUSERSITE=1
129
+
130
+ set TMP=%cd%\tmp
131
+ set TEMP=%cd%\tmp
132
+
133
+ @call pip install -e git+https://github.com/xinntao/Real-ESRGAN#egg=realesrgan || (
134
+ @echo. & echo "Error installing the packages necessary for ESRGAN (Resolution Upscaling). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
135
+ pause
136
+ exit /b
137
+ )
138
+
139
+ for /f "tokens=*" %%a in ('python -c "from basicsr.archs.rrdbnet_arch import RRDBNet; from realesrgan import RealESRGANer; print(42)"') do if "%%a" NEQ "42" (
140
+ @echo. & echo "Dependency test failed! Error installing the packages necessary for ESRGAN (Resolution Upscaling). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
141
+ pause
142
+ exit /b
143
+ )
144
+
145
+ @echo conda_sd_esrgan_deps_installed >> ..\scripts\install_status.txt
146
+ )
147
+
148
+ @>nul grep -c "conda_sd_ui_deps_installed" ..\scripts\install_status.txt
149
+ @if "%ERRORLEVEL%" EQU "0" (
150
+ echo "Packages necessary for Stable Diffusion UI were already installed"
151
+ ) else (
152
+ @echo. & echo "Downloading packages necessary for Stable Diffusion UI.." & echo.
153
+
154
+ @set PYTHONNOUSERSITE=1
155
+
156
+ set TMP=%cd%\tmp
157
+ set TEMP=%cd%\tmp
158
+
159
+ @call conda install -c conda-forge -y --prefix env uvicorn fastapi || (
160
+ echo "Error installing the packages necessary for Stable Diffusion UI. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!"
161
+ pause
162
+ exit /b
163
+ )
164
+ )
165
+
166
+ call WHERE uvicorn > .tmp
167
+ @>nul grep -c "uvicorn" .tmp
168
+ @if "%ERRORLEVEL%" NEQ "0" (
169
+ @echo. & echo "UI packages not found! Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
170
+ pause
171
+ exit /b
172
+ )
173
+
174
+ @>nul grep -c "conda_sd_ui_deps_installed" ..\scripts\install_status.txt
175
+ @if "%ERRORLEVEL%" NEQ "0" (
176
+ @echo conda_sd_ui_deps_installed >> ..\scripts\install_status.txt
177
+ )
178
+
179
+
180
+
181
+ if not exist "..\models\stable-diffusion" mkdir "..\models\stable-diffusion"
182
+ echo. > "..\models\stable-diffusion\Put your custom ckpt files here.txt"
183
+
184
+ @if exist "sd-v1-4.ckpt" (
185
+ for %%I in ("sd-v1-4.ckpt") do if "%%~zI" EQU "4265380512" (
186
+ echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the HuggingFace 4 GB Model."
187
+ ) else (
188
+ for %%J in ("sd-v1-4.ckpt") do if "%%~zJ" EQU "7703807346" (
189
+ echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the HuggingFace 7 GB Model."
190
+ ) else (
191
+ for %%K in ("sd-v1-4.ckpt") do if "%%~zK" EQU "7703810927" (
192
+ echo "Data files (weights) necessary for Stable Diffusion were already downloaded. Using the Waifu Model."
193
+ ) else (
194
+ echo. & echo "The model file present at %cd%\sd-v1-4.ckpt is invalid. It is only %%~zK bytes in size. Re-downloading.." & echo.
195
+ del "sd-v1-4.ckpt"
196
+ )
197
+ )
198
+ )
199
+ )
200
+
201
+ @if not exist "sd-v1-4.ckpt" (
202
+ @echo. & echo "Downloading data files (weights) for Stable Diffusion.." & echo.
203
+
204
+ @call curl -L -k https://me.cmdr2.org/stable-diffusion-ui/sd-v1-4.ckpt > sd-v1-4.ckpt
205
+
206
+ @if exist "sd-v1-4.ckpt" (
207
+ for %%I in ("sd-v1-4.ckpt") do if "%%~zI" NEQ "4265380512" (
208
+ echo. & echo "Error: The downloaded model file was invalid! Bytes downloaded: %%~zI" & echo.
209
+ echo. & echo "Error downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
210
+ pause
211
+ exit /b
212
+ )
213
+ ) else (
214
+ @echo. & echo "Error downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
215
+ pause
216
+ exit /b
217
+ )
218
+ )
219
+
220
+
221
+
222
+ @if exist "GFPGANv1.3.pth" (
223
+ for %%I in ("GFPGANv1.3.pth") do if "%%~zI" EQU "348632874" (
224
+ echo "Data files (weights) necessary for GFPGAN (Face Correction) were already downloaded"
225
+ ) else (
226
+ echo. & echo "The GFPGAN model file present at %cd%\GFPGANv1.3.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo.
227
+ del "GFPGANv1.3.pth"
228
+ )
229
+ )
230
+
231
+ @if not exist "GFPGANv1.3.pth" (
232
+ @echo. & echo "Downloading data files (weights) for GFPGAN (Face Correction).." & echo.
233
+
234
+ @call curl -L -k https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth > GFPGANv1.3.pth
235
+
236
+ @if exist "GFPGANv1.3.pth" (
237
+ for %%I in ("GFPGANv1.3.pth") do if "%%~zI" NEQ "348632874" (
238
+ echo. & echo "Error: The downloaded GFPGAN model file was invalid! Bytes downloaded: %%~zI" & echo.
239
+ echo. & echo "Error downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
240
+ pause
241
+ exit /b
242
+ )
243
+ ) else (
244
+ @echo. & echo "Error downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
245
+ pause
246
+ exit /b
247
+ )
248
+ )
249
+
250
+
251
+
252
+ @if exist "RealESRGAN_x4plus.pth" (
253
+ for %%I in ("RealESRGAN_x4plus.pth") do if "%%~zI" EQU "67040989" (
254
+ echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus were already downloaded"
255
+ ) else (
256
+ echo. & echo "The GFPGAN model file present at %cd%\RealESRGAN_x4plus.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo.
257
+ del "RealESRGAN_x4plus.pth"
258
+ )
259
+ )
260
+
261
+ @if not exist "RealESRGAN_x4plus.pth" (
262
+ @echo. & echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus.." & echo.
263
+
264
+ @call curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth > RealESRGAN_x4plus.pth
265
+
266
+ @if exist "RealESRGAN_x4plus.pth" (
267
+ for %%I in ("RealESRGAN_x4plus.pth") do if "%%~zI" NEQ "67040989" (
268
+ echo. & echo "Error: The downloaded ESRGAN x4plus model file was invalid! Bytes downloaded: %%~zI" & echo.
269
+ echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
270
+ pause
271
+ exit /b
272
+ )
273
+ ) else (
274
+ @echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
275
+ pause
276
+ exit /b
277
+ )
278
+ )
279
+
280
+
281
+
282
+ @if exist "RealESRGAN_x4plus_anime_6B.pth" (
283
+ for %%I in ("RealESRGAN_x4plus_anime_6B.pth") do if "%%~zI" EQU "17938799" (
284
+ echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus_anime were already downloaded"
285
+ ) else (
286
+ echo. & echo "The GFPGAN model file present at %cd%\RealESRGAN_x4plus_anime_6B.pth is invalid. It is only %%~zI bytes in size. Re-downloading.." & echo.
287
+ del "RealESRGAN_x4plus_anime_6B.pth"
288
+ )
289
+ )
290
+
291
+ @if not exist "RealESRGAN_x4plus_anime_6B.pth" (
292
+ @echo. & echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime.." & echo.
293
+
294
+ @call curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth > RealESRGAN_x4plus_anime_6B.pth
295
+
296
+ @if exist "RealESRGAN_x4plus_anime_6B.pth" (
297
+ for %%I in ("RealESRGAN_x4plus_anime_6B.pth") do if "%%~zI" NEQ "17938799" (
298
+ echo. & echo "Error: The downloaded ESRGAN x4plus_anime model file was invalid! Bytes downloaded: %%~zI" & echo.
299
+ echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
300
+ pause
301
+ exit /b
302
+ )
303
+ ) else (
304
+ @echo. & echo "Error downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:" & echo " 1. Run this installer again." & echo " 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md" & echo " 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB" & echo " 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues" & echo "Thanks!" & echo.
305
+ pause
306
+ exit /b
307
+ )
308
+ )
309
+
310
+
311
+
312
+ @>nul grep -c "sd_install_complete" ..\scripts\install_status.txt
313
+ @if "%ERRORLEVEL%" NEQ "0" (
314
+ @echo sd_weights_downloaded >> ..\scripts\install_status.txt
315
+ @echo sd_install_complete >> ..\scripts\install_status.txt
316
+ )
317
+
318
+ @echo. & echo "Stable Diffusion is ready!" & echo.
319
+
320
+ @set SD_DIR=%cd%
321
+
322
+ @cd env\lib\site-packages
323
+ @set PYTHONPATH=%SD_DIR%;%cd%
324
+ @cd ..\..\..
325
+ @echo PYTHONPATH=%PYTHONPATH%
326
+
327
+ @cd ..
328
+ @set SD_UI_PATH=%cd%\ui
329
+ @cd stable-diffusion
330
+
331
+ @call python --version
332
+
333
+ @uvicorn server:app --app-dir "%SD_UI_PATH%" --port 9000 --host 0.0.0.0
334
+
335
+ @pause
ui/scripts/on_sd_start.sh ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ cp sd-ui-files/scripts/on_env_start.sh scripts/
4
+
5
+ source installer/etc/profile.d/conda.sh
6
+
7
+ cp sd-ui-files/scripts/developer_console.sh .
8
+ if [ -e "open_dev_console.sh" ]; then
9
+ rm "open_dev_console.sh"
10
+ fi
11
+
12
+ python -c "import os; import shutil; frm = 'sd-ui-files/ui/hotfix/9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'; dst = os.path.join(os.path.expanduser('~'), '.cache', 'huggingface', 'transformers', '9c24e6cd9f499d02c4f21a033736dabd365962dc80fe3aeb57a8f85ea45a20a3.26fead7ea4f0f843f6eb4055dfd25693f1a71f3c6871b184042d4b126244e142'); shutil.copyfile(frm, dst) if os.path.exists(dst) else print(''); print('Hotfixed broken JSON file from OpenAI');"
13
+
14
+ # Caution, this file will make your eyes and brain bleed. It's such an unholy mess.
15
+ # Note to self: Please rewrite this in Python. For the sake of your own sanity.
16
+
17
+ if [ -e "scripts/install_status.txt" ] && [ `grep -c sd_git_cloned scripts/install_status.txt` -gt "0" ]; then
18
+ echo "Stable Diffusion's git repository was already installed. Updating.."
19
+
20
+ cd stable-diffusion
21
+
22
+ git reset --hard
23
+ git pull
24
+ git checkout f6cfebffa752ee11a7b07497b8529d5971de916c
25
+
26
+ git apply ../ui/sd_internal/ddim_callback.patch
27
+ git apply ../ui/sd_internal/env_yaml.patch
28
+
29
+ cd ..
30
+ else
31
+ printf "\n\nDownloading Stable Diffusion..\n\n"
32
+
33
+ if git clone https://github.com/basujindal/stable-diffusion.git ; then
34
+ echo sd_git_cloned >> scripts/install_status.txt
35
+ else
36
+ printf "\n\nError downloading Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
37
+ read -p "Press any key to continue"
38
+ exit
39
+ fi
40
+
41
+ cd stable-diffusion
42
+ git checkout f6cfebffa752ee11a7b07497b8529d5971de916c
43
+
44
+ git apply ../ui/sd_internal/ddim_callback.patch
45
+ git apply ../ui/sd_internal/env_yaml.patch
46
+
47
+ cd ..
48
+ fi
49
+
50
+ cd stable-diffusion
51
+
52
+ if [ `grep -c conda_sd_env_created ../scripts/install_status.txt` -gt "0" ]; then
53
+ echo "Packages necessary for Stable Diffusion were already installed"
54
+
55
+ conda activate ./env
56
+ else
57
+ printf "\n\nDownloading packages necessary for Stable Diffusion..\n"
58
+ printf "\n\n***** This will take some time (depending on the speed of the Internet connection) and may appear to be stuck, but please be patient ***** ..\n\n"
59
+
60
+ # prevent conda from using packages from the user's home directory, to avoid conflicts
61
+ export PYTHONNOUSERSITE=1
62
+
63
+ if conda env create --prefix env --force -f environment.yaml ; then
64
+ echo "Installed. Testing.."
65
+ else
66
+ printf "\n\nError installing the packages necessary for Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
67
+ read -p "Press any key to continue"
68
+ exit
69
+ fi
70
+
71
+ conda activate ./env
72
+
73
+ if conda install -c conda-forge --prefix ./env -y antlr4-python3-runtime=4.8 ; then
74
+ echo "Installed. Testing.."
75
+ else
76
+ printf "\n\nError installing antlr4-python3-runtime for Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
77
+ read -p "Press any key to continue"
78
+ exit
79
+ fi
80
+
81
+ out_test=`python -c "import torch; import ldm; import transformers; import numpy; import antlr4; print(42)"`
82
+ if [ "$out_test" != "42" ]; then
83
+ printf "\n\nDependency test failed! Error installing the packages necessary for Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
84
+ read -p "Press any key to continue"
85
+ exit
86
+ fi
87
+
88
+ echo conda_sd_env_created >> ../scripts/install_status.txt
89
+ fi
90
+
91
+ if [ `grep -c conda_sd_gfpgan_deps_installed ../scripts/install_status.txt` -gt "0" ]; then
92
+ echo "Packages necessary for GFPGAN (Face Correction) were already installed"
93
+ else
94
+ printf "\n\nDownloading packages necessary for GFPGAN (Face Correction)..\n"
95
+
96
+ export PYTHONNOUSERSITE=1
97
+
98
+ if pip install -e git+https://github.com/TencentARC/GFPGAN#egg=GFPGAN ; then
99
+ echo "Installed. Testing.."
100
+ else
101
+ printf "\n\nError installing the packages necessary for GFPGAN (Face Correction). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
102
+ read -p "Press any key to continue"
103
+ exit
104
+ fi
105
+
106
+ out_test=`python -c "from gfpgan import GFPGANer; print(42)"`
107
+ if [ "$out_test" != "42" ]; then
108
+ printf "\n\nDependency test failed! Error installing the packages necessary for GFPGAN (Face Correction). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
109
+ read -p "Press any key to continue"
110
+ exit
111
+ fi
112
+
113
+ echo conda_sd_gfpgan_deps_installed >> ../scripts/install_status.txt
114
+ fi
115
+
116
+ if [ `grep -c conda_sd_esrgan_deps_installed ../scripts/install_status.txt` -gt "0" ]; then
117
+ echo "Packages necessary for ESRGAN (Resolution Upscaling) were already installed"
118
+ else
119
+ printf "\n\nDownloading packages necessary for ESRGAN (Resolution Upscaling)..\n"
120
+
121
+ export PYTHONNOUSERSITE=1
122
+
123
+ if pip install -e git+https://github.com/xinntao/Real-ESRGAN#egg=realesrgan ; then
124
+ echo "Installed. Testing.."
125
+ else
126
+ printf "\n\nError installing the packages necessary for ESRGAN (Resolution Upscaling). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
127
+ read -p "Press any key to continue"
128
+ exit
129
+ fi
130
+
131
+ out_test=`python -c "from basicsr.archs.rrdbnet_arch import RRDBNet; from realesrgan import RealESRGANer; print(42)"`
132
+ if [ "$out_test" != "42" ]; then
133
+ printf "\n\nDependency test failed! Error installing the packages necessary for ESRGAN (Resolution Upscaling). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
134
+ read -p "Press any key to continue"
135
+ exit
136
+ fi
137
+
138
+ echo conda_sd_esrgan_deps_installed >> ../scripts/install_status.txt
139
+ fi
140
+
141
+ if [ `grep -c conda_sd_ui_deps_installed ../scripts/install_status.txt` -gt "0" ]; then
142
+ echo "Packages necessary for Stable Diffusion UI were already installed"
143
+ else
144
+ printf "\n\nDownloading packages necessary for Stable Diffusion UI..\n\n"
145
+
146
+ export PYTHONNOUSERSITE=1
147
+
148
+ if conda install -c conda-forge --prefix ./env -y uvicorn fastapi ; then
149
+ echo "Installed. Testing.."
150
+ else
151
+ printf "\n\nError installing the packages necessary for Stable Diffusion UI. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
152
+ read -p "Press any key to continue"
153
+ exit
154
+ fi
155
+
156
+ if ! command -v uvicorn &> /dev/null; then
157
+ printf "\n\nUI packages not found! Error installing the packages necessary for Stable Diffusion UI. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
158
+ read -p "Press any key to continue"
159
+ exit
160
+ fi
161
+
162
+ echo conda_sd_ui_deps_installed >> ../scripts/install_status.txt
163
+ fi
164
+
165
+
166
+
167
+ mkdir -p "../models/stable-diffusion"
168
+ echo "" > "../models/stable-diffusion/Put your custom ckpt files here.txt"
169
+
170
+ if [ -f "sd-v1-4.ckpt" ]; then
171
+ model_size=`find "sd-v1-4.ckpt" -printf "%s"`
172
+
173
+ if [ "$model_size" -eq "4265380512" ] || [ "$model_size" -eq "7703807346" ] || [ "$model_size" -eq "7703810927" ]; then
174
+ echo "Data files (weights) necessary for Stable Diffusion were already downloaded"
175
+ else
176
+ printf "\n\nThe model file present at $PWD/sd-v1-4.ckpt is invalid. It is only $model_size bytes in size. Re-downloading.."
177
+ rm sd-v1-4.ckpt
178
+ fi
179
+ fi
180
+
181
+ if [ ! -f "sd-v1-4.ckpt" ]; then
182
+ echo "Downloading data files (weights) for Stable Diffusion.."
183
+
184
+ curl -L -k https://me.cmdr2.org/stable-diffusion-ui/sd-v1-4.ckpt > sd-v1-4.ckpt
185
+
186
+ if [ -f "sd-v1-4.ckpt" ]; then
187
+ model_size=`find "sd-v1-4.ckpt" -printf "%s"`
188
+ if [ ! "$model_size" == "4265380512" ]; then
189
+ printf "\n\nError: The downloaded model file was invalid! Bytes downloaded: $model_size\n\n"
190
+ printf "\n\nError downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
191
+ read -p "Press any key to continue"
192
+ exit
193
+ fi
194
+ else
195
+ printf "\n\nError downloading the data files (weights) for Stable Diffusion. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
196
+ read -p "Press any key to continue"
197
+ exit
198
+ fi
199
+ fi
200
+
201
+
202
+ if [ -f "GFPGANv1.3.pth" ]; then
203
+ model_size=`find "GFPGANv1.3.pth" -printf "%s"`
204
+
205
+ if [ "$model_size" -eq "348632874" ]; then
206
+ echo "Data files (weights) necessary for GFPGAN (Face Correction) were already downloaded"
207
+ else
208
+ printf "\n\nThe model file present at $PWD/GFPGANv1.3.pth is invalid. It is only $model_size bytes in size. Re-downloading.."
209
+ rm GFPGANv1.3.pth
210
+ fi
211
+ fi
212
+
213
+ if [ ! -f "GFPGANv1.3.pth" ]; then
214
+ echo "Downloading data files (weights) for GFPGAN (Face Correction).."
215
+
216
+ curl -L -k https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth > GFPGANv1.3.pth
217
+
218
+ if [ -f "GFPGANv1.3.pth" ]; then
219
+ model_size=`find "GFPGANv1.3.pth" -printf "%s"`
220
+ if [ ! "$model_size" -eq "348632874" ]; then
221
+ printf "\n\nError: The downloaded GFPGAN model file was invalid! Bytes downloaded: $model_size\n\n"
222
+ printf "\n\nError downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
223
+ read -p "Press any key to continue"
224
+ exit
225
+ fi
226
+ else
227
+ printf "\n\nError downloading the data files (weights) for GFPGAN (Face Correction). Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
228
+ read -p "Press any key to continue"
229
+ exit
230
+ fi
231
+ fi
232
+
233
+
234
+ if [ -f "RealESRGAN_x4plus.pth" ]; then
235
+ model_size=`find "RealESRGAN_x4plus.pth" -printf "%s"`
236
+
237
+ if [ "$model_size" -eq "67040989" ]; then
238
+ echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus were already downloaded"
239
+ else
240
+ printf "\n\nThe model file present at $PWD/RealESRGAN_x4plus.pth is invalid. It is only $model_size bytes in size. Re-downloading.."
241
+ rm RealESRGAN_x4plus.pth
242
+ fi
243
+ fi
244
+
245
+ if [ ! -f "RealESRGAN_x4plus.pth" ]; then
246
+ echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus.."
247
+
248
+ curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth > RealESRGAN_x4plus.pth
249
+
250
+ if [ -f "RealESRGAN_x4plus.pth" ]; then
251
+ model_size=`find "RealESRGAN_x4plus.pth" -printf "%s"`
252
+ if [ ! "$model_size" -eq "67040989" ]; then
253
+ printf "\n\nError: The downloaded ESRGAN x4plus model file was invalid! Bytes downloaded: $model_size\n\n"
254
+ printf "\n\nError downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
255
+ read -p "Press any key to continue"
256
+ exit
257
+ fi
258
+ else
259
+ printf "\n\nError downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
260
+ read -p "Press any key to continue"
261
+ exit
262
+ fi
263
+ fi
264
+
265
+
266
+ if [ -f "RealESRGAN_x4plus_anime_6B.pth" ]; then
267
+ model_size=`find "RealESRGAN_x4plus_anime_6B.pth" -printf "%s"`
268
+
269
+ if [ "$model_size" -eq "17938799" ]; then
270
+ echo "Data files (weights) necessary for ESRGAN (Resolution Upscaling) x4plus_anime were already downloaded"
271
+ else
272
+ printf "\n\nThe model file present at $PWD/RealESRGAN_x4plus_anime_6B.pth is invalid. It is only $model_size bytes in size. Re-downloading.."
273
+ rm RealESRGAN_x4plus_anime_6B.pth
274
+ fi
275
+ fi
276
+
277
+ if [ ! -f "RealESRGAN_x4plus_anime_6B.pth" ]; then
278
+ echo "Downloading data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime.."
279
+
280
+ curl -L -k https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth > RealESRGAN_x4plus_anime_6B.pth
281
+
282
+ if [ -f "RealESRGAN_x4plus_anime_6B.pth" ]; then
283
+ model_size=`find "RealESRGAN_x4plus_anime_6B.pth" -printf "%s"`
284
+ if [ ! "$model_size" -eq "17938799" ]; then
285
+ printf "\n\nError: The downloaded ESRGAN x4plus_anime model file was invalid! Bytes downloaded: $model_size\n\n"
286
+ printf "\n\nError downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
287
+ read -p "Press any key to continue"
288
+ exit
289
+ fi
290
+ else
291
+ printf "\n\nError downloading the data files (weights) for ESRGAN (Resolution Upscaling) x4plus_anime. Sorry about that, please try to:\n 1. Run this installer again.\n 2. If that doesn't fix it, please try the common troubleshooting steps at https://github.com/cmdr2/stable-diffusion-ui/blob/main/Troubleshooting.md\n 3. If those steps don't help, please copy *all* the error messages in this window, and ask the community at https://discord.com/invite/u9yhsFmEkB\n 4. If that doesn't solve the problem, please file an issue at https://github.com/cmdr2/stable-diffusion-ui/issues\nThanks!\n\n"
292
+ read -p "Press any key to continue"
293
+ exit
294
+ fi
295
+ fi
296
+
297
+
298
+ if [ `grep -c sd_install_complete ../scripts/install_status.txt` -gt "0" ]; then
299
+ echo sd_weights_downloaded >> ../scripts/install_status.txt
300
+ echo sd_install_complete >> ../scripts/install_status.txt
301
+ fi
302
+
303
+ printf "\n\nStable Diffusion is ready!\n\n"
304
+
305
+ SD_PATH=`pwd`
306
+ export PYTHONPATH="$SD_PATH;$SD_PATH/env/lib/python3.8/site-packages"
307
+ echo "PYTHONPATH=$PYTHONPATH"
308
+
309
+ cd ..
310
+ export SD_UI_PATH=`pwd`/ui
311
+ cd stable-diffusion
312
+
313
+ python --version
314
+
315
+ uvicorn server:app --app-dir "$SD_UI_PATH" --port 9000 --host 0.0.0.0
316
+
317
+ read -p "Press any key to continue"
ui/scripts/post_activate.bat ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ @call conda --version
2
+ @call git --version
3
+
4
+ cd %CONDA_PREFIX%\..\scripts
5
+
6
+ on_env_start.bat
ui/scripts/post_activate.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ conda-unpack
4
+
5
+ source $CONDA_PREFIX/etc/profile.d/conda.sh
6
+
7
+ conda --version
8
+ git --version
9
+
10
+ cd $CONDA_PREFIX/../scripts
11
+
12
+ ./on_env_start.sh
ui/scripts/start.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ source installer/bin/activate
4
+
5
+ conda-unpack
6
+
7
+ conda --version
8
+ git --version
9
+
10
+ scripts/on_env_start.sh
ui/scripts/win_enable_long_filepaths.ps1 ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem' -Name LongPathsEnabled -Type DWord -Value 1
2
+ pause