add load and save workflows

This commit is contained in:
i-h4x 2023-04-15 09:55:39 +01:00 committed by GitHub
parent 04d9bc13af
commit a68a846f6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 324 additions and 75 deletions

View File

@ -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") 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") 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") 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): if not os.path.exists(input_directory):
os.makedirs(input_directory) os.makedirs(input_directory)
@ -51,6 +52,10 @@ def get_input_directory():
global input_directory global input_directory
return 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 #NOTE: used in http server so don't put folders that should not be accessed remotely
def get_directory_by_type(type_name): def get_directory_by_type(type_name):

View File

@ -265,6 +265,41 @@ class PromptServer():
return web.Response(status=200) 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): def add_routes(self):
self.app.add_routes(self.routes) self.app.add_routes(self.routes)
self.app.add_routes([ self.app.add_routes([

View File

@ -223,7 +223,7 @@ class ComfyApi extends EventTarget {
*/ */
async #postItem(type, body) { async #postItem(type, body) {
try { try {
await fetch("/" + type, { return await fetch("/" + type, {
method: "POST", method: "POST",
headers: { headers: {
"Content-Type": "application/json", "Content-Type": "application/json",
@ -258,6 +258,36 @@ class ComfyApi extends EventTarget {
async interrupt() { async interrupt() {
await this.#postItem("interrupt", null); 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(); export const api = new ComfyApi();

View File

@ -1,43 +1,7 @@
import { api } from "./api.js"; import { api } from "./api.js";
import { $el } from "./ui/helpers.js";
export function $el(tag, propsOrChildren, children) { import { ComfyWorkflows } from "./ui/comfyWorkflows.js";
const split = tag.split("."); export { $el } from "./ui/helpers.js";
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;
}
function dragElement(dragEl, settings) { function dragElement(dragEl, settings) {
var posDiffX = 0, var posDiffX = 0,
@ -418,6 +382,7 @@ export class ComfyUI {
this.lastQueueSize = 0; this.lastQueueSize = 0;
this.queue = new ComfyList("Queue"); this.queue = new ComfyList("Queue");
this.history = new ComfyList("History"); this.history = new ComfyList("History");
this.workflows = new ComfyWorkflows();
api.addEventListener("status", () => { api.addEventListener("status", () => {
this.queue.update(); this.queue.update();
@ -431,18 +396,11 @@ export class ComfyUI {
defaultValue: true, defaultValue: true,
}); });
const fileInput = $el("input", { this.menuContainer = $el("div.comfy-menu", {
type: "file", parent: document.body,
accept: ".json,image/png", onmousedown: () => LiteGraph.closeAllContextMenus()
style: { display: "none" }, }, [
parent: document.body, $el("div.drag-handle", { style: { overflow: "hidden", position: "relative", width: "100%", cursor: "default" } }, [
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" } }, [
$el("span.drag-handle"), $el("span.drag-handle"),
$el("span", { $: (q) => (this.queueSize = q) }), $el("span", { $: (q) => (this.queueSize = q) }),
$el("button.comfy-settings-btn", { textContent: "⚙️", onclick: () => this.settings.show() }), $el("button.comfy-settings-btn", { textContent: "⚙️", onclick: () => this.settings.show() }),
@ -516,26 +474,15 @@ export class ComfyUI {
]), ]),
this.queue.element, this.queue.element,
this.history.element, this.history.element,
this.workflows.save_button.element,
this.workflows.load_button.element,
$el("button", { $el("button", {
textContent: "Save", textContent: "Refresh",
onclick: () => { onclick: () => {
const json = JSON.stringify(app.graph.serialize(), null, 2); // convert the data to a JSON string this.workflows.load();
const blob = new Blob([json], { type: "application/json" }); app.refreshComboInNodes();
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);
}, },
}), }),
$el("button", { textContent: "Load", onclick: () => fileInput.click() }),
$el("button", { textContent: "Refresh", onclick: () => app.refreshComboInNodes() }), $el("button", { textContent: "Refresh", onclick: () => app.refreshComboInNodes() }),
$el("button", { textContent: "Clear", onclick: () => { $el("button", { textContent: "Clear", onclick: () => {
if (!confirmClear.value || confirm("Clear workflow?")) { if (!confirmClear.value || confirm("Clear workflow?")) {

View File

@ -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]);
}
}

View File

@ -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();
}
}

38
web/scripts/ui/helpers.js Normal file
View File

@ -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;
}

View File

@ -117,10 +117,11 @@ body {
width: 100%; width: 100%;
} }
.comfy-menu-button,
.comfy-menu > button, .comfy-menu > button,
.comfy-menu-btns button, .comfy-menu-btns button,
.comfy-menu .comfy-list button, .comfy-menu .comfy-list button,
.comfy-modal button{ .comfy-modal button {
color: var(--input-text); color: var(--input-text);
background-color: var(--comfy-input-bg); background-color: var(--comfy-input-bg);
border-radius: 8px; border-radius: 8px;
@ -129,6 +130,16 @@ body {
margin-top: 2px; 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 { .comfy-menu span.drag-handle {
width: 10px; width: 10px;
height: 20px; height: 20px;
@ -268,12 +279,52 @@ button.comfy-queue-btn {
.litegraph .litemenu-entry.has_submenu { .litegraph .litemenu-entry.has_submenu {
position: relative; position: relative;
padding-right: 20px; padding-right: 20px;
} }
.litemenu-entry.has_submenu::after { .litemenu-entry.has_submenu::after {
content: ">"; content: ">";
position: absolute; position: absolute;
top: 0; top: 0;
right: 2px; right: 2px;
} }
.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);
}

1
workflows/default.json Normal file
View File

@ -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}