2023-01-29 08:34:58 +00:00
|
|
|
import glob
|
2023-01-21 05:36:07 +00:00
|
|
|
import os.path
|
2023-01-28 19:52:27 +00:00
|
|
|
import urllib.parse
|
|
|
|
from pathlib import Path
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
from modules import shared
|
|
|
|
import gradio as gr
|
|
|
|
import json
|
2023-01-23 20:11:34 +00:00
|
|
|
import html
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
from modules.generation_parameters_copypaste import image_from_url_text
|
|
|
|
|
|
|
|
extra_pages = []
|
2023-01-28 19:52:27 +00:00
|
|
|
allowed_dirs = set()
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
def register_page(page):
|
2023-01-21 13:15:53 +00:00
|
|
|
"""registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions"""
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
extra_pages.append(page)
|
2023-01-28 19:52:27 +00:00
|
|
|
allowed_dirs.clear()
|
|
|
|
allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], [])))
|
|
|
|
|
|
|
|
|
|
|
|
def add_pages_to_demo(app):
|
|
|
|
def fetch_file(filename: str = ""):
|
|
|
|
from starlette.responses import FileResponse
|
|
|
|
|
2023-02-04 17:10:00 +00:00
|
|
|
if not any([Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs]):
|
2023-01-28 19:52:27 +00:00
|
|
|
raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.")
|
|
|
|
|
2023-02-01 20:58:09 +00:00
|
|
|
ext = os.path.splitext(filename)[1].lower()
|
|
|
|
if ext not in (".png", ".jpg"):
|
|
|
|
raise ValueError(f"File cannot be fetched: {filename}. Only png and jpg.")
|
2023-01-28 19:52:27 +00:00
|
|
|
|
|
|
|
# would profit from returning 304
|
|
|
|
return FileResponse(filename, headers={"Accept-Ranges": "bytes"})
|
|
|
|
|
|
|
|
app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"])
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ExtraNetworksPage:
|
|
|
|
def __init__(self, title):
|
|
|
|
self.title = title
|
2023-01-21 14:20:24 +00:00
|
|
|
self.name = title.lower()
|
2023-01-21 05:36:07 +00:00
|
|
|
self.card_page = shared.html("extra-networks-card.html")
|
|
|
|
self.allow_negative_prompt = False
|
|
|
|
|
|
|
|
def refresh(self):
|
|
|
|
pass
|
|
|
|
|
2023-01-28 19:52:27 +00:00
|
|
|
def link_preview(self, filename):
|
|
|
|
return "./sd_extra_networks/thumb?filename=" + urllib.parse.quote(filename.replace('\\', '/')) + "&mtime=" + str(os.path.getmtime(filename))
|
|
|
|
|
2023-01-29 07:20:19 +00: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()):
|
|
|
|
parentdir = os.path.abspath(parentdir)
|
|
|
|
if abspath.startswith(parentdir):
|
2023-01-29 08:34:58 +00:00
|
|
|
return abspath[len(parentdir):].replace('\\', '/')
|
2023-01-29 07:20:19 +00:00
|
|
|
|
|
|
|
return ""
|
|
|
|
|
2023-01-23 01:01:24 +00:00
|
|
|
def create_html(self, tabname):
|
|
|
|
view = shared.opts.extra_networks_default_view
|
2023-01-21 05:36:07 +00:00
|
|
|
items_html = ''
|
|
|
|
|
2023-01-29 08:34:58 +00:00
|
|
|
subdirs = {}
|
|
|
|
for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]:
|
|
|
|
for x in glob.glob(os.path.join(parentdir, '**/*'), recursive=True):
|
|
|
|
if not os.path.isdir(x):
|
|
|
|
continue
|
|
|
|
|
|
|
|
subdir = os.path.abspath(x)[len(parentdir):].replace("\\", "/")
|
|
|
|
while subdir.startswith("/"):
|
|
|
|
subdir = subdir[1:]
|
|
|
|
|
2023-02-19 09:09:25 +00:00
|
|
|
is_empty = len(os.listdir(x)) == 0
|
|
|
|
if not is_empty and not subdir.endswith("/"):
|
|
|
|
subdir = subdir + "/"
|
|
|
|
|
2023-01-29 08:34:58 +00:00
|
|
|
subdirs[subdir] = 1
|
|
|
|
|
|
|
|
if subdirs:
|
|
|
|
subdirs = {"": 1, **subdirs}
|
|
|
|
|
|
|
|
subdirs_html = "".join([f"""
|
|
|
|
<button class='gr-button gr-button-lg gr-button-secondary{" search-all" if subdir=="" else ""}' onclick='extraNetworksSearchButton("{tabname}_extra_tabs", event)'>
|
|
|
|
{html.escape(subdir if subdir!="" else "all")}
|
|
|
|
</button>
|
|
|
|
""" for subdir in subdirs])
|
|
|
|
|
2023-01-21 05:36:07 +00:00
|
|
|
for item in self.list_items():
|
|
|
|
items_html += self.create_html_for_item(item, tabname)
|
|
|
|
|
|
|
|
if items_html == '':
|
|
|
|
dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()])
|
|
|
|
items_html = shared.html("extra-networks-no-cards.html").format(dirs=dirs)
|
|
|
|
|
2023-02-05 21:42:45 +00:00
|
|
|
self_name_id = self.name.replace(" ", "_")
|
|
|
|
|
2023-01-21 14:20:24 +00:00
|
|
|
res = f"""
|
2023-02-05 21:42:45 +00:00
|
|
|
<div id='{tabname}_{self_name_id}_subdirs' class='extra-network-subdirs extra-network-subdirs-{view}'>
|
2023-01-29 08:34:58 +00:00
|
|
|
{subdirs_html}
|
|
|
|
</div>
|
2023-02-05 21:42:45 +00:00
|
|
|
<div id='{tabname}_{self_name_id}_cards' class='extra-network-{view}'>
|
2023-01-21 14:20:24 +00:00
|
|
|
{items_html}
|
|
|
|
</div>
|
|
|
|
"""
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
|
|
|
def list_items(self):
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
def allowed_directories_for_previews(self):
|
|
|
|
return []
|
|
|
|
|
|
|
|
def create_html_for_item(self, item, tabname):
|
|
|
|
preview = item.get("preview", None)
|
|
|
|
|
2023-01-28 19:52:27 +00:00
|
|
|
onclick = item.get("onclick", None)
|
|
|
|
if onclick is None:
|
|
|
|
onclick = '"' + html.escape(f"""return cardClicked({json.dumps(tabname)}, {item["prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
|
|
|
|
|
2023-01-21 05:36:07 +00:00
|
|
|
args = {
|
2023-01-23 20:11:34 +00:00
|
|
|
"preview_html": "style='background-image: url(\"" + html.escape(preview) + "\")'" if preview else '',
|
2023-01-28 19:52:27 +00:00
|
|
|
"prompt": item.get("prompt", None),
|
2023-01-21 05:36:07 +00:00
|
|
|
"tabname": json.dumps(tabname),
|
|
|
|
"local_preview": json.dumps(item["local_preview"]),
|
|
|
|
"name": item["name"],
|
2023-03-06 19:14:06 +00:00
|
|
|
"description": (item.get("description") or ""),
|
2023-01-28 19:52:27 +00:00
|
|
|
"card_clicked": onclick,
|
2023-01-23 20:11:34 +00:00
|
|
|
"save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {json.dumps(tabname)}, {json.dumps(item["local_preview"])})""") + '"',
|
2023-01-29 07:20:19 +00:00
|
|
|
"search_term": item.get("search_term", ""),
|
2023-01-21 05:36:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return self.card_page.format(**args)
|
|
|
|
|
2023-03-11 12:27:42 +00:00
|
|
|
def find_preview(self, path):
|
2023-03-06 19:00:34 +00:00
|
|
|
"""
|
|
|
|
Find a preview PNG for a given path (without extension) and call link_preview on it.
|
|
|
|
"""
|
|
|
|
for file in [path + ".png", path + ".preview.png"]:
|
|
|
|
if os.path.isfile(file):
|
|
|
|
return self.link_preview(file)
|
2023-03-11 12:27:42 +00:00
|
|
|
|
2023-03-06 19:00:34 +00:00
|
|
|
return None
|
|
|
|
|
2023-03-11 12:27:42 +00:00
|
|
|
def find_description(self, path):
|
2023-03-06 19:14:06 +00:00
|
|
|
"""
|
|
|
|
Find and read a description file for a given path (without extension).
|
|
|
|
"""
|
|
|
|
for file in [f"{path}.txt", f"{path}.description.txt"]:
|
|
|
|
try:
|
|
|
|
with open(file, "r", encoding="utf-8", errors="replace") as f:
|
|
|
|
return f.read()
|
|
|
|
except OSError:
|
|
|
|
pass
|
|
|
|
return None
|
|
|
|
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
def intialize():
|
|
|
|
extra_pages.clear()
|
|
|
|
|
|
|
|
|
|
|
|
class ExtraNetworksUi:
|
|
|
|
def __init__(self):
|
|
|
|
self.pages = None
|
|
|
|
self.stored_extra_pages = None
|
|
|
|
|
|
|
|
self.button_save_preview = None
|
|
|
|
self.preview_target_filename = None
|
|
|
|
|
|
|
|
self.tabname = None
|
|
|
|
|
|
|
|
|
2023-01-22 08:00:05 +00: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-01-21 05:36:07 +00:00
|
|
|
def create_ui(container, button, tabname):
|
|
|
|
ui = ExtraNetworksUi()
|
|
|
|
ui.pages = []
|
2023-01-22 08:04:02 +00:00
|
|
|
ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy())
|
2023-01-21 05:36:07 +00:00
|
|
|
ui.tabname = tabname
|
|
|
|
|
|
|
|
with gr.Tabs(elem_id=tabname+"_extra_tabs") as tabs:
|
2023-01-22 08:04:02 +00:00
|
|
|
for page in ui.stored_extra_pages:
|
2023-01-21 05:36:07 +00:00
|
|
|
with gr.Tab(page.title):
|
|
|
|
page_elem = gr.HTML(page.create_html(ui.tabname))
|
|
|
|
ui.pages.append(page_elem)
|
|
|
|
|
2023-01-21 14:20:24 +00:00
|
|
|
filter = gr.Textbox('', show_label=False, elem_id=tabname+"_extra_search", placeholder="Search...", visible=False)
|
|
|
|
button_refresh = gr.Button('Refresh', elem_id=tabname+"_extra_refresh")
|
|
|
|
button_close = gr.Button('Close', elem_id=tabname+"_extra_close")
|
|
|
|
|
2023-01-21 05:36:07 +00: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-25 16:55:31 +00:00
|
|
|
def toggle_visibility(is_visible):
|
|
|
|
is_visible = not is_visible
|
|
|
|
return is_visible, gr.update(visible=is_visible)
|
|
|
|
|
|
|
|
state_visible = gr.State(value=False)
|
|
|
|
button.click(fn=toggle_visibility, inputs=[state_visible], outputs=[state_visible, container])
|
|
|
|
button_close.click(fn=toggle_visibility, inputs=[state_visible], outputs=[state_visible, container])
|
2023-01-21 05:36:07 +00:00
|
|
|
|
2023-01-23 01:01:24 +00:00
|
|
|
def refresh():
|
2023-01-21 05:36:07 +00:00
|
|
|
res = []
|
|
|
|
|
|
|
|
for pg in ui.stored_extra_pages:
|
|
|
|
pg.refresh()
|
2023-01-23 01:01:24 +00:00
|
|
|
res.append(pg.create_html(ui.tabname))
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
return res
|
|
|
|
|
2023-01-23 01:01:24 +00:00
|
|
|
button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages)
|
2023-01-21 05:36:07 +00: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-28 19:52:27 +00:00
|
|
|
return child_path.startswith(parent_path)
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
def setup_ui(ui, gallery):
|
2023-01-23 01:01:24 +00:00
|
|
|
def save_preview(index, images, filename):
|
2023-01-21 05:36:07 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
is_allowed = False
|
|
|
|
for extra_page in ui.stored_extra_pages:
|
|
|
|
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'
|
|
|
|
|
|
|
|
image.save(filename)
|
|
|
|
|
2023-01-23 01:01:24 +00:00
|
|
|
return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
|
2023-01-21 05:36:07 +00:00
|
|
|
|
|
|
|
ui.button_save_preview.click(
|
|
|
|
fn=save_preview,
|
2023-01-28 19:52:27 +00:00
|
|
|
_js="function(x, y, z){return [selected_gallery_index(), y, z]}",
|
2023-01-23 01:01:24 +00:00
|
|
|
inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename],
|
2023-01-21 05:36:07 +00:00
|
|
|
outputs=[*ui.pages]
|
|
|
|
)
|
2023-01-28 19:52:27 +00:00
|
|
|
|