ui_extensions.py 26 KB

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