ui_extensions.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import json
  2. import os.path
  3. import threading
  4. import time
  5. from datetime import datetime
  6. import git
  7. import gradio as gr
  8. import html
  9. import shutil
  10. import errno
  11. from modules import extensions, shared, paths, config_states, errors, restart
  12. from modules.paths_internal import config_states_dir
  13. from modules.call_queue import wrap_gradio_gpu_call
  14. available_extensions = {"extensions": []}
  15. STYLE_PRIMARY = ' style="color: var(--primary-400)"'
  16. def check_access():
  17. assert not shared.cmd_opts.disable_extension_access, "extension access disabled because of command line flags"
  18. def apply_and_restart(disable_list, update_list, disable_all):
  19. check_access()
  20. disabled = json.loads(disable_list)
  21. assert type(disabled) == list, f"wrong disable_list data for apply_and_restart: {disable_list}"
  22. update = json.loads(update_list)
  23. assert type(update) == list, f"wrong update_list data for apply_and_restart: {update_list}"
  24. if update:
  25. save_config_state("Backup (pre-update)")
  26. update = set(update)
  27. for ext in extensions.extensions:
  28. if ext.name not in update:
  29. continue
  30. try:
  31. ext.fetch_and_reset_hard()
  32. except Exception:
  33. errors.report(f"Error getting updates for {ext.name}", exc_info=True)
  34. shared.opts.disabled_extensions = disabled
  35. shared.opts.disable_all_extensions = disable_all
  36. shared.opts.save(shared.config_filename)
  37. if restart.is_restartable():
  38. restart.restart_program()
  39. else:
  40. restart.stop_program()
  41. def save_config_state(name):
  42. current_config_state = config_states.get_config()
  43. if not name:
  44. name = "Config"
  45. current_config_state["name"] = name
  46. timestamp = datetime.now().strftime('%Y_%m_%d-%H_%M_%S')
  47. filename = os.path.join(config_states_dir, f"{timestamp}_{name}.json")
  48. print(f"Saving backup of webui/extension state to {filename}.")
  49. with open(filename, "w", encoding="utf-8") as f:
  50. json.dump(current_config_state, f)
  51. config_states.list_config_states()
  52. new_value = next(iter(config_states.all_config_states.keys()), "Current")
  53. new_choices = ["Current"] + list(config_states.all_config_states.keys())
  54. return gr.Dropdown.update(value=new_value, choices=new_choices), f"<span>Saved current webui/extension state to \"{filename}\"</span>"
  55. def restore_config_state(confirmed, config_state_name, restore_type):
  56. if config_state_name == "Current":
  57. return "<span>Select a config to restore from.</span>"
  58. if not confirmed:
  59. return "<span>Cancelled.</span>"
  60. check_access()
  61. config_state = config_states.all_config_states[config_state_name]
  62. print(f"*** Restoring webui state from backup: {restore_type} ***")
  63. if restore_type == "extensions" or restore_type == "both":
  64. shared.opts.restore_config_state_file = config_state["filepath"]
  65. shared.opts.save(shared.config_filename)
  66. if restore_type == "webui" or restore_type == "both":
  67. config_states.restore_webui_config(config_state)
  68. shared.state.request_restart()
  69. return ""
  70. def check_updates(id_task, disable_list):
  71. check_access()
  72. disabled = json.loads(disable_list)
  73. assert type(disabled) == list, f"wrong disable_list data for apply_and_restart: {disable_list}"
  74. exts = [ext for ext in extensions.extensions if ext.remote is not None and ext.name not in disabled]
  75. shared.state.job_count = len(exts)
  76. for ext in exts:
  77. shared.state.textinfo = ext.name
  78. try:
  79. ext.check_updates()
  80. except FileNotFoundError as e:
  81. if 'FETCH_HEAD' not in str(e):
  82. raise
  83. except Exception:
  84. errors.report(f"Error checking updates for {ext.name}", exc_info=True)
  85. shared.state.nextjob()
  86. return extension_table(), ""
  87. def make_commit_link(commit_hash, remote, text=None):
  88. if text is None:
  89. text = commit_hash[:8]
  90. if remote.startswith("https://github.com/"):
  91. if remote.endswith(".git"):
  92. remote = remote[:-4]
  93. href = remote + "/commit/" + commit_hash
  94. return f'<a href="{href}" target="_blank">{text}</a>'
  95. else:
  96. return text
  97. def extension_table():
  98. code = f"""<!-- {time.time()} -->
  99. <table id="extensions">
  100. <thead>
  101. <tr>
  102. <th><abbr title="Use checkbox to enable the extension; it will be enabled or disabled when you click apply button">Extension</abbr></th>
  103. <th>URL</th>
  104. <th>Branch</th>
  105. <th>Version</th>
  106. <th>Date</th>
  107. <th><abbr title="Use checkbox to mark the extension for update; it will be updated when you click apply button">Update</abbr></th>
  108. </tr>
  109. </thead>
  110. <tbody>
  111. """
  112. for ext in extensions.extensions:
  113. ext: extensions.Extension
  114. ext.read_info_from_repo()
  115. remote = f"""<a href="{html.escape(ext.remote or '')}" target="_blank">{html.escape("built-in" if ext.is_builtin else ext.remote or '')}</a>"""
  116. if ext.can_update:
  117. ext_status = f"""<label><input class="gr-check-radio gr-checkbox" name="update_{html.escape(ext.name)}" checked="checked" type="checkbox">{html.escape(ext.status)}</label>"""
  118. else:
  119. ext_status = ext.status
  120. style = ""
  121. if shared.opts.disable_all_extensions == "extra" and not ext.is_builtin or shared.opts.disable_all_extensions == "all":
  122. style = STYLE_PRIMARY
  123. version_link = ext.version
  124. if ext.commit_hash and ext.remote:
  125. version_link = make_commit_link(ext.commit_hash, ext.remote, ext.version)
  126. code += f"""
  127. <tr>
  128. <td><label{style}><input class="gr-check-radio gr-checkbox" name="enable_{html.escape(ext.name)}" type="checkbox" {'checked="checked"' if ext.enabled else ''}>{html.escape(ext.name)}</label></td>
  129. <td>{remote}</td>
  130. <td>{ext.branch}</td>
  131. <td>{version_link}</td>
  132. <td>{time.asctime(time.gmtime(ext.commit_date))}</td>
  133. <td{' class="extension_status"' if ext.remote is not None else ''}>{ext_status}</td>
  134. </tr>
  135. """
  136. code += """
  137. </tbody>
  138. </table>
  139. """
  140. return code
  141. def update_config_states_table(state_name):
  142. if state_name == "Current":
  143. config_state = config_states.get_config()
  144. else:
  145. config_state = config_states.all_config_states[state_name]
  146. config_name = config_state.get("name", "Config")
  147. created_date = time.asctime(time.gmtime(config_state["created_at"]))
  148. filepath = config_state.get("filepath", "<unknown>")
  149. code = f"""<!-- {time.time()} -->"""
  150. webui_remote = config_state["webui"]["remote"] or ""
  151. webui_branch = config_state["webui"]["branch"]
  152. webui_commit_hash = config_state["webui"]["commit_hash"] or "<unknown>"
  153. webui_commit_date = config_state["webui"]["commit_date"]
  154. if webui_commit_date:
  155. webui_commit_date = time.asctime(time.gmtime(webui_commit_date))
  156. else:
  157. webui_commit_date = "<unknown>"
  158. remote = f"""<a href="{html.escape(webui_remote)}" target="_blank">{html.escape(webui_remote or '')}</a>"""
  159. commit_link = make_commit_link(webui_commit_hash, webui_remote)
  160. date_link = make_commit_link(webui_commit_hash, webui_remote, webui_commit_date)
  161. current_webui = config_states.get_webui_config()
  162. style_remote = ""
  163. style_branch = ""
  164. style_commit = ""
  165. if current_webui["remote"] != webui_remote:
  166. style_remote = STYLE_PRIMARY
  167. if current_webui["branch"] != webui_branch:
  168. style_branch = STYLE_PRIMARY
  169. if current_webui["commit_hash"] != webui_commit_hash:
  170. style_commit = STYLE_PRIMARY
  171. code += f"""<h2>Config Backup: {config_name}</h2>
  172. <div><b>Filepath:</b> {filepath}</div>
  173. <div><b>Created at:</b> {created_date}</div>"""
  174. code += f"""<h2>WebUI State</h2>
  175. <table id="config_state_webui">
  176. <thead>
  177. <tr>
  178. <th>URL</th>
  179. <th>Branch</th>
  180. <th>Commit</th>
  181. <th>Date</th>
  182. </tr>
  183. </thead>
  184. <tbody>
  185. <tr>
  186. <td><label{style_remote}>{remote}</label></td>
  187. <td><label{style_branch}>{webui_branch}</label></td>
  188. <td><label{style_commit}>{commit_link}</label></td>
  189. <td><label{style_commit}>{date_link}</label></td>
  190. </tr>
  191. </tbody>
  192. </table>
  193. """
  194. code += """<h2>Extension State</h2>
  195. <table id="config_state_extensions">
  196. <thead>
  197. <tr>
  198. <th>Extension</th>
  199. <th>URL</th>
  200. <th>Branch</th>
  201. <th>Commit</th>
  202. <th>Date</th>
  203. </tr>
  204. </thead>
  205. <tbody>
  206. """
  207. ext_map = {ext.name: ext for ext in extensions.extensions}
  208. for ext_name, ext_conf in config_state["extensions"].items():
  209. ext_remote = ext_conf["remote"] or ""
  210. ext_branch = ext_conf["branch"] or "<unknown>"
  211. ext_enabled = ext_conf["enabled"]
  212. ext_commit_hash = ext_conf["commit_hash"] or "<unknown>"
  213. ext_commit_date = ext_conf["commit_date"]
  214. if ext_commit_date:
  215. ext_commit_date = time.asctime(time.gmtime(ext_commit_date))
  216. else:
  217. ext_commit_date = "<unknown>"
  218. remote = f"""<a href="{html.escape(ext_remote)}" target="_blank">{html.escape(ext_remote or '')}</a>"""
  219. commit_link = make_commit_link(ext_commit_hash, ext_remote)
  220. date_link = make_commit_link(ext_commit_hash, ext_remote, ext_commit_date)
  221. style_enabled = ""
  222. style_remote = ""
  223. style_branch = ""
  224. style_commit = ""
  225. if ext_name in ext_map:
  226. current_ext = ext_map[ext_name]
  227. current_ext.read_info_from_repo()
  228. if current_ext.enabled != ext_enabled:
  229. style_enabled = STYLE_PRIMARY
  230. if current_ext.remote != ext_remote:
  231. style_remote = STYLE_PRIMARY
  232. if current_ext.branch != ext_branch:
  233. style_branch = STYLE_PRIMARY
  234. if current_ext.commit_hash != ext_commit_hash:
  235. style_commit = STYLE_PRIMARY
  236. code += f"""
  237. <tr>
  238. <td><label{style_enabled}><input class="gr-check-radio gr-checkbox" type="checkbox" disabled="true" {'checked="checked"' if ext_enabled else ''}>{html.escape(ext_name)}</label></td>
  239. <td><label{style_remote}>{remote}</label></td>
  240. <td><label{style_branch}>{ext_branch}</label></td>
  241. <td><label{style_commit}>{commit_link}</label></td>
  242. <td><label{style_commit}>{date_link}</label></td>
  243. </tr>
  244. """
  245. code += """
  246. </tbody>
  247. </table>
  248. """
  249. return code
  250. def normalize_git_url(url):
  251. if url is None:
  252. return ""
  253. url = url.replace(".git", "")
  254. return url
  255. def install_extension_from_url(dirname, url, branch_name=None):
  256. check_access()
  257. assert url, 'No URL specified'
  258. if dirname is None or dirname == "":
  259. *parts, last_part = url.split('/')
  260. last_part = normalize_git_url(last_part)
  261. dirname = last_part
  262. target_dir = os.path.join(extensions.extensions_dir, dirname)
  263. assert not os.path.exists(target_dir), f'Extension directory already exists: {target_dir}'
  264. normalized_url = normalize_git_url(url)
  265. if any(x for x in extensions.extensions if normalize_git_url(x.remote) == normalized_url):
  266. raise Exception(f'Extension with this URL is already installed: {url}')
  267. tmpdir = os.path.join(paths.data_path, "tmp", dirname)
  268. try:
  269. shutil.rmtree(tmpdir, True)
  270. if not branch_name:
  271. # if no branch is specified, use the default branch
  272. with git.Repo.clone_from(url, tmpdir, filter=['blob:none']) as repo:
  273. repo.remote().fetch()
  274. for submodule in repo.submodules:
  275. submodule.update()
  276. else:
  277. with git.Repo.clone_from(url, tmpdir, filter=['blob:none'], branch=branch_name) as repo:
  278. repo.remote().fetch()
  279. for submodule in repo.submodules:
  280. submodule.update()
  281. try:
  282. os.rename(tmpdir, target_dir)
  283. except OSError as err:
  284. if err.errno == errno.EXDEV:
  285. # Cross device link, typical in docker or when tmp/ and extensions/ are on different file systems
  286. # Since we can't use a rename, do the slower but more versitile shutil.move()
  287. shutil.move(tmpdir, target_dir)
  288. else:
  289. # Something else, not enough free space, permissions, etc. rethrow it so that it gets handled.
  290. raise err
  291. import launch
  292. launch.run_extension_installer(target_dir)
  293. extensions.list_extensions()
  294. return [extension_table(), html.escape(f"Installed into {target_dir}. Use Installed tab to restart.")]
  295. finally:
  296. shutil.rmtree(tmpdir, True)
  297. def install_extension_from_index(url, hide_tags, sort_column, filter_text):
  298. ext_table, message = install_extension_from_url(None, url)
  299. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  300. return code, ext_table, message, ''
  301. def refresh_available_extensions(url, hide_tags, sort_column):
  302. global available_extensions
  303. import urllib.request
  304. with urllib.request.urlopen(url) as response:
  305. text = response.read()
  306. available_extensions = json.loads(text)
  307. code, tags = refresh_available_extensions_from_data(hide_tags, sort_column)
  308. return url, code, gr.CheckboxGroup.update(choices=tags), '', ''
  309. def refresh_available_extensions_for_tags(hide_tags, sort_column, filter_text):
  310. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  311. return code, ''
  312. def search_extensions(filter_text, hide_tags, sort_column):
  313. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  314. return code, ''
  315. sort_ordering = [
  316. # (reverse, order_by_function)
  317. (True, lambda x: x.get('added', 'z')),
  318. (False, lambda x: x.get('added', 'z')),
  319. (False, lambda x: x.get('name', 'z')),
  320. (True, lambda x: x.get('name', 'z')),
  321. (False, lambda x: 'z'),
  322. ]
  323. def refresh_available_extensions_from_data(hide_tags, sort_column, filter_text=""):
  324. extlist = available_extensions["extensions"]
  325. installed_extension_urls = {normalize_git_url(extension.remote): extension.name for extension in extensions.extensions}
  326. tags = available_extensions.get("tags", {})
  327. tags_to_hide = set(hide_tags)
  328. hidden = 0
  329. code = f"""<!-- {time.time()} -->
  330. <table id="available_extensions">
  331. <thead>
  332. <tr>
  333. <th>Extension</th>
  334. <th>Description</th>
  335. <th>Action</th>
  336. </tr>
  337. </thead>
  338. <tbody>
  339. """
  340. sort_reverse, sort_function = sort_ordering[sort_column if 0 <= sort_column < len(sort_ordering) else 0]
  341. for ext in sorted(extlist, key=sort_function, reverse=sort_reverse):
  342. name = ext.get("name", "noname")
  343. added = ext.get('added', 'unknown')
  344. url = ext.get("url", None)
  345. description = ext.get("description", "")
  346. extension_tags = ext.get("tags", [])
  347. if url is None:
  348. continue
  349. existing = installed_extension_urls.get(normalize_git_url(url), None)
  350. extension_tags = extension_tags + ["installed"] if existing else extension_tags
  351. if any(x for x in extension_tags if x in tags_to_hide):
  352. hidden += 1
  353. continue
  354. if filter_text and filter_text.strip():
  355. if filter_text.lower() not in html.escape(name).lower() and filter_text.lower() not in html.escape(description).lower():
  356. hidden += 1
  357. continue
  358. install_code = f"""<button onclick="install_extension_from_index(this, '{html.escape(url)}')" {"disabled=disabled" if existing else ""} class="lg secondary gradio-button custom-button">{"Install" if not existing else "Installed"}</button>"""
  359. tags_text = ", ".join([f"<span class='extension-tag' title='{tags.get(x, '')}'>{x}</span>" for x in extension_tags])
  360. code += f"""
  361. <tr>
  362. <td><a href="{html.escape(url)}" target="_blank">{html.escape(name)}</a><br />{tags_text}</td>
  363. <td>{html.escape(description)}<p class="info"><span class="date_added">Added: {html.escape(added)}</span></p></td>
  364. <td>{install_code}</td>
  365. </tr>
  366. """
  367. for tag in [x for x in extension_tags if x not in tags]:
  368. tags[tag] = tag
  369. code += """
  370. </tbody>
  371. </table>
  372. """
  373. if hidden > 0:
  374. code += f"<p>Extension hidden: {hidden}</p>"
  375. return code, list(tags)
  376. def preload_extensions_git_metadata():
  377. t0 = time.time()
  378. for extension in extensions.extensions:
  379. extension.read_info_from_repo()
  380. print(
  381. f"preload_extensions_git_metadata for "
  382. f"{len(extensions.extensions)} extensions took "
  383. f"{time.time() - t0:.2f}s"
  384. )
  385. def create_ui():
  386. import modules.ui
  387. config_states.list_config_states()
  388. threading.Thread(target=preload_extensions_git_metadata).start()
  389. with gr.Blocks(analytics_enabled=False) as ui:
  390. with gr.Tabs(elem_id="tabs_extensions"):
  391. with gr.TabItem("Installed", id="installed"):
  392. with gr.Row(elem_id="extensions_installed_top"):
  393. apply_label = ("Apply and restart UI" if restart.is_restartable() else "Apply and quit")
  394. apply = gr.Button(value=apply_label, variant="primary")
  395. check = gr.Button(value="Check for updates")
  396. extensions_disable_all = gr.Radio(label="Disable all extensions", choices=["none", "extra", "all"], value=shared.opts.disable_all_extensions, elem_id="extensions_disable_all")
  397. extensions_disabled_list = gr.Text(elem_id="extensions_disabled_list", visible=False).style(container=False)
  398. extensions_update_list = gr.Text(elem_id="extensions_update_list", visible=False).style(container=False)
  399. html = ""
  400. if shared.opts.disable_all_extensions != "none":
  401. html = """
  402. <span style="color: var(--primary-400);">
  403. "Disable all extensions" was set, change it to "none" to load all extensions again
  404. </span>
  405. """
  406. info = gr.HTML(html)
  407. extensions_table = gr.HTML('Loading...')
  408. ui.load(fn=extension_table, inputs=[], outputs=[extensions_table])
  409. apply.click(
  410. fn=apply_and_restart,
  411. _js="extensions_apply",
  412. inputs=[extensions_disabled_list, extensions_update_list, extensions_disable_all],
  413. outputs=[],
  414. )
  415. check.click(
  416. fn=wrap_gradio_gpu_call(check_updates, extra_outputs=[gr.update()]),
  417. _js="extensions_check",
  418. inputs=[info, extensions_disabled_list],
  419. outputs=[extensions_table, info],
  420. )
  421. with gr.TabItem("Available", id="available"):
  422. with gr.Row():
  423. refresh_available_extensions_button = gr.Button(value="Load from:", variant="primary")
  424. available_extensions_index = gr.Text(value="https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json", label="Extension index URL").style(container=False)
  425. extension_to_install = gr.Text(elem_id="extension_to_install", visible=False)
  426. install_extension_button = gr.Button(elem_id="install_extension_button", visible=False)
  427. with gr.Row():
  428. hide_tags = gr.CheckboxGroup(value=["ads", "localization", "installed"], label="Hide extensions with tags", choices=["script", "ads", "localization", "installed"])
  429. sort_column = gr.Radio(value="newest first", label="Order", choices=["newest first", "oldest first", "a-z", "z-a", "internal order", ], type="index")
  430. with gr.Row():
  431. search_extensions_text = gr.Text(label="Search").style(container=False)
  432. install_result = gr.HTML()
  433. available_extensions_table = gr.HTML()
  434. refresh_available_extensions_button.click(
  435. fn=modules.ui.wrap_gradio_call(refresh_available_extensions, extra_outputs=[gr.update(), gr.update(), gr.update()]),
  436. inputs=[available_extensions_index, hide_tags, sort_column],
  437. outputs=[available_extensions_index, available_extensions_table, hide_tags, install_result, search_extensions_text],
  438. )
  439. install_extension_button.click(
  440. fn=modules.ui.wrap_gradio_call(install_extension_from_index, extra_outputs=[gr.update(), gr.update()]),
  441. inputs=[extension_to_install, hide_tags, sort_column, search_extensions_text],
  442. outputs=[available_extensions_table, extensions_table, install_result],
  443. )
  444. search_extensions_text.change(
  445. fn=modules.ui.wrap_gradio_call(search_extensions, extra_outputs=[gr.update()]),
  446. inputs=[search_extensions_text, hide_tags, sort_column],
  447. outputs=[available_extensions_table, install_result],
  448. )
  449. hide_tags.change(
  450. fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
  451. inputs=[hide_tags, sort_column, search_extensions_text],
  452. outputs=[available_extensions_table, install_result]
  453. )
  454. sort_column.change(
  455. fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
  456. inputs=[hide_tags, sort_column, search_extensions_text],
  457. outputs=[available_extensions_table, install_result]
  458. )
  459. with gr.TabItem("Install from URL", id="install_from_url"):
  460. install_url = gr.Text(label="URL for extension's git repository")
  461. install_branch = gr.Text(label="Specific branch name", placeholder="Leave empty for default main branch")
  462. install_dirname = gr.Text(label="Local directory name", placeholder="Leave empty for auto")
  463. install_button = gr.Button(value="Install", variant="primary")
  464. install_result = gr.HTML(elem_id="extension_install_result")
  465. install_button.click(
  466. fn=modules.ui.wrap_gradio_call(lambda *args: [gr.update(), *install_extension_from_url(*args)], extra_outputs=[gr.update(), gr.update()]),
  467. inputs=[install_dirname, install_url, install_branch],
  468. outputs=[install_url, extensions_table, install_result],
  469. )
  470. with gr.TabItem("Backup/Restore"):
  471. with gr.Row(elem_id="extensions_backup_top_row"):
  472. config_states_list = gr.Dropdown(label="Saved Configs", elem_id="extension_backup_saved_configs", value="Current", choices=["Current"] + list(config_states.all_config_states.keys()))
  473. modules.ui.create_refresh_button(config_states_list, config_states.list_config_states, lambda: {"choices": ["Current"] + list(config_states.all_config_states.keys())}, "refresh_config_states")
  474. config_restore_type = gr.Radio(label="State to restore", choices=["extensions", "webui", "both"], value="extensions", elem_id="extension_backup_restore_type")
  475. config_restore_button = gr.Button(value="Restore Selected Config", variant="primary", elem_id="extension_backup_restore")
  476. with gr.Row(elem_id="extensions_backup_top_row2"):
  477. config_save_name = gr.Textbox("", placeholder="Config Name", show_label=False)
  478. config_save_button = gr.Button(value="Save Current Config")
  479. config_states_info = gr.HTML("")
  480. config_states_table = gr.HTML("Loading...")
  481. ui.load(fn=update_config_states_table, inputs=[config_states_list], outputs=[config_states_table])
  482. config_save_button.click(fn=save_config_state, inputs=[config_save_name], outputs=[config_states_list, config_states_info])
  483. dummy_component = gr.Label(visible=False)
  484. config_restore_button.click(fn=restore_config_state, _js="config_state_confirm_restore", inputs=[dummy_component, config_states_list, config_restore_type], outputs=[config_states_info])
  485. config_states_list.change(
  486. fn=update_config_states_table,
  487. inputs=[config_states_list],
  488. outputs=[config_states_table],
  489. )
  490. return ui