api.py 24 KB

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