api.py 29 KB

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