From a68a846f6f09a7a40287d78ce8166dd7018ec682 Mon Sep 17 00:00:00 2001 From: i-h4x <130828882+i-h4x@users.noreply.github.com> Date: Sat, 15 Apr 2023 09:55:39 +0100 Subject: [PATCH] add load and save workflows --- folder_paths.py | 5 ++ server.py | 35 +++++++++ web/scripts/api.js | 32 +++++++- web/scripts/ui.js | 83 ++++----------------- web/scripts/ui/comfySplitButton.js | 27 +++++++ web/scripts/ui/comfyWorkflows.js | 115 +++++++++++++++++++++++++++++ web/scripts/ui/helpers.js | 38 ++++++++++ web/style.css | 63 ++++++++++++++-- workflows/default.json | 1 + 9 files changed, 324 insertions(+), 75 deletions(-) create mode 100644 web/scripts/ui/comfySplitButton.js create mode 100644 web/scripts/ui/comfyWorkflows.js create mode 100644 web/scripts/ui/helpers.js create mode 100644 workflows/default.json diff --git a/folder_paths.py b/folder_paths.py index ab3359347..f4ee26bac 100644 --- a/folder_paths.py +++ b/folder_paths.py @@ -31,6 +31,7 @@ folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_m output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output") temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp") input_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input") +workflows_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "workflows") if not os.path.exists(input_directory): os.makedirs(input_directory) @@ -51,6 +52,10 @@ def get_input_directory(): global input_directory return input_directory +def get_workflows_directory(): + global workflows_directory + return workflows_directory + #NOTE: used in http server so don't put folders that should not be accessed remotely def get_directory_by_type(type_name): diff --git a/server.py b/server.py index b5403670f..a49887b6e 100644 --- a/server.py +++ b/server.py @@ -264,6 +264,41 @@ class PromptServer(): self.prompt_queue.delete_history_item(id_to_delete) return web.Response(status=200) + + @routes.get("/workflows") + async def get_workflows(request): + dir = folder_paths.get_workflows_directory() + files = glob.glob('**/*.json', root_dir=dir, recursive=True) + return web.json_response(list(map(lambda f: os.path.splitext(f)[0].replace("\\", "/"), files))) + + @routes.get("/workflows/{name:.+}") + async def get_workflow(request): + dir = folder_paths.get_workflows_directory() + file = os.path.abspath(os.path.join(dir, request.match_info["name"] + ".json")) + if os.path.commonpath([file, dir]) != dir: + return web.Response(status=403) + + return web.FileResponse(file) + + @routes.post("/workflows") + async def save_workflow(request): + json_data = await request.json() + dir = folder_paths.get_workflows_directory() + file = os.path.abspath(os.path.join(dir, json_data["name"] + ".json")) + if os.path.commonpath([file, dir]) != dir: + return web.Response(status=403) + + if os.path.exists(file) and ("overwrite" not in json_data or json_data["overwrite"] == False): + return web.Response(status=409) + + sub_path = os.path.dirname(file) + if not os.path.exists(sub_path): + os.makedirs(sub_path) + + with open(file, "w") as f: + f.write(json.dumps(json_data["workflow"])) + + return web.Response(status=201) def add_routes(self): self.app.add_routes(self.routes) diff --git a/web/scripts/api.js b/web/scripts/api.js index 2b90c2abc..821163c4a 100644 --- a/web/scripts/api.js +++ b/web/scripts/api.js @@ -223,7 +223,7 @@ class ComfyApi extends EventTarget { */ async #postItem(type, body) { try { - await fetch("/" + type, { + return await fetch("/" + type, { method: "POST", headers: { "Content-Type": "application/json", @@ -258,6 +258,36 @@ class ComfyApi extends EventTarget { async interrupt() { await this.#postItem("interrupt", null); } + + /** + * Gets a list of saved workflows + */ + async get_workflows() { + const response = await fetch("/workflows", { cache: "no-store" }); + return await response.json(); + } + + /** + * Gets a saved workflow + */ + async get_workflow(name) { + const response = await fetch(`/workflows/${encodeURIComponent(name)}`, { cache: "no-store" }); + return await response.json(); + } + + /** + * Gets a saved workflow + */ + async save_workflow(name, workflow, overwrite) { + const response = await this.#postItem("workflows", { name, workflow, overwrite }); + if (response.status === 201) { + return true; + } + if (response.status === 409) { + return false; + } + throw new Error(response.statusText); + } } export const api = new ComfyApi(); diff --git a/web/scripts/ui.js b/web/scripts/ui.js index 09861c440..a82264e39 100644 --- a/web/scripts/ui.js +++ b/web/scripts/ui.js @@ -1,43 +1,7 @@ import { api } from "./api.js"; - -export function $el(tag, propsOrChildren, children) { - const split = tag.split("."); - const element = document.createElement(split.shift()); - element.classList.add(...split); - if (propsOrChildren) { - if (Array.isArray(propsOrChildren)) { - element.append(...propsOrChildren); - } else { - const { parent, $: cb, dataset, style } = propsOrChildren; - delete propsOrChildren.parent; - delete propsOrChildren.$; - delete propsOrChildren.dataset; - delete propsOrChildren.style; - - if (style) { - Object.assign(element.style, style); - } - - if (dataset) { - Object.assign(element.dataset, dataset); - } - - Object.assign(element, propsOrChildren); - if (children) { - element.append(...children); - } - - if (parent) { - parent.append(element); - } - - if (cb) { - cb(element); - } - } - } - return element; -} +import { $el } from "./ui/helpers.js"; +import { ComfyWorkflows } from "./ui/comfyWorkflows.js"; +export { $el } from "./ui/helpers.js"; function dragElement(dragEl, settings) { var posDiffX = 0, @@ -418,6 +382,7 @@ export class ComfyUI { this.lastQueueSize = 0; this.queue = new ComfyList("Queue"); this.history = new ComfyList("History"); + this.workflows = new ComfyWorkflows(); api.addEventListener("status", () => { this.queue.update(); @@ -431,18 +396,11 @@ export class ComfyUI { defaultValue: true, }); - const fileInput = $el("input", { - type: "file", - accept: ".json,image/png", - style: { display: "none" }, - parent: document.body, - onchange: () => { - app.handleFile(fileInput.files[0]); - }, - }); - - this.menuContainer = $el("div.comfy-menu", { parent: document.body }, [ - $el("div.drag-handle", { style: { overflow: "hidden", position: "relative", width: "100%", cursor: "default" } }, [ + this.menuContainer = $el("div.comfy-menu", { + parent: document.body, + onmousedown: () => LiteGraph.closeAllContextMenus() + }, [ + $el("div.drag-handle", { style: { overflow: "hidden", position: "relative", width: "100%", cursor: "default" } }, [ $el("span.drag-handle"), $el("span", { $: (q) => (this.queueSize = q) }), $el("button.comfy-settings-btn", { textContent: "⚙️", onclick: () => this.settings.show() }), @@ -516,26 +474,15 @@ export class ComfyUI { ]), this.queue.element, this.history.element, + this.workflows.save_button.element, + this.workflows.load_button.element, $el("button", { - textContent: "Save", - onclick: () => { - const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string - const blob = new Blob([json], { type: "application/json" }); - const url = URL.createObjectURL(blob); - const a = $el("a", { - href: url, - download: "workflow.json", - style: { display: "none" }, - parent: document.body, - }); - a.click(); - setTimeout(function () { - a.remove(); - window.URL.revokeObjectURL(url); - }, 0); + textContent: "Refresh", + onclick: () => { + this.workflows.load(); + app.refreshComboInNodes(); }, }), - $el("button", { textContent: "Load", onclick: () => fileInput.click() }), $el("button", { textContent: "Refresh", onclick: () => app.refreshComboInNodes() }), $el("button", { textContent: "Clear", onclick: () => { if (!confirmClear.value || confirm("Clear workflow?")) { diff --git a/web/scripts/ui/comfySplitButton.js b/web/scripts/ui/comfySplitButton.js new file mode 100644 index 000000000..b701d69a5 --- /dev/null +++ b/web/scripts/ui/comfySplitButton.js @@ -0,0 +1,27 @@ +import { $el } from "./helpers.js"; + +export class ComfySplitButton { + constructor(text, default_action, { get_options }) { + this.button = $el("button", { + textContent: text, + onclick: default_action, + }); + this.arrow = $el("div.comfy-split-arrow", { + textContent: "▼", + onclick: (e) => { + LiteGraph.closeAllContextMenus(); + var menu = new LiteGraph.ContextMenu( + get_options(), + { + event: e, + scale: 1.3, + }, + window + ); + menu.root.classList.add("comfy-split-popup"); + }, + }); + + this.element = $el("div.comfy-menu-button.comfy-split-button", {}, [this.button, this.arrow]); + } +} \ No newline at end of file diff --git a/web/scripts/ui/comfyWorkflows.js b/web/scripts/ui/comfyWorkflows.js new file mode 100644 index 000000000..eee96cdbf --- /dev/null +++ b/web/scripts/ui/comfyWorkflows.js @@ -0,0 +1,115 @@ +import { $el } from "./helpers.js"; +import { ComfySplitButton } from "./comfySplitButton.js"; +import { api } from "../api.js"; + +export class ComfyWorkflows { + async load() { + this.workflows = await api.get_workflows(); + this.load_button.arrow.style.display = this.workflows.length ? "flex" : "none"; + } + + constructor() { + function build_menu(workflows) { + var menu = []; + var directories = new Map(); + for (const workflow of workflows) { + var path = workflow.split("/"); + var parent = menu; + var current_path = ""; + for (var i = 0; i < path.length - 1; i++) { + current_path += "/" + path[i]; + var new_parent = directories.get(current_path); + if (!new_parent) { + new_parent = { + title: path[i], + has_submenu: true, + submenu: { + options: [], + }, + }; + parent.push(new_parent); + new_parent = new_parent.submenu.options; + directories.set(current_path, new_parent); + } + parent = new_parent; + } + parent.push({ + title: path[path.length - 1], + callback: async () => { + const json = await api.get_workflow(workflow); + app.loadGraphData(json); + }, + }); + } + return menu; + } + + const fileInput = $el("input", { + type: "file", + accept: ".json,image/png", + style: { display: "none" }, + parent: document.body, + onchange: () => { + app.handleFile(fileInput.files[0]); + }, + }); + + this.load_button = new ComfySplitButton("Load", () => fileInput.click(), { + get_options: () => { + return build_menu(this.workflows || []); + }, + }); + + function save(name) { + const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string + const blob = new Blob([json], { type: "application/json" }); + const url = URL.createObjectURL(blob); + const a = $el("a", { + href: url, + download: name + ".json", + style: { display: "none" }, + parent: document.body, + }); + a.click(); + setTimeout(function () { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + + this.save_button = new ComfySplitButton("Save", () => save("workflow"), { + get_options: () => { + return [ + { + title: "Save as", + callback() { + var name = prompt("Enter filename", "workflow"); + if (name) { + save(name); + } + }, + }, + { + title: "Save to workflows", + callback: async () => { + var name = prompt("Enter filename", "workflow"); + if (name) { + var data = app.graph.serialize(); + if (!(await api.save_workflow(name, data))) { + if (confirm("A workspace with this name already exists, do you want to overwrite it?")) { + await api.save_workflow(name, app.graph.serialize(), true); + } else { + return; + } + } + await this.load(); + } + }, + }, + ]; + }, + }); + + this.load(); + } +} diff --git a/web/scripts/ui/helpers.js b/web/scripts/ui/helpers.js new file mode 100644 index 000000000..738e7b7df --- /dev/null +++ b/web/scripts/ui/helpers.js @@ -0,0 +1,38 @@ +export function $el(tag, propsOrChildren, children) { + const split = tag.split("."); + const element = document.createElement(split.shift()); + element.classList.add(...split); + if (propsOrChildren) { + if (Array.isArray(propsOrChildren)) { + element.append(...propsOrChildren); + } else { + const { parent, $: cb, dataset, style } = propsOrChildren; + delete propsOrChildren.parent; + delete propsOrChildren.$; + delete propsOrChildren.dataset; + delete propsOrChildren.style; + + if (style) { + Object.assign(element.style, style); + } + + if (dataset) { + Object.assign(element.dataset, dataset); + } + + Object.assign(element, propsOrChildren); + if (children) { + element.append(...children); + } + + if (parent) { + parent.append(element); + } + + if (cb) { + cb(element); + } + } + } + return element; +} \ No newline at end of file diff --git a/web/style.css b/web/style.css index 312fc046a..b99b9af42 100644 --- a/web/style.css +++ b/web/style.css @@ -117,10 +117,11 @@ body { width: 100%; } +.comfy-menu-button, .comfy-menu > button, .comfy-menu-btns button, .comfy-menu .comfy-list button, -.comfy-modal button{ +.comfy-modal button { color: var(--input-text); background-color: var(--comfy-input-bg); border-radius: 8px; @@ -129,6 +130,16 @@ body { margin-top: 2px; } +.comfy-settings-btn:hover, +.comfy-menu-button:hover, +.comfy-menu > button:hover, +.comfy-menu-btns button:hover, +.comfy-menu .comfy-list button:hover, +.comfy-modal button:hover { + filter: brightness(1.2); + cursor: pointer; +} + .comfy-menu span.drag-handle { width: 10px; height: 20px; @@ -209,7 +220,7 @@ button.comfy-queue-btn { margin: 6px 0 !important; } -.comfy-modal.comfy-settings, +.comfy-modal.comfy-settings, .comfy-modal.comfy-manage-templates { text-align: center; font-family: sans-serif; @@ -268,12 +279,52 @@ button.comfy-queue-btn { .litegraph .litemenu-entry.has_submenu { position: relative; padding-right: 20px; - } +} - .litemenu-entry.has_submenu::after { +.litemenu-entry.has_submenu::after { content: ">"; position: absolute; top: 0; right: 2px; - } - \ No newline at end of file +} + +.litecontextmenu { + z-index: 9999 !important; +} + +.comfy-split-button { + width: 100%; + position: relative; + border-width: 2px; + box-sizing: border-box; +} + +.comfy-split-arrow { + padding: 0 2px; + border-top-right-radius: 5px; + position: absolute; + display: flex; + align-items: center; + top: 0; + right: 0; + bottom: 0; +} + +.comfy-split-arrow:hover { + background-color: rgba(255, 255, 255, 0.5); +} + +.comfy-split-button button { + margin: 0; + padding: 0; + background-color: transparent; + color: var(--input-text); + border: none; + width: 100%; + cursor: pointer; +} + +.comfy-split-popup, +.comfy-split-popup ~ .litecontextmenu { + transform: scale(1.3); +} diff --git a/workflows/default.json b/workflows/default.json new file mode 100644 index 000000000..3de17b305 --- /dev/null +++ b/workflows/default.json @@ -0,0 +1 @@ +{"last_node_id":9,"last_link_id":9,"nodes":[{"id":7,"type":"CLIPTextEncode","pos":[413,389],"size":{"0":425.27801513671875,"1":180.6060791015625},"flags":{},"order":3,"mode":0,"inputs":[{"name":"clip","type":"CLIP","link":5}],"outputs":[{"name":"CONDITIONING","type":"CONDITIONING","links":[6],"slot_index":0}],"properties":{},"widgets_values":["text, watermark"]},{"id":6,"type":"CLIPTextEncode","pos":[415,186],"size":{"0":422.84503173828125,"1":164.31304931640625},"flags":{},"order":2,"mode":0,"inputs":[{"name":"clip","type":"CLIP","link":3}],"outputs":[{"name":"CONDITIONING","type":"CONDITIONING","links":[4],"slot_index":0}],"properties":{},"widgets_values":["beautiful scenery nature glass bottle landscape, , purple galaxy bottle,"]},{"id":5,"type":"EmptyLatentImage","pos":[473,609],"size":{"0":315,"1":106},"flags":{},"order":1,"mode":0,"outputs":[{"name":"LATENT","type":"LATENT","links":[2],"slot_index":0}],"properties":{},"widgets_values":[512,512,1]},{"id":3,"type":"KSampler","pos":[863,186],"size":{"0":315,"1":262},"flags":{},"order":4,"mode":0,"inputs":[{"name":"model","type":"MODEL","link":1},{"name":"positive","type":"CONDITIONING","link":4},{"name":"negative","type":"CONDITIONING","link":6},{"name":"latent_image","type":"LATENT","link":2}],"outputs":[{"name":"LATENT","type":"LATENT","links":[7],"slot_index":0}],"properties":{},"widgets_values":[156680208700286,true,20,8,"euler","normal",1]},{"id":8,"type":"VAEDecode","pos":[1209,188],"size":{"0":210,"1":46},"flags":{},"order":5,"mode":0,"inputs":[{"name":"samples","type":"LATENT","link":7},{"name":"vae","type":"VAE","link":8}],"outputs":[{"name":"IMAGE","type":"IMAGE","links":[9],"slot_index":0}],"properties":{}},{"id":9,"type":"SaveImage","pos":[1451,189],"size":{"0":210,"1":26},"flags":{},"order":6,"mode":0,"inputs":[{"name":"images","type":"IMAGE","link":9}],"properties":{}},{"id":4,"type":"CheckpointLoaderSimple","pos":[26,474],"size":{"0":315,"1":98},"flags":{},"order":0,"mode":0,"outputs":[{"name":"MODEL","type":"MODEL","links":[1],"slot_index":0},{"name":"CLIP","type":"CLIP","links":[3,5],"slot_index":1},{"name":"VAE","type":"VAE","links":[8],"slot_index":2}],"properties":{},"widgets_values":["v1-5-pruned-emaonly.ckpt"]}],"links":[[1,4,0,3,0,"MODEL"],[2,5,0,3,3,"LATENT"],[3,4,1,6,0,"CLIP"],[4,6,0,3,1,"CONDITIONING"],[5,4,1,7,0,"CLIP"],[6,7,0,3,2,"CONDITIONING"],[7,3,0,8,0,"LATENT"],[8,4,2,8,1,"VAE"],[9,8,0,9,0,"IMAGE"]],"groups":[],"config":{},"extra":{},"version":0.4} \ No newline at end of file