ui_extra_networks.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. import os.path
  2. import urllib.parse
  3. from pathlib import Path
  4. from modules import shared, ui_extra_networks_user_metadata, errors
  5. from modules.images import read_info_from_image, save_image_with_geninfo
  6. from modules.ui import up_down_symbol
  7. import gradio as gr
  8. import json
  9. import html
  10. from fastapi.exceptions import HTTPException
  11. from modules.generation_parameters_copypaste import image_from_url_text
  12. from modules.ui_components import ToolButton
  13. extra_pages = []
  14. allowed_dirs = set()
  15. def register_page(page):
  16. """registers extra networks page for the UI; recommend doing it in on_before_ui() callback for extensions"""
  17. extra_pages.append(page)
  18. allowed_dirs.clear()
  19. allowed_dirs.update(set(sum([x.allowed_directories_for_previews() for x in extra_pages], [])))
  20. def fetch_file(filename: str = ""):
  21. from starlette.responses import FileResponse
  22. if not os.path.isfile(filename):
  23. raise HTTPException(status_code=404, detail="File not found")
  24. if not any(Path(x).absolute() in Path(filename).absolute().parents for x in allowed_dirs):
  25. raise ValueError(f"File cannot be fetched: {filename}. Must be in one of directories registered by extra pages.")
  26. ext = os.path.splitext(filename)[1].lower()
  27. if ext not in (".png", ".jpg", ".jpeg", ".webp", ".gif"):
  28. raise ValueError(f"File cannot be fetched: {filename}. Only png, jpg, webp, and gif.")
  29. # would profit from returning 304
  30. return FileResponse(filename, headers={"Accept-Ranges": "bytes"})
  31. def get_metadata(page: str = "", item: str = ""):
  32. from starlette.responses import JSONResponse
  33. page = next(iter([x for x in extra_pages if x.name == page]), None)
  34. if page is None:
  35. return JSONResponse({})
  36. metadata = page.metadata.get(item)
  37. if metadata is None:
  38. return JSONResponse({})
  39. return JSONResponse({"metadata": json.dumps(metadata, indent=4, ensure_ascii=False)})
  40. def get_single_card(page: str = "", tabname: str = "", name: str = ""):
  41. from starlette.responses import JSONResponse
  42. page = next(iter([x for x in extra_pages if x.name == page]), None)
  43. try:
  44. item = page.create_item(name, enable_filter=False)
  45. page.items[name] = item
  46. except Exception as e:
  47. errors.display(e, "creating item for extra network")
  48. item = page.items.get(name)
  49. page.read_user_metadata(item)
  50. item_html = page.create_html_for_item(item, tabname)
  51. return JSONResponse({"html": item_html})
  52. def add_pages_to_demo(app):
  53. app.add_api_route("/sd_extra_networks/thumb", fetch_file, methods=["GET"])
  54. app.add_api_route("/sd_extra_networks/metadata", get_metadata, methods=["GET"])
  55. app.add_api_route("/sd_extra_networks/get-single-card", get_single_card, methods=["GET"])
  56. def quote_js(s):
  57. s = s.replace('\\', '\\\\')
  58. s = s.replace('"', '\\"')
  59. return f'"{s}"'
  60. class ExtraNetworksPage:
  61. def __init__(self, title):
  62. self.title = title
  63. self.name = title.lower()
  64. self.id_page = self.name.replace(" ", "_")
  65. self.card_page = shared.html("extra-networks-card.html")
  66. self.allow_negative_prompt = False
  67. self.metadata = {}
  68. self.items = {}
  69. def refresh(self):
  70. pass
  71. def read_user_metadata(self, item):
  72. filename = item.get("filename", None)
  73. basename, ext = os.path.splitext(filename)
  74. metadata_filename = basename + '.json'
  75. metadata = {}
  76. try:
  77. if os.path.isfile(metadata_filename):
  78. with open(metadata_filename, "r", encoding="utf8") as file:
  79. metadata = json.load(file)
  80. except Exception as e:
  81. errors.display(e, f"reading extra network user metadata from {metadata_filename}")
  82. desc = metadata.get("description", None)
  83. if desc is not None:
  84. item["description"] = desc
  85. item["user_metadata"] = metadata
  86. def link_preview(self, filename):
  87. quoted_filename = urllib.parse.quote(filename.replace('\\', '/'))
  88. mtime = os.path.getmtime(filename)
  89. return f"./sd_extra_networks/thumb?filename={quoted_filename}&mtime={mtime}"
  90. def search_terms_from_path(self, filename, possible_directories=None):
  91. abspath = os.path.abspath(filename)
  92. for parentdir in (possible_directories if possible_directories is not None else self.allowed_directories_for_previews()):
  93. parentdir = os.path.abspath(parentdir)
  94. if abspath.startswith(parentdir):
  95. return abspath[len(parentdir):].replace('\\', '/')
  96. return ""
  97. def create_html(self, tabname):
  98. items_html = ''
  99. self.metadata = {}
  100. subdirs = {}
  101. for parentdir in [os.path.abspath(x) for x in self.allowed_directories_for_previews()]:
  102. for root, dirs, _ in sorted(os.walk(parentdir, followlinks=True), key=lambda x: shared.natural_sort_key(x[0])):
  103. for dirname in sorted(dirs, key=shared.natural_sort_key):
  104. x = os.path.join(root, dirname)
  105. if not os.path.isdir(x):
  106. continue
  107. subdir = os.path.abspath(x)[len(parentdir):].replace("\\", "/")
  108. while subdir.startswith("/"):
  109. subdir = subdir[1:]
  110. is_empty = len(os.listdir(x)) == 0
  111. if not is_empty and not subdir.endswith("/"):
  112. subdir = subdir + "/"
  113. if ("/." in subdir or subdir.startswith(".")) and not shared.opts.extra_networks_show_hidden_directories:
  114. continue
  115. subdirs[subdir] = 1
  116. if subdirs:
  117. subdirs = {"": 1, **subdirs}
  118. subdirs_html = "".join([f"""
  119. <button class='lg secondary gradio-button custom-button{" search-all" if subdir=="" else ""}' onclick='extraNetworksSearchButton("{tabname}_extra_tabs", event)'>
  120. {html.escape(subdir if subdir!="" else "all")}
  121. </button>
  122. """ for subdir in subdirs])
  123. self.items = {x["name"]: x for x in self.list_items()}
  124. for item in self.items.values():
  125. metadata = item.get("metadata")
  126. if metadata:
  127. self.metadata[item["name"]] = metadata
  128. if "user_metadata" not in item:
  129. self.read_user_metadata(item)
  130. items_html += self.create_html_for_item(item, tabname)
  131. if items_html == '':
  132. dirs = "".join([f"<li>{x}</li>" for x in self.allowed_directories_for_previews()])
  133. items_html = shared.html("extra-networks-no-cards.html").format(dirs=dirs)
  134. self_name_id = self.name.replace(" ", "_")
  135. res = f"""
  136. <div id='{tabname}_{self_name_id}_subdirs' class='extra-network-subdirs extra-network-subdirs-cards'>
  137. {subdirs_html}
  138. </div>
  139. <div id='{tabname}_{self_name_id}_cards' class='extra-network-cards'>
  140. {items_html}
  141. </div>
  142. """
  143. return res
  144. def create_item(self, name, index=None):
  145. raise NotImplementedError()
  146. def list_items(self):
  147. raise NotImplementedError()
  148. def allowed_directories_for_previews(self):
  149. return []
  150. def create_html_for_item(self, item, tabname):
  151. """
  152. Create HTML for card item in tab tabname; can return empty string if the item is not meant to be shown.
  153. """
  154. preview = item.get("preview", None)
  155. onclick = item.get("onclick", None)
  156. if onclick is None:
  157. onclick = '"' + html.escape(f"""return cardClicked({quote_js(tabname)}, {item["prompt"]}, {"true" if self.allow_negative_prompt else "false"})""") + '"'
  158. height = f"height: {shared.opts.extra_networks_card_height}px;" if shared.opts.extra_networks_card_height else ''
  159. width = f"width: {shared.opts.extra_networks_card_width}px;" if shared.opts.extra_networks_card_width else ''
  160. background_image = f'<img src="{html.escape(preview)}" class="preview" loading="lazy">' if preview else ''
  161. metadata_button = ""
  162. metadata = item.get("metadata")
  163. if metadata:
  164. metadata_button = f"<div class='metadata-button card-button' title='Show internal metadata' onclick='extraNetworksRequestMetadata(event, {quote_js(self.name)}, {quote_js(item['name'])})'></div>"
  165. 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(item['name'])})'></div>"
  166. local_path = ""
  167. filename = item.get("filename", "")
  168. for reldir in self.allowed_directories_for_previews():
  169. absdir = os.path.abspath(reldir)
  170. if filename.startswith(absdir):
  171. local_path = filename[len(absdir):]
  172. # if this is true, the item must not be shown in the default view, and must instead only be
  173. # shown when searching for it
  174. if shared.opts.extra_networks_hidden_models == "Always":
  175. search_only = False
  176. else:
  177. search_only = "/." in local_path or "\\." in local_path
  178. if search_only and shared.opts.extra_networks_hidden_models == "Never":
  179. return ""
  180. sort_keys = " ".join([html.escape(f'data-sort-{k}={v}') for k, v in item.get("sort_keys", {}).items()]).strip()
  181. args = {
  182. "background_image": background_image,
  183. "style": f"'display: none; {height}{width}; font-size: {shared.opts.extra_networks_card_text_scale*100}%'",
  184. "prompt": item.get("prompt", None),
  185. "tabname": quote_js(tabname),
  186. "local_preview": quote_js(item["local_preview"]),
  187. "name": html.escape(item["name"]),
  188. "description": (item.get("description") or "" if shared.opts.extra_networks_card_show_desc else ""),
  189. "card_clicked": onclick,
  190. "save_card_preview": '"' + html.escape(f"""return saveCardPreview(event, {quote_js(tabname)}, {quote_js(item["local_preview"])})""") + '"',
  191. "search_term": item.get("search_term", ""),
  192. "metadata_button": metadata_button,
  193. "edit_button": edit_button,
  194. "search_only": " search_only" if search_only else "",
  195. "sort_keys": sort_keys,
  196. }
  197. return self.card_page.format(**args)
  198. def get_sort_keys(self, path):
  199. """
  200. List of default keys used for sorting in the UI.
  201. """
  202. pth = Path(path)
  203. stat = pth.stat()
  204. return {
  205. "date_created": int(stat.st_ctime or 0),
  206. "date_modified": int(stat.st_mtime or 0),
  207. "name": pth.name.lower(),
  208. }
  209. def find_preview(self, path):
  210. """
  211. Find a preview PNG for a given path (without extension) and call link_preview on it.
  212. """
  213. preview_extensions = ["png", "jpg", "jpeg", "webp"]
  214. if shared.opts.samples_format not in preview_extensions:
  215. preview_extensions.append(shared.opts.samples_format)
  216. potential_files = sum([[path + "." + ext, path + ".preview." + ext] for ext in preview_extensions], [])
  217. for file in potential_files:
  218. if os.path.isfile(file):
  219. return self.link_preview(file)
  220. return None
  221. def find_description(self, path):
  222. """
  223. Find and read a description file for a given path (without extension).
  224. """
  225. for file in [f"{path}.txt", f"{path}.description.txt"]:
  226. try:
  227. with open(file, "r", encoding="utf-8", errors="replace") as f:
  228. return f.read()
  229. except OSError:
  230. pass
  231. return None
  232. def create_user_metadata_editor(self, ui, tabname):
  233. return ui_extra_networks_user_metadata.UserMetadataEditor(ui, tabname, self)
  234. def initialize():
  235. extra_pages.clear()
  236. def register_default_pages():
  237. from modules.ui_extra_networks_textual_inversion import ExtraNetworksPageTextualInversion
  238. from modules.ui_extra_networks_hypernets import ExtraNetworksPageHypernetworks
  239. from modules.ui_extra_networks_checkpoints import ExtraNetworksPageCheckpoints
  240. register_page(ExtraNetworksPageTextualInversion())
  241. register_page(ExtraNetworksPageHypernetworks())
  242. register_page(ExtraNetworksPageCheckpoints())
  243. class ExtraNetworksUi:
  244. def __init__(self):
  245. self.pages = None
  246. """gradio HTML components related to extra networks' pages"""
  247. self.page_contents = None
  248. """HTML content of the above; empty initially, filled when extra pages have to be shown"""
  249. self.stored_extra_pages = None
  250. self.button_save_preview = None
  251. self.preview_target_filename = None
  252. self.tabname = None
  253. def pages_in_preferred_order(pages):
  254. tab_order = [x.lower().strip() for x in shared.opts.ui_extra_networks_tab_reorder.split(",")]
  255. def tab_name_score(name):
  256. name = name.lower()
  257. for i, possible_match in enumerate(tab_order):
  258. if possible_match in name:
  259. return i
  260. return len(pages)
  261. tab_scores = {page.name: (tab_name_score(page.name), original_index) for original_index, page in enumerate(pages)}
  262. return sorted(pages, key=lambda x: tab_scores[x.name])
  263. def create_ui(container, button, tabname):
  264. ui = ExtraNetworksUi()
  265. ui.pages = []
  266. ui.pages_contents = []
  267. ui.user_metadata_editors = []
  268. ui.stored_extra_pages = pages_in_preferred_order(extra_pages.copy())
  269. ui.tabname = tabname
  270. with gr.Tabs(elem_id=tabname+"_extra_tabs"):
  271. for page in ui.stored_extra_pages:
  272. with gr.Tab(page.title, id=page.id_page):
  273. elem_id = f"{tabname}_{page.id_page}_cards_html"
  274. page_elem = gr.HTML('Loading...', elem_id=elem_id)
  275. ui.pages.append(page_elem)
  276. page_elem.change(fn=lambda: None, _js='function(){applyExtraNetworkFilter(' + quote_js(tabname) + '); return []}', inputs=[], outputs=[])
  277. editor = page.create_user_metadata_editor(ui, tabname)
  278. editor.create_ui()
  279. ui.user_metadata_editors.append(editor)
  280. gr.Textbox('', show_label=False, elem_id=tabname+"_extra_search", placeholder="Search...", visible=False)
  281. gr.Dropdown(choices=['Default Sort', 'Date Created', 'Date Modified', 'Name'], value='Default Sort', elem_id=tabname+"_extra_sort", multiselect=False, visible=False, show_label=False, interactive=True)
  282. ToolButton(up_down_symbol, elem_id=tabname+"_extra_sortorder")
  283. button_refresh = gr.Button('Refresh', elem_id=tabname+"_extra_refresh")
  284. ui.button_save_preview = gr.Button('Save preview', elem_id=tabname+"_save_preview", visible=False)
  285. ui.preview_target_filename = gr.Textbox('Preview save filename', elem_id=tabname+"_preview_filename", visible=False)
  286. def toggle_visibility(is_visible):
  287. is_visible = not is_visible
  288. return is_visible, gr.update(visible=is_visible), gr.update(variant=("secondary-down" if is_visible else "secondary"))
  289. def fill_tabs(is_empty):
  290. """Creates HTML for extra networks' tabs when the extra networks button is clicked for the first time."""
  291. if not ui.pages_contents:
  292. refresh()
  293. if is_empty:
  294. return True, *ui.pages_contents
  295. return True, *[gr.update() for _ in ui.pages_contents]
  296. state_visible = gr.State(value=False)
  297. button.click(fn=toggle_visibility, inputs=[state_visible], outputs=[state_visible, container, button], show_progress=False)
  298. state_empty = gr.State(value=True)
  299. button.click(fn=fill_tabs, inputs=[state_empty], outputs=[state_empty, *ui.pages], show_progress=False)
  300. def refresh():
  301. for pg in ui.stored_extra_pages:
  302. pg.refresh()
  303. ui.pages_contents = [pg.create_html(ui.tabname) for pg in ui.stored_extra_pages]
  304. return ui.pages_contents
  305. button_refresh.click(fn=refresh, inputs=[], outputs=ui.pages)
  306. return ui
  307. def path_is_parent(parent_path, child_path):
  308. parent_path = os.path.abspath(parent_path)
  309. child_path = os.path.abspath(child_path)
  310. return child_path.startswith(parent_path)
  311. def setup_ui(ui, gallery):
  312. def save_preview(index, images, filename):
  313. # this function is here for backwards compatibility and likely will be removed soon
  314. if len(images) == 0:
  315. print("There is no image in gallery to save as a preview.")
  316. return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
  317. index = int(index)
  318. index = 0 if index < 0 else index
  319. index = len(images) - 1 if index >= len(images) else index
  320. img_info = images[index if index >= 0 else 0]
  321. image = image_from_url_text(img_info)
  322. geninfo, items = read_info_from_image(image)
  323. is_allowed = False
  324. for extra_page in ui.stored_extra_pages:
  325. if any(path_is_parent(x, filename) for x in extra_page.allowed_directories_for_previews()):
  326. is_allowed = True
  327. break
  328. assert is_allowed, f'writing to {filename} is not allowed'
  329. save_image_with_geninfo(image, geninfo, filename)
  330. return [page.create_html(ui.tabname) for page in ui.stored_extra_pages]
  331. ui.button_save_preview.click(
  332. fn=save_preview,
  333. _js="function(x, y, z){return [selected_gallery_index(), y, z]}",
  334. inputs=[ui.preview_target_filename, gallery, ui.preview_target_filename],
  335. outputs=[*ui.pages]
  336. )
  337. for editor in ui.user_metadata_editors:
  338. editor.setup_ui(gallery)