api.py 32 KB

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