2023-09-30 15:29:10 +08:00
|
|
|
import functools
|
2023-01-21 13:36:07 +08:00
|
|
|
import os.path
|
2023-01-29 03:52:27 +08:00
|
|
|
import urllib.parse
|
|
|
|
from pathlib import Path
|
2024-01-09 03:10:03 +08:00
|
|
|
from typing import Optional, Union
|
|
|
|
from dataclasses import dataclass
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2024-01-04 07:28:05 +08:00
|
|
|
from modules import shared, ui_extra_networks_user_metadata, errors, extra_networks, util
|
2023-05-18 02:03:41 +08:00
|
|
|
from modules.images import read_info_from_image, save_image_with_geninfo
|
2023-01-21 13:36:07 +08:00
|
|
|
import gradio as gr
|
|
|
|
import json
|
2023-01-24 04:11:34 +08:00
|
|
|
import html
|
2023-07-16 11:43:49 +08:00
|
|
|
from fastapi.exceptions import HTTPException
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2024-01-01 22:25:30 +08:00
|
|
|
from modules.infotext_utils import image_from_url_text
|
2023-07-16 15:44:04 +08:00
|
|
|
from modules.ui_components import ToolButton
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
extra_pages = []
|
2023-01-29 03:52:27 +08:00
|
|
|
allowed_dirs = set()
|
2023-09-30 15:29:10 +08: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 11:11:36 +08:00
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2024-01-09 03:10:03 +08:00
|
|
|
@dataclass
|
|
|
|
class ExtraNetworksItem:
|
|
|
|
"""Wrapper for dictionaries representing ExtraNetworks items."""
|
|
|
|
item: dict
|
|
|
|
|
|
|
|
|
|
|
|
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]
|
|
|
|
|
2024-01-12 04:06:57 +08:00
|
|
|
def _get_tree(_paths: list[str], _root: str):
|
2024-01-09 03:10:03 +08:00
|
|
|
_res = {}
|
|
|
|
for path in _paths:
|
2024-01-12 04:06:57 +08:00
|
|
|
relpath = os.path.relpath(path, _root)
|
2024-01-09 03:10:03 +08:00
|
|
|
if os.path.isdir(path):
|
|
|
|
dir_items = os.listdir(path)
|
|
|
|
# Ignore empty directories.
|
|
|
|
if not dir_items:
|
|
|
|
continue
|
2024-01-12 04:06:57 +08:00
|
|
|
dir_tree = _get_tree([os.path.join(path, x) for x in dir_items], _root)
|
2024-01-09 03:10:03 +08:00
|
|
|
# We only want to store non-empty folders in the tree.
|
|
|
|
if dir_tree:
|
2024-01-12 04:06:57 +08:00
|
|
|
_res[relpath] = dir_tree
|
2024-01-09 03:10:03 +08:00
|
|
|
else:
|
|
|
|
if path not in items:
|
|
|
|
continue
|
|
|
|
# Add the ExtraNetworksItem to the result.
|
2024-01-12 04:06:57 +08:00
|
|
|
_res[relpath] = items[path]
|
2024-01-09 03:10:03 +08:00
|
|
|
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:
|
2024-01-12 04:06:57 +08:00
|
|
|
root = os.path.dirname(path)
|
|
|
|
relpath = os.path.relpath(path, root)
|
2024-01-09 03:10:03 +08:00
|
|
|
# Wrap the path in a list since that is what the `_get_tree` expects.
|
2024-01-12 04:06:57 +08:00
|
|
|
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]
|
2024-01-09 03:10:03 +08:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
def register_page(page):
|
2023-01-21 21:15:53 +08:00
|
|
|
"""registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions"""
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
extra_pages.append(page)
|
2023-01-29 03:52:27 +08:00
|
|
|
allowed_dirs.clear()
|
|
|
|
allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], [])))
|
|
|
|
|
|
|
|
|
2023-03-25 15:11:04 +08:00
|
|
|
def fetch_file(filename: str = ""):
|
|
|
|
from starlette.responses import FileResponse
|
|
|
|
|
2023-07-16 11:43:49 +08:00
|
|
|
if not os.path.isfile(filename):
|
|
|
|
raise HTTPException(status_code=404, detail="File not found")
|
|
|
|
|
2023-05-10 16:05:02 +08:00
|
|
|
if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs):
|
2023-03-25 15:11:04 +08:00
|
|
|
raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.")
|
|
|
|
|
2023-09-30 15:29:10 +08: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()}.")
|
2023-03-25 15:11:04 +08:00
|
|
|
|
|
|
|
# would profit from returning 304
|
|
|
|
return FileResponse(filename, headers={"Accept-Ranges": "bytes"})
|
|
|
|
|
|
|
|
|
|
|
|
def get_metadata(page: str = "", item: str = ""):
|
|
|
|
from starlette.responses import JSONResponse
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-03-25 15:11:04 +08:00
|
|
|
page = next(iter([x for x in extra_pages if x.name == page]), None)
|
|
|
|
if page is None:
|
|
|
|
return JSONResponse({})
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-03-25 15:11:04 +08:00
|
|
|
metadata = page.metadata.get(item)
|
|
|
|
if metadata is None:
|
|
|
|
return JSONResponse({})
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-07-16 14:49:22 +08:00
|
|
|
return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)})
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-03-25 15:11:04 +08:00
|
|
|
|
2023-07-16 13:38:23 +08:00
|
|
|
def get_single_card(page: str = "", tabname: str = "", name: str = ""):
|
|
|
|
from starlette.responses import JSONResponse
|
|
|
|
|
|
|
|
page = next(iter([x for x in extra_pages if x.name == page]), None)
|
|
|
|
|
|
|
|
try:
|
2023-07-17 23:56:14 +08:00
|
|
|
item = page.create_item(name, enable_filter=False)
|
|
|
|
page.items[name] = item
|
2023-07-16 13:38:23 +08:00
|
|
|
except Exception as e:
|
|
|
|
errors.display(e, "creating item for extra network")
|
|
|
|
item = page.items.get(name)
|
|
|
|
|
2023-07-16 14:49:22 +08:00
|
|
|
page.read_user_metadata(item)
|
2024-01-09 03:10:03 +08:00
|
|
|
item_html = page.create_item_html(tabname, item)
|
2023-07-16 13:38:23 +08:00
|
|
|
|
|
|
|
return JSONResponse({"html": item_html})
|
|
|
|
|
|
|
|
|
2023-03-25 15:11:04 +08:00
|
|
|
def add_pages_to_demo(app):
|
2023-01-29 03:52:27 +08:00
|
|
|
app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"])
|
2023-03-25 15:11:04 +08:00
|
|
|
app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"])
|
2023-07-16 13:38:23 +08:00
|
|
|
app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"])
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
|
2023-07-16 14:25:32 +08:00
|
|
|
def quote_js(s):
|
|
|
|
s = s.replace('\\', '\\\\')
|
|
|
|
s = s.replace('"', '\\"')
|
|
|
|
return f'"{s}"'
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
class ExtraNetworksPage:
|
|
|
|
def __init__(self, title):
|
|
|
|
self.title = title
|
2023-01-21 22:20:24 +08:00
|
|
|
self.name = title.lower()
|
2023-07-16 01:39:04 +08:00
|
|
|
self.id_page = self.name.replace(" ", "_")
|
2024-01-11 07:11:48 +08:00
|
|
|
self.extra_networks_pane_template = shared.html("extra-networks-pane.html")
|
|
|
|
self.card_page_template = shared.html("extra-networks-card.html")
|
|
|
|
self.card_page_minimal_template = shared.html("extra-networks-card-minimal.html")
|
2023-11-06 00:19:55 +08:00
|
|
|
self.allow_prompt = True
|
2023-01-21 13:36:07 +08:00
|
|
|
self.allow_negative_prompt = False
|
2023-03-25 15:11:04 +08:00
|
|
|
self.metadata = {}
|
2023-07-16 01:39:04 +08:00
|
|
|
self.items = {}
|
2024-01-04 07:28:05 +08:00
|
|
|
self.lister = util.MassFileLister()
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
def refresh(self):
|
|
|
|
pass
|
|
|
|
|
2023-07-16 01:39:04 +08:00
|
|
|
def read_user_metadata(self, item):
|
|
|
|
filename = item.get("filename", None)
|
2024-01-04 07:39:02 +08:00
|
|
|
metadata = extra_networks.get_user_metadata(filename, lister=self.lister)
|
2023-07-16 01:39:04 +08:00
|
|
|
|
|
|
|
desc = metadata.get("description", None)
|
|
|
|
if desc is not None:
|
|
|
|
item["description"] = desc
|
|
|
|
|
|
|
|
item["user_metadata"] = metadata
|
|
|
|
|
2023-01-29 03:52:27 +08:00
|
|
|
def link_preview(self, filename):
|
2023-05-10 03:17:58 +08:00
|
|
|
quoted_filename = urllib.parse.quote(filename.replace('\\', '/'))
|
2024-01-04 07:28:05 +08:00
|
|
|
mtime, _ = self.lister.mctime(filename)
|
2023-05-10 03:17:58 +08:00
|
|
|
return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}"
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-01-29 15:20:19 +08:00
|
|
|
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-11 07:11:48 +08:00
|
|
|
parentdir = os.path.dirname(os.path.abspath(parentdir))
|
2023-01-29 15:20:19 +08:00
|
|
|
if abspath.startswith(parentdir):
|
2024-01-11 07:11:48 +08:00
|
|
|
return os.path.relpath(abspath, parentdir)
|
2023-01-29 15:20:19 +08:00
|
|
|
|
|
|
|
return ""
|
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
def create_item_html(self, tabname: str, item: dict, template: Optional[str] = None) -> str:
|
2024-01-09 03:10:03 +08:00
|
|
|
"""Generates HTML for a single ExtraNetworks Item
|
|
|
|
|
|
|
|
Args:
|
|
|
|
tabname: The name of the active tab.
|
|
|
|
item: Dictionary containing item information.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
HTML string generated for this item.
|
|
|
|
Can be empty if the item is not meant to be shown.
|
|
|
|
"""
|
|
|
|
metadata = item.get("metadata")
|
|
|
|
if metadata:
|
|
|
|
self.metadata[item["name"]] = metadata
|
|
|
|
|
|
|
|
if "user_metadata" not in item:
|
|
|
|
self.read_user_metadata(item)
|
|
|
|
|
|
|
|
preview = item.get("preview", None)
|
|
|
|
height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else ''
|
|
|
|
width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else ''
|
|
|
|
background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else ''
|
|
|
|
|
|
|
|
onclick = item.get("onclick", None)
|
|
|
|
if onclick is None:
|
2023-12-31 04:52:27 +08:00
|
|
|
if "negative_prompt" in item:
|
|
|
|
onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {item["negative_prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
|
|
|
|
else:
|
|
|
|
onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {'""'}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
|
2024-01-09 03:23:01 +08:00
|
|
|
|
2024-01-09 03:10:03 +08:00
|
|
|
copy_path_button = f"<div class='copy-path-button card-button' title='Copy path to clipboard' onclick='extraNetworksCopyCardPath(event, {quote_js(item['filename'])})' data-clipboard-text='{quote_js(item['filename'])}'></div>"
|
|
|
|
|
|
|
|
metadata_button = ""
|
|
|
|
metadata = item.get("metadata")
|
|
|
|
if metadata:
|
|
|
|
metadata_button = f"<div class='metadata-button card-button' title='Show internal metadata' onclick='extraNetworksRequestMetadata(event, {quote_js(self.name)}, {quote_js(html.escape(item['name']))})'></div>"
|
|
|
|
|
|
|
|
edit_button = f"<div class='edit-button card-button' title='Edit metadata' onclick='extraNetworksEditUserMetadata(event, {quote_js(tabname)}, {quote_js(self.id_page)}, {quote_js(html.escape(item['name']))})'></div>"
|
|
|
|
|
|
|
|
local_path = ""
|
|
|
|
filename = item.get("filename", "")
|
|
|
|
for reldir in self.allowed_directories_for_previews():
|
|
|
|
absdir = os.path.abspath(reldir)
|
|
|
|
|
|
|
|
if filename.startswith(absdir):
|
|
|
|
local_path = filename[len(absdir):]
|
|
|
|
|
|
|
|
# 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:
|
|
|
|
search_only = "/." in local_path or "\\." in local_path
|
|
|
|
|
|
|
|
if search_only and shared.opts.extra_networks_hidden_models == "Never":
|
|
|
|
return ""
|
|
|
|
|
|
|
|
sort_keys = " ".join([f'data-sort-{k}="{html.escape(str(v))}"' for k, v in item.get("sort_keys", {}).items()]).strip()
|
|
|
|
|
2024-01-12 04:06:57 +08:00
|
|
|
search_terms_html = ""
|
|
|
|
search_term_template = "<span style='{style}' class='{class}'>{search_term}</span>"
|
|
|
|
for search_term in item.get("search_terms", []):
|
|
|
|
search_terms_html += search_term_template.format(
|
|
|
|
**{
|
|
|
|
"style": "display: none;",
|
|
|
|
"class": "search_terms" + (" search_only" if search_only else ""),
|
|
|
|
"search_term": search_term,
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2024-01-09 03:10:03 +08:00
|
|
|
# Some items here might not be used depending on HTML template used.
|
|
|
|
args = {
|
|
|
|
"background_image": background_image,
|
|
|
|
"card_clicked": onclick,
|
|
|
|
"copy_path_button": copy_path_button,
|
|
|
|
"description": (item.get("description") or "" if shared.opts.extra_networks_card_show_desc else ""),
|
|
|
|
"edit_button": edit_button,
|
|
|
|
"local_preview": quote_js(item["local_preview"]),
|
|
|
|
"metadata_button": metadata_button,
|
|
|
|
"name": html.escape(item["name"]),
|
|
|
|
"prompt": item.get("prompt", None),
|
|
|
|
"save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {quote_js(tabname)}, {quote_js(item["local_preview"])})""") + '"',
|
|
|
|
"search_only": " search_only" if search_only else "",
|
2024-01-12 04:06:57 +08:00
|
|
|
"search_terms": search_terms_html,
|
2024-01-09 03:10:03 +08:00
|
|
|
"sort_keys": sort_keys,
|
|
|
|
"style": f"'display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%'",
|
|
|
|
"tabname": quote_js(tabname),
|
|
|
|
}
|
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
if template:
|
|
|
|
return template.format(**args)
|
|
|
|
else:
|
|
|
|
return self.card_page.format(**args)
|
2024-01-09 03:10:03 +08:00
|
|
|
|
|
|
|
def create_tree_view_html(self, tabname: str) -> str:
|
|
|
|
"""Generates HTML for displaying folders in a tree view.
|
|
|
|
|
|
|
|
Args:
|
|
|
|
tabname: The name of the active tab.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
HTML string generated for this tree view.
|
|
|
|
"""
|
2024-01-12 04:06:57 +08:00
|
|
|
res = ""
|
2023-03-25 15:11:04 +08:00
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
# Generate HTML for the tree.
|
2024-01-09 03:10:03 +08:00
|
|
|
roots = self.allowed_directories_for_previews()
|
|
|
|
tree_items = {v["filename"]: ExtraNetworksItem(v) for v in self.items.values()}
|
|
|
|
tree = get_tree([os.path.abspath(x) for x in roots], items=tree_items)
|
|
|
|
|
|
|
|
if not tree:
|
2024-01-11 07:11:48 +08:00
|
|
|
return res
|
2024-01-09 03:10:03 +08:00
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
file_template = "<li class='file-item'>{card}</li>"
|
2024-01-09 03:10:03 +08:00
|
|
|
dir_template = (
|
2024-01-11 07:11:48 +08:00
|
|
|
"<details {attributes} class='folder-item'>"
|
2024-01-12 04:06:57 +08:00
|
|
|
"<summary class='folder-item-summary' data-path='{data_path}' "
|
|
|
|
"onclick='extraNetworksFolderClick(event, \"{tabname}_extra_search\");'>"
|
2024-01-11 07:11:48 +08:00
|
|
|
"{folder_name}"
|
|
|
|
"</summary>"
|
|
|
|
"<ul class='folder-container'>{content}</ul>"
|
2024-01-09 03:10:03 +08:00
|
|
|
"</details>"
|
|
|
|
)
|
|
|
|
|
|
|
|
def _build_tree(data: Optional[dict[str, ExtraNetworksItem]] = None) -> str:
|
|
|
|
"""Recursively builds HTML for a tree."""
|
2024-01-11 07:11:48 +08:00
|
|
|
_res = ""
|
2024-01-09 03:10:03 +08:00
|
|
|
if not data:
|
2024-01-11 07:11:48 +08:00
|
|
|
return "<li style='list-style-type: \"⚠️\";'>DIRECTORY IS EMPTY</li>"
|
2024-01-09 03:10:03 +08:00
|
|
|
|
|
|
|
for k, v in sorted(data.items(), key=lambda x: shared.natural_sort_key(x[0])):
|
|
|
|
if isinstance(v, (ExtraNetworksItem,)):
|
2024-01-11 07:11:48 +08:00
|
|
|
item_html = self.create_item_html(tabname, v.item, self.card_page_minimal_template)
|
|
|
|
_res += file_template.format(**{"card": item_html})
|
2024-01-09 03:10:03 +08:00
|
|
|
else:
|
2024-01-12 04:06:57 +08:00
|
|
|
_res += dir_template.format(
|
2024-01-11 07:11:48 +08:00
|
|
|
**{
|
|
|
|
"attributes": "",
|
|
|
|
"tabname": tabname,
|
2024-01-12 04:06:57 +08:00
|
|
|
"folder_name": os.path.basename(k),
|
|
|
|
"data_path": k,
|
2024-01-11 07:11:48 +08:00
|
|
|
"content": _build_tree(v),
|
|
|
|
}
|
|
|
|
)
|
2024-01-09 03:10:03 +08:00
|
|
|
return _res
|
|
|
|
|
|
|
|
# Add each root directory to the tree.
|
|
|
|
for k, v in sorted(tree.items(), key=lambda x: shared.natural_sort_key(x[0])):
|
|
|
|
# If root is empty, append the "disabled" attribute to the template details tag.
|
2024-01-11 07:11:48 +08:00
|
|
|
res += "<ul class='folder-container'>"
|
|
|
|
res += dir_template.format(
|
|
|
|
**{
|
|
|
|
"attributes": "open" if v else "open",
|
|
|
|
"tabname": tabname,
|
2024-01-12 04:06:57 +08:00
|
|
|
"folder_name": os.path.basename(k),
|
|
|
|
"data_path": k,
|
2024-01-11 07:11:48 +08:00
|
|
|
"content": _build_tree(v),
|
|
|
|
}
|
|
|
|
)
|
|
|
|
res += "</ul>"
|
2024-01-09 03:10:03 +08:00
|
|
|
res += "</ul>"
|
|
|
|
return res
|
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
def create_card_view_html(self, tabname):
|
|
|
|
res = ""
|
2023-07-16 01:39:04 +08:00
|
|
|
self.items = {x["name"]: x for x in self.list_items()}
|
|
|
|
for item in self.items.values():
|
2024-01-11 07:11:48 +08:00
|
|
|
res += self.create_item_html(tabname, item, self.card_page_template)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
if res == "":
|
2023-01-21 13:36:07 +08:00
|
|
|
dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()])
|
2024-01-11 07:11:48 +08:00
|
|
|
res = shared.html("extra-networks-no-cards.html").format(dirs=dirs)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
2024-01-09 03:10:03 +08:00
|
|
|
def create_html(self, tabname):
|
2024-01-12 05:37:35 +08:00
|
|
|
self.lister.reset()
|
2024-01-11 07:11:48 +08:00
|
|
|
self.metadata = {}
|
|
|
|
self.items = {x["name"]: x for x in self.list_items()}
|
|
|
|
|
|
|
|
tree_view_html = self.create_tree_view_html(tabname)
|
|
|
|
card_view_html = self.create_card_view_html(tabname)
|
|
|
|
network_type_id = self.name.replace(" ", "_")
|
|
|
|
|
|
|
|
return self.extra_networks_pane_template.format(
|
|
|
|
**{
|
|
|
|
"tabname": tabname,
|
|
|
|
"network_type_id": network_type_id,
|
|
|
|
"tree_html": tree_view_html,
|
|
|
|
"items_html": card_view_html,
|
|
|
|
}
|
|
|
|
)
|
2024-01-09 03:10:03 +08:00
|
|
|
|
2023-07-16 13:38:23 +08:00
|
|
|
def create_item(self, name, index=None):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
def list_items(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def allowed_directories_for_previews(self):
|
|
|
|
return []
|
|
|
|
|
2023-06-02 12:08:45 +08:00
|
|
|
def get_sort_keys(self, path):
|
|
|
|
"""
|
|
|
|
List of default keys used for sorting in the UI.
|
|
|
|
"""
|
2023-06-03 04:12:24 +08:00
|
|
|
pth = Path(path)
|
2024-01-04 07:28:05 +08:00
|
|
|
mtime, ctime = self.lister.mctime(path)
|
2023-06-02 12:08:45 +08:00
|
|
|
return {
|
2024-01-04 07:28:05 +08:00
|
|
|
"date_created": int(mtime),
|
|
|
|
"date_modified": int(ctime),
|
2023-06-03 04:12:24 +08:00
|
|
|
"name": pth.name.lower(),
|
2023-11-14 00:01:52 +08:00
|
|
|
"path": str(pth.parent).lower(),
|
2023-06-02 12:08:45 +08:00
|
|
|
}
|
|
|
|
|
2023-03-11 20:27:42 +08:00
|
|
|
def find_preview(self, path):
|
2023-03-07 03:00:34 +08:00
|
|
|
"""
|
|
|
|
Find a preview PNG for a given path (without extension) and call link_preview on it.
|
|
|
|
"""
|
2023-03-11 20:33:24 +08:00
|
|
|
|
2023-09-30 15:29:10 +08:00
|
|
|
potential_files = sum([[path + "." + ext, path + ".preview." + ext] for ext in allowed_preview_extensions()], [])
|
2023-03-11 20:33:24 +08:00
|
|
|
|
|
|
|
for file in potential_files:
|
2024-01-04 07:28:05 +08:00
|
|
|
if self.lister.exists(file):
|
2023-03-07 03:00:34 +08:00
|
|
|
return self.link_preview(file)
|
2023-03-11 20:27:42 +08:00
|
|
|
|
2023-03-07 03:00:34 +08:00
|
|
|
return None
|
|
|
|
|
2023-03-11 20:27:42 +08:00
|
|
|
def find_description(self, path):
|
2023-03-07 03:14:06 +08:00
|
|
|
"""
|
|
|
|
Find and read a description file for a given path (without extension).
|
|
|
|
"""
|
|
|
|
for file in [f"{path}.txt", f"{path}.description.txt"]:
|
2024-01-04 07:28:05 +08:00
|
|
|
if not self.lister.exists(file):
|
|
|
|
continue
|
|
|
|
|
2023-03-07 03:14:06 +08:00
|
|
|
try:
|
|
|
|
with open(file, "r", encoding="utf-8", errors="replace") as f:
|
|
|
|
return f.read()
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
return None
|
|
|
|
|
2023-07-16 01:39:04 +08:00
|
|
|
def create_user_metadata_editor(self, ui, tabname):
|
|
|
|
return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self)
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2023-05-19 20:27:23 +08:00
|
|
|
def initialize():
|
2023-01-21 13:36:07 +08:00
|
|
|
extra_pages.clear()
|
|
|
|
|
|
|
|
|
2023-05-19 20:35:16 +08:00
|
|
|
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())
|
|
|
|
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
class ExtraNetworksUi:
|
|
|
|
def __init__(self):
|
|
|
|
self.pages = None
|
2023-05-08 16:33:45 +08:00
|
|
|
"""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"""
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
self.stored_extra_pages = None
|
|
|
|
|
|
|
|
self.button_save_preview = None
|
|
|
|
self.preview_target_filename = None
|
|
|
|
|
|
|
|
self.tabname = None
|
|
|
|
|
|
|
|
|
2023-01-22 16:00:05 +08:00
|
|
|
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])
|
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
def create_ui(interface: gr.Blocks, unrelated_tabs, tabname):
|
2023-08-10 02:40:18 +08:00
|
|
|
from modules.ui import switch_values_symbol
|
2023-08-09 23:11:13 +08:00
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
ui = ExtraNetworksUi()
|
|
|
|
ui.pages = []
|
2023-05-08 16:33:45 +08:00
|
|
|
ui.pages_contents = []
|
2023-07-16 01:39:04 +08:00
|
|
|
ui.user_metadata_editors = []
|
2023-01-22 16:04:02 +08:00
|
|
|
ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy())
|
2023-01-21 13:36:07 +08:00
|
|
|
ui.tabname = tabname
|
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
related_tabs = []
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
for page in ui.stored_extra_pages:
|
2023-11-06 00:19:55 +08:00
|
|
|
with gr.Tab(page.title, elem_id=f"{tabname}_{page.id_page}", elem_classes=["extra-page"]) as tab:
|
2023-11-26 19:58:47 +08:00
|
|
|
with gr.Column(elem_id=f"{tabname}_{page.id_page}_prompts", elem_classes=["extra-page-prompts"]):
|
|
|
|
pass
|
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
elem_id = f"{tabname}_{page.id_page}_cards_html"
|
|
|
|
page_elem = gr.HTML('Loading...', elem_id=elem_id)
|
|
|
|
ui.pages.append(page_elem)
|
2024-01-12 04:06:57 +08:00
|
|
|
page_elem.change(
|
|
|
|
fn=lambda: None,
|
|
|
|
_js=f"function(){{applyExtraNetworkFilter({tabname}_extra_search); return []}}",
|
|
|
|
inputs=[],
|
|
|
|
outputs=[],
|
|
|
|
)
|
2023-07-16 01:39:04 +08:00
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
editor = page.create_user_metadata_editor(ui, tabname)
|
|
|
|
editor.create_ui()
|
|
|
|
ui.user_metadata_editors.append(editor)
|
2023-01-21 22:20:24 +08:00
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
related_tabs.append(tab)
|
2023-05-16 01:33:44 +08:00
|
|
|
|
2024-01-12 04:06:57 +08:00
|
|
|
edit_search = gr.Textbox('', show_label=False, elem_id=f"{tabname}_extra_search", elem_classes="search", placeholder="Search...", visible=False, interactive=True)
|
2023-11-14 00:01:52 +08:00
|
|
|
dropdown_sort = gr.Dropdown(choices=['Path', 'Name', 'Date Created', 'Date Modified', ], value=shared.opts.extra_networks_card_order_field, elem_id=tabname+"_extra_sort", elem_classes="sort", multiselect=False, visible=False, show_label=False, interactive=True, label=tabname+"_extra_sort_order")
|
2023-11-05 15:12:50 +08:00
|
|
|
button_sortorder = ToolButton(switch_values_symbol, elem_id=tabname+"_extra_sortorder", elem_classes=["sortorder"] + ([] if shared.opts.extra_networks_card_order == "Ascending" else ["sortReverse"]), visible=False, tooltip="Invert sort order")
|
2023-07-16 16:38:59 +08:00
|
|
|
button_refresh = gr.Button('Refresh', elem_id=tabname+"_extra_refresh", visible=False)
|
2024-01-09 03:23:01 +08:00
|
|
|
|
2024-01-11 07:11:48 +08:00
|
|
|
tab_controls = [
|
|
|
|
edit_search,
|
|
|
|
dropdown_sort,
|
|
|
|
button_sortorder,
|
|
|
|
button_refresh,
|
|
|
|
]
|
2023-05-16 01:33:44 +08:00
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
ui.button_save_preview = gr.Button('Save preview', elem_id=tabname+"_save_preview", visible=False)
|
|
|
|
ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=tabname+"_preview_filename", visible=False)
|
2023-01-26 00:55:31 +08:00
|
|
|
|
2023-07-16 16:38:59 +08:00
|
|
|
for tab in unrelated_tabs:
|
2024-01-09 03:10:03 +08:00
|
|
|
tab.select(
|
|
|
|
fn=lambda: [gr.update(visible=False) for _ in tab_controls],
|
2024-01-12 04:06:57 +08:00
|
|
|
_js=f"function(){{ extraNetworksUnrelatedTabSelected('{tabname}'); }}",
|
2024-01-09 03:10:03 +08:00
|
|
|
inputs=[],
|
2024-01-11 07:11:48 +08:00
|
|
|
outputs=tab_controls,
|
2024-01-09 03:10:03 +08:00
|
|
|
show_progress=False,
|
|
|
|
)
|
|
|
|
|
2023-11-06 00:19:55 +08:00
|
|
|
for page, tab in zip(ui.stored_extra_pages, related_tabs):
|
|
|
|
allow_prompt = "true" if page.allow_prompt else "false"
|
|
|
|
allow_negative_prompt = "true" if page.allow_negative_prompt else "false"
|
|
|
|
|
2024-01-09 03:10:03 +08:00
|
|
|
jscode = (
|
|
|
|
"extraNetworksTabSelected("
|
2024-01-11 07:11:48 +08:00
|
|
|
f"'{tabname}', "
|
|
|
|
f"'{tabname}_{page.id_page}_prompts', "
|
|
|
|
f"'{allow_prompt}', "
|
|
|
|
f"'{allow_negative_prompt}'"
|
2024-01-09 03:10:03 +08:00
|
|
|
");"
|
|
|
|
)
|
|
|
|
|
|
|
|
tab.select(
|
2024-01-11 07:11:48 +08:00
|
|
|
fn=lambda: [gr.update(visible=True) for _ in tab_controls],
|
2024-01-09 03:10:03 +08:00
|
|
|
_js="function(){ " + jscode + " }",
|
|
|
|
inputs=[],
|
2024-01-11 07:11:48 +08:00
|
|
|
outputs=tab_controls,
|
2024-01-09 03:10:03 +08:00
|
|
|
show_progress=False,
|
|
|
|
)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2023-11-05 15:12:50 +08:00
|
|
|
dropdown_sort.change(fn=lambda: None, _js="function(){ applyExtraNetworkSort('" + tabname + "'); }")
|
|
|
|
|
2024-01-03 17:55:43 +08:00
|
|
|
def create_html():
|
|
|
|
ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages]
|
2024-01-09 03:10:03 +08:00
|
|
|
|
2023-07-16 16:52:29 +08:00
|
|
|
def pages_html():
|
|
|
|
if not ui.pages_contents:
|
2024-01-03 17:55:43 +08:00
|
|
|
create_html()
|
2023-07-16 16:52:29 +08:00
|
|
|
return ui.pages_contents
|
|
|
|
|
2023-01-23 09:01:24 +08:00
|
|
|
def refresh():
|
2023-01-21 13:36:07 +08:00
|
|
|
for pg in ui.stored_extra_pages:
|
|
|
|
pg.refresh()
|
2024-01-03 17:55:43 +08:00
|
|
|
create_html()
|
2023-05-08 16:33:45 +08:00
|
|
|
return ui.pages_contents
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2024-01-03 17:55:43 +08:00
|
|
|
interface.load(fn=pages_html, inputs=[], outputs=ui.pages)
|
2023-01-23 09:01:24 +08:00
|
|
|
button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
return ui
|
|
|
|
|
|
|
|
|
|
|
|
def path_is_parent(parent_path, child_path):
|
|
|
|
parent_path = os.path.abspath(parent_path)
|
|
|
|
child_path = os.path.abspath(child_path)
|
|
|
|
|
2023-01-29 03:52:27 +08:00
|
|
|
return child_path.startswith(parent_path)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
|
|
|
|
def setup_ui(ui, gallery):
|
2023-01-23 09:01:24 +08:00
|
|
|
def save_preview(index, images, filename):
|
2023-07-16 01:39:04 +08:00
|
|
|
# this function is here for backwards compatibility and likely will be removed soon
|
|
|
|
|
2023-01-21 13:36:07 +08:00
|
|
|
if len(images) == 0:
|
|
|
|
print("There is no image in gallery to save as a preview.")
|
2023-04-29 22:45:22 +08:00
|
|
|
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
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-26 03:59:50 +08:00
|
|
|
geninfo, items = read_info_from_image(image)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
is_allowed = False
|
|
|
|
for extra_page in ui.stored_extra_pages:
|
2023-05-10 16:05:02 +08:00
|
|
|
if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()):
|
2023-01-21 13:36:07 +08:00
|
|
|
is_allowed = True
|
|
|
|
break
|
|
|
|
|
|
|
|
assert is_allowed, f'writing to {filename} is not allowed'
|
|
|
|
|
2023-05-18 02:03:41 +08:00
|
|
|
save_image_with_geninfo(image, geninfo, filename)
|
2023-01-21 13:36:07 +08:00
|
|
|
|
2023-04-29 22:45:22 +08:00
|
|
|
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
|
2023-01-21 13:36:07 +08:00
|
|
|
|
|
|
|
ui.button_save_preview.click(
|
|
|
|
fn=save_preview,
|
2023-01-29 03:52:27 +08:00
|
|
|
_js="function(x, y, z){return [selected_gallery_index(), y, z]}",
|
2023-01-23 09:01:24 +08:00
|
|
|
inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename],
|
2023-01-21 13:36:07 +08:00
|
|
|
outputs=[*ui.pages]
|
|
|
|
)
|
2023-01-29 03:52:27 +08:00
|
|
|
|
2023-07-16 01:39:04 +08:00
|
|
|
for editor in ui.user_metadata_editors:
|
|
|
|
editor.setup_ui(gallery)
|