api.py 34 KB

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