Qi28 commited on
Commit
8a414fc
·
verified ·
1 Parent(s): 2cc41d7

Upload 3 files

Browse files
Files changed (3) hide show
  1. modules/api.py +937 -0
  2. modules/img2img.py +256 -0
  3. modules/txt2img.py +123 -0
modules/api.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import io
3
+ import os
4
+ import time
5
+ import datetime
6
+ import uvicorn
7
+ import ipaddress
8
+ import requests
9
+ import gradio as gr
10
+ from threading import Lock
11
+ from io import BytesIO
12
+ from fastapi import APIRouter, Depends, FastAPI, Request, Response
13
+ from fastapi.security import HTTPBasic, HTTPBasicCredentials
14
+ from fastapi.exceptions import HTTPException
15
+ from fastapi.responses import JSONResponse
16
+ from fastapi.encoders import jsonable_encoder
17
+ from secrets import compare_digest
18
+
19
+ import modules.shared as shared
20
+ from modules import sd_samplers, deepbooru, sd_hijack, images, scripts, ui, postprocessing, errors, restart, shared_items, script_callbacks, infotext_utils, sd_models, sd_schedulers
21
+ from modules.api import models
22
+ from modules.shared import opts
23
+ from modules.processing import StableDiffusionProcessingTxt2Img, StableDiffusionProcessingImg2Img, process_images
24
+ from modules.textual_inversion.textual_inversion import create_embedding, train_embedding
25
+ from modules.hypernetworks.hypernetwork import create_hypernetwork, train_hypernetwork
26
+ from PIL import PngImagePlugin
27
+ from modules.sd_models_config import find_checkpoint_config_near_filename
28
+ from modules.realesrgan_model import get_realesrgan_models
29
+ from modules import devices
30
+ from typing import Any
31
+ import piexif
32
+ import piexif.helper
33
+ from contextlib import closing
34
+ from modules.progress import create_task_id, add_task_to_queue, start_task, finish_task, current_task
35
+
36
+ def script_name_to_index(name, scripts):
37
+ try:
38
+ return [script.title().lower() for script in scripts].index(name.lower())
39
+ except Exception as e:
40
+ raise HTTPException(status_code=422, detail=f"Script '{name}' not found") from e
41
+
42
+
43
+ def validate_sampler_name(name):
44
+ config = sd_samplers.all_samplers_map.get(name, None)
45
+ if config is None:
46
+ raise HTTPException(status_code=400, detail="Sampler not found")
47
+
48
+ return name
49
+
50
+
51
+ def setUpscalers(req: dict):
52
+ reqDict = vars(req)
53
+ reqDict['extras_upscaler_1'] = reqDict.pop('upscaler_1', None)
54
+ reqDict['extras_upscaler_2'] = reqDict.pop('upscaler_2', None)
55
+ return reqDict
56
+
57
+
58
+ def verify_url(url):
59
+ """Returns True if the url refers to a global resource."""
60
+
61
+ import socket
62
+ from urllib.parse import urlparse
63
+ try:
64
+ parsed_url = urlparse(url)
65
+ domain_name = parsed_url.netloc
66
+ host = socket.gethostbyname_ex(domain_name)
67
+ for ip in host[2]:
68
+ ip_addr = ipaddress.ip_address(ip)
69
+ if not ip_addr.is_global:
70
+ return False
71
+ except Exception:
72
+ return False
73
+
74
+ return True
75
+
76
+
77
+ def decode_base64_to_image(encoding):
78
+ if encoding.startswith("http://") or encoding.startswith("https://"):
79
+ if not opts.api_enable_requests:
80
+ raise HTTPException(status_code=500, detail="Requests not allowed")
81
+
82
+ if opts.api_forbid_local_requests and not verify_url(encoding):
83
+ raise HTTPException(status_code=500, detail="Request to local resource not allowed")
84
+
85
+ headers = {'user-agent': opts.api_useragent} if opts.api_useragent else {}
86
+ response = requests.get(encoding, timeout=30, headers=headers)
87
+ try:
88
+ image = images.read(BytesIO(response.content))
89
+ return image
90
+ except Exception as e:
91
+ raise HTTPException(status_code=500, detail="Invalid image url") from e
92
+
93
+ if encoding.startswith("data:image/"):
94
+ encoding = encoding.split(";")[1].split(",")[1]
95
+ try:
96
+ image = images.read(BytesIO(base64.b64decode(encoding)))
97
+ return image
98
+ except Exception as e:
99
+ raise HTTPException(status_code=500, detail="Invalid encoded image") from e
100
+
101
+
102
+ def encode_pil_to_base64(image):
103
+ with io.BytesIO() as output_bytes:
104
+ if isinstance(image, str):
105
+ return image
106
+ if opts.samples_format.lower() == 'png':
107
+ use_metadata = False
108
+ metadata = PngImagePlugin.PngInfo()
109
+ for key, value in image.info.items():
110
+ if isinstance(key, str) and isinstance(value, str):
111
+ metadata.add_text(key, value)
112
+ use_metadata = True
113
+ image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)
114
+
115
+ elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
116
+ if image.mode in ("RGBA", "P"):
117
+ image = image.convert("RGB")
118
+ parameters = image.info.get('parameters', None)
119
+ exif_bytes = piexif.dump({
120
+ "Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode") }
121
+ })
122
+ if opts.samples_format.lower() in ("jpg", "jpeg"):
123
+ image.save(output_bytes, format="JPEG", exif = exif_bytes, quality=opts.jpeg_quality)
124
+ else:
125
+ image.save(output_bytes, format="WEBP", exif = exif_bytes, quality=opts.jpeg_quality)
126
+
127
+ else:
128
+ raise HTTPException(status_code=500, detail="Invalid image format")
129
+
130
+ bytes_data = output_bytes.getvalue()
131
+
132
+ return base64.b64encode(bytes_data)
133
+
134
+
135
+ def api_middleware(app: FastAPI):
136
+ rich_available = False
137
+ try:
138
+ if os.environ.get('WEBUI_RICH_EXCEPTIONS', None) is not None:
139
+ import anyio # importing just so it can be placed on silent list
140
+ import starlette # importing just so it can be placed on silent list
141
+ from rich.console import Console
142
+ console = Console()
143
+ rich_available = True
144
+ except Exception:
145
+ pass
146
+
147
+ @app.middleware("http")
148
+ async def log_and_time(req: Request, call_next):
149
+ ts = time.time()
150
+ res: Response = await call_next(req)
151
+ duration = str(round(time.time() - ts, 4))
152
+ res.headers["X-Process-Time"] = duration
153
+ endpoint = req.scope.get('path', 'err')
154
+ if shared.cmd_opts.api_log and endpoint.startswith('/sdapi'):
155
+ print('API {t} {code} {prot}/{ver} {method} {endpoint} {cli} {duration}'.format(
156
+ t=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
157
+ code=res.status_code,
158
+ ver=req.scope.get('http_version', '0.0'),
159
+ cli=req.scope.get('client', ('0:0.0.0', 0))[0],
160
+ prot=req.scope.get('scheme', 'err'),
161
+ method=req.scope.get('method', 'err'),
162
+ endpoint=endpoint,
163
+ duration=duration,
164
+ ))
165
+ return res
166
+
167
+ def handle_exception(request: Request, e: Exception):
168
+ err = {
169
+ "error": type(e).__name__,
170
+ "detail": vars(e).get('detail', ''),
171
+ "body": vars(e).get('body', ''),
172
+ "errors": str(e),
173
+ }
174
+ if not isinstance(e, HTTPException): # do not print backtrace on known httpexceptions
175
+ message = f"API error: {request.method}: {request.url} {err}"
176
+ if rich_available:
177
+ print(message)
178
+ console.print_exception(show_locals=True, max_frames=2, extra_lines=1, suppress=[anyio, starlette], word_wrap=False, width=min([console.width, 200]))
179
+ else:
180
+ errors.report(message, exc_info=True)
181
+ return JSONResponse(status_code=vars(e).get('status_code', 500), content=jsonable_encoder(err))
182
+
183
+ @app.middleware("http")
184
+ async def exception_handling(request: Request, call_next):
185
+ try:
186
+ return await call_next(request)
187
+ except Exception as e:
188
+ return handle_exception(request, e)
189
+
190
+ @app.exception_handler(Exception)
191
+ async def fastapi_exception_handler(request: Request, e: Exception):
192
+ return handle_exception(request, e)
193
+
194
+ @app.exception_handler(HTTPException)
195
+ async def http_exception_handler(request: Request, e: HTTPException):
196
+ return handle_exception(request, e)
197
+
198
+
199
+ class Api:
200
+ def __init__(self, app: FastAPI, queue_lock: Lock):
201
+ if shared.cmd_opts.api_auth:
202
+ self.credentials = {}
203
+ for auth in shared.cmd_opts.api_auth.split(","):
204
+ user, password = auth.split(":")
205
+ self.credentials[user] = password
206
+
207
+ self.router = APIRouter()
208
+ self.app = app
209
+ self.queue_lock = queue_lock
210
+ api_middleware(self.app)
211
+ self.add_api_route("/sdapi/v1/txt2img", self.text2imgapi, methods=["POST"], response_model=models.TextToImageResponse)
212
+ self.add_api_route("/sdapi/v1/img2img", self.img2imgapi, methods=["POST"], response_model=models.ImageToImageResponse)
213
+ self.add_api_route("/sdapi/v1/extra-single-image", self.extras_single_image_api, methods=["POST"], response_model=models.ExtrasSingleImageResponse)
214
+ self.add_api_route("/sdapi/v1/extra-batch-images", self.extras_batch_images_api, methods=["POST"], response_model=models.ExtrasBatchImagesResponse)
215
+ self.add_api_route("/sdapi/v1/png-info", self.pnginfoapi, methods=["POST"], response_model=models.PNGInfoResponse)
216
+ self.add_api_route("/sdapi/v1/progress", self.progressapi, methods=["GET"], response_model=models.ProgressResponse)
217
+ self.add_api_route("/sdapi/v1/interrogate", self.interrogateapi, methods=["POST"])
218
+ self.add_api_route("/sdapi/v1/interrupt", self.interruptapi, methods=["POST"])
219
+ self.add_api_route("/sdapi/v1/skip", self.skip, methods=["POST"])
220
+ self.add_api_route("/sdapi/v1/options", self.get_config, methods=["GET"], response_model=models.OptionsModel)
221
+ self.add_api_route("/sdapi/v1/options", self.set_config, methods=["POST"])
222
+ self.add_api_route("/sdapi/v1/cmd-flags", self.get_cmd_flags, methods=["GET"], response_model=models.FlagsModel)
223
+ self.add_api_route("/sdapi/v1/samplers", self.get_samplers, methods=["GET"], response_model=list[models.SamplerItem])
224
+ self.add_api_route("/sdapi/v1/schedulers", self.get_schedulers, methods=["GET"], response_model=list[models.SchedulerItem])
225
+ self.add_api_route("/sdapi/v1/upscalers", self.get_upscalers, methods=["GET"], response_model=list[models.UpscalerItem])
226
+ self.add_api_route("/sdapi/v1/latent-upscale-modes", self.get_latent_upscale_modes, methods=["GET"], response_model=list[models.LatentUpscalerModeItem])
227
+ self.add_api_route("/sdapi/v1/sd-models", self.get_sd_models, methods=["GET"], response_model=list[models.SDModelItem])
228
+ self.add_api_route("/sdapi/v1/sd-vae", self.get_sd_vaes, methods=["GET"], response_model=list[models.SDVaeItem])
229
+ self.add_api_route("/sdapi/v1/hypernetworks", self.get_hypernetworks, methods=["GET"], response_model=list[models.HypernetworkItem])
230
+ self.add_api_route("/sdapi/v1/face-restorers", self.get_face_restorers, methods=["GET"], response_model=list[models.FaceRestorerItem])
231
+ self.add_api_route("/sdapi/v1/realesrgan-models", self.get_realesrgan_models, methods=["GET"], response_model=list[models.RealesrganItem])
232
+ self.add_api_route("/sdapi/v1/prompt-styles", self.get_prompt_styles, methods=["GET"], response_model=list[models.PromptStyleItem])
233
+ self.add_api_route("/sdapi/v1/embeddings", self.get_embeddings, methods=["GET"], response_model=models.EmbeddingsResponse)
234
+ self.add_api_route("/sdapi/v1/refresh-embeddings", self.refresh_embeddings, methods=["POST"])
235
+ self.add_api_route("/sdapi/v1/refresh-checkpoints", self.refresh_checkpoints, methods=["POST"])
236
+ self.add_api_route("/sdapi/v1/refresh-vae", self.refresh_vae, methods=["POST"])
237
+ self.add_api_route("/sdapi/v1/create/embedding", self.create_embedding, methods=["POST"], response_model=models.CreateResponse)
238
+ self.add_api_route("/sdapi/v1/create/hypernetwork", self.create_hypernetwork, methods=["POST"], response_model=models.CreateResponse)
239
+ self.add_api_route("/sdapi/v1/train/embedding", self.train_embedding, methods=["POST"], response_model=models.TrainResponse)
240
+ self.add_api_route("/sdapi/v1/train/hypernetwork", self.train_hypernetwork, methods=["POST"], response_model=models.TrainResponse)
241
+ self.add_api_route("/sdapi/v1/memory", self.get_memory, methods=["GET"], response_model=models.MemoryResponse)
242
+ self.add_api_route("/sdapi/v1/unload-checkpoint", self.unloadapi, methods=["POST"])
243
+ self.add_api_route("/sdapi/v1/reload-checkpoint", self.reloadapi, methods=["POST"])
244
+ self.add_api_route("/sdapi/v1/scripts", self.get_scripts_list, methods=["GET"], response_model=models.ScriptsList)
245
+ self.add_api_route("/sdapi/v1/script-info", self.get_script_info, methods=["GET"], response_model=list[models.ScriptInfo])
246
+ self.add_api_route("/sdapi/v1/extensions", self.get_extensions_list, methods=["GET"], response_model=list[models.ExtensionItem])
247
+
248
+ if shared.cmd_opts.api_server_stop:
249
+ self.add_api_route("/sdapi/v1/server-kill", self.kill_webui, methods=["POST"])
250
+ self.add_api_route("/sdapi/v1/server-restart", self.restart_webui, methods=["POST"])
251
+ self.add_api_route("/sdapi/v1/server-stop", self.stop_webui, methods=["POST"])
252
+
253
+ self.default_script_arg_txt2img = []
254
+ self.default_script_arg_img2img = []
255
+
256
+ txt2img_script_runner = scripts.scripts_txt2img
257
+ img2img_script_runner = scripts.scripts_img2img
258
+
259
+ if not txt2img_script_runner.scripts or not img2img_script_runner.scripts:
260
+ ui.create_ui()
261
+
262
+ if not txt2img_script_runner.scripts:
263
+ txt2img_script_runner.initialize_scripts(False)
264
+ if not self.default_script_arg_txt2img:
265
+ self.default_script_arg_txt2img = self.init_default_script_args(txt2img_script_runner)
266
+
267
+ if not img2img_script_runner.scripts:
268
+ img2img_script_runner.initialize_scripts(True)
269
+ if not self.default_script_arg_img2img:
270
+ self.default_script_arg_img2img = self.init_default_script_args(img2img_script_runner)
271
+
272
+
273
+
274
+ def add_api_route(self, path: str, endpoint, **kwargs):
275
+ if shared.cmd_opts.api_auth:
276
+ return self.app.add_api_route(path, endpoint, dependencies=[Depends(self.auth)], **kwargs)
277
+ return self.app.add_api_route(path, endpoint, **kwargs)
278
+
279
+ def auth(self, credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
280
+ if credentials.username in self.credentials:
281
+ if compare_digest(credentials.password, self.credentials[credentials.username]):
282
+ return True
283
+
284
+ raise HTTPException(status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"})
285
+
286
+ def get_selectable_script(self, script_name, script_runner):
287
+ if script_name is None or script_name == "":
288
+ return None, None
289
+
290
+ script_idx = script_name_to_index(script_name, script_runner.selectable_scripts)
291
+ script = script_runner.selectable_scripts[script_idx]
292
+ return script, script_idx
293
+
294
+ def get_scripts_list(self):
295
+ t2ilist = [script.name for script in scripts.scripts_txt2img.scripts if script.name is not None]
296
+ i2ilist = [script.name for script in scripts.scripts_img2img.scripts if script.name is not None]
297
+
298
+ return models.ScriptsList(txt2img=t2ilist, img2img=i2ilist)
299
+
300
+ def get_script_info(self):
301
+ res = []
302
+
303
+ for script_list in [scripts.scripts_txt2img.scripts, scripts.scripts_img2img.scripts]:
304
+ res += [script.api_info for script in script_list if script.api_info is not None]
305
+
306
+ return res
307
+
308
+ def get_script(self, script_name, script_runner):
309
+ if script_name is None or script_name == "":
310
+ return None, None
311
+
312
+ script_idx = script_name_to_index(script_name, script_runner.scripts)
313
+ return script_runner.scripts[script_idx]
314
+
315
+ def init_default_script_args(self, script_runner):
316
+ #find max idx from the scripts in runner and generate a none array to init script_args
317
+ last_arg_index = 1
318
+ for script in script_runner.scripts:
319
+ if last_arg_index < script.args_to:
320
+ last_arg_index = script.args_to
321
+ # None everywhere except position 0 to initialize script args
322
+ script_args = [None]*last_arg_index
323
+ script_args[0] = 0
324
+
325
+ # get default values
326
+ with gr.Blocks(): # will throw errors calling ui function without this
327
+ for script in script_runner.scripts:
328
+ if script.ui(script.is_img2img):
329
+ ui_default_values = []
330
+ for elem in script.ui(script.is_img2img):
331
+ ui_default_values.append(elem.value)
332
+ script_args[script.args_from:script.args_to] = ui_default_values
333
+ return script_args
334
+
335
+ def init_script_args(self, request, default_script_args, selectable_scripts, selectable_idx, script_runner, *, input_script_args=None):
336
+ script_args = default_script_args.copy()
337
+
338
+ if input_script_args is not None:
339
+ for index, value in input_script_args.items():
340
+ script_args[index] = value
341
+
342
+ # position 0 in script_arg is the idx+1 of the selectable script that is going to be run when using scripts.scripts_*2img.run()
343
+ if selectable_scripts:
344
+ script_args[selectable_scripts.args_from:selectable_scripts.args_to] = request.script_args
345
+ script_args[0] = selectable_idx + 1
346
+
347
+ # Now check for always on scripts
348
+ if request.alwayson_scripts:
349
+ for alwayson_script_name in request.alwayson_scripts.keys():
350
+ alwayson_script = self.get_script(alwayson_script_name, script_runner)
351
+ if alwayson_script is None:
352
+ raise HTTPException(status_code=422, detail=f"always on script {alwayson_script_name} not found")
353
+ # Selectable script in always on script param check
354
+ if alwayson_script.alwayson is False:
355
+ raise HTTPException(status_code=422, detail="Cannot have a selectable script in the always on scripts params")
356
+ # always on script with no arg should always run so you don't really need to add them to the requests
357
+ if "args" in request.alwayson_scripts[alwayson_script_name]:
358
+ # min between arg length in scriptrunner and arg length in the request
359
+ for idx in range(0, min((alwayson_script.args_to - alwayson_script.args_from), len(request.alwayson_scripts[alwayson_script_name]["args"]))):
360
+ script_args[alwayson_script.args_from + idx] = request.alwayson_scripts[alwayson_script_name]["args"][idx]
361
+ return script_args
362
+
363
+ def apply_infotext(self, request, tabname, *, script_runner=None, mentioned_script_args=None):
364
+ """Processes `infotext` field from the `request`, and sets other fields of the `request` according to what's in infotext.
365
+
366
+ If request already has a field set, and that field is encountered in infotext too, the value from infotext is ignored.
367
+
368
+ Additionally, fills `mentioned_script_args` dict with index: value pairs for script arguments read from infotext.
369
+ """
370
+
371
+ if not request.infotext:
372
+ return {}
373
+
374
+ possible_fields = infotext_utils.paste_fields[tabname]["fields"]
375
+ set_fields = request.model_dump(exclude_unset=True) if hasattr(request, "request") else request.dict(exclude_unset=True) # pydantic v1/v2 have different names for this
376
+ params = infotext_utils.parse_generation_parameters(request.infotext)
377
+
378
+ def get_field_value(field, params):
379
+ value = field.function(params) if field.function else params.get(field.label)
380
+ if value is None:
381
+ return None
382
+
383
+ if field.api in request.__fields__:
384
+ target_type = request.__fields__[field.api].type_
385
+ else:
386
+ target_type = type(field.component.value)
387
+
388
+ if target_type == type(None):
389
+ return None
390
+
391
+ if isinstance(value, dict) and value.get('__type__') == 'generic_update': # this is a gradio.update rather than a value
392
+ value = value.get('value')
393
+
394
+ if value is not None and not isinstance(value, target_type):
395
+ value = target_type(value)
396
+
397
+ return value
398
+
399
+ for field in possible_fields:
400
+ if not field.api:
401
+ continue
402
+
403
+ if field.api in set_fields:
404
+ continue
405
+
406
+ value = get_field_value(field, params)
407
+ if value is not None:
408
+ setattr(request, field.api, value)
409
+
410
+ if request.override_settings is None:
411
+ request.override_settings = {}
412
+
413
+ overridden_settings = infotext_utils.get_override_settings(params)
414
+ for _, setting_name, value in overridden_settings:
415
+ if setting_name not in request.override_settings:
416
+ request.override_settings[setting_name] = value
417
+
418
+ if script_runner is not None and mentioned_script_args is not None:
419
+ indexes = {v: i for i, v in enumerate(script_runner.inputs)}
420
+ script_fields = ((field, indexes[field.component]) for field in possible_fields if field.component in indexes)
421
+
422
+ for field, index in script_fields:
423
+ value = get_field_value(field, params)
424
+
425
+ if value is None:
426
+ continue
427
+
428
+ mentioned_script_args[index] = value
429
+
430
+ return params
431
+
432
+ def text2imgapi(self, txt2imgreq: models.StableDiffusionTxt2ImgProcessingAPI):
433
+ task_id = txt2imgreq.force_task_id or create_task_id("txt2img")
434
+ script_runner = scripts.scripts_txt2img
435
+ print('-------------API----------------')
436
+ # print(txt2imgreq)
437
+ print(f'宽高:{txt2imgreq.width}X{txt2imgreq.height} 数量:{txt2imgreq.batch_size} 批次:{txt2imgreq.n_iter} 步数:{txt2imgreq.steps} CFG:{txt2imgreq.cfg_scale} 高清修复:{txt2imgreq.enable_hr} ')
438
+ print('文生图正面提示词',txt2imgreq.prompt)
439
+ print('文生图负面提示词',txt2imgreq.negative_prompt)
440
+ print('-------------------------------')
441
+ infotext_script_args = {}
442
+ self.apply_infotext(txt2imgreq, "txt2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
443
+
444
+ selectable_scripts, selectable_script_idx = self.get_selectable_script(txt2imgreq.script_name, script_runner)
445
+ sampler, scheduler = sd_samplers.get_sampler_and_scheduler(txt2imgreq.sampler_name or txt2imgreq.sampler_index, txt2imgreq.scheduler)
446
+
447
+ populate = txt2imgreq.copy(update={ # Override __init__ params
448
+ "sampler_name": validate_sampler_name(sampler),
449
+ "do_not_save_samples": not txt2imgreq.save_images,
450
+ "do_not_save_grid": not txt2imgreq.save_images,
451
+ })
452
+ if populate.sampler_name:
453
+ populate.sampler_index = None # prevent a warning later on
454
+
455
+ if not populate.scheduler and scheduler != "Automatic":
456
+ populate.scheduler = scheduler
457
+
458
+ args = vars(populate)
459
+ args.pop('script_name', None)
460
+ args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
461
+ args.pop('alwayson_scripts', None)
462
+ args.pop('infotext', None)
463
+
464
+ script_args = self.init_script_args(txt2imgreq, self.default_script_arg_txt2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
465
+
466
+ send_images = args.pop('send_images', True)
467
+ args.pop('save_images', None)
468
+
469
+ add_task_to_queue(task_id)
470
+
471
+ with self.queue_lock:
472
+ with closing(StableDiffusionProcessingTxt2Img(sd_model=shared.sd_model, **args)) as p:
473
+ p.is_api = True
474
+ p.scripts = script_runner
475
+ p.outpath_grids = opts.outdir_txt2img_grids
476
+ p.outpath_samples = opts.outdir_txt2img_samples
477
+
478
+ try:
479
+ shared.state.begin(job="scripts_txt2img")
480
+ start_task(task_id)
481
+ if selectable_scripts is not None:
482
+ p.script_args = script_args
483
+ processed = scripts.scripts_txt2img.run(p, *p.script_args) # Need to pass args as list here
484
+ else:
485
+ p.script_args = tuple(script_args) # Need to pass args as tuple here
486
+ processed = process_images(p)
487
+ finish_task(task_id)
488
+ finally:
489
+ shared.state.end()
490
+ shared.total_tqdm.clear()
491
+
492
+ b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
493
+
494
+ return models.TextToImageResponse(images=b64images, parameters=vars(txt2imgreq), info=processed.js())
495
+
496
+ def img2imgapi(self, img2imgreq: models.StableDiffusionImg2ImgProcessingAPI):
497
+ task_id = img2imgreq.force_task_id or create_task_id("img2img")
498
+ init_images = img2imgreq.init_images
499
+ print('-------------API----------------')
500
+ # print(txt2imgreq)
501
+ print(f'宽高:{txt2imgreq.width}X{txt2imgreq.height} 数量:{txt2imgreq.batch_size} 批次:{txt2imgreq.n_iter} 步数:{txt2imgreq.steps} CFG:{txt2imgreq.cfg_scale} 高清修复:{txt2imgreq.enable_hr} ')
502
+ print('文生图正面提示词',txt2imgreq.prompt)
503
+ print('文生图负面提示词',txt2imgreq.negative_prompt)
504
+ print('-------------------------------')
505
+ if init_images is None:
506
+ raise HTTPException(status_code=404, detail="Init image not found")
507
+
508
+ mask = img2imgreq.mask
509
+ if mask:
510
+ mask = decode_base64_to_image(mask)
511
+
512
+ script_runner = scripts.scripts_img2img
513
+
514
+ infotext_script_args = {}
515
+ self.apply_infotext(img2imgreq, "img2img", script_runner=script_runner, mentioned_script_args=infotext_script_args)
516
+
517
+ selectable_scripts, selectable_script_idx = self.get_selectable_script(img2imgreq.script_name, script_runner)
518
+ sampler, scheduler = sd_samplers.get_sampler_and_scheduler(img2imgreq.sampler_name or img2imgreq.sampler_index, img2imgreq.scheduler)
519
+
520
+ populate = img2imgreq.copy(update={ # Override __init__ params
521
+ "sampler_name": validate_sampler_name(sampler),
522
+ "do_not_save_samples": not img2imgreq.save_images,
523
+ "do_not_save_grid": not img2imgreq.save_images,
524
+ "mask": mask,
525
+ })
526
+ if populate.sampler_name:
527
+ populate.sampler_index = None # prevent a warning later on
528
+
529
+ if not populate.scheduler and scheduler != "Automatic":
530
+ populate.scheduler = scheduler
531
+
532
+ args = vars(populate)
533
+ args.pop('include_init_images', None) # this is meant to be done by "exclude": True in model, but it's for a reason that I cannot determine.
534
+ args.pop('script_name', None)
535
+ args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
536
+ args.pop('alwayson_scripts', None)
537
+ args.pop('infotext', None)
538
+
539
+ script_args = self.init_script_args(img2imgreq, self.default_script_arg_img2img, selectable_scripts, selectable_script_idx, script_runner, input_script_args=infotext_script_args)
540
+
541
+ send_images = args.pop('send_images', True)
542
+ args.pop('save_images', None)
543
+
544
+ add_task_to_queue(task_id)
545
+
546
+ with self.queue_lock:
547
+ with closing(StableDiffusionProcessingImg2Img(sd_model=shared.sd_model, **args)) as p:
548
+ p.init_images = [decode_base64_to_image(x) for x in init_images]
549
+ p.is_api = True
550
+ p.scripts = script_runner
551
+ p.outpath_grids = opts.outdir_img2img_grids
552
+ p.outpath_samples = opts.outdir_img2img_samples
553
+
554
+ try:
555
+ shared.state.begin(job="scripts_img2img")
556
+ start_task(task_id)
557
+ if selectable_scripts is not None:
558
+ p.script_args = script_args
559
+ processed = scripts.scripts_img2img.run(p, *p.script_args) # Need to pass args as list here
560
+ else:
561
+ p.script_args = tuple(script_args) # Need to pass args as tuple here
562
+ processed = process_images(p)
563
+ finish_task(task_id)
564
+ finally:
565
+ shared.state.end()
566
+ shared.total_tqdm.clear()
567
+
568
+ b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
569
+
570
+ if not img2imgreq.include_init_images:
571
+ img2imgreq.init_images = None
572
+ img2imgreq.mask = None
573
+
574
+ return models.ImageToImageResponse(images=b64images, parameters=vars(img2imgreq), info=processed.js())
575
+
576
+ def extras_single_image_api(self, req: models.ExtrasSingleImageRequest):
577
+ reqDict = setUpscalers(req)
578
+
579
+ reqDict['image'] = decode_base64_to_image(reqDict['image'])
580
+
581
+ with self.queue_lock:
582
+ result = postprocessing.run_extras(extras_mode=0, image_folder="", input_dir="", output_dir="", save_output=False, **reqDict)
583
+
584
+ return models.ExtrasSingleImageResponse(image=encode_pil_to_base64(result[0][0]), html_info=result[1])
585
+
586
+ def extras_batch_images_api(self, req: models.ExtrasBatchImagesRequest):
587
+ reqDict = setUpscalers(req)
588
+
589
+ image_list = reqDict.pop('imageList', [])
590
+ image_folder = [decode_base64_to_image(x.data) for x in image_list]
591
+
592
+ with self.queue_lock:
593
+ result = postprocessing.run_extras(extras_mode=1, image_folder=image_folder, image="", input_dir="", output_dir="", save_output=False, **reqDict)
594
+
595
+ return models.ExtrasBatchImagesResponse(images=list(map(encode_pil_to_base64, result[0])), html_info=result[1])
596
+
597
+ def pnginfoapi(self, req: models.PNGInfoRequest):
598
+ image = decode_base64_to_image(req.image.strip())
599
+ if image is None:
600
+ return models.PNGInfoResponse(info="")
601
+
602
+ geninfo, items = images.read_info_from_image(image)
603
+ if geninfo is None:
604
+ geninfo = ""
605
+
606
+ params = infotext_utils.parse_generation_parameters(geninfo)
607
+ script_callbacks.infotext_pasted_callback(geninfo, params)
608
+
609
+ return models.PNGInfoResponse(info=geninfo, items=items, parameters=params)
610
+
611
+ def progressapi(self, req: models.ProgressRequest = Depends()):
612
+ # copy from check_progress_call of ui.py
613
+
614
+ if shared.state.job_count == 0:
615
+ return models.ProgressResponse(progress=0, eta_relative=0, state=shared.state.dict(), textinfo=shared.state.textinfo)
616
+
617
+ # avoid dividing zero
618
+ progress = 0.01
619
+
620
+ if shared.state.job_count > 0:
621
+ progress += shared.state.job_no / shared.state.job_count
622
+ if shared.state.sampling_steps > 0:
623
+ progress += 1 / shared.state.job_count * shared.state.sampling_step / shared.state.sampling_steps
624
+
625
+ time_since_start = time.time() - shared.state.time_start
626
+ eta = (time_since_start/progress)
627
+ eta_relative = eta-time_since_start
628
+
629
+ progress = min(progress, 1)
630
+
631
+ shared.state.set_current_image()
632
+
633
+ current_image = None
634
+ if shared.state.current_image and not req.skip_current_image:
635
+ current_image = encode_pil_to_base64(shared.state.current_image)
636
+
637
+ return models.ProgressResponse(progress=progress, eta_relative=eta_relative, state=shared.state.dict(), current_image=current_image, textinfo=shared.state.textinfo, current_task=current_task)
638
+
639
+ def interrogateapi(self, interrogatereq: models.InterrogateRequest):
640
+ image_b64 = interrogatereq.image
641
+ if image_b64 is None:
642
+ raise HTTPException(status_code=404, detail="Image not found")
643
+
644
+ img = decode_base64_to_image(image_b64)
645
+ img = img.convert('RGB')
646
+
647
+ # Override object param
648
+ with self.queue_lock:
649
+ if interrogatereq.model == "clip":
650
+ processed = shared.interrogator.interrogate(img)
651
+ elif interrogatereq.model == "deepdanbooru":
652
+ processed = deepbooru.model.tag(img)
653
+ else:
654
+ raise HTTPException(status_code=404, detail="Model not found")
655
+
656
+ return models.InterrogateResponse(caption=processed)
657
+
658
+ def interruptapi(self):
659
+ shared.state.interrupt()
660
+
661
+ return {}
662
+
663
+ def unloadapi(self):
664
+ sd_models.unload_model_weights()
665
+
666
+ return {}
667
+
668
+ def reloadapi(self):
669
+ sd_models.send_model_to_device(shared.sd_model)
670
+
671
+ return {}
672
+
673
+ def skip(self):
674
+ shared.state.skip()
675
+
676
+ def get_config(self):
677
+ options = {}
678
+ for key in shared.opts.data.keys():
679
+ metadata = shared.opts.data_labels.get(key)
680
+ if(metadata is not None):
681
+ options.update({key: shared.opts.data.get(key, shared.opts.data_labels.get(key).default)})
682
+ else:
683
+ options.update({key: shared.opts.data.get(key, None)})
684
+
685
+ return options
686
+
687
+ def set_config(self, req: dict[str, Any]):
688
+ checkpoint_name = req.get("sd_model_checkpoint", None)
689
+ if checkpoint_name is not None and checkpoint_name not in sd_models.checkpoint_aliases:
690
+ raise RuntimeError(f"model {checkpoint_name!r} not found")
691
+
692
+ for k, v in req.items():
693
+ shared.opts.set(k, v, is_api=True)
694
+
695
+ shared.opts.save(shared.config_filename)
696
+ return
697
+
698
+ def get_cmd_flags(self):
699
+ return vars(shared.cmd_opts)
700
+
701
+ def get_samplers(self):
702
+ return [{"name": sampler[0], "aliases":sampler[2], "options":sampler[3]} for sampler in sd_samplers.all_samplers]
703
+
704
+ def get_schedulers(self):
705
+ return [
706
+ {
707
+ "name": scheduler.name,
708
+ "label": scheduler.label,
709
+ "aliases": scheduler.aliases,
710
+ "default_rho": scheduler.default_rho,
711
+ "need_inner_model": scheduler.need_inner_model,
712
+ }
713
+ for scheduler in sd_schedulers.schedulers]
714
+
715
+ def get_upscalers(self):
716
+ return [
717
+ {
718
+ "name": upscaler.name,
719
+ "model_name": upscaler.scaler.model_name,
720
+ "model_path": upscaler.data_path,
721
+ "model_url": None,
722
+ "scale": upscaler.scale,
723
+ }
724
+ for upscaler in shared.sd_upscalers
725
+ ]
726
+
727
+ def get_latent_upscale_modes(self):
728
+ return [
729
+ {
730
+ "name": upscale_mode,
731
+ }
732
+ for upscale_mode in [*(shared.latent_upscale_modes or {})]
733
+ ]
734
+
735
+ def get_sd_models(self):
736
+ import modules.sd_models as sd_models
737
+ return [{"title": x.title, "model_name": x.model_name, "hash": x.shorthash, "sha256": x.sha256, "filename": x.filename, "config": find_checkpoint_config_near_filename(x)} for x in sd_models.checkpoints_list.values()]
738
+
739
+ def get_sd_vaes(self):
740
+ import modules.sd_vae as sd_vae
741
+ return [{"model_name": x, "filename": sd_vae.vae_dict[x]} for x in sd_vae.vae_dict.keys()]
742
+
743
+ def get_hypernetworks(self):
744
+ return [{"name": name, "path": shared.hypernetworks[name]} for name in shared.hypernetworks]
745
+
746
+ def get_face_restorers(self):
747
+ return [{"name":x.name(), "cmd_dir": getattr(x, "cmd_dir", None)} for x in shared.face_restorers]
748
+
749
+ def get_realesrgan_models(self):
750
+ return [{"name":x.name,"path":x.data_path, "scale":x.scale} for x in get_realesrgan_models(None)]
751
+
752
+ def get_prompt_styles(self):
753
+ styleList = []
754
+ for k in shared.prompt_styles.styles:
755
+ style = shared.prompt_styles.styles[k]
756
+ styleList.append({"name":style[0], "prompt": style[1], "negative_prompt": style[2]})
757
+
758
+ return styleList
759
+
760
+ def get_embeddings(self):
761
+ db = sd_hijack.model_hijack.embedding_db
762
+
763
+ def convert_embedding(embedding):
764
+ return {
765
+ "step": embedding.step,
766
+ "sd_checkpoint": embedding.sd_checkpoint,
767
+ "sd_checkpoint_name": embedding.sd_checkpoint_name,
768
+ "shape": embedding.shape,
769
+ "vectors": embedding.vectors,
770
+ }
771
+
772
+ def convert_embeddings(embeddings):
773
+ return {embedding.name: convert_embedding(embedding) for embedding in embeddings.values()}
774
+
775
+ return {
776
+ "loaded": convert_embeddings(db.word_embeddings),
777
+ "skipped": convert_embeddings(db.skipped_embeddings),
778
+ }
779
+
780
+ def refresh_embeddings(self):
781
+ with self.queue_lock:
782
+ sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True)
783
+
784
+ def refresh_checkpoints(self):
785
+ with self.queue_lock:
786
+ shared.refresh_checkpoints()
787
+
788
+ def refresh_vae(self):
789
+ with self.queue_lock:
790
+ shared_items.refresh_vae_list()
791
+
792
+ def create_embedding(self, args: dict):
793
+ try:
794
+ shared.state.begin(job="create_embedding")
795
+ filename = create_embedding(**args) # create empty embedding
796
+ sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings() # reload embeddings so new one can be immediately used
797
+ return models.CreateResponse(info=f"create embedding filename: {filename}")
798
+ except AssertionError as e:
799
+ return models.TrainResponse(info=f"create embedding error: {e}")
800
+ finally:
801
+ shared.state.end()
802
+
803
+
804
+ def create_hypernetwork(self, args: dict):
805
+ try:
806
+ shared.state.begin(job="create_hypernetwork")
807
+ filename = create_hypernetwork(**args) # create empty embedding
808
+ return models.CreateResponse(info=f"create hypernetwork filename: {filename}")
809
+ except AssertionError as e:
810
+ return models.TrainResponse(info=f"create hypernetwork error: {e}")
811
+ finally:
812
+ shared.state.end()
813
+
814
+ def train_embedding(self, args: dict):
815
+ try:
816
+ shared.state.begin(job="train_embedding")
817
+ apply_optimizations = shared.opts.training_xattention_optimizations
818
+ error = None
819
+ filename = ''
820
+ if not apply_optimizations:
821
+ sd_hijack.undo_optimizations()
822
+ try:
823
+ embedding, filename = train_embedding(**args) # can take a long time to complete
824
+ except Exception as e:
825
+ error = e
826
+ finally:
827
+ if not apply_optimizations:
828
+ sd_hijack.apply_optimizations()
829
+ return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
830
+ except Exception as msg:
831
+ return models.TrainResponse(info=f"train embedding error: {msg}")
832
+ finally:
833
+ shared.state.end()
834
+
835
+ def train_hypernetwork(self, args: dict):
836
+ try:
837
+ shared.state.begin(job="train_hypernetwork")
838
+ shared.loaded_hypernetworks = []
839
+ apply_optimizations = shared.opts.training_xattention_optimizations
840
+ error = None
841
+ filename = ''
842
+ if not apply_optimizations:
843
+ sd_hijack.undo_optimizations()
844
+ try:
845
+ hypernetwork, filename = train_hypernetwork(**args)
846
+ except Exception as e:
847
+ error = e
848
+ finally:
849
+ shared.sd_model.cond_stage_model.to(devices.device)
850
+ shared.sd_model.first_stage_model.to(devices.device)
851
+ if not apply_optimizations:
852
+ sd_hijack.apply_optimizations()
853
+ shared.state.end()
854
+ return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
855
+ except Exception as exc:
856
+ return models.TrainResponse(info=f"train embedding error: {exc}")
857
+ finally:
858
+ shared.state.end()
859
+
860
+ def get_memory(self):
861
+ try:
862
+ import os
863
+ import psutil
864
+ process = psutil.Process(os.getpid())
865
+ res = process.memory_info() # only rss is cross-platform guaranteed so we dont rely on other values
866
+ ram_total = 100 * res.rss / process.memory_percent() # and total memory is calculated as actual value is not cross-platform safe
867
+ ram = { 'free': ram_total - res.rss, 'used': res.rss, 'total': ram_total }
868
+ except Exception as err:
869
+ ram = { 'error': f'{err}' }
870
+ try:
871
+ import torch
872
+ if torch.cuda.is_available():
873
+ s = torch.cuda.mem_get_info()
874
+ system = { 'free': s[0], 'used': s[1] - s[0], 'total': s[1] }
875
+ s = dict(torch.cuda.memory_stats(shared.device))
876
+ allocated = { 'current': s['allocated_bytes.all.current'], 'peak': s['allocated_bytes.all.peak'] }
877
+ reserved = { 'current': s['reserved_bytes.all.current'], 'peak': s['reserved_bytes.all.peak'] }
878
+ active = { 'current': s['active_bytes.all.current'], 'peak': s['active_bytes.all.peak'] }
879
+ inactive = { 'current': s['inactive_split_bytes.all.current'], 'peak': s['inactive_split_bytes.all.peak'] }
880
+ warnings = { 'retries': s['num_alloc_retries'], 'oom': s['num_ooms'] }
881
+ cuda = {
882
+ 'system': system,
883
+ 'active': active,
884
+ 'allocated': allocated,
885
+ 'reserved': reserved,
886
+ 'inactive': inactive,
887
+ 'events': warnings,
888
+ }
889
+ else:
890
+ cuda = {'error': 'unavailable'}
891
+ except Exception as err:
892
+ cuda = {'error': f'{err}'}
893
+ return models.MemoryResponse(ram=ram, cuda=cuda)
894
+
895
+ def get_extensions_list(self):
896
+ from modules import extensions
897
+ extensions.list_extensions()
898
+ ext_list = []
899
+ for ext in extensions.extensions:
900
+ ext: extensions.Extension
901
+ ext.read_info_from_repo()
902
+ if ext.remote is not None:
903
+ ext_list.append({
904
+ "name": ext.name,
905
+ "remote": ext.remote,
906
+ "branch": ext.branch,
907
+ "commit_hash":ext.commit_hash,
908
+ "commit_date":ext.commit_date,
909
+ "version":ext.version,
910
+ "enabled":ext.enabled
911
+ })
912
+ return ext_list
913
+
914
+ def launch(self, server_name, port, root_path):
915
+ self.app.include_router(self.router)
916
+ uvicorn.run(
917
+ self.app,
918
+ host=server_name,
919
+ port=port,
920
+ timeout_keep_alive=shared.cmd_opts.timeout_keep_alive,
921
+ root_path=root_path,
922
+ ssl_keyfile=shared.cmd_opts.tls_keyfile,
923
+ ssl_certfile=shared.cmd_opts.tls_certfile
924
+ )
925
+
926
+ def kill_webui(self):
927
+ restart.stop_program()
928
+
929
+ def restart_webui(self):
930
+ if restart.is_restartable():
931
+ restart.restart_program()
932
+ return Response(status_code=501)
933
+
934
+ def stop_webui(request):
935
+ shared.state.server_command = "stop"
936
+ return Response("Stopping.")
937
+
modules/img2img.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from contextlib import closing
3
+ from pathlib import Path
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageOps, ImageFilter, ImageEnhance, UnidentifiedImageError
7
+ import gradio as gr
8
+
9
+ from modules import images
10
+ from modules.infotext_utils import create_override_settings_dict, parse_generation_parameters
11
+ from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images
12
+ from modules.shared import opts, state
13
+ from modules.sd_models import get_closet_checkpoint_match
14
+ import modules.shared as shared
15
+ import modules.processing as processing
16
+ from modules.ui import plaintext_to_html
17
+ import modules.scripts
18
+
19
+
20
+ def process_batch(p, input, output_dir, inpaint_mask_dir, args, to_scale=False, scale_by=1.0, use_png_info=False, png_info_props=None, png_info_dir=None):
21
+ output_dir = output_dir.strip()
22
+ processing.fix_seed(p)
23
+
24
+ if isinstance(input, str):
25
+ batch_images = list(shared.walk_files(input, allowed_extensions=(".png", ".jpg", ".jpeg", ".webp", ".tif", ".tiff")))
26
+ else:
27
+ batch_images = [os.path.abspath(x.name) for x in input]
28
+
29
+ is_inpaint_batch = False
30
+ if inpaint_mask_dir:
31
+ inpaint_masks = shared.listfiles(inpaint_mask_dir)
32
+ is_inpaint_batch = bool(inpaint_masks)
33
+
34
+ if is_inpaint_batch:
35
+ print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")
36
+
37
+ print(f"Will process {len(batch_images)} images, creating {p.n_iter * p.batch_size} new images for each.")
38
+
39
+ state.job_count = len(batch_images) * p.n_iter
40
+
41
+ # extract "default" params to use in case getting png info fails
42
+ prompt = p.prompt
43
+ negative_prompt = p.negative_prompt
44
+ seed = p.seed
45
+ cfg_scale = p.cfg_scale
46
+ sampler_name = p.sampler_name
47
+ steps = p.steps
48
+ override_settings = p.override_settings
49
+ sd_model_checkpoint_override = get_closet_checkpoint_match(override_settings.get("sd_model_checkpoint", None))
50
+ batch_results = None
51
+ discard_further_results = False
52
+ for i, image in enumerate(batch_images):
53
+ state.job = f"{i+1} out of {len(batch_images)}"
54
+ if state.skipped:
55
+ state.skipped = False
56
+
57
+ if state.interrupted or state.stopping_generation:
58
+ break
59
+
60
+ try:
61
+ img = images.read(image)
62
+ except UnidentifiedImageError as e:
63
+ print(e)
64
+ continue
65
+ # Use the EXIF orientation of photos taken by smartphones.
66
+ img = ImageOps.exif_transpose(img)
67
+
68
+ if to_scale:
69
+ p.width = int(img.width * scale_by)
70
+ p.height = int(img.height * scale_by)
71
+
72
+ p.init_images = [img] * p.batch_size
73
+
74
+ image_path = Path(image)
75
+ if is_inpaint_batch:
76
+ # try to find corresponding mask for an image using simple filename matching
77
+ if len(inpaint_masks) == 1:
78
+ mask_image_path = inpaint_masks[0]
79
+ else:
80
+ # try to find corresponding mask for an image using simple filename matching
81
+ mask_image_dir = Path(inpaint_mask_dir)
82
+ masks_found = list(mask_image_dir.glob(f"{image_path.stem}.*"))
83
+
84
+ if len(masks_found) == 0:
85
+ print(f"Warning: mask is not found for {image_path} in {mask_image_dir}. Skipping it.")
86
+ continue
87
+
88
+ # it should contain only 1 matching mask
89
+ # otherwise user has many masks with the same name but different extensions
90
+ mask_image_path = masks_found[0]
91
+
92
+ mask_image = images.read(mask_image_path)
93
+ p.image_mask = mask_image
94
+
95
+ if use_png_info:
96
+ try:
97
+ info_img = img
98
+ if png_info_dir:
99
+ info_img_path = os.path.join(png_info_dir, os.path.basename(image))
100
+ info_img = images.read(info_img_path)
101
+ geninfo, _ = images.read_info_from_image(info_img)
102
+ parsed_parameters = parse_generation_parameters(geninfo)
103
+ parsed_parameters = {k: v for k, v in parsed_parameters.items() if k in (png_info_props or {})}
104
+ except Exception:
105
+ parsed_parameters = {}
106
+
107
+ p.prompt = prompt + (" " + parsed_parameters["Prompt"] if "Prompt" in parsed_parameters else "")
108
+ p.negative_prompt = negative_prompt + (" " + parsed_parameters["Negative prompt"] if "Negative prompt" in parsed_parameters else "")
109
+ p.seed = int(parsed_parameters.get("Seed", seed))
110
+ p.cfg_scale = float(parsed_parameters.get("CFG scale", cfg_scale))
111
+ p.sampler_name = parsed_parameters.get("Sampler", sampler_name)
112
+ p.steps = int(parsed_parameters.get("Steps", steps))
113
+
114
+ model_info = get_closet_checkpoint_match(parsed_parameters.get("Model hash", None))
115
+ if model_info is not None:
116
+ p.override_settings['sd_model_checkpoint'] = model_info.name
117
+ elif sd_model_checkpoint_override:
118
+ p.override_settings['sd_model_checkpoint'] = sd_model_checkpoint_override
119
+ else:
120
+ p.override_settings.pop("sd_model_checkpoint", None)
121
+
122
+ if output_dir:
123
+ p.outpath_samples = output_dir
124
+ p.override_settings['save_to_dirs'] = False
125
+ p.override_settings['save_images_replace_action'] = "Add number suffix"
126
+ if p.n_iter > 1 or p.batch_size > 1:
127
+ p.override_settings['samples_filename_pattern'] = f'{image_path.stem}-[generation_number]'
128
+ else:
129
+ p.override_settings['samples_filename_pattern'] = f'{image_path.stem}'
130
+
131
+ proc = modules.scripts.scripts_img2img.run(p, *args)
132
+
133
+ if proc is None:
134
+ p.override_settings.pop('save_images_replace_action', None)
135
+ proc = process_images(p)
136
+
137
+ if not discard_further_results and proc:
138
+ if batch_results:
139
+ batch_results.images.extend(proc.images)
140
+ batch_results.infotexts.extend(proc.infotexts)
141
+ else:
142
+ batch_results = proc
143
+
144
+ if 0 <= shared.opts.img2img_batch_show_results_limit < len(batch_results.images):
145
+ discard_further_results = True
146
+ batch_results.images = batch_results.images[:int(shared.opts.img2img_batch_show_results_limit)]
147
+ batch_results.infotexts = batch_results.infotexts[:int(shared.opts.img2img_batch_show_results_limit)]
148
+
149
+ return batch_results
150
+
151
+
152
+ def img2img(id_task: str, request: gr.Request, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint, init_mask_inpaint, mask_blur: int, mask_alpha: float, inpainting_fill: int, n_iter: int, batch_size: int, cfg_scale: float, image_cfg_scale: float, denoising_strength: float, selected_scale_tab: int, height: int, width: int, scale_by: float, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, img2img_batch_inpaint_mask_dir: str, override_settings_texts, img2img_batch_use_png_info: bool, img2img_batch_png_info_props: list, img2img_batch_png_info_dir: str, img2img_batch_source_type: str, img2img_batch_upload: list, *args):
153
+ override_settings = create_override_settings_dict(override_settings_texts)
154
+ print('图生图宽高:',f'{width}X{height}')
155
+ print('图生图正向提示词:',prompt)
156
+ print('图生图负面提示词:',negative_prompt)
157
+
158
+ is_batch = mode == 5
159
+
160
+ if mode == 0: # img2img
161
+ image = init_img
162
+ mask = None
163
+ elif mode == 1: # img2img sketch
164
+ image = sketch
165
+ mask = None
166
+ elif mode == 2: # inpaint
167
+ image, mask = init_img_with_mask["image"], init_img_with_mask["mask"]
168
+ mask = processing.create_binary_mask(mask)
169
+ elif mode == 3: # inpaint sketch
170
+ image = inpaint_color_sketch
171
+ orig = inpaint_color_sketch_orig or inpaint_color_sketch
172
+ pred = np.any(np.array(image) != np.array(orig), axis=-1)
173
+ mask = Image.fromarray(pred.astype(np.uint8) * 255, "L")
174
+ mask = ImageEnhance.Brightness(mask).enhance(1 - mask_alpha / 100)
175
+ blur = ImageFilter.GaussianBlur(mask_blur)
176
+ image = Image.composite(image.filter(blur), orig, mask.filter(blur))
177
+ elif mode == 4: # inpaint upload mask
178
+ image = init_img_inpaint
179
+ mask = init_mask_inpaint
180
+ else:
181
+ image = None
182
+ mask = None
183
+
184
+ image = images.fix_image(image)
185
+ mask = images.fix_image(mask)
186
+
187
+ if selected_scale_tab == 1 and not is_batch:
188
+ assert image, "Can't scale by because no image is selected"
189
+
190
+ width = int(image.width * scale_by)
191
+ height = int(image.height * scale_by)
192
+
193
+ assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'
194
+
195
+ p = StableDiffusionProcessingImg2Img(
196
+ sd_model=shared.sd_model,
197
+ outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
198
+ outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
199
+ prompt=prompt,
200
+ negative_prompt=negative_prompt,
201
+ styles=prompt_styles,
202
+ batch_size=batch_size,
203
+ n_iter=n_iter,
204
+ cfg_scale=cfg_scale,
205
+ width=width,
206
+ height=height,
207
+ init_images=[image],
208
+ mask=mask,
209
+ mask_blur=mask_blur,
210
+ inpainting_fill=inpainting_fill,
211
+ resize_mode=resize_mode,
212
+ denoising_strength=denoising_strength,
213
+ image_cfg_scale=image_cfg_scale,
214
+ inpaint_full_res=inpaint_full_res,
215
+ inpaint_full_res_padding=inpaint_full_res_padding,
216
+ inpainting_mask_invert=inpainting_mask_invert,
217
+ override_settings=override_settings,
218
+ )
219
+
220
+ p.scripts = modules.scripts.scripts_img2img
221
+ p.script_args = args
222
+
223
+ p.user = request.username
224
+
225
+ if shared.opts.enable_console_prompts:
226
+ print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
227
+
228
+ with closing(p):
229
+ if is_batch:
230
+ if img2img_batch_source_type == "upload":
231
+ assert isinstance(img2img_batch_upload, list) and img2img_batch_upload
232
+ output_dir = ""
233
+ inpaint_mask_dir = ""
234
+ png_info_dir = img2img_batch_png_info_dir if not shared.cmd_opts.hide_ui_dir_config else ""
235
+ processed = process_batch(p, img2img_batch_upload, output_dir, inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=png_info_dir)
236
+ else: # "from dir"
237
+ assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
238
+ processed = process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by, use_png_info=img2img_batch_use_png_info, png_info_props=img2img_batch_png_info_props, png_info_dir=img2img_batch_png_info_dir)
239
+
240
+ if processed is None:
241
+ processed = Processed(p, [], p.seed, "")
242
+ else:
243
+ processed = modules.scripts.scripts_img2img.run(p, *args)
244
+ if processed is None:
245
+ processed = process_images(p)
246
+
247
+ shared.total_tqdm.clear()
248
+
249
+ generation_info_js = processed.js()
250
+ if opts.samples_log_stdout:
251
+ print(generation_info_js)
252
+
253
+ if opts.do_not_show_images:
254
+ processed.images = []
255
+
256
+ return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")
modules/txt2img.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from contextlib import closing
3
+
4
+ import modules.scripts
5
+ from modules import processing, infotext_utils
6
+ from modules.infotext_utils import create_override_settings_dict, parse_generation_parameters
7
+ from modules.shared import opts
8
+ import modules.shared as shared
9
+ from modules.ui import plaintext_to_html
10
+ from PIL import Image
11
+ import gradio as gr
12
+
13
+
14
+ def txt2img_create_processing(id_task: str, request: gr.Request, prompt: str, negative_prompt: str, prompt_styles, n_iter: int, batch_size: int, cfg_scale: float, height: int, width: int, enable_hr: bool, denoising_strength: float, hr_scale: float, hr_upscaler: str, hr_second_pass_steps: int, hr_resize_x: int, hr_resize_y: int, hr_checkpoint_name: str, hr_sampler_name: str, hr_scheduler: str, hr_prompt: str, hr_negative_prompt, override_settings_texts, *args, force_enable_hr=False):
15
+ override_settings = create_override_settings_dict(override_settings_texts)
16
+ print('文生图宽高:',f'{width}X{height}')
17
+ print('文生图正向提示词:',prompt)
18
+ print('文生图负面提示词:',negative_prompt)
19
+ if force_enable_hr:
20
+ enable_hr = True
21
+
22
+ p = processing.StableDiffusionProcessingTxt2Img(
23
+
24
+ sd_model=shared.sd_model,
25
+ outpath_samples=opts.outdir_samples or opts.outdir_txt2img_samples,
26
+ outpath_grids=opts.outdir_grids or opts.outdir_txt2img_grids,
27
+ prompt=prompt,
28
+ styles=prompt_styles,
29
+ negative_prompt=negative_prompt,
30
+ batch_size=batch_size,
31
+ n_iter=n_iter,
32
+ cfg_scale=cfg_scale,
33
+ width=width,
34
+ height=height,
35
+ enable_hr=enable_hr,
36
+ denoising_strength=denoising_strength,
37
+ hr_scale=hr_scale,
38
+ hr_upscaler=hr_upscaler,
39
+ hr_second_pass_steps=hr_second_pass_steps,
40
+ hr_resize_x=hr_resize_x,
41
+ hr_resize_y=hr_resize_y,
42
+ hr_checkpoint_name=None if hr_checkpoint_name == 'Use same checkpoint' else hr_checkpoint_name,
43
+ hr_sampler_name=None if hr_sampler_name == 'Use same sampler' else hr_sampler_name,
44
+ hr_scheduler=None if hr_scheduler == 'Use same scheduler' else hr_scheduler,
45
+ hr_prompt=hr_prompt,
46
+ hr_negative_prompt=hr_negative_prompt,
47
+ override_settings=override_settings,
48
+ )
49
+
50
+ p.scripts = modules.scripts.scripts_txt2img
51
+ p.script_args = args
52
+
53
+ p.user = request.username
54
+
55
+ if shared.opts.enable_console_prompts:
56
+ print(f"\ntxt2img: {prompt}", file=shared.progress_print_out)
57
+
58
+ return p
59
+
60
+
61
+ def txt2img_upscale(id_task: str, request: gr.Request, gallery, gallery_index, generation_info, *args):
62
+ assert len(gallery) > 0, 'No image to upscale'
63
+ assert 0 <= gallery_index < len(gallery), f'Bad image index: {gallery_index}'
64
+
65
+ p = txt2img_create_processing(id_task, request, *args, force_enable_hr=True)
66
+ p.batch_size = 1
67
+ p.n_iter = 1
68
+ # txt2img_upscale attribute that signifies this is called by txt2img_upscale
69
+ p.txt2img_upscale = True
70
+
71
+ geninfo = json.loads(generation_info)
72
+
73
+ image_info = gallery[gallery_index] if 0 <= gallery_index < len(gallery) else gallery[0]
74
+ p.firstpass_image = infotext_utils.image_from_url_text(image_info)
75
+
76
+ parameters = parse_generation_parameters(geninfo.get('infotexts')[gallery_index], [])
77
+ p.seed = parameters.get('Seed', -1)
78
+ p.subseed = parameters.get('Variation seed', -1)
79
+
80
+ p.override_settings['save_images_before_highres_fix'] = False
81
+
82
+ with closing(p):
83
+ processed = modules.scripts.scripts_txt2img.run(p, *p.script_args)
84
+
85
+ if processed is None:
86
+ processed = processing.process_images(p)
87
+
88
+ shared.total_tqdm.clear()
89
+
90
+ new_gallery = []
91
+ for i, image in enumerate(gallery):
92
+ if i == gallery_index:
93
+ geninfo["infotexts"][gallery_index: gallery_index+1] = processed.infotexts
94
+ new_gallery.extend(processed.images)
95
+ else:
96
+ fake_image = Image.new(mode="RGB", size=(1, 1))
97
+ fake_image.already_saved_as = image["name"].rsplit('?', 1)[0]
98
+ new_gallery.append(fake_image)
99
+
100
+ geninfo["infotexts"][gallery_index] = processed.info
101
+
102
+ return new_gallery, json.dumps(geninfo), plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")
103
+
104
+
105
+ def txt2img(id_task: str, request: gr.Request, *args):
106
+ p = txt2img_create_processing(id_task, request, *args)
107
+
108
+ with closing(p):
109
+ processed = modules.scripts.scripts_txt2img.run(p, *p.script_args)
110
+
111
+ if processed is None:
112
+ processed = processing.process_images(p)
113
+
114
+ shared.total_tqdm.clear()
115
+
116
+ generation_info_js = processed.js()
117
+ if opts.samples_log_stdout:
118
+ print(generation_info_js)
119
+
120
+ if opts.do_not_show_images:
121
+ processed.images = []
122
+
123
+ return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments, classname="comments")