api.py 34 KB

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