ui_extensions.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. import json
  2. import os
  3. import threading
  4. import time
  5. from datetime import datetime, timezone
  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, indent=4, ensure_ascii=False)
  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>
  103. <input class="gr-check-radio gr-checkbox all_extensions_toggle" type="checkbox" {'checked="checked"' if all(ext.enabled for ext in extensions.extensions) else ''} onchange="toggle_all_extensions(event)" />
  104. <abbr title="Use checkbox to enable the extension; it will be enabled or disabled when you click apply button">Extension</abbr>
  105. </th>
  106. <th>URL</th>
  107. <th>Branch</th>
  108. <th>Version</th>
  109. <th>Date</th>
  110. <th><abbr title="Use checkbox to mark the extension for update; it will be updated when you click apply button">Update</abbr></th>
  111. </tr>
  112. </thead>
  113. <tbody>
  114. """
  115. for ext in extensions.extensions:
  116. ext: extensions.Extension
  117. ext.read_info_from_repo()
  118. remote = f"""<a href="{html.escape(ext.remote or '')}" target="_blank">{html.escape("built-in" if ext.is_builtin else ext.remote or '')}</a>"""
  119. if ext.can_update:
  120. 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>"""
  121. else:
  122. ext_status = ext.status
  123. style = ""
  124. if shared.cmd_opts.disable_extra_extensions and not ext.is_builtin or shared.opts.disable_all_extensions == "extra" and not ext.is_builtin or shared.cmd_opts.disable_all_extensions or shared.opts.disable_all_extensions == "all":
  125. style = STYLE_PRIMARY
  126. version_link = ext.version
  127. if ext.commit_hash and ext.remote:
  128. version_link = make_commit_link(ext.commit_hash, ext.remote, ext.version)
  129. code += f"""
  130. <tr>
  131. <td><label{style}><input class="gr-check-radio gr-checkbox extension_toggle" name="enable_{html.escape(ext.name)}" type="checkbox" {'checked="checked"' if ext.enabled else ''} onchange="toggle_extension(event)" />{html.escape(ext.name)}</label></td>
  132. <td>{remote}</td>
  133. <td>{ext.branch}</td>
  134. <td>{version_link}</td>
  135. <td>{datetime.fromtimestamp(ext.commit_date) if ext.commit_date else ""}</td>
  136. <td{' class="extension_status"' if ext.remote is not None else ''}>{ext_status}</td>
  137. </tr>
  138. """
  139. code += """
  140. </tbody>
  141. </table>
  142. """
  143. return code
  144. def update_config_states_table(state_name):
  145. if state_name == "Current":
  146. config_state = config_states.get_config()
  147. else:
  148. config_state = config_states.all_config_states[state_name]
  149. config_name = config_state.get("name", "Config")
  150. created_date = datetime.fromtimestamp(config_state["created_at"]).strftime('%Y-%m-%d %H:%M:%S')
  151. filepath = config_state.get("filepath", "<unknown>")
  152. try:
  153. webui_remote = config_state["webui"]["remote"] or ""
  154. webui_branch = config_state["webui"]["branch"]
  155. webui_commit_hash = config_state["webui"]["commit_hash"] or "<unknown>"
  156. webui_commit_date = config_state["webui"]["commit_date"]
  157. if webui_commit_date:
  158. webui_commit_date = time.asctime(time.gmtime(webui_commit_date))
  159. else:
  160. webui_commit_date = "<unknown>"
  161. remote = f"""<a href="{html.escape(webui_remote)}" target="_blank">{html.escape(webui_remote or '')}</a>"""
  162. commit_link = make_commit_link(webui_commit_hash, webui_remote)
  163. date_link = make_commit_link(webui_commit_hash, webui_remote, webui_commit_date)
  164. current_webui = config_states.get_webui_config()
  165. style_remote = ""
  166. style_branch = ""
  167. style_commit = ""
  168. if current_webui["remote"] != webui_remote:
  169. style_remote = STYLE_PRIMARY
  170. if current_webui["branch"] != webui_branch:
  171. style_branch = STYLE_PRIMARY
  172. if current_webui["commit_hash"] != webui_commit_hash:
  173. style_commit = STYLE_PRIMARY
  174. code = f"""<!-- {time.time()} -->
  175. <h2>Config Backup: {config_name}</h2>
  176. <div><b>Filepath:</b> {filepath}</div>
  177. <div><b>Created at:</b> {created_date}</div>
  178. <h2>WebUI State</h2>
  179. <table id="config_state_webui">
  180. <thead>
  181. <tr>
  182. <th>URL</th>
  183. <th>Branch</th>
  184. <th>Commit</th>
  185. <th>Date</th>
  186. </tr>
  187. </thead>
  188. <tbody>
  189. <tr>
  190. <td>
  191. <label{style_remote}>{remote}</label>
  192. </td>
  193. <td>
  194. <label{style_branch}>{webui_branch}</label>
  195. </td>
  196. <td>
  197. <label{style_commit}>{commit_link}</label>
  198. </td>
  199. <td>
  200. <label{style_commit}>{date_link}</label>
  201. </td>
  202. </tr>
  203. </tbody>
  204. </table>
  205. <h2>Extension State</h2>
  206. <table id="config_state_extensions">
  207. <thead>
  208. <tr>
  209. <th>Extension</th>
  210. <th>URL</th>
  211. <th>Branch</th>
  212. <th>Commit</th>
  213. <th>Date</th>
  214. </tr>
  215. </thead>
  216. <tbody>
  217. """
  218. ext_map = {ext.name: ext for ext in extensions.extensions}
  219. for ext_name, ext_conf in config_state["extensions"].items():
  220. ext_remote = ext_conf["remote"] or ""
  221. ext_branch = ext_conf["branch"] or "<unknown>"
  222. ext_enabled = ext_conf["enabled"]
  223. ext_commit_hash = ext_conf["commit_hash"] or "<unknown>"
  224. ext_commit_date = ext_conf["commit_date"]
  225. if ext_commit_date:
  226. ext_commit_date = time.asctime(time.gmtime(ext_commit_date))
  227. else:
  228. ext_commit_date = "<unknown>"
  229. remote = f"""<a href="{html.escape(ext_remote)}" target="_blank">{html.escape(ext_remote or '')}</a>"""
  230. commit_link = make_commit_link(ext_commit_hash, ext_remote)
  231. date_link = make_commit_link(ext_commit_hash, ext_remote, ext_commit_date)
  232. style_enabled = ""
  233. style_remote = ""
  234. style_branch = ""
  235. style_commit = ""
  236. if ext_name in ext_map:
  237. current_ext = ext_map[ext_name]
  238. current_ext.read_info_from_repo()
  239. if current_ext.enabled != ext_enabled:
  240. style_enabled = STYLE_PRIMARY
  241. if current_ext.remote != ext_remote:
  242. style_remote = STYLE_PRIMARY
  243. if current_ext.branch != ext_branch:
  244. style_branch = STYLE_PRIMARY
  245. if current_ext.commit_hash != ext_commit_hash:
  246. style_commit = STYLE_PRIMARY
  247. code += f""" <tr>
  248. <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>
  249. <td><label{style_remote}>{remote}</label></td>
  250. <td><label{style_branch}>{ext_branch}</label></td>
  251. <td><label{style_commit}>{commit_link}</label></td>
  252. <td><label{style_commit}>{date_link}</label></td>
  253. </tr>
  254. """
  255. code += """ </tbody>
  256. </table>"""
  257. except Exception as e:
  258. print(f"[ERROR]: Config states {filepath}, {e}")
  259. code = f"""<!-- {time.time()} -->
  260. <h2>Config Backup: {config_name}</h2>
  261. <div><b>Filepath:</b> {filepath}</div>
  262. <div><b>Created at:</b> {created_date}</div>
  263. <h2>This file is corrupted</h2>"""
  264. return code
  265. def normalize_git_url(url):
  266. if url is None:
  267. return ""
  268. url = url.replace(".git", "")
  269. return url
  270. def get_extension_dirname_from_url(url):
  271. *parts, last_part = url.split('/')
  272. return normalize_git_url(last_part)
  273. def install_extension_from_url(dirname, url, branch_name=None):
  274. check_access()
  275. if isinstance(dirname, str):
  276. dirname = dirname.strip()
  277. if isinstance(url, str):
  278. url = url.strip()
  279. assert url, 'No URL specified'
  280. if dirname is None or dirname == "":
  281. dirname = get_extension_dirname_from_url(url)
  282. target_dir = os.path.join(extensions.extensions_dir, dirname)
  283. assert not os.path.exists(target_dir), f'Extension directory already exists: {target_dir}'
  284. normalized_url = normalize_git_url(url)
  285. if any(x for x in extensions.extensions if normalize_git_url(x.remote) == normalized_url):
  286. raise Exception(f'Extension with this URL is already installed: {url}')
  287. tmpdir = os.path.join(paths.data_path, "tmp", dirname)
  288. try:
  289. shutil.rmtree(tmpdir, True)
  290. if not branch_name:
  291. # if no branch is specified, use the default branch
  292. with git.Repo.clone_from(url, tmpdir, filter=['blob:none']) as repo:
  293. repo.remote().fetch()
  294. for submodule in repo.submodules:
  295. submodule.update()
  296. else:
  297. with git.Repo.clone_from(url, tmpdir, filter=['blob:none'], branch=branch_name) as repo:
  298. repo.remote().fetch()
  299. for submodule in repo.submodules:
  300. submodule.update()
  301. try:
  302. os.rename(tmpdir, target_dir)
  303. except OSError as err:
  304. if err.errno == errno.EXDEV:
  305. # Cross device link, typical in docker or when tmp/ and extensions/ are on different file systems
  306. # Since we can't use a rename, do the slower but more versitile shutil.move()
  307. shutil.move(tmpdir, target_dir)
  308. else:
  309. # Something else, not enough free space, permissions, etc. rethrow it so that it gets handled.
  310. raise err
  311. import launch
  312. launch.run_extension_installer(target_dir)
  313. extensions.list_extensions()
  314. return [extension_table(), html.escape(f"Installed into {target_dir}. Use Installed tab to restart.")]
  315. finally:
  316. shutil.rmtree(tmpdir, True)
  317. def install_extension_from_index(url, hide_tags, sort_column, filter_text):
  318. ext_table, message = install_extension_from_url(None, url)
  319. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  320. return code, ext_table, message, ''
  321. def refresh_available_extensions(url, hide_tags, sort_column):
  322. global available_extensions
  323. import urllib.request
  324. with urllib.request.urlopen(url) as response:
  325. text = response.read()
  326. available_extensions = json.loads(text)
  327. code, tags = refresh_available_extensions_from_data(hide_tags, sort_column)
  328. return url, code, gr.CheckboxGroup.update(choices=tags), '', ''
  329. def refresh_available_extensions_for_tags(hide_tags, sort_column, filter_text):
  330. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  331. return code, ''
  332. def search_extensions(filter_text, hide_tags, sort_column):
  333. code, _ = refresh_available_extensions_from_data(hide_tags, sort_column, filter_text)
  334. return code, ''
  335. sort_ordering = [
  336. # (reverse, order_by_function)
  337. (True, lambda x: x.get('added', 'z')),
  338. (False, lambda x: x.get('added', 'z')),
  339. (False, lambda x: x.get('name', 'z')),
  340. (True, lambda x: x.get('name', 'z')),
  341. (False, lambda x: 'z'),
  342. (True, lambda x: x.get('commit_time', '')),
  343. (True, lambda x: x.get('created_at', '')),
  344. (True, lambda x: x.get('stars', 0)),
  345. ]
  346. def get_date(info: dict, key):
  347. try:
  348. return datetime.strptime(info.get(key), "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc).astimezone().strftime("%Y-%m-%d")
  349. except (ValueError, TypeError):
  350. return ''
  351. def refresh_available_extensions_from_data(hide_tags, sort_column, filter_text=""):
  352. extlist = available_extensions["extensions"]
  353. installed_extensions = {extension.name for extension in extensions.extensions}
  354. installed_extension_urls = {normalize_git_url(extension.remote) for extension in extensions.extensions if extension.remote is not None}
  355. tags = available_extensions.get("tags", {})
  356. tags_to_hide = set(hide_tags)
  357. hidden = 0
  358. code = f"""<!-- {time.time()} -->
  359. <table id="available_extensions">
  360. <thead>
  361. <tr>
  362. <th>Extension</th>
  363. <th>Description</th>
  364. <th>Action</th>
  365. </tr>
  366. </thead>
  367. <tbody>
  368. """
  369. sort_reverse, sort_function = sort_ordering[sort_column if 0 <= sort_column < len(sort_ordering) else 0]
  370. for ext in sorted(extlist, key=sort_function, reverse=sort_reverse):
  371. name = ext.get("name", "noname")
  372. stars = int(ext.get("stars", 0))
  373. added = ext.get('added', 'unknown')
  374. update_time = get_date(ext, 'commit_time')
  375. create_time = get_date(ext, 'created_at')
  376. url = ext.get("url", None)
  377. description = ext.get("description", "")
  378. extension_tags = ext.get("tags", [])
  379. if url is None:
  380. continue
  381. existing = get_extension_dirname_from_url(url) in installed_extensions or normalize_git_url(url) in installed_extension_urls
  382. extension_tags = extension_tags + ["installed"] if existing else extension_tags
  383. if any(x for x in extension_tags if x in tags_to_hide):
  384. hidden += 1
  385. continue
  386. if filter_text and filter_text.strip():
  387. if filter_text.lower() not in html.escape(name).lower() and filter_text.lower() not in html.escape(description).lower():
  388. hidden += 1
  389. continue
  390. 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>"""
  391. tags_text = ", ".join([f"<span class='extension-tag' title='{tags.get(x, '')}'>{x}</span>" for x in extension_tags])
  392. code += f"""
  393. <tr>
  394. <td><a href="{html.escape(url)}" target="_blank">{html.escape(name)}</a><br />{tags_text}</td>
  395. <td>{html.escape(description)}<p class="info">
  396. <span class="date_added">Update: {html.escape(update_time)} Added: {html.escape(added)} Created: {html.escape(create_time)}</span><span class="star_count">stars: <b>{stars}</b></a></p></td>
  397. <td>{install_code}</td>
  398. </tr>
  399. """
  400. for tag in [x for x in extension_tags if x not in tags]:
  401. tags[tag] = tag
  402. code += """
  403. </tbody>
  404. </table>
  405. """
  406. if hidden > 0:
  407. code += f"<p>Extension hidden: {hidden}</p>"
  408. return code, list(tags)
  409. def preload_extensions_git_metadata():
  410. for extension in extensions.extensions:
  411. extension.read_info_from_repo()
  412. def create_ui():
  413. import modules.ui
  414. config_states.list_config_states()
  415. threading.Thread(target=preload_extensions_git_metadata).start()
  416. with gr.Blocks(analytics_enabled=False) as ui:
  417. with gr.Tabs(elem_id="tabs_extensions"):
  418. with gr.TabItem("Installed", id="installed"):
  419. with gr.Row(elem_id="extensions_installed_top"):
  420. apply_label = ("Apply and restart UI" if restart.is_restartable() else "Apply and quit")
  421. apply = gr.Button(value=apply_label, variant="primary")
  422. check = gr.Button(value="Check for updates")
  423. extensions_disable_all = gr.Radio(label="Disable all extensions", choices=["none", "extra", "all"], value=shared.opts.disable_all_extensions, elem_id="extensions_disable_all")
  424. extensions_disabled_list = gr.Text(elem_id="extensions_disabled_list", visible=False, container=False)
  425. extensions_update_list = gr.Text(elem_id="extensions_update_list", visible=False, container=False)
  426. refresh = gr.Button(value='Refresh', variant="compact")
  427. html = ""
  428. if shared.cmd_opts.disable_all_extensions or shared.cmd_opts.disable_extra_extensions or shared.opts.disable_all_extensions != "none":
  429. if shared.cmd_opts.disable_all_extensions:
  430. msg = '"--disable-all-extensions" was used, remove it to load all extensions again'
  431. elif shared.opts.disable_all_extensions != "none":
  432. msg = '"Disable all extensions" was set, change it to "none" to load all extensions again'
  433. elif shared.cmd_opts.disable_extra_extensions:
  434. msg = '"--disable-extra-extensions" was used, remove it to load all extensions again'
  435. html = f'<span style="color: var(--primary-400);">{msg}</span>'
  436. with gr.Row():
  437. info = gr.HTML(html)
  438. with gr.Row(elem_classes="progress-container"):
  439. extensions_table = gr.HTML('Loading...', elem_id="extensions_installed_html")
  440. ui.load(fn=extension_table, inputs=[], outputs=[extensions_table], show_progress=False)
  441. refresh.click(fn=extension_table, inputs=[], outputs=[extensions_table], show_progress=False)
  442. apply.click(
  443. fn=apply_and_restart,
  444. _js="extensions_apply",
  445. inputs=[extensions_disabled_list, extensions_update_list, extensions_disable_all],
  446. outputs=[],
  447. )
  448. check.click(
  449. fn=wrap_gradio_gpu_call(check_updates, extra_outputs=[gr.update()]),
  450. _js="extensions_check",
  451. inputs=[info, extensions_disabled_list],
  452. outputs=[extensions_table, info],
  453. )
  454. with gr.TabItem("Available", id="available"):
  455. with gr.Row():
  456. refresh_available_extensions_button = gr.Button(value="Load from:", variant="primary")
  457. extensions_index_url = os.environ.get('WEBUI_EXTENSIONS_INDEX', "https://raw.githubusercontent.com/AUTOMATIC1111/stable-diffusion-webui-extensions/master/index.json")
  458. available_extensions_index = gr.Text(value=extensions_index_url, label="Extension index URL", container=False)
  459. extension_to_install = gr.Text(elem_id="extension_to_install", visible=False)
  460. install_extension_button = gr.Button(elem_id="install_extension_button", visible=False)
  461. with gr.Row():
  462. hide_tags = gr.CheckboxGroup(value=["ads", "localization", "installed"], label="Hide extensions with tags", choices=["script", "ads", "localization", "installed"])
  463. sort_column = gr.Radio(value="newest first", label="Order", choices=["newest first", "oldest first", "a-z", "z-a", "internal order",'update time', 'create time', "stars"], type="index")
  464. with gr.Row():
  465. search_extensions_text = gr.Text(label="Search", container=False)
  466. install_result = gr.HTML()
  467. available_extensions_table = gr.HTML()
  468. refresh_available_extensions_button.click(
  469. fn=modules.ui.wrap_gradio_call(refresh_available_extensions, extra_outputs=[gr.update(), gr.update(), gr.update(), gr.update()]),
  470. inputs=[available_extensions_index, hide_tags, sort_column],
  471. outputs=[available_extensions_index, available_extensions_table, hide_tags, search_extensions_text, install_result],
  472. )
  473. install_extension_button.click(
  474. fn=modules.ui.wrap_gradio_call(install_extension_from_index, extra_outputs=[gr.update(), gr.update()]),
  475. inputs=[extension_to_install, hide_tags, sort_column, search_extensions_text],
  476. outputs=[available_extensions_table, extensions_table, install_result],
  477. )
  478. search_extensions_text.change(
  479. fn=modules.ui.wrap_gradio_call(search_extensions, extra_outputs=[gr.update()]),
  480. inputs=[search_extensions_text, hide_tags, sort_column],
  481. outputs=[available_extensions_table, install_result],
  482. )
  483. hide_tags.change(
  484. fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
  485. inputs=[hide_tags, sort_column, search_extensions_text],
  486. outputs=[available_extensions_table, install_result]
  487. )
  488. sort_column.change(
  489. fn=modules.ui.wrap_gradio_call(refresh_available_extensions_for_tags, extra_outputs=[gr.update()]),
  490. inputs=[hide_tags, sort_column, search_extensions_text],
  491. outputs=[available_extensions_table, install_result]
  492. )
  493. with gr.TabItem("Install from URL", id="install_from_url"):
  494. install_url = gr.Text(label="URL for extension's git repository")
  495. install_branch = gr.Text(label="Specific branch name", placeholder="Leave empty for default main branch")
  496. install_dirname = gr.Text(label="Local directory name", placeholder="Leave empty for auto")
  497. install_button = gr.Button(value="Install", variant="primary")
  498. install_result = gr.HTML(elem_id="extension_install_result")
  499. install_button.click(
  500. fn=modules.ui.wrap_gradio_call(lambda *args: [gr.update(), *install_extension_from_url(*args)], extra_outputs=[gr.update(), gr.update()]),
  501. inputs=[install_dirname, install_url, install_branch],
  502. outputs=[install_url, extensions_table, install_result],
  503. )
  504. with gr.TabItem("Backup/Restore"):
  505. with gr.Row(elem_id="extensions_backup_top_row"):
  506. 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()))
  507. 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")
  508. config_restore_type = gr.Radio(label="State to restore", choices=["extensions", "webui", "both"], value="extensions", elem_id="extension_backup_restore_type")
  509. config_restore_button = gr.Button(value="Restore Selected Config", variant="primary", elem_id="extension_backup_restore")
  510. with gr.Row(elem_id="extensions_backup_top_row2"):
  511. config_save_name = gr.Textbox("", placeholder="Config Name", show_label=False)
  512. config_save_button = gr.Button(value="Save Current Config")
  513. config_states_info = gr.HTML("")
  514. config_states_table = gr.HTML("Loading...")
  515. ui.load(fn=update_config_states_table, inputs=[config_states_list], outputs=[config_states_table])
  516. config_save_button.click(fn=save_config_state, inputs=[config_save_name], outputs=[config_states_list, config_states_info])
  517. dummy_component = gr.Label(visible=False)
  518. 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])
  519. config_states_list.change(
  520. fn=update_config_states_table,
  521. inputs=[config_states_list],
  522. outputs=[config_states_table],
  523. )
  524. return ui