api.py 24 KB

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