api.py 24 KB

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