stable-diffusion-webui/modules/ui_extra_networks.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

1056 lines
40 KiB
Python
Raw Normal View History

2023-09-30 07:29:10 +00:00
import functools
import os.path
import urllib.parse
2024-03-24 06:33:10 +00:00
from base64 import b64decode
from io import BytesIO
from pathlib import Path
2024-04-09 11:19:07 +00:00
from typing import Optional, Union, Any, Callable
from dataclasses import dataclass
import zlib
2024-03-13 21:11:44 +00:00
import base64
import re
2024-04-09 11:19:07 +00:00
from starlette.responses import Response, FileResponse, JSONResponse, PlainTextResponse
from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util
from modules.images import read_info_from_image, save_image_with_geninfo
import gradio as gr
import json
import html
2023-07-16 03:43:49 +00:00
from fastapi.exceptions import HTTPException
2024-03-24 06:33:10 +00:00
from PIL import Image
from modules.infotext_utils import image_from_url_text
extra_pages = []
allowed_dirs = set()
2023-09-30 07:29:10 +00:00
default_allowed_preview_extensions = ["png", "jpg", "jpeg", "webp", "gif"]
@functools.cache
def allowed_preview_extensions_with_extra(extra_extensions=None):
return set(default_allowed_preview_extensions) | set(extra_extensions or [])
def allowed_preview_extensions():
return allowed_preview_extensions_with_extra((shared.opts.samples_format, ))
2023-09-07 03:11:36 +00:00
@dataclass
class ExtraNetworksItem:
"""Wrapper for dictionaries representing ExtraNetworks items."""
item: dict
2024-03-26 17:58:21 +00:00
2024-04-09 11:19:07 +00:00
class ListItem:
"""
Attributes:
id [str]: The ID of this list item.
html [str]: The HTML string for this item.
"""
def __init__(self, _id: str, _html: str) -> None:
self.id = _id
self.html = _html
class CardListItem(ListItem):
"""
Attributes:
visible [bool]: Whether the item should be shown in the list.
sort_keys [dict]: Nested dict where keys are sort modes and values are sort keys.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.visible: bool = False
self.sort_keys = {}
self.search_terms = []
class TreeListItem(ListItem):
"""
Attributes:
visible [bool]: Whether the item should be shown in the list.
expanded [bool]: Whether the item children should be shown.
selected [bool]: Whether the item is selected by user.
"""
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.node: Optional[DirectoryTreeNode] = None
self.visible: bool = False
self.expanded: bool = False
self.selected: bool = False
class DirectoryTreeNode:
def __init__(
self,
root_dir: str,
abspath: str,
parent: Optional["DirectoryTreeNode"] = None,
) -> None:
self.abspath = abspath
self.root_dir = root_dir
self.parent = parent
self.is_dir = False
self.item = None
self.relpath = os.path.relpath(self.abspath, self.root_dir)
self.children: list["DirectoryTreeNode"] = []
# If a parent is passed, then we add this instance to the parent's children.
if self.parent is not None:
self.parent.add_child(self)
def add_child(self, child: "DirectoryTreeNode") -> None:
self.children.append(child)
def build(self, items: dict[str, dict]) -> None:
"""Builds a tree of nodes as children of this instance.
Args:
items: A dictionary where keys are absolute filepaths for directories/files.
The values are dictionaries representing extra networks items.
"""
self.is_dir = os.path.isdir(self.abspath)
if self.is_dir:
for x in os.listdir(self.abspath):
child_path = os.path.join(self.abspath, x)
DirectoryTreeNode(self.root_dir, child_path, self).build(items)
else:
self.item = items.get(self.abspath, None)
def flatten(self, res: dict, dirs_only: bool = False) -> None:
"""Flattens the keys/values of the tree nodes into a dictionary.
Args:
res: The dictionary result updated in place. On initial call, should be passed
as an empty dictionary.
dirs_only: Whether to only add directories to the result.
Raises:
KeyError: If any nodes in the tree have the same ID.
"""
if self.abspath in res:
raise KeyError(f"duplicate key: {self.abspath}")
if not dirs_only or (dirs_only and self.is_dir):
res[self.abspath] = self
for child in self.children:
child.flatten(res, dirs_only)
def apply(self, fn: Callable) -> None:
"""Recursively calls passed function with instance for entire tree."""
fn(self)
for child in self.children:
child.apply(fn)
def get_tree(paths: Union[str, list[str]], items: dict[str, ExtraNetworksItem]) -> dict:
"""Recursively builds a directory tree.
Args:
paths: Path or list of paths to directories. These paths are treated as roots from which
the tree will be built.
items: A dictionary associating filepaths to an ExtraNetworksItem instance.
Returns:
The result directory tree.
"""
if isinstance(paths, (str,)):
paths = [paths]
def _get_tree(_paths: list[str], _root: str):
_res = {}
for path in _paths:
relpath = os.path.relpath(path, _root)
if os.path.isdir(path):
dir_items = os.listdir(path)
# Ignore empty directories.
if not dir_items:
continue
dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root)
# We only want to store non-empty folders in the tree.
if dir_tree:
_res[relpath] = dir_tree
else:
if path not in items:
continue
# Add the ExtraNetworksItem to the result.
_res[relpath] = items[path]
return _res
res = {}
# Handle each root directory separately.
# Each root WILL have a key/value at the root of the result dict though
# the value can be an empty dict if the directory is empty. We want these
# placeholders for empty dirs so we can inform the user later.
for path in paths:
root = os.path.dirname(path)
relpath = os.path.relpath(path, root)
# Wrap the path in a list since that is what the `_get_tree` expects.
res[relpath] = _get_tree([path], root)
if res[relpath]:
# We need to pull the inner path out one for these root dirs.
res[relpath] = res[relpath][relpath]
return res
2024-03-26 17:58:21 +00:00
def register_page(page):
2024-03-26 17:58:21 +00:00
"""registers extra networks page for the UI
recommend doing it in on_before_ui() callback for extensions
"""
extra_pages.append(page)
allowed_dirs.clear()
allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], [])))
2024-04-09 11:19:07 +00:00
def get_page_by_name(extra_networks_tabname: str = "") -> "ExtraNetworksPage":
for page in extra_pages:
if page.extra_networks_tabname == extra_networks_tabname:
return page
2024-04-09 11:19:07 +00:00
raise HTTPException(status_code=404, detail=f"Page not found: {extra_networks_tabname}")
2024-04-09 11:19:07 +00:00
def fetch_file(filename: str = ""):
2023-07-16 03:43:49 +00:00
if not os.path.isfile(filename):
raise HTTPException(status_code=404, detail="File not found")
2023-05-10 08:05:02 +00:00
if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs):
raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.")
2023-09-30 07:29:10 +00:00
ext = os.path.splitext(filename)[1].lower()[1:]
if ext not in allowed_preview_extensions():
raise ValueError(f"File cannot be fetched: {filename}. Extensions allowed: {allowed_preview_extensions()}.")
# would profit from returning 304
return FileResponse(filename, headers={"Accept-Ranges": "bytes"})
2024-04-09 11:19:07 +00:00
def fetch_cover_images(extra_networks_tabname: str = "", item: str = "", index: int = 0):
page = get_page_by_name(extra_networks_tabname)
2024-03-24 06:33:10 +00:00
metadata = page.metadata.get(item)
if metadata is None:
raise HTTPException(status_code=404, detail="File not found")
cover_images = json.loads(metadata.get('ssmd_cover_images', {}))
image = cover_images[index] if index < len(cover_images) else None
if not image:
raise HTTPException(status_code=404, detail="File not found")
try:
image = Image.open(BytesIO(b64decode(image)))
buffer = BytesIO()
image.save(buffer, format=image.format)
return Response(content=buffer.getvalue(), media_type=image.get_format_mimetype())
except Exception as err:
raise ValueError(f"File cannot be fetched: {item}. Failed to load cover image.") from err
2024-04-09 11:19:07 +00:00
def init_tree_data(tabname: str = "", extra_networks_tabname: str = "") -> JSONResponse:
page = get_page_by_name(extra_networks_tabname)
data = page.generate_tree_view_data(tabname)
return JSONResponse(data, status_code=200)
2024-03-24 06:33:10 +00:00
2024-04-09 11:19:07 +00:00
def fetch_tree_data(
extra_networks_tabname: str = "",
2024-04-09 11:19:07 +00:00
div_ids: Optional[list[str]] = None,
) -> JSONResponse:
page = get_page_by_name(extra_networks_tabname)
2024-04-09 11:19:07 +00:00
if div_ids is None:
return JSONResponse({})
2024-04-09 11:19:07 +00:00
res = {}
for div_id in div_ids:
if div_id in page.tree:
res[div_id] = page.tree[div_id].html
2024-04-09 11:19:07 +00:00
return JSONResponse(res)
2024-04-09 11:19:07 +00:00
def fetch_cards_data(
extra_networks_tabname: str = "",
div_ids: Optional[list[str]] = None,
) -> JSONResponse:
page = get_page_by_name(extra_networks_tabname)
if div_ids is None:
return JSONResponse({})
res = {}
for div_id in div_ids:
if div_id in page.cards:
res[div_id] = page.cards[div_id].html
2024-04-09 11:19:07 +00:00
return JSONResponse(res)
2024-04-09 11:19:07 +00:00
def init_cards_data(tabname: str = "", extra_networks_tabname: str = "") -> JSONResponse:
page = get_page_by_name(extra_networks_tabname)
data = page.generate_cards_view_data(tabname)
return JSONResponse(data, status_code=200)
def get_metadata(extra_networks_tabname: str = "", item: str = "") -> JSONResponse:
try:
page = get_page_by_name(extra_networks_tabname)
except HTTPException:
return JSONResponse({})
metadata = page.metadata.get(item)
if metadata is None:
return JSONResponse({})
2024-04-09 11:19:07 +00:00
# those are cover images, and they are too big to display in UI as text
metadata = {i: metadata[i] for i in metadata if i != 'ssmd_cover_images'}
2024-03-24 06:33:10 +00:00
return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)})
2024-04-09 11:19:07 +00:00
def get_single_card(tabname: str = "", extra_networks_tabname: str = "", name: str = "") -> JSONResponse:
page = get_page_by_name(extra_networks_tabname)
try:
item = page.create_item(name, enable_filter=False)
page.items[name] = item
2024-04-09 11:19:07 +00:00
except Exception as exc:
errors.display(exc, "creating item for extra network")
item = page.items.get(name, None)
if item is None:
return JSONResponse({})
page.read_user_metadata(item, use_cache=False)
item_html = page.create_card_html(tabname=tabname, item=item)
return JSONResponse({"html": item_html})
def add_pages_to_demo(app):
app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"])
2024-03-24 06:33:10 +00:00
app.add_api_route("/sd_extra_networks/cover-images", fetch_cover_images, methods=["GET"])
app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"])
app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"])
2024-04-09 11:19:07 +00:00
#app.add_api_route("/sd_extra_networks/init-tree-data", init_tree_data, methods=["GET"])
#app.add_api_route("/sd_extra_networks/init-cards-data", init_cards_data, methods=["GET"])
#app.add_api_route("/sd_extra_networks/fetch-tree-data", fetch_tree_data, methods=["GET"])
#app.add_api_route("/sd_extra_networks/fetch-cards-data", fetch_cards_data, methods=["GET"])
2023-07-16 06:25:32 +00:00
def quote_js(s):
s = s.replace('\\', '\\\\')
s = s.replace('"', '\\"')
return f'"{s}"'
class ExtraNetworksPage:
def __init__(self, title):
self.title = title
2023-01-21 14:20:24 +00:00
self.name = title.lower()
2024-01-16 18:35:01 +00:00
# This is the actual name of the extra networks tab (not txt2img/img2img).
self.extra_networks_tabname = self.name.replace(" ", "_")
self.allow_prompt = True
self.allow_negative_prompt = False
self.metadata = {}
self.items = {}
2024-04-09 11:19:07 +00:00
self.cards = {}
self.tree = {}
2024-04-09 11:19:07 +00:00
self.tree_roots = {}
2024-01-16 18:35:01 +00:00
self.lister = util.MassFileLister()
# HTML Templates
self.pane_tpl = shared.html("extra-networks-pane.html")
self.card_tpl = shared.html("extra-networks-card.html")
2024-03-13 21:11:44 +00:00
self.tree_row_tpl = shared.html("extra-networks-tree-row.html")
2024-04-09 11:19:07 +00:00
self.btn_copy_path_tpl = shared.html("extra-networks-btn-copy-path.html")
self.btn_show_metadata_tpl = shared.html("extra-networks-btn-show-metadata.html")
self.btn_edit_metadata_tpl = shared.html("extra-networks-btn-edit-metadata.html")
self.btn_dirs_view_item_tpl = shared.html("extra-networks-btn-dirs-view-item.html")
# Sorted lists
# These just store ints so it won't use hardly any memory to just sort ahead
# of time for each sort mode. These are lists of keys for each file.
self.keys_sorted = {}
self.keys_by_name = []
self.keys_by_path = []
self.keys_by_created = []
self.keys_by_modified = []
def refresh(self):
pass
def read_user_metadata(self, item, use_cache=True):
filename = item.get("filename", None)
metadata = extra_networks.get_user_metadata(filename, lister=self.lister if use_cache else None)
desc = metadata.get("description", None)
if desc is not None:
item["description"] = desc
item["user_metadata"] = metadata
def link_preview(self, filename):
quoted_filename = urllib.parse.quote(filename.replace('\\', '/'))
mtime, _ = self.lister.mctime(filename)
return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}"
def search_terms_from_path(self, filename, possible_directories=None):
abspath = os.path.abspath(filename)
for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()):
2024-01-10 23:11:48 +00:00
parentdir = os.path.dirname(os.path.abspath(parentdir))
if abspath.startswith(parentdir):
2024-01-10 23:11:48 +00:00
return os.path.relpath(abspath, parentdir)
return ""
def build_tree_html_dict_row(
2024-03-19 01:59:41 +00:00
self,
tabname: str,
label: str,
btn_type: str,
btn_title: Optional[str] = None,
2024-04-09 11:19:07 +00:00
data_attributes: Optional[dict] = None,
2024-03-19 01:59:41 +00:00
dir_is_empty: bool = False,
item: Optional[dict] = None,
2024-03-19 01:59:41 +00:00
onclick_extra: Optional[str] = None,
) -> str:
if btn_type not in ["file", "dir"]:
raise ValueError("Invalid button type:", btn_type)
2024-03-29 16:26:29 +00:00
if data_attributes is None:
data_attributes = {}
2024-03-27 20:11:13 +00:00
label = label.strip()
# If not specified, title will just reflect the label
btn_title = btn_title.strip() if btn_title else label
2024-03-19 01:59:41 +00:00
action_list_item_action_leading = "<i class='tree-list-item-action-chevron'></i>"
action_list_item_visual_leading = "🗀"
action_list_item_visual_trailing = ""
action_list_item_action_trailing = ""
if dir_is_empty:
action_list_item_action_leading = "<i class='tree-list-item-action-chevron' style='visibility: hidden'></i>"
if btn_type == "file":
action_list_item_visual_leading = "🗎"
# Action buttons
if item is not None:
action_list_item_action_trailing += self.get_button_row(tabname, item)
data_attributes_str = ""
for k, v in data_attributes.items():
if isinstance(v, (bool,)):
# Boolean data attributes only need a key when true.
if v:
data_attributes_str += f"{k} "
elif v not in [None, "", "\'\'", "\"\""]:
data_attributes_str += f"{k}={v} "
2024-03-19 01:59:41 +00:00
res = self.tree_row_tpl.format(
**{
"data_attributes": data_attributes_str,
2024-03-19 01:59:41 +00:00
"search_terms": "",
"btn_type": btn_type,
2024-03-27 20:11:13 +00:00
"btn_title": btn_title,
2024-03-19 01:59:41 +00:00
"tabname": tabname,
"onclick_extra": onclick_extra if onclick_extra else "",
"extra_networks_tabname": self.extra_networks_tabname,
"action_list_item_action_leading": action_list_item_action_leading,
"action_list_item_visual_leading": action_list_item_visual_leading,
"action_list_item_label": label,
"action_list_item_visual_trailing": action_list_item_visual_trailing,
"action_list_item_action_trailing": action_list_item_action_trailing,
}
)
res = res.strip()
res = re.sub(" +", " ", res.replace("\n", ""))
return res
def get_button_row(self, tabname: str, item: dict) -> str:
metadata = item.get("metadata", None)
name = item.get("name", "")
filename = item.get("filename", "")
button_row_tpl = '<div class="button-row">{btn_copy_path}{btn_edit_item}{btn_metadata}</div>'
btn_copy_path = self.btn_copy_path_tpl.format(filename=filename)
2024-04-09 11:19:07 +00:00
btn_edit_item = self.btn_edit_metadata_tpl.format(
tabname=tabname,
extra_networks_tabname=self.extra_networks_tabname,
name=name,
)
btn_metadata = ""
if metadata:
2024-04-09 11:19:07 +00:00
btn_metadata = self.btn_show_metadata_tpl.format(
extra_networks_tabname=self.extra_networks_tabname,
name=name,
)
return button_row_tpl.format(
btn_copy_path=btn_copy_path,
btn_edit_item=btn_edit_item,
btn_metadata=btn_metadata,
)
def create_card_html(
2024-01-15 18:40:47 +00:00
self,
tabname: str,
item: dict,
2024-04-09 11:19:07 +00:00
div_id: Optional[str] = None,
) -> str:
2024-01-16 18:35:01 +00:00
"""Generates HTML for a single ExtraNetworks Item.
Args:
tabname: The name of the active tab.
item: Dictionary containing item information.
2024-01-16 18:35:01 +00:00
template: Optional template string to use.
Returns:
HTML string generated for this item. Can be empty if the item is not meant to be shown.
"""
2024-04-09 11:19:07 +00:00
style = f"font-size: {shared.opts.extra_networks_card_text_scale*100}%;"
if shared.opts.extra_networks_card_height:
style += f"height: {shared.opts.extra_networks_card_height}px;"
if shared.opts.extra_networks_card_width:
style += f"width: {shared.opts.extra_networks_card_width}px;"
background_image = None
preview = html.escape(item.get("preview", ""))
if preview:
background_image = f'<img src="{preview}" class="preview" loading="lazy">'
onclick = item.get("onclick", None)
if onclick is None:
onclick = html.escape(f"extraNetworksCardOnClick(event, '{tabname}');")
2024-01-15 23:01:13 +00:00
button_row = self.get_button_row(tabname, item)
filename = item.get("filename", "")
2024-04-09 11:19:07 +00:00
# if this is true, the item must not be shown in the default view,
# and must instead only be shown when searching for it
if shared.opts.extra_networks_hidden_models == "Always":
search_only = False
else:
2024-04-09 11:19:07 +00:00
search_only = filename.startswith(".")
if search_only and shared.opts.extra_networks_hidden_models == "Never":
return ""
2024-04-09 11:19:07 +00:00
sort_keys = {}
for sort_mode, sort_key in item.get("sort_keys", {}).items():
sort_keys[sort_mode.strip().lower()] = html.escape(str(sort_key))
search_terms_html = ""
search_terms_tpl = "<span class='hidden {class}'>{search_term}</span>"
for search_term in item.get("search_terms", []):
search_terms_html += search_terms_tpl.format(
**{
2024-01-16 19:54:07 +00:00
"class": f"search_terms{' search_only' if search_only else ''}",
"search_term": search_term,
}
)
2024-04-09 11:19:07 +00:00
description = ""
if shared.opts.extra_networks_card_show_desc:
description = item.get("description", "")
if not shared.opts.extra_networks_card_description_is_html:
description = html.escape(description)
data_attributes = {
"data-div-id": div_id if div_id else "",
"data-name": item.get("name", "").strip(),
"data-path": item.get("filename", "").strip(),
"data-hash": item.get("shorthash", None),
"data-prompt": item.get("prompt", "").strip(),
"data-neg-prompt": item.get("negative_prompt", "").strip(),
"data-allow-neg": self.allow_negative_prompt,
2024-04-09 11:19:07 +00:00
**{f"data-sort-{sort_mode}": sort_key for sort_mode, sort_key in sort_keys},
}
data_attributes_str = ""
for k, v in data_attributes.items():
if isinstance(v, (bool,)):
# Boolean data attributes only need a key when true.
if v:
data_attributes_str += f"{k} "
elif v not in [None, "", "\'\'", "\"\""]:
data_attributes_str += f"{k}={v} "
return self.card_tpl.format(
style=style,
onclick=onclick,
data_attributes=data_attributes_str,
sort_keys=sort_keys,
background_image=background_image,
button_row=button_row,
search_terms=search_terms_html,
name=html.escape(item["name"].strip()),
description=description,
)
2024-04-09 11:19:07 +00:00
def generate_cards_view_data(self, tabname: str) -> dict:
for i, item in enumerate(self.items.values()):
div_id = str(i)
card_html = self.create_card_html(tabname=tabname, item=item, div_id=div_id)
sort_keys = {
k.strip().lower().replace(" ", "_"): html.escape(str(v))
for k, v in item.get("sort_keys", {}).items()
}
search_terms = item.get("search_terms", [])
self.cards[div_id] = CardListItem(div_id, card_html)
self.cards[div_id].sort_keys = sort_keys
self.cards[div_id].search_terms = search_terms
# Sort cards for all sort modes
sort_modes = ["name", "path", "date_created", "date_modified"]
for mode in sort_modes:
self.keys_sorted[mode] = sorted(
self.cards.keys(),
key=lambda k: shared.natural_sort_key(self.cards[k].sort_keys[mode]),
)
2024-04-09 11:19:07 +00:00
res = {}
for div_id, card_item in self.cards.items():
res[div_id] = {
**{f"sort_{mode}": key for mode, key in card_item.sort_keys.items()},
"search_terms": card_item.search_terms,
}
return res
2024-04-09 11:19:07 +00:00
def generate_tree_view_data(self, tabname: str) -> dict:
if not self.tree_roots:
return {}
# Flatten each root into a single dict
tree = {}
for node in self.tree_roots.values():
subtree = {}
node.flatten(subtree)
tree.update(subtree)
path_to_div_id = {}
div_id_to_node = {} # reverse mapping
# First assign div IDs to each node. Used for parent ID lookup later.
for i, path in enumerate(sorted(tree.keys(), key=shared.natural_sort_key)):
div_id = str(i)
path_to_div_id[path] = div_id
div_id_to_node[div_id] = tree[path]
show_files = shared.opts.extra_networks_tree_view_show_files is True
for div_id, node in div_id_to_node.items():
self.tree[div_id] = TreeListItem(div_id, "")
self.tree[div_id].node = node
parent_id = None
if node.parent is not None:
parent_id = path_to_div_id.get(node.parent.abspath, None)
if node.item is None: # directory
dir_is_empty = show_files and any(x.item is not None for x in node.children)
self.tree[div_id].html = self.build_tree_html_dict_row(
tabname=tabname,
label=os.path.basename(node.abspath),
btn_type="dir",
btn_title=node.abspath,
dir_is_empty=dir_is_empty,
data_attributes={
"data-div-id": div_id,
"data-parent-id": parent_id,
"data-tree-entry-type": "dir",
"data-depth": node.depth,
"data-path": node.abspath,
"data-expanded": node.parent is None, # Expand root directories
},
)
else: # file
if not show_files:
# Don't add file if files are disabled in the options.
continue
2024-04-09 11:19:07 +00:00
onclick = node.item.get("onclick", None)
if onclick is None:
onclick = html.escape(f"extraNetworksCardOnClick(event, '{tabname}');")
2024-04-09 11:19:07 +00:00
item_name = node.item.get("name", "").strip()
self.tree[div_id].html = self.build_tree_html_dict_row(
tabname=tabname,
label=html.escape(item_name),
btn_type="file",
data_attributes={
"data-div-id": div_id,
"data-parent-id": parent_id,
"data-tree-entry-type": "file",
"data-name": item_name,
"data-depth": node.depth,
"data-path": node.item.get("filename", "").strip(),
"data-hash": node.item.get("shorthash", None),
"data-prompt": node.item.get("prompt", "").strip(),
"data-neg-prompt": node.item.get("negative_prompt", "").strip(),
"data-allow-neg": self.allow_negative_prompt,
},
item=node.item,
onclick_extra=onclick,
)
2024-04-09 11:19:07 +00:00
res = {}
2024-04-09 11:19:07 +00:00
# Expand all root directories and set them to active so they are displayed.
for path in self.tree_roots.keys():
div_id = path_to_div_id[path]
self.tree[div_id].expanded = True
self.tree[div_id].visible = True
# Set all direct children to active
for child_node in self.tree[div_id].node.children:
self.tree[child_node.id].visible = True
for div_id, tree_item in self.tree.items():
# Expand root nodes and make them visible.
expanded = tree_item.node.parent is None
visible = tree_item.node.parent is None
parent = None
if tree_item.node.parent is not None:
parent = path_to_div_id[tree_item.node.parent.abspath]
# Direct children of root nodes should be visible by default.
if tree_item.node.parent.node is None:
visible = True
res[div_id] = {
"parent": parent,
"children": [path_to_div_id[child.abspath] for child in tree_item.node.children],
"visible": visible,
"expanded": expanded,
}
return res
2024-04-09 11:19:07 +00:00
def create_dirs_view_html(self, tabname: str) -> str:
"""Generates HTML for displaying folders."""
# Flatten each root into a single dict. Only get the directories for buttons.
tree = {}
for node in self.tree_roots.values():
subtree = {}
node.flatten(subtree, dirs_only=True)
tree.update(subtree)
# Sort the tree nodes by relative paths
dir_nodes = list(sorted(
tree.values(),
key=lambda x: shared.natural_sort_key(x.relpath),
))
dirs_html = "".join([
2024-04-09 11:19:07 +00:00
self.btn_dirs_view_item_tpl.format(**{
"extra_class": "search-all" if node.relpath == "" else "",
2024-03-13 21:11:44 +00:00
"tabname_full": f"{tabname}_{self.extra_networks_tabname}",
2024-04-09 11:19:07 +00:00
"path": html.escape(node.relpath),
}) for node in dir_nodes
2024-03-13 21:11:44 +00:00
])
return dirs_html
def create_html(self, tabname, *, empty=False):
2024-01-16 18:35:01 +00:00
"""Generates an HTML string for the current pane.
The generated HTML uses `extra-networks-pane.html` as a template.
Args:
tabname: The name of the active tab.
empty: create an empty HTML page with no items
2024-01-16 18:35:01 +00:00
Returns:
HTML formatted string.
"""
2024-01-11 21:37:35 +00:00
self.lister.reset()
2024-01-10 23:11:48 +00:00
self.metadata = {}
items_list = [] if empty else self.list_items()
self.items = {x["name"]: x for x in items_list}
# Populate the instance metadata for each item.
for item in self.items.values():
metadata = item.get("metadata")
if metadata:
self.metadata[item["name"]] = metadata
if "user_metadata" not in item:
self.read_user_metadata(item)
2024-01-10 23:11:48 +00:00
# Setup the tree dictionary.
2024-04-09 11:19:07 +00:00
tree_items = {v["filename"]: v for v in self.items.values()}
# Create a DirectoryTreeNode for each root directory since they might not share
# a common path.
for path in self.allowed_directories_for_previews():
abspath = os.path.abspath(path)
self.tree_roots[abspath] = DirectoryTreeNode(os.path.dirname(abspath), abspath, None)
self.tree_roots[abspath].build(tree_items)
# Generate the html for displaying directory buttons
2024-03-19 01:59:41 +00:00
dirs_html = self.create_dirs_view_html(tabname)
sort_mode = shared.opts.extra_networks_card_order_field.lower().strip().replace(" ", "_")
sort_dir = shared.opts.extra_networks_card_order.lower().strip()
dirs_view_en = shared.opts.extra_networks_dirs_view_default_enabled
tree_view_en = shared.opts.extra_networks_tree_view_default_enabled
2024-03-19 01:59:41 +00:00
return self.pane_tpl.format(**{
"tabname": tabname,
"extra_networks_tabname": self.extra_networks_tabname,
"data_sort_dir": sort_dir,
"btn_sort_mode_path_data_attributes": "data-selected" if sort_mode == "path" else "",
"btn_sort_mode_name_data_attributes": "data-selected" if sort_mode == "name" else "",
"btn_sort_mode_date_created_data_attributes": "data-selected" if sort_mode == "date_created" else "",
"btn_sort_mode_date_modified_data_attributes": "data-selected" if sort_mode == "date_modified" else "",
"btn_dirs_view_data_attributes": "data-selected" if dirs_view_en else "",
"btn_tree_view_data_attributes": "data-selected" if tree_view_en else "",
"dirs_view_hidden_cls": "" if dirs_view_en else "hidden",
"tree_view_hidden_cls": "" if tree_view_en else "hidden",
"tree_view_style": f"flex-basis: {shared.opts.extra_networks_tree_view_default_width}px;",
"cards_view_style": "flex-grow: 1;",
2024-03-19 01:59:41 +00:00
"dirs_html": dirs_html,
})
def create_item(self, name, index=None):
raise NotImplementedError()
def list_items(self):
raise NotImplementedError()
def allowed_directories_for_previews(self):
return []
2023-06-02 04:08:45 +00:00
def get_sort_keys(self, path):
"""
List of default keys used for sorting in the UI.
"""
pth = Path(path)
mtime, ctime = self.lister.mctime(path)
2023-06-02 04:08:45 +00:00
return {
"date_created": int(mtime),
"date_modified": int(ctime),
"name": pth.name.lower(),
"path": str(pth).lower(),
2023-06-02 04:08:45 +00:00
}
def find_preview(self, path):
"""
Find a preview PNG for a given path (without extension) and call link_preview on it.
"""
2024-01-16 19:54:07 +00:00
potential_files = sum([[f"{path}.{ext}", f"{path}.preview.{ext}"] for ext in allowed_preview_extensions()], [])
for file in potential_files:
if self.lister.exists(file):
return self.link_preview(file)
return None
2024-03-24 06:33:10 +00:00
def find_embedded_preview(self, path, name, metadata):
"""
Find if embedded preview exists in safetensors metadata and return endpoint for it.
"""
file = f"{path}.safetensors"
if self.lister.exists(file) and 'ssmd_cover_images' in metadata and len(list(filter(None, json.loads(metadata['ssmd_cover_images'])))) > 0:
2024-04-09 11:19:07 +00:00
return f"./sd_extra_networks/cover-images?extra_networks_tabname={self.extra_networks_tabname}&item={name}"
2024-03-24 06:33:10 +00:00
return None
def find_description(self, path):
"""
Find and read a description file for a given path (without extension).
"""
for file in [f"{path}.txt", f"{path}.description.txt"]:
if not self.lister.exists(file):
continue
try:
with open(file, "r", encoding="utf-8", errors="replace") as f:
return f.read()
except OSError:
pass
return None
def create_user_metadata_editor(self, ui, tabname):
return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self)
2023-05-19 12:27:23 +00:00
def initialize():
extra_pages.clear()
def register_default_pages():
from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion
from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks
from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints
register_page(ExtraNetworksPageTextualInversion())
register_page(ExtraNetworksPageHypernetworks())
register_page(ExtraNetworksPageCheckpoints())
class ExtraNetworksUi:
def __init__(self):
self.pages = None
"""gradio HTML components related to extra networks' pages"""
self.page_contents = None
"""HTML content of the above; empty initially, filled when extra pages have to be shown"""
self.stored_extra_pages = None
self.button_save_preview = None
self.preview_target_filename = None
self.tabname = None
def pages_in_preferred_order(pages):
tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")]
def tab_name_score(name):
name = name.lower()
for i, possible_match in enumerate(tab_order):
if possible_match in name:
return i
return len(pages)
tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)}
return sorted(pages, key=lambda x: tab_scores[x.name])
def create_ui(interface: gr.Blocks, unrelated_tabs, tabname):
ui = ExtraNetworksUi()
ui.pages = []
ui.pages_contents = []
ui.user_metadata_editors = []
ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy())
ui.tabname = tabname
related_tabs = []
for page in ui.stored_extra_pages:
2024-01-16 18:35:01 +00:00
with gr.Tab(page.title, elem_id=f"{tabname}_{page.extra_networks_tabname}", elem_classes=["extra-page"]) as tab:
with gr.Column(elem_id=f"{tabname}_{page.extra_networks_tabname}_prompts", elem_classes=["extra-page-prompts"]):
pass
2024-03-19 01:59:41 +00:00
elem_id = f"{tabname}_{page.extra_networks_tabname}_pane_container"
page_elem = gr.HTML(page.create_html(tabname, empty=True), elem_id=elem_id)
ui.pages.append(page_elem)
editor = page.create_user_metadata_editor(ui, tabname)
editor.create_ui()
ui.user_metadata_editors.append(editor)
related_tabs.append(tab)
2024-01-16 19:54:07 +00:00
ui.button_save_preview = gr.Button('Save preview', elem_id=f"{tabname}_save_preview", visible=False)
ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=f"{tabname}_preview_filename", visible=False)
2024-01-15 23:01:13 +00:00
for tab in unrelated_tabs:
2024-04-09 11:19:07 +00:00
tab.select(
fn=None,
_js=f"fujnction(){{extraNetworksUnrelatedTabSelected('{tabname}');}}",
inputs=[],
outputs=[],
show_progress=False,
)
2024-01-16 19:54:07 +00:00
for page, tab in zip(ui.stored_extra_pages, related_tabs):
jscode = (
2024-04-09 11:19:07 +00:00
"function(){extraNetworksTabSelected("
f"'{tabname}', "
f"'{tabname}_{page.extra_networks_tabname}_prompts', "
f"{str(page.allow_prompt).lower()}, "
f"{str(page.allow_negative_prompt).lower()}, "
f"'{tabname}_{page.extra_networks_tabname}'"
");}"
2024-01-16 19:54:07 +00:00
)
tab.select(fn=None, _js=jscode, inputs=[], outputs=[], show_progress=False)
2024-01-15 23:01:13 +00:00
def refresh():
for pg in ui.stored_extra_pages:
pg.refresh()
create_html()
return ui.pages_contents
button_refresh = gr.Button("Refresh", elem_id=f"{tabname}_{page.extra_networks_tabname}_extra_refresh_internal", visible=False)
2024-03-13 21:11:44 +00:00
button_refresh.click(
fn=refresh,
inputs=[],
outputs=ui.pages,
).then(
fn=lambda: None,
_js='setupAllResizeHandles'
).then(
fn=lambda: None,
_js=f"function(){{ extraNetworksRefreshTab('{tabname}_{page.extra_networks_tabname}'); }}",
)
def create_html():
ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages]
2023-07-16 08:52:29 +00:00
def pages_html():
if not ui.pages_contents:
create_html()
2023-07-16 08:52:29 +00:00
return ui.pages_contents
2024-03-13 21:11:44 +00:00
interface.load(
fn=pages_html,
inputs=[],
outputs=ui.pages,
).then(
fn=lambda: None,
_js="setupAllResizeHandles",
)
return ui
def path_is_parent(parent_path, child_path):
parent_path = os.path.abspath(parent_path)
child_path = os.path.abspath(child_path)
return child_path.startswith(parent_path)
def setup_ui(ui, gallery):
def save_preview(index, images, filename):
# this function is here for backwards compatibility and likely will be removed soon
if len(images) == 0:
print("There is no image in gallery to save as a preview.")
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
index = int(index)
index = 0 if index < 0 else index
index = len(images) - 1 if index >= len(images) else index
img_info = images[index if index >= 0 else 0]
image = image_from_url_text(img_info)
2023-03-25 19:59:50 +00:00
geninfo, items = read_info_from_image(image)
is_allowed = False
for extra_page in ui.stored_extra_pages:
2023-05-10 08:05:02 +00:00
if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()):
is_allowed = True
break
assert is_allowed, f'writing to {filename} is not allowed'
save_image_with_geninfo(image, geninfo, filename)
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
ui.button_save_preview.click(
fn=save_preview,
_js="function(x, y, z){return [selected_gallery_index(), y, z]}",
inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename],
outputs=[*ui.pages]
)
for editor in ui.user_metadata_editors:
editor.setup_ui(gallery)