ui_extensions.py 30 KB

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