dputilov commited on
Commit
59c58ec
1 Parent(s): f0dce06

Upload api.py

Browse files
Files changed (1) hide show
  1. api.py +789 -0
api.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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.textual_inversion.preprocess import preprocess
26
+ from modules.hypernetworks.hypernetwork import create_hypernetwork, train_hypernetwork
27
+ from PIL import PngImagePlugin,Image
28
+ from modules.sd_models import unload_model_weights, reload_model_weights, checkpoint_aliases
29
+ from modules.sd_models_config import find_checkpoint_config_near_filename
30
+ from modules.realesrgan_model import get_realesrgan_models
31
+ from modules import devices
32
+ from typing import Dict, List, Any
33
+ import piexif
34
+ import piexif.helper
35
+ from contextlib import closing
36
+
37
+
38
+ def script_name_to_index(name, scripts):
39
+ try:
40
+ return [script.title().lower() for script in scripts].index(name.lower())
41
+ except Exception as e:
42
+ raise HTTPException(status_code=422, detail=f"Script '{name}' not found") from e
43
+
44
+
45
+ def validate_sampler_name(name):
46
+ config = sd_samplers.all_samplers_map.get(name, None)
47
+ if config is None:
48
+ raise HTTPException(status_code=404, detail="Sampler not found")
49
+
50
+ return name
51
+
52
+
53
+ def setUpscalers(req: dict):
54
+ reqDict = vars(req)
55
+ reqDict['extras_upscaler_1'] = reqDict.pop('upscaler_1', None)
56
+ reqDict['extras_upscaler_2'] = reqDict.pop('upscaler_2', None)
57
+ return reqDict
58
+
59
+
60
+ def verify_url(url):
61
+ """Returns True if the url refers to a global resource."""
62
+
63
+ import socket
64
+ from urllib.parse import urlparse
65
+ try:
66
+ parsed_url = urlparse(url)
67
+ domain_name = parsed_url.netloc
68
+ host = socket.gethostbyname_ex(domain_name)
69
+ for ip in host[2]:
70
+ ip_addr = ipaddress.ip_address(ip)
71
+ if not ip_addr.is_global:
72
+ return False
73
+ except Exception:
74
+ return False
75
+
76
+ return True
77
+
78
+
79
+ def decode_base64_to_image(encoding):
80
+ if encoding.startswith("http://") or encoding.startswith("https://"):
81
+ if not opts.api_enable_requests:
82
+ raise HTTPException(status_code=500, detail="Requests not allowed")
83
+
84
+ if opts.api_forbid_local_requests and not verify_url(encoding):
85
+ raise HTTPException(status_code=500, detail="Request to local resource not allowed")
86
+
87
+ headers = {'user-agent': opts.api_useragent} if opts.api_useragent else {}
88
+ response = requests.get(encoding, timeout=30, headers=headers)
89
+ try:
90
+ image = Image.open(BytesIO(response.content))
91
+ return image
92
+ except Exception as e:
93
+ raise HTTPException(status_code=500, detail="Invalid image url") from e
94
+
95
+ if encoding.startswith("data:image/"):
96
+ encoding = encoding.split(";")[1].split(",")[1]
97
+ try:
98
+ image = Image.open(BytesIO(base64.b64decode(encoding)))
99
+ return image
100
+ except Exception as e:
101
+ raise HTTPException(status_code=500, detail="Invalid encoded image") from e
102
+
103
+
104
+ def encode_pil_to_base64(image):
105
+ with io.BytesIO() as output_bytes:
106
+
107
+ if opts.samples_format.lower() == 'png':
108
+ use_metadata = False
109
+ metadata = PngImagePlugin.PngInfo()
110
+ for key, value in image.info.items():
111
+ if isinstance(key, str) and isinstance(value, str):
112
+ metadata.add_text(key, value)
113
+ use_metadata = True
114
+ image.save(output_bytes, format="PNG", pnginfo=(metadata if use_metadata else None), quality=opts.jpeg_quality)
115
+
116
+ elif opts.samples_format.lower() in ("jpg", "jpeg", "webp"):
117
+ if image.mode == "RGBA":
118
+ image = image.convert("RGB")
119
+ parameters = image.info.get('parameters', None)
120
+ exif_bytes = piexif.dump({
121
+ "Exif": { piexif.ExifIFD.UserComment: piexif.helper.UserComment.dump(parameters or "", encoding="unicode") }
122
+ })
123
+ if opts.samples_format.lower() in ("jpg", "jpeg"):
124
+ image.save(output_bytes, format="JPEG", exif = exif_bytes, quality=opts.jpeg_quality)
125
+ else:
126
+ image.save(output_bytes, format="WEBP", exif = exif_bytes, quality=opts.jpeg_quality)
127
+
128
+ else:
129
+ raise HTTPException(status_code=500, detail="Invalid image format")
130
+
131
+ bytes_data = output_bytes.getvalue()
132
+
133
+ return base64.b64encode(bytes_data)
134
+
135
+
136
+ def api_middleware(app: FastAPI):
137
+ rich_available = False
138
+ try:
139
+ if os.environ.get('WEBUI_RICH_EXCEPTIONS', None) is not None:
140
+ import anyio # importing just so it can be placed on silent list
141
+ import starlette # importing just so it can be placed on silent list
142
+ from rich.console import Console
143
+ console = Console()
144
+ rich_available = True
145
+ except Exception:
146
+ pass
147
+
148
+ @app.middleware("http")
149
+ async def log_and_time(req: Request, call_next):
150
+ ts = time.time()
151
+ res: Response = await call_next(req)
152
+ duration = str(round(time.time() - ts, 4))
153
+ res.headers["X-Process-Time"] = duration
154
+ endpoint = req.scope.get('path', 'err')
155
+ if shared.cmd_opts.api_log and endpoint.startswith('/sdapi'):
156
+ print('API {t} {code} {prot}/{ver} {method} {endpoint} {cli} {duration}'.format(
157
+ t=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"),
158
+ code=res.status_code,
159
+ ver=req.scope.get('http_version', '0.0'),
160
+ cli=req.scope.get('client', ('0:0.0.0', 0))[0],
161
+ prot=req.scope.get('scheme', 'err'),
162
+ method=req.scope.get('method', 'err'),
163
+ endpoint=endpoint,
164
+ duration=duration,
165
+ ))
166
+ return res
167
+
168
+ def handle_exception(request: Request, e: Exception):
169
+ err = {
170
+ "error": type(e).__name__,
171
+ "detail": vars(e).get('detail', ''),
172
+ "body": vars(e).get('body', ''),
173
+ "errors": str(e),
174
+ }
175
+ if not isinstance(e, HTTPException): # do not print backtrace on known httpexceptions
176
+ message = f"API error: {request.method}: {request.url} {err}"
177
+ if rich_available:
178
+ print(message)
179
+ console.print_exception(show_locals=True, max_frames=2, extra_lines=1, suppress=[anyio, starlette], word_wrap=False, width=min([console.width, 200]))
180
+ else:
181
+ errors.report(message, exc_info=True)
182
+ return JSONResponse(status_code=vars(e).get('status_code', 500), content=jsonable_encoder(err))
183
+
184
+ @app.middleware("http")
185
+ async def exception_handling(request: Request, call_next):
186
+ try:
187
+ return await call_next(request)
188
+ except Exception as e:
189
+ return handle_exception(request, e)
190
+
191
+ @app.exception_handler(Exception)
192
+ async def fastapi_exception_handler(request: Request, e: Exception):
193
+ return handle_exception(request, e)
194
+
195
+ @app.exception_handler(HTTPException)
196
+ async def http_exception_handler(request: Request, e: HTTPException):
197
+ return handle_exception(request, e)
198
+
199
+
200
+ class Api:
201
+ def __init__(self, app: FastAPI, queue_lock: Lock):
202
+ if shared.cmd_opts.api_auth:
203
+ self.credentials = {}
204
+ for auth in shared.cmd_opts.api_auth.split(","):
205
+ user, password = auth.split(":")
206
+ self.credentials[user] = password
207
+
208
+ self.router = APIRouter()
209
+ self.app = app
210
+ self.queue_lock = queue_lock
211
+ api_middleware(self.app)
212
+ self.add_api_route("/sdapi/v1/txt2img", self.text2imgapi, methods=["POST"], response_model=models.TextToImageResponse)
213
+ self.add_api_route("/sdapi/v1/img2img", self.img2imgapi, methods=["POST"], response_model=models.ImageToImageResponse)
214
+ self.add_api_route("/sdapi/v1/extra-single-image", self.extras_single_image_api, methods=["POST"], response_model=models.ExtrasSingleImageResponse)
215
+ self.add_api_route("/sdapi/v1/extra-batch-images", self.extras_batch_images_api, methods=["POST"], response_model=models.ExtrasBatchImagesResponse)
216
+ self.add_api_route("/sdapi/v1/png-info", self.pnginfoapi, methods=["POST"], response_model=models.PNGInfoResponse)
217
+ self.add_api_route("/sdapi/v1/progress", self.progressapi, methods=["GET"], response_model=models.ProgressResponse)
218
+ self.add_api_route("/sdapi/v1/interrogate", self.interrogateapi, methods=["POST"])
219
+ self.add_api_route("/sdapi/v1/interrupt", self.interruptapi, methods=["POST"])
220
+ self.add_api_route("/sdapi/v1/skip", self.skip, methods=["POST"])
221
+ self.add_api_route("/sdapi/v1/options", self.get_config, methods=["GET"], response_model=models.OptionsModel)
222
+ self.add_api_route("/sdapi/v1/options", self.set_config, methods=["POST"])
223
+ self.add_api_route("/sdapi/v1/cmd-flags", self.get_cmd_flags, methods=["GET"], response_model=models.FlagsModel)
224
+ self.add_api_route("/sdapi/v1/samplers", self.get_samplers, methods=["GET"], response_model=List[models.SamplerItem])
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-checkpoints", self.refresh_checkpoints, methods=["POST"])
235
+ self.add_api_route("/sdapi/v1/refresh-vae", self.refresh_vae, methods=["POST"])
236
+ self.add_api_route("/sdapi/v1/create/embedding", self.create_embedding, methods=["POST"], response_model=models.CreateResponse)
237
+ self.add_api_route("/sdapi/v1/create/hypernetwork", self.create_hypernetwork, methods=["POST"], response_model=models.CreateResponse)
238
+ self.add_api_route("/sdapi/v1/preprocess", self.preprocess, methods=["POST"], response_model=models.PreprocessResponse)
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
+
247
+ if shared.cmd_opts.api_server_stop:
248
+ self.add_api_route("/sdapi/v1/server-kill", self.kill_webui, methods=["POST"])
249
+ self.add_api_route("/sdapi/v1/server-restart", self.restart_webui, methods=["POST"])
250
+ self.add_api_route("/sdapi/v1/server-stop", self.stop_webui, methods=["POST"])
251
+
252
+ self.default_script_arg_txt2img = []
253
+ self.default_script_arg_img2img = []
254
+
255
+ def add_api_route(self, path: str, endpoint, **kwargs):
256
+ if shared.cmd_opts.api_auth:
257
+ return self.app.add_api_route(path, endpoint, dependencies=[Depends(self.auth)], **kwargs)
258
+ return self.app.add_api_route(path, endpoint, **kwargs)
259
+
260
+ def auth(self, credentials: HTTPBasicCredentials = Depends(HTTPBasic())):
261
+ if credentials.username in self.credentials:
262
+ if compare_digest(credentials.password, self.credentials[credentials.username]):
263
+ return True
264
+
265
+ raise HTTPException(status_code=401, detail="Incorrect username or password", headers={"WWW-Authenticate": "Basic"})
266
+
267
+ def get_selectable_script(self, script_name, script_runner):
268
+ if script_name is None or script_name == "":
269
+ return None, None
270
+
271
+ script_idx = script_name_to_index(script_name, script_runner.selectable_scripts)
272
+ script = script_runner.selectable_scripts[script_idx]
273
+ return script, script_idx
274
+
275
+ def get_scripts_list(self):
276
+ t2ilist = [script.name for script in scripts.scripts_txt2img.scripts if script.name is not None]
277
+ i2ilist = [script.name for script in scripts.scripts_img2img.scripts if script.name is not None]
278
+
279
+ return models.ScriptsList(txt2img=t2ilist, img2img=i2ilist)
280
+
281
+ def get_script_info(self):
282
+ res = []
283
+
284
+ for script_list in [scripts.scripts_txt2img.scripts, scripts.scripts_img2img.scripts]:
285
+ res += [script.api_info for script in script_list if script.api_info is not None]
286
+
287
+ return res
288
+
289
+ def get_script(self, script_name, script_runner):
290
+ if script_name is None or script_name == "":
291
+ return None, None
292
+
293
+ script_idx = script_name_to_index(script_name, script_runner.scripts)
294
+ return script_runner.scripts[script_idx]
295
+
296
+ def init_default_script_args(self, script_runner):
297
+ #find max idx from the scripts in runner and generate a none array to init script_args
298
+ last_arg_index = 1
299
+ for script in script_runner.scripts:
300
+ if last_arg_index < script.args_to:
301
+ last_arg_index = script.args_to
302
+ # None everywhere except position 0 to initialize script args
303
+ script_args = [None]*last_arg_index
304
+ script_args[0] = 0
305
+
306
+ # get default values
307
+ with gr.Blocks(): # will throw errors calling ui function without this
308
+ for script in script_runner.scripts:
309
+ if script.ui(script.is_img2img):
310
+ ui_default_values = []
311
+ for elem in script.ui(script.is_img2img):
312
+ ui_default_values.append(elem.value)
313
+ script_args[script.args_from:script.args_to] = ui_default_values
314
+ return script_args
315
+
316
+ def init_script_args(self, request, default_script_args, selectable_scripts, selectable_idx, script_runner):
317
+ script_args = default_script_args.copy()
318
+ # 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()
319
+ if selectable_scripts:
320
+ script_args[selectable_scripts.args_from:selectable_scripts.args_to] = request.script_args
321
+ script_args[0] = selectable_idx + 1
322
+
323
+ # Now check for always on scripts
324
+ if request.alwayson_scripts:
325
+ for alwayson_script_name in request.alwayson_scripts.keys():
326
+ alwayson_script = self.get_script(alwayson_script_name, script_runner)
327
+ if alwayson_script is None:
328
+ raise HTTPException(status_code=422, detail=f"always on script {alwayson_script_name} not found")
329
+ # Selectable script in always on script param check
330
+ if alwayson_script.alwayson is False:
331
+ raise HTTPException(status_code=422, detail="Cannot have a selectable script in the always on scripts params")
332
+ # always on script with no arg should always run so you don't really need to add them to the requests
333
+ if "args" in request.alwayson_scripts[alwayson_script_name]:
334
+ # min between arg length in scriptrunner and arg length in the request
335
+ for idx in range(0, min((alwayson_script.args_to - alwayson_script.args_from), len(request.alwayson_scripts[alwayson_script_name]["args"]))):
336
+ script_args[alwayson_script.args_from + idx] = request.alwayson_scripts[alwayson_script_name]["args"][idx]
337
+ return script_args
338
+
339
+ def text2imgapi(self, txt2imgreq: models.StableDiffusionTxt2ImgProcessingAPI):
340
+ script_runner = scripts.scripts_txt2img
341
+ if not script_runner.scripts:
342
+ script_runner.initialize_scripts(False)
343
+ ui.create_ui()
344
+ if not self.default_script_arg_txt2img:
345
+ self.default_script_arg_txt2img = self.init_default_script_args(script_runner)
346
+ selectable_scripts, selectable_script_idx = self.get_selectable_script(txt2imgreq.script_name, script_runner)
347
+
348
+ populate = txt2imgreq.copy(update={ # Override __init__ params
349
+ "sampler_name": validate_sampler_name(txt2imgreq.sampler_name or txt2imgreq.sampler_index),
350
+ "do_not_save_samples": not txt2imgreq.save_images,
351
+ "do_not_save_grid": not txt2imgreq.save_images,
352
+ })
353
+ if populate.sampler_name:
354
+ populate.sampler_index = None # prevent a warning later on
355
+
356
+ args = vars(populate)
357
+ args.pop('script_name', None)
358
+ args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
359
+ args.pop('alwayson_scripts', None)
360
+
361
+ script_args = self.init_script_args(txt2imgreq, self.default_script_arg_txt2img, selectable_scripts, selectable_script_idx, script_runner)
362
+
363
+ send_images = args.pop('send_images', True)
364
+ args.pop('save_images', None)
365
+
366
+ with self.queue_lock:
367
+ with closing(StableDiffusionProcessingTxt2Img(sd_model=shared.sd_model, **args)) as p:
368
+ p.is_api = True
369
+ p.scripts = script_runner
370
+ p.outpath_grids = opts.outdir_txt2img_grids
371
+ p.outpath_samples = opts.outdir_txt2img_samples
372
+
373
+ try:
374
+ shared.state.begin(job="scripts_txt2img")
375
+ if selectable_scripts is not None:
376
+ p.script_args = script_args
377
+ processed = scripts.scripts_txt2img.run(p, *p.script_args) # Need to pass args as list here
378
+ else:
379
+ p.script_args = tuple(script_args) # Need to pass args as tuple here
380
+ processed = process_images(p)
381
+ finally:
382
+ shared.state.end()
383
+ shared.total_tqdm.clear()
384
+
385
+ b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
386
+
387
+ return models.TextToImageResponse(images=b64images, parameters=vars(txt2imgreq), info=processed.js())
388
+
389
+ def img2imgapi(self, img2imgreq: models.StableDiffusionImg2ImgProcessingAPI):
390
+ print('start img2img', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
391
+ init_images = img2imgreq.init_images
392
+ if init_images is None:
393
+ raise HTTPException(status_code=404, detail="Init image not found")
394
+
395
+ mask = img2imgreq.mask
396
+ if mask:
397
+ mask = decode_base64_to_image(mask)
398
+
399
+ script_runner = scripts.scripts_img2img
400
+ if not script_runner.scripts:
401
+ script_runner.initialize_scripts(True)
402
+ ui.create_ui()
403
+ if not self.default_script_arg_img2img:
404
+ self.default_script_arg_img2img = self.init_default_script_args(script_runner)
405
+ selectable_scripts, selectable_script_idx = self.get_selectable_script(img2imgreq.script_name, script_runner)
406
+
407
+ populate = img2imgreq.copy(update={ # Override __init__ params
408
+ "sampler_name": validate_sampler_name(img2imgreq.sampler_name or img2imgreq.sampler_index),
409
+ "do_not_save_samples": not img2imgreq.save_images,
410
+ "do_not_save_grid": not img2imgreq.save_images,
411
+ "mask": mask,
412
+ })
413
+ if populate.sampler_name:
414
+ populate.sampler_index = None # prevent a warning later on
415
+
416
+ args = vars(populate)
417
+ 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.
418
+ args.pop('script_name', None)
419
+ args.pop('script_args', None) # will refeed them to the pipeline directly after initializing them
420
+ args.pop('alwayson_scripts', None)
421
+
422
+ script_args = self.init_script_args(img2imgreq, self.default_script_arg_img2img, selectable_scripts, selectable_script_idx, script_runner)
423
+
424
+ send_images = args.pop('send_images', True)
425
+ args.pop('save_images', None)
426
+
427
+ with self.queue_lock:
428
+ with closing(StableDiffusionProcessingImg2Img(sd_model=shared.sd_model, **args)) as p:
429
+ p.init_images = [decode_base64_to_image(x) for x in init_images]
430
+ p.is_api = True
431
+ p.scripts = script_runner
432
+ p.outpath_grids = opts.outdir_img2img_grids
433
+ p.outpath_samples = opts.outdir_img2img_samples
434
+ print('decoded img2img', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
435
+ try:
436
+ shared.state.begin(job="scripts_img2img")
437
+ if selectable_scripts is not None:
438
+ p.script_args = script_args
439
+ processed = scripts.scripts_img2img.run(p, *p.script_args) # Need to pass args as list here
440
+ else:
441
+ p.script_args = tuple(script_args) # Need to pass args as tuple here
442
+ processed = process_images(p)
443
+ finally:
444
+ shared.state.end()
445
+ shared.total_tqdm.clear()
446
+
447
+ b64images = list(map(encode_pil_to_base64, processed.images)) if send_images else []
448
+
449
+ if not img2imgreq.include_init_images:
450
+ img2imgreq.init_images = None
451
+ img2imgreq.mask = None
452
+ print('return img2img', datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"))
453
+ return models.ImageToImageResponse(images=b64images, parameters=vars(img2imgreq), info=processed.js())
454
+
455
+ def extras_single_image_api(self, req: models.ExtrasSingleImageRequest):
456
+ reqDict = setUpscalers(req)
457
+
458
+ reqDict['image'] = decode_base64_to_image(reqDict['image'])
459
+
460
+ with self.queue_lock:
461
+ result = postprocessing.run_extras(extras_mode=0, image_folder="", input_dir="", output_dir="", save_output=False, **reqDict)
462
+
463
+ return models.ExtrasSingleImageResponse(image=encode_pil_to_base64(result[0][0]), html_info=result[1])
464
+
465
+ def extras_batch_images_api(self, req: models.ExtrasBatchImagesRequest):
466
+ reqDict = setUpscalers(req)
467
+
468
+ image_list = reqDict.pop('imageList', [])
469
+ image_folder = [decode_base64_to_image(x.data) for x in image_list]
470
+
471
+ with self.queue_lock:
472
+ result = postprocessing.run_extras(extras_mode=1, image_folder=image_folder, image="", input_dir="", output_dir="", save_output=False, **reqDict)
473
+
474
+ return models.ExtrasBatchImagesResponse(images=list(map(encode_pil_to_base64, result[0])), html_info=result[1])
475
+
476
+ def pnginfoapi(self, req: models.PNGInfoRequest):
477
+ if(not req.image.strip()):
478
+ return models.PNGInfoResponse(info="")
479
+
480
+ image = decode_base64_to_image(req.image.strip())
481
+ if image is None:
482
+ return models.PNGInfoResponse(info="")
483
+
484
+ geninfo, items = images.read_info_from_image(image)
485
+ if geninfo is None:
486
+ geninfo = ""
487
+
488
+ items = {**{'parameters': geninfo}, **items}
489
+
490
+ return models.PNGInfoResponse(info=geninfo, items=items)
491
+
492
+ def progressapi(self, req: models.ProgressRequest = Depends()):
493
+ # copy from check_progress_call of ui.py
494
+
495
+ if shared.state.job_count == 0:
496
+ return models.ProgressResponse(progress=0, eta_relative=0, state=shared.state.dict(), textinfo=shared.state.textinfo)
497
+
498
+ # avoid dividing zero
499
+ progress = 0.01
500
+
501
+ if shared.state.job_count > 0:
502
+ progress += shared.state.job_no / shared.state.job_count
503
+ if shared.state.sampling_steps > 0:
504
+ progress += 1 / shared.state.job_count * shared.state.sampling_step / shared.state.sampling_steps
505
+
506
+ time_since_start = time.time() - shared.state.time_start
507
+ eta = (time_since_start/progress)
508
+ eta_relative = eta-time_since_start
509
+
510
+ progress = min(progress, 1)
511
+
512
+ shared.state.set_current_image()
513
+
514
+ current_image = None
515
+ if shared.state.current_image and not req.skip_current_image:
516
+ current_image = encode_pil_to_base64(shared.state.current_image)
517
+
518
+ return models.ProgressResponse(progress=progress, eta_relative=eta_relative, state=shared.state.dict(), current_image=current_image, textinfo=shared.state.textinfo)
519
+
520
+ def interrogateapi(self, interrogatereq: models.InterrogateRequest):
521
+ image_b64 = interrogatereq.image
522
+ if image_b64 is None:
523
+ raise HTTPException(status_code=404, detail="Image not found")
524
+
525
+ img = decode_base64_to_image(image_b64)
526
+ img = img.convert('RGB')
527
+
528
+ # Override object param
529
+ with self.queue_lock:
530
+ if interrogatereq.model == "clip":
531
+ processed = shared.interrogator.interrogate(img)
532
+ elif interrogatereq.model == "deepdanbooru":
533
+ processed = deepbooru.model.tag(img)
534
+ else:
535
+ raise HTTPException(status_code=404, detail="Model not found")
536
+
537
+ return models.InterrogateResponse(caption=processed)
538
+
539
+ def interruptapi(self):
540
+ shared.state.interrupt()
541
+
542
+ return {}
543
+
544
+ def unloadapi(self):
545
+ unload_model_weights()
546
+
547
+ return {}
548
+
549
+ def reloadapi(self):
550
+ reload_model_weights()
551
+
552
+ return {}
553
+
554
+ def skip(self):
555
+ shared.state.skip()
556
+
557
+ def get_config(self):
558
+ options = {}
559
+ for key in shared.opts.data.keys():
560
+ metadata = shared.opts.data_labels.get(key)
561
+ if(metadata is not None):
562
+ options.update({key: shared.opts.data.get(key, shared.opts.data_labels.get(key).default)})
563
+ else:
564
+ options.update({key: shared.opts.data.get(key, None)})
565
+
566
+ return options
567
+
568
+ def set_config(self, req: Dict[str, Any]):
569
+ checkpoint_name = req.get("sd_model_checkpoint", None)
570
+ if checkpoint_name is not None and checkpoint_name not in checkpoint_aliases:
571
+ raise RuntimeError(f"model {checkpoint_name!r} not found")
572
+
573
+ for k, v in req.items():
574
+ shared.opts.set(k, v, is_api=True)
575
+
576
+ shared.opts.save(shared.config_filename)
577
+ return
578
+
579
+ def get_cmd_flags(self):
580
+ return vars(shared.cmd_opts)
581
+
582
+ def get_samplers(self):
583
+ return [{"name": sampler[0], "aliases":sampler[2], "options":sampler[3]} for sampler in sd_samplers.all_samplers]
584
+
585
+ def get_upscalers(self):
586
+ return [
587
+ {
588
+ "name": upscaler.name,
589
+ "model_name": upscaler.scaler.model_name,
590
+ "model_path": upscaler.data_path,
591
+ "model_url": None,
592
+ "scale": upscaler.scale,
593
+ }
594
+ for upscaler in shared.sd_upscalers
595
+ ]
596
+
597
+ def get_latent_upscale_modes(self):
598
+ return [
599
+ {
600
+ "name": upscale_mode,
601
+ }
602
+ for upscale_mode in [*(shared.latent_upscale_modes or {})]
603
+ ]
604
+
605
+ def get_sd_models(self):
606
+ import modules.sd_models as sd_models
607
+ 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()]
608
+
609
+ def get_sd_vaes(self):
610
+ import modules.sd_vae as sd_vae
611
+ return [{"model_name": x, "filename": sd_vae.vae_dict[x]} for x in sd_vae.vae_dict.keys()]
612
+
613
+ def get_hypernetworks(self):
614
+ return [{"name": name, "path": shared.hypernetworks[name]} for name in shared.hypernetworks]
615
+
616
+ def get_face_restorers(self):
617
+ return [{"name":x.name(), "cmd_dir": getattr(x, "cmd_dir", None)} for x in shared.face_restorers]
618
+
619
+ def get_realesrgan_models(self):
620
+ return [{"name":x.name,"path":x.data_path, "scale":x.scale} for x in get_realesrgan_models(None)]
621
+
622
+ def get_prompt_styles(self):
623
+ styleList = []
624
+ for k in shared.prompt_styles.styles:
625
+ style = shared.prompt_styles.styles[k]
626
+ styleList.append({"name":style[0], "prompt": style[1], "negative_prompt": style[2]})
627
+
628
+ return styleList
629
+
630
+ def get_embeddings(self):
631
+ db = sd_hijack.model_hijack.embedding_db
632
+
633
+ def convert_embedding(embedding):
634
+ return {
635
+ "step": embedding.step,
636
+ "sd_checkpoint": embedding.sd_checkpoint,
637
+ "sd_checkpoint_name": embedding.sd_checkpoint_name,
638
+ "shape": embedding.shape,
639
+ "vectors": embedding.vectors,
640
+ }
641
+
642
+ def convert_embeddings(embeddings):
643
+ return {embedding.name: convert_embedding(embedding) for embedding in embeddings.values()}
644
+
645
+ return {
646
+ "loaded": convert_embeddings(db.word_embeddings),
647
+ "skipped": convert_embeddings(db.skipped_embeddings),
648
+ }
649
+
650
+ def refresh_checkpoints(self):
651
+ with self.queue_lock:
652
+ shared.refresh_checkpoints()
653
+
654
+ def refresh_vae(self):
655
+ with self.queue_lock:
656
+ shared_items.refresh_vae_list()
657
+
658
+ def create_embedding(self, args: dict):
659
+ try:
660
+ shared.state.begin(job="create_embedding")
661
+ filename = create_embedding(**args) # create empty embedding
662
+ sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings() # reload embeddings so new one can be immediately used
663
+ return models.CreateResponse(info=f"create embedding filename: {filename}")
664
+ except AssertionError as e:
665
+ return models.TrainResponse(info=f"create embedding error: {e}")
666
+ finally:
667
+ shared.state.end()
668
+
669
+
670
+ def create_hypernetwork(self, args: dict):
671
+ try:
672
+ shared.state.begin(job="create_hypernetwork")
673
+ filename = create_hypernetwork(**args) # create empty embedding
674
+ return models.CreateResponse(info=f"create hypernetwork filename: {filename}")
675
+ except AssertionError as e:
676
+ return models.TrainResponse(info=f"create hypernetwork error: {e}")
677
+ finally:
678
+ shared.state.end()
679
+
680
+ def preprocess(self, args: dict):
681
+ try:
682
+ shared.state.begin(job="preprocess")
683
+ preprocess(**args) # quick operation unless blip/booru interrogation is enabled
684
+ shared.state.end()
685
+ return models.PreprocessResponse(info='preprocess complete')
686
+ except KeyError as e:
687
+ return models.PreprocessResponse(info=f"preprocess error: invalid token: {e}")
688
+ except Exception as e:
689
+ return models.PreprocessResponse(info=f"preprocess error: {e}")
690
+ finally:
691
+ shared.state.end()
692
+
693
+ def train_embedding(self, args: dict):
694
+ try:
695
+ shared.state.begin(job="train_embedding")
696
+ apply_optimizations = shared.opts.training_xattention_optimizations
697
+ error = None
698
+ filename = ''
699
+ if not apply_optimizations:
700
+ sd_hijack.undo_optimizations()
701
+ try:
702
+ embedding, filename = train_embedding(**args) # can take a long time to complete
703
+ except Exception as e:
704
+ error = e
705
+ finally:
706
+ if not apply_optimizations:
707
+ sd_hijack.apply_optimizations()
708
+ return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
709
+ except Exception as msg:
710
+ return models.TrainResponse(info=f"train embedding error: {msg}")
711
+ finally:
712
+ shared.state.end()
713
+
714
+ def train_hypernetwork(self, args: dict):
715
+ try:
716
+ shared.state.begin(job="train_hypernetwork")
717
+ shared.loaded_hypernetworks = []
718
+ apply_optimizations = shared.opts.training_xattention_optimizations
719
+ error = None
720
+ filename = ''
721
+ if not apply_optimizations:
722
+ sd_hijack.undo_optimizations()
723
+ try:
724
+ hypernetwork, filename = train_hypernetwork(**args)
725
+ except Exception as e:
726
+ error = e
727
+ finally:
728
+ shared.sd_model.cond_stage_model.to(devices.device)
729
+ shared.sd_model.first_stage_model.to(devices.device)
730
+ if not apply_optimizations:
731
+ sd_hijack.apply_optimizations()
732
+ shared.state.end()
733
+ return models.TrainResponse(info=f"train embedding complete: filename: {filename} error: {error}")
734
+ except Exception as exc:
735
+ return models.TrainResponse(info=f"train embedding error: {exc}")
736
+ finally:
737
+ shared.state.end()
738
+
739
+ def get_memory(self):
740
+ try:
741
+ import os
742
+ import psutil
743
+ process = psutil.Process(os.getpid())
744
+ res = process.memory_info() # only rss is cross-platform guaranteed so we dont rely on other values
745
+ ram_total = 100 * res.rss / process.memory_percent() # and total memory is calculated as actual value is not cross-platform safe
746
+ ram = { 'free': ram_total - res.rss, 'used': res.rss, 'total': ram_total }
747
+ except Exception as err:
748
+ ram = { 'error': f'{err}' }
749
+ try:
750
+ import torch
751
+ if torch.cuda.is_available():
752
+ s = torch.cuda.mem_get_info()
753
+ system = { 'free': s[0], 'used': s[1] - s[0], 'total': s[1] }
754
+ s = dict(torch.cuda.memory_stats(shared.device))
755
+ allocated = { 'current': s['allocated_bytes.all.current'], 'peak': s['allocated_bytes.all.peak'] }
756
+ reserved = { 'current': s['reserved_bytes.all.current'], 'peak': s['reserved_bytes.all.peak'] }
757
+ active = { 'current': s['active_bytes.all.current'], 'peak': s['active_bytes.all.peak'] }
758
+ inactive = { 'current': s['inactive_split_bytes.all.current'], 'peak': s['inactive_split_bytes.all.peak'] }
759
+ warnings = { 'retries': s['num_alloc_retries'], 'oom': s['num_ooms'] }
760
+ cuda = {
761
+ 'system': system,
762
+ 'active': active,
763
+ 'allocated': allocated,
764
+ 'reserved': reserved,
765
+ 'inactive': inactive,
766
+ 'events': warnings,
767
+ }
768
+ else:
769
+ cuda = {'error': 'unavailable'}
770
+ except Exception as err:
771
+ cuda = {'error': f'{err}'}
772
+ return models.MemoryResponse(ram=ram, cuda=cuda)
773
+
774
+ def launch(self, server_name, port, root_path):
775
+ self.app.include_router(self.router)
776
+ uvicorn.run(self.app, host=server_name, port=port, timeout_keep_alive=shared.cmd_opts.timeout_keep_alive, root_path=root_path)
777
+
778
+ def kill_webui(self):
779
+ restart.stop_program()
780
+
781
+ def restart_webui(self):
782
+ if restart.is_restartable():
783
+ restart.restart_program()
784
+ return Response(status_code=501)
785
+
786
+ def stop_webui(request):
787
+ shared.state.server_command = "stop"
788
+ return Response("Stopping.")
789
+