This commit is contained in:
Crystian
2024-01-02 16:18:48 +01:00
parent d5bcd66b73
commit f2a99d3215
5 changed files with 257 additions and 729 deletions
+20 -499
View File
@@ -1,511 +1,32 @@
# ComfyUI-Crystools [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fcrystian%2FComfyUI-Crystools&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com) [![Donate](https://img.shields.io/badge/Donate-PayPal-blue.svg)](https://paypal.me/crystian77)
# ComfyUI-Crystools-save [![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Fcrystian%2FComfyUI-Crystools-save&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)](https://hits.seeyoufarm.com) [![Donate](https://img.shields.io/badge/Donate-PayPal-blue.svg)](https://paypal.me/crystian77)
**_A powerful set of tools for your belt when you work with ComfyUI_**
**_You can save your workflows with a particular file name (finally!), and save author info as metadata_**
You can see the metadata and compare between two images, compare between two JSONs, show any value to console/display, pipes, and more!
This provides a better nodes to load images, previews, etc, and see "hidden" data, but without load a new workflow.
With this quality of life extension, you can save your workflow with a specific name and include additional details such as the author, a description, and the version (in metadata/json).
**Important:** When you share your workflow (via png/json), others will be able to see your information!
![Show metadata](./docs/jake.gif)
It works transparently; you can load/import the information in the traditional way.
# Table of contents
## Settings
![Settings](./docs/settings.png)
* `Use new save button?`: I've to change the default behavior of the "save" button. Now it saves the workflow with the name of the project, may you don't want this, so you can turn off this feature.
* `Show project name in menu`: Show the project name in the menu (see below).
* `Project name`: The name of the project, it will be used to save the workflow and file name.
* `Author`: The author of the project.
* `Description`: A description of the project.
* `Version`: The version of the project.
- [Metadata](#metadata)
- [Debugger](#debugger)
- [Image](#image)
- [Pipe](#pipe)
- [Utils](#utils)
- [Primitives](#primitives)
- [List](#list)
- [Switch](#switch)
- Others: [About](#about), [To do](#to-do), [Changelog](#changelog), [Installation](#installation), [Use](#use)
## Menu
![Project-name](./docs/project-name.png)
---
You can turn on/off the project name in the menu (see settings).
## Metadata
### Node: Metadata extractor
If you want to see the metadata, you can use the "Crystools" extension with a node for this.
This node is used to extract the metadata from the image and handle it as a JSON as source for other nodes.
You can see **all information**, even metadata from others sources (like photoshop, see sample).
The input comes from the [load image with metadata](#node-load-image-with-metadata) or [preview from image](#node-preview-from-image) nodes (an others in the future).
## Important notes
![Metadata extractor](./docs/metadata-extractor.png)
**Sample:** [metadata-extractor.json](./samples/metadata-extractor.json)
><details>
> <summary>Other metadata sample (photoshop)</summary>
>
> With metadata from Photoshop
![Metadata extractor](./docs/metadata-extractor-photoshop.png)
></details>
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - metadata_raw: The metadata raw from the image or preview node
> - Output:
> - prompt: The prompt used to produce the image.
> - workflow: The workflow used to produce the image (all information about nodes, values, etc).
> - file info: The file info of the image/metadata (resolution, size, etc) as human readable.
> - raw to JSON: The entire metadata raw but formatted/readable.
> - raw to property: The entire metadata raw as "properties" format.
> - raw to csv: The entire metadata raw as "csv" format.
></details>
<br />
### Node: Metadata comparator
This node is so useful to compare two metadata and see the differences (**the main reason why I created this extension!**)
You can compare 3 inputs: "Prompt", "Workflow" and "Fileinfo"
There are tree potential "outputs": `values_changed`, `dictionary_item_added`, `dictionary_item_removed` (in this order of priority).
![Metadata extractor](./docs/metadata-comparator.png)
**Sample:** [metadata-comparator.json](./samples/metadata-comparator.json)
**Notes:**
- I use [DeepDiff](https://pypi.org/project/deepdiff) for that, for more info check the link.
- If you want to compare two JSONs, you can use the [JSON comparator](#node-JSON-comparator) node.
><details>
> <summary><i>Parameters</i></summary>
>
> - options:
> - what: What to compare, you can choose between "Prompt", "Workflow" and "Fileinfo"
> - input:
> - metadata_raw_old: The metadata raw to start compare
> - metadata_raw_new: The metadata raw to compare
> - Output:
> - diff: This is the same output you can see in the display of the node, you can use it on others nodes.
></details>
<br />
---
## Debugger
### Node: Show Metadata
With this node, you will be able to see the JSON produced from your entire prompt and workflow so that you can really know all the values (and more) of your prompt quickly without the need to open the file (PNG or JSON).
![Show metadata](./docs/debugger-show-metadata.png)
**Sample:** [debugger-metadata.json](./samples/debugger-metadata.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Options:
> - Active: Enable/disable the node
> - Parsed: Show the parsed JSON or plain text
> - What: Show the prompt or workflow (prompt are values to produce the image, and workflow is the entire workflow of ComfyUI)
></details>
<br />
### Node: Show any
You can see on the console or display any text or data from the nodes. Connect it to what you want to inspect, and you will see it.
![Show any](./docs/debugger-show-any.png)
**Sample:** [debugger-any.json](./samples/debugger-any.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_value: Any value to show, can be a string, number, etc.
> - Options:
> - Console: Enable/disable write to console
> - Display: Enable/disable write on this node
> - Prefix: Prefix to console
></details>
<br />
### Node: Show any to JSON
As same the previous one, but it formatted the value to JSON (only display).
![Show any](./docs/debugger-show-json.png)
**Sample:** [debugger-json.json](./samples/debugger-json.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_value: Any value to try to convert to JSON
> - Output:
> - string: The same string is shown on display
></details>
<br />
---
## Image
### Node: Load image with metadata
This node is the same as the default one, but it adds three features: Prompt, Metadata, and supports **subfolders** of the "input" folder.
![Load image with metadata](./docs/image-load.png)
**Sample:** [image-load.json](./samples/image-load.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Read the images from the input folder (and subfolder) (you can drop the image here, or even paste an image from clipboard)
> - Output:
> - Image/Mask: The same as the default node
> - Prompt: The prompt used to produce the image (not the workflow)
> - Metadata RAW: The metadata raw of the image (full workflow) as string
></details>
**Note:** The subfolders support inspired on: [comfyui-imagesubfolders](https://github.com/catscandrive/comfyui-imagesubfolders)
<br />
### Node: Save image with extra metadata
This node is the same as the default one, but it adds two features: Save the workflow or not in the png, and you can add any piece of metadata (as JSON).
This save custom data on the image, so you can share it with others, and they can see the workflow and metadata (see [preview from metadata](#node-preview-from-metadata)), even your custom data.
It can be any type of information supports text and JSON.
![Save image with extra metadata](./docs/image-save.png)
**Sample:** [image-save.json](./samples/image-save.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - options:
> - with_workflow: If you want to save into the image the workflow (special to share the workflow with others)
> - Input:
> - image: The image to save (same as the default node)
> - Output:
> - Metadata RAW: The metadata raw of the image (full workflow) as string
></details>
**Note:** The data is saved as special "exif" (as ComfyUI do) in the png file, you can read it with [Load image with metadata](#node-load-image-with-metadata).
<br />
### Node: Preview from image
This node is used to preview the image with the **current prompt** and additional features.
![Preview from image](./docs/image-preview.png)
**Feature:** It supports cache (shows as "CACHED") (not permanent yet!), so you can disconnect the node and still see the image and data, so you can use it to compare with others!
![Preview from image](./docs/image-preview-diff.png)
As you can see the seed, steps, and cfg were changed
**Sample:** [image-preview-image.json](./samples/image-preview-image.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Any kind of image link
> - Output:
> - Metadata RAW: The metadata raw of the image and full workflow.
> - You can use it to **compare with others** (see [metadata comparator](#node-metadata-comparator))
> - The file info like filename, resolution, datetime and size with **the current prompt, not the original one!** (see important note)
></details>
> **Important:**
> - If you want to read the metadata of the image, you need to use the [load image with metadata](#node-load-image-with-metadata) and use the output "metadata RAW" not image link.
> - To do a preview it is necessary save it first on temporal folder, and the data shown is from the temporal image, **not the original one** even **the prompt!**
<br />
### Node: Preview from metadata
This node is used to preview the image from the metadata and shows additional data (all around this one).
It supports same features as [preview from image](#node-preview-from-image) (cache, metadata raw, etc.). But the important difference is you see **real data from the image** (not the temporal one either current prompt).
![Preview from metadata](./docs/image-preview-metadata.png)
**Sample:** [image-preview-metadata.json](./samples/image-preview-metadata.json)
<br />
### Node: Show resolution
This node is used to show the resolution of an image.
> Can be used with any image link.
![Show resolution](./docs/image-resolution.png)
**Sample:** [image-resolution.json](./samples/image-resolution.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - image: Any kind of image link
> - Output:
> - Width: The width of the image
> - Height: The height of the image
></details>
<br />
---
## Pipe
### Nodes: Pipe to/edit any, Pipe from any
This powerful set of nodes is used to better organize your pipes.
The "Pipe to/edit any" node is used to encapsulate multiple links into a single one. It includes support for editing, easily adding the modified content back to the same pipe number.
The "Pipe from any" node is used to extract the content of a pipe.
Typical example:
![Pipes](./docs/pipe-0.png)
With pipes:
![Pipes](./docs/pipe-1.png)
**Sample:** [pipe-1.json](./samples/pipe-1.json)
Editing pipes:
![Pipes](./docs/pipe-2.png)
**Sample:** [pipe-2.json](./samples/pipe-2.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - CPipeAny: This is the type of this pipe you can use it to edit (see the sample)
> - any_*: 6 possible inputs to use
> - Output:
> - CPipeAny: You can continue the pipe with this output, you can use it to bifurcate the pipe (see the sample)
></details>
>**Important:**
> - Please note that it supports "any," meaning it does not validate (not yet!) the correspondence of input nodes with the output ones. When creating the link, it is recommended to link consciously number by number.
> - "RecursionError", It's crucial to note that the flow of links **must be in the same direction**, and they cannot be mixed with other flows that use the result of this one. Otherwise, this may lead to recursion and block the server (you need to restart it!)
><details>
> <summary><i>Bad example with "RecursionError: maximum recursion depth exceeded"</i></summary>
>
> If you see on your console something like this, you need to check your pipes. That is bad sample of pipes, you can't mix the flows.
![Pipes](./docs/pipe-3.png)
></details>
<br />
---
## Utils
Some useful nodes to use in your workflow.
### Node: JSON comparator
This node is so useful to compare two JSONs and see the differences.
![JSON comparator](./docs/utils-json-comparator.png)
**Sample:** [utils-json-comparator.json](./samples/utils-json-comparator.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - json_old: The first json to start compare
> - json_new: The json to compare
> - Output:
> - diff: A new JSON with the differences
></details>
**Notes:**
As you can see, it is the same as the [metadata comparator](#node-metadata-comparator) but with JSONs.
The other is intentionally simple to compare two images metadata, this is more generic.
The main difference is that you can compare any JSON, not only metadata.
<br />
### Node: Stats system
This node is used to show the stats of the system (RAM, VRAM and Space).
It **should** connect as a pipe.
![JSON comparator](./docs/utils-stats.png)
**Sample:** [utils-stats.json](./samples/utils-stats.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - input:
> - latent: The latent to use to measure the stats
> - Output:
> - latent: Return the same latent to continue the pipe
></details>
**Notes:** The original is in [WAS](https://github.com/WASasquatch/was-node-suite-comfyui), I only show it on the display.
<br />
---
## Primitives
### Nodes: Primitive boolean, Primitive integer, Primitive float, Primitive string, Primitive string multiline
A set of nodes with primitive values to use in your prompts.
![Primitives](./docs/primitives.png)
<br />
---
## List
A set of nodes with list of values (any or strings/texts) for any propose (news nodes to use it coming soon!).
> **Important:** You can use with others nodes like "Show any" to see the values of the list
### Node: List of strings
**Feature:** You can concatenate them.
![Lists](./docs/list-string.png)
**Sample:** [list-strings.json](./samples/list-strings.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - string_*: 8 possible inputs to use
> - delimiter: Use to concatenate the values on output
> - Output:
> - concatenated: A string with all values concatenated
> - list_string: The list of strings (only with values)
></details>
<br />
### Node: List of any
You can concatenate any value (it will try to convert to string and show the value), so util to see several values at the same time.
![Lists](./docs/list-any.png)
**Sample:** [list-any.json](./samples/list-any.json)
><details>
> <summary><i>Parameters</i></summary>
>
> - Input:
> - any_*: 8 possible inputs to use
> - Output:
> - list_any: The list of any elements (only with values)
></details>
<br />
---
## Switch
A set of nodes to switch between flows.
All switches are boolean, you can switch between flows by simply changing the value of the switch.
You have predefined switches (string, latent, image, conditioning) but you can use "Switch any" for any value/type.
![Switches](./docs/switches.png)
**Sample:** [switch.json](./samples/switch.json)
<br />
---
## About
**Notes from the author:**
- This is my first project in python ¯\\_(ツ)_/¯ (PR are welcome!)
- I'm software engineer but in other languages (web technologies)
- My instagram is: https://www.instagram.com/crystian.ia I'll publish my works on it, consider follow me for news! :)
- I'm not a native english speaker, so sorry for my english :P
---
## To do
- [✅] Review the priority of list of nodes
- [❌] Add support for others image formats (jpg, gif, etc.) - nope, I don't need it, it's complicated
- [ ] Several unit tests
- [ ] Add permanent cache for preview/metadata image (to survive to F5! or restart the server)
---
## Changelog
### 1.1.0 (29/12/2023)
- Node added: "Save image with extra metadata"
- Support to **read** Jpeg metadata added (not save)
### 1.0.0 (26/12/2023)
- First release
---
## Installation
### Install from GitHub
1. Install [ComfyUi](https://github.com/comfyanonymous/ComfyUI).
2. Clone this repo into `custom_modules`:
```
cd ComfyUI/custom_nodes
git clone https://github.com/crystian/ComfyUI-Crystools.git
cd ComfyUI-Crystools
pip install -r requirements.txt
```
3. Start up ComfyUI.
### Install from manager
Search for `crystools` in the [manager](https://github.com/ltdrdata/ComfyUI-Manager.git) and install it.
---
## Use
You can use it as any other node, just using the menu in the category `crystools` or double click on the canvas (I recommended to use the "oo" to fast filter), all nodes were posfixing with `[Crystools]`.
![Menu](./docs/menu.png)
![shortcut](./docs/shortcut.png)
If for some reason you need to see the logs, you can define the environment variable `CRYSTOOLS_LOGLEVEL` and set the [value](https://docs.python.org/es/3/howto/logging.html).
---
Made with ❤️ by Crystian.
* I used a specific field in metadata/json: "workflow.extra." I've created an "info" property to store this information. I don't know, and I haven't found any documentation about this, so I hope it's not a problem.
+1 -2
View File
@@ -4,10 +4,9 @@
@nickname: Crystools-save
@version: 1.0.0
@project: "https://github.com/crystian/ComfyUI-Crystools-save",
@description: Plugins for multiples uses, mainly for debugging, you need them! IG: https://www.instagram.com/crystian.ia
@description: With this quality of life extension, you can save your workflow with a specific name and include additional details such as the author, a description, and the version (in metadata/json) IG: https://www.instagram.com/crystian.ia
"""
WEB_DIRECTORY = "web"
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+236 -228
View File
@@ -2,249 +2,119 @@ import { app } from '../../../scripts/app.js';
import { $el } from '../../../scripts/ui.js';
// common variables
const idExtensionName = 'Crystools.save';
const idNewSave = 'Crystools.newSave';
const idProjectNameShow = 'Crystools.projectNameShow';
const idProjectNameText = 'Crystools.projectNameText';
const idAuthor = 'Crystools.author';
const idDescription = 'Crystools.description';
const idVersion = 'Crystools.version';
class CrystoolsSave {
// common variables
idExtensionName = 'Crystools.save';
idNewSave = 'Crystools.newSave';
idProjectNameShow = 'Crystools.projectNameShow';
idProjectNameText = 'Crystools.projectNameText';
idAuthor = 'Crystools.author';
idDescription = 'Crystools.description';
idVersion = 'Crystools.version';
const defaultNewSave = true;
const defaultProjectNameShow = true;
const defaultProjectNameText = 'workflow';
const defaultAuthor = 'Crystools';
const defaultDescription = 'd';
const defaultVersion = '1';
defaultNewSave = true;
defaultProjectNameShow = true;
defaultProjectNameText = 'workflow';
defaultAuthor = 'Crystools';
defaultDescription = '';
defaultVersion = '1';
const menuPrefix = '';
const htmlIdCrystoolsMenu = 'crystools-menu';
menuPrefix = '';
htmlIdCrystoolsMenu = 'crystools-menu';
// references of htmls elements
inputRefProjectNameText = null;
originalSaveEventsRef = null;
saveButtonRef = null;
// references of htmls elements
let inputRefProjectNameText = null;
let originalSaveEventsRef = null;
let saveButtonRef = null;
const getInfoOnGraph = () => {
return app.graphToPrompt();
};
// just persist the data on workflow reference
const setInfoOnGraph = (values) => {
// create the info object if not exists on workflow
let name = values?.name || defaultProjectNameText;
app.ui.settings.setSettingValue(idProjectNameText, name);
values.name = name;
let author = values?.author || defaultAuthor;
app.ui.settings.setSettingValue(idAuthor, author);
values.author = author;
let description = values?.description || defaultDescription;
app.ui.settings.setSettingValue(idDescription, description);
values.description = description;
let version = values?.version || defaultVersion;
app.ui.settings.setSettingValue(idVersion, version);
values.version = version;
if (!(values?.created)) {
values.created = new Date().toISOString();
constructor() {
this.createSettings();
}
inputRefProjectNameText.value = values.name;
values.modified = new Date().toISOString();
values.software = 'ComfyUI';
};
// not on setup because this affect the order on settings, I prefer to options at first
createSettings = () => {
/** Form on settings: (the order is important) */
// just the name of project
const updateProjectName = (value) => {
const ctools = document.getElementById(htmlIdCrystoolsMenu);
// validation because this run before setup
if (ctools && inputRefProjectNameText) {
getInfoOnGraph().then((p) => {
if (!p.workflow.extra.info) {
p.workflow.extra.info = {};
}
setInfoOnGraph(Object.assign(p.workflow.extra.info, {name: value}));
// use new save button
app.ui.settings.addSetting({
id: this.idNewSave,
name: this.menuPrefix + 'Use new save button? (requires page reload)',
type: 'boolean',
tooltip: 'This will replace the save button function and propose the name of project as filename!',
defaultValue: this.defaultNewSave,
onChange: this.saveFunctionSwitch,
});
}
};
// remember to send `{ property: value }`
const updateInfoOnGraph = (value) => {
if (typeof value !== 'object') {
console.warn('updateInfoOnGraph: value must be an object');
return;
}
if (app.graph) {
getInfoOnGraph().then((p) => {
setInfoOnGraph(Object.assign(p.workflow.extra.info, value));
// show the input on menu
app.ui.settings.addSetting({
id: this.idProjectNameShow,
name: this.menuPrefix + 'Show project name in menu',
type: 'boolean',
defaultValue: this.defaultProjectNameShow,
onChange: this.showProjectName,
});
}
};
const showProjectName = (value) => {
const ctools = document.getElementById(htmlIdCrystoolsMenu);
// project name
app.ui.settings.addSetting({
id: this.idProjectNameText,
name: this.menuPrefix + 'Project name',
type: 'text',
defaultValue: this.defaultProjectNameText,
onChange: this.updateProjectName,
});
// validation because this run before setup
if (ctools) {
ctools.style.display = value ? 'block' : 'none';
}
};
// author
app.ui.settings.addSetting({
id: this.idAuthor,
name: this.menuPrefix + 'Author',
type: 'text',
defaultValue: this.defaultAuthor,
onChange: (value) => {
this.updateInfoOnGraph({author: value});
},
});
const saveFunctionOldHandler = (event) => {
originalSaveEventsRef && originalSaveEventsRef(event);
};
// description
app.ui.settings.addSetting({
id: this.idDescription,
name: this.menuPrefix + 'Description',
type: 'text',
defaultValue: this.defaultDescription,
onChange: (value) => {
this.updateInfoOnGraph({description: value});
},
});
const saveFunctionNewHandler = async() => {
let filename = inputRefProjectNameText.value + '.json';
const promptFilename = app.ui.settings.getSettingValue('Comfy.PromptFilename', true);
// literally copied and pasted from comfy ui.js ... https://github.com/comfyanonymous/ComfyUI/blob/master/web/scripts/ui.js#L710C10-L710C10
// ¯\_(ツ)_/¯
if (promptFilename) {
filename = prompt('Save workflow as:', filename);
if (!filename) {
return;
}
if (!filename.toLowerCase().endsWith('.json')) {
filename += '.json';
}
}
const p = await app.graphToPrompt();
const json = JSON.stringify(p.workflow, 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: filename,
style: {display: 'none'},
parent: document.body,
});
a.click();
setTimeout(function() {
a.remove();
window.URL.revokeObjectURL(url);
}, 0);
};
const saveFunctionSwitch = (newOne) => {
// for ignore the first call
if (originalSaveEventsRef === null) {
return;
}
let handler = null;
// remove all event listeners
const clone = saveButtonRef.cloneNode(true);
if (newOne) {
handler = saveFunctionNewHandler;
} else {
handler = saveFunctionOldHandler;
}
handler && clone.addEventListener('click', handler, true);
saveButtonRef.replaceWith(clone);
};
/** Form on settings: (the order is important) */
// use new save button
app.ui.settings.addSetting({
id: idNewSave,
name: menuPrefix + 'Use new save button? (requires page reload)',
type: 'boolean',
tooltip: 'This will replace the save button function and propose the name of project as filename!',
defaultValue: defaultNewSave,
onChange: saveFunctionSwitch,
});
// show the input on menu
app.ui.settings.addSetting({
id: idProjectNameShow,
name: menuPrefix + 'Show project name in menu',
type: 'boolean',
defaultValue: defaultProjectNameShow,
onChange: showProjectName,
});
// project name
app.ui.settings.addSetting({
id: idProjectNameText,
name: menuPrefix + 'Project name',
type: 'text',
defaultValue: defaultProjectNameText,
onChange: updateProjectName,
});
// author
app.ui.settings.addSetting({
id: idAuthor,
name: menuPrefix + 'Author',
type: 'text',
defaultValue: defaultAuthor,
onChange: (value) => {
updateInfoOnGraph({author: value});
},
});
// description
app.ui.settings.addSetting({
id: idDescription,
name: menuPrefix + 'Description',
type: 'text',
defaultValue: defaultDescription,
onChange: (value) => {
updateInfoOnGraph({description: value});
},
});
// version
app.ui.settings.addSetting({
id: idVersion,
name: menuPrefix + 'Version',
type: 'text',
defaultValue: defaultVersion,
onChange: (value) => {
updateInfoOnGraph({version: value});
},
});
app.registerExtension({
name: idExtensionName,
async setup() {
// version
app.ui.settings.addSetting({
id: this.idVersion,
name: this.menuPrefix + 'Version',
type: 'text',
defaultValue: this.defaultVersion,
onChange: (value) => {
this.updateInfoOnGraph({version: value});
},
});
};
setup() {
app.graph.onConfigure = (a) => {
// on drops a file on the canvas
getInfoOnGraph().then((p) => {
this.getInfoOnGraph().then((p) => {
if (!p.workflow.extra.info) {
p.workflow.extra.info = {};
}
setInfoOnGraph(p.workflow.extra.info);
this.setInfoOnGraph(p.workflow.extra.info);
});
};
const queueBtn = document.getElementById('queue-button');
const ctools = document.createElement('div');
ctools.setAttribute('id', htmlIdCrystoolsMenu);
ctools.classList.add(htmlIdCrystoolsMenu);
ctools.setAttribute('id', this.htmlIdCrystoolsMenu);
ctools.classList.add(this.htmlIdCrystoolsMenu);
ctools.classList.add('comfy-menu-btns');
ctools.style.margin = '8px 0';
ctools.style.width = '100%';
@@ -253,23 +123,161 @@ app.registerExtension({
const projectNameInput = document.createElement('input');
projectNameInput.setAttribute('placeholder', 'Project name');
projectNameInput.style.width = '80%';
inputRefProjectNameText = projectNameInput;
ctools.append(projectNameInput);
// this boolean does not save the value on workflow
showProjectName(app.ui.settings.getSettingValue(idProjectNameShow, defaultProjectNameShow));
// this text save the value on workflow and localstorage
updateProjectName(app.ui.settings.getSettingValue(idProjectNameText, defaultProjectNameText));
this.inputRefProjectNameText = projectNameInput;
// events for the input to persist the data on workflow
projectNameInput.addEventListener('keyup', (event) => {
updateProjectName(event.target.value);
this.updateProjectName(event.target.value);
});
// this boolean does not save the value on workflow
this.showProjectName(app.ui.settings.getSettingValue(this.idProjectNameShow, this.defaultProjectNameShow));
// this text save the value on workflow and localstorage
this.updateProjectName(app.ui.settings.getSettingValue(this.idProjectNameText, this.defaultProjectNameText));
// save the original save button event
saveButtonRef = document.getElementById('comfy-save-button');
originalSaveEventsRef = saveButtonRef.onclick;
saveFunctionSwitch(app.ui.settings.getSettingValue(idNewSave, defaultNewSave));
},
});
this.saveButtonRef = document.getElementById('comfy-save-button');
this.originalSaveEventsRef = this.saveButtonRef.onclick;
this.saveFunctionSwitch(app.ui.settings.getSettingValue(this.idNewSave, this.defaultNewSave));
}
showProjectName = (value) => {
const ctools = document.getElementById(this.htmlIdCrystoolsMenu);
// validation because this run before setup
if (ctools) {
ctools.style.display = value ? 'block' : 'none';
}
};
// just persist the data on workflow reference
setInfoOnGraph = (values) => {
// create the info object if not exists on workflow
let name = values?.name || this.defaultProjectNameText;
app.ui.settings.setSettingValue(this.idProjectNameText, name);
values.name = name;
let author = values?.author || this.defaultAuthor;
app.ui.settings.setSettingValue(this.idAuthor, author);
values.author = author;
let description = values?.description || this.defaultDescription;
app.ui.settings.setSettingValue(this.idDescription, description);
values.description = description;
let version = values?.version || this.defaultVersion;
app.ui.settings.setSettingValue(this.idVersion, version);
values.version = version;
if (!(values?.created)) {
values.created = new Date().toISOString();
}
this.inputRefProjectNameText.value = values.name;
values.modified = new Date().toISOString();
values.software = 'ComfyUI';
};
// remember to send `{ property: value }`
updateInfoOnGraph = (value) => {
if (typeof value !== 'object') {
console.warn('updateInfoOnGraph: value must be an object');
return;
}
if (app.graph) {
this.getInfoOnGraph().then((p) => {
this.setInfoOnGraph(Object.assign(p.workflow.extra.info, value));
});
}
};
getInfoOnGraph = () => {
return app.graphToPrompt();
};
// just the name of project
updateProjectName = (value) => {
const ctools = document.getElementById(this.htmlIdCrystoolsMenu);
// validation because this run before setup
if (ctools && this.inputRefProjectNameText) {
this.getInfoOnGraph().then((p) => {
if (!p.workflow.extra.info) {
p.workflow.extra.info = {};
}
this.setInfoOnGraph(Object.assign(p.workflow.extra.info, {name: value}));
});
}
};
saveFunctionOldHandler = (event) => {
this.updateInfoOnGraph({modified: new Date().toISOString()});
this.originalSaveEventsRef && this.originalSaveEventsRef(event);
};
saveFunctionNewHandler = async() => {
this.updateInfoOnGraph({modified: new Date().toISOString()});
let filename = this.inputRefProjectNameText.value + '.json';
const promptFilename = app.ui.settings.getSettingValue('Comfy.PromptFilename', true);
// literally copied and pasted from comfy ui.js ... https://github.com/comfyanonymous/ComfyUI/blob/master/web/scripts/ui.js#L710C10-L710C10
// ¯\_(ツ)_/¯
if (promptFilename) {
filename = prompt('Save workflow as:', filename);
if (!filename) {
return;
}
if (!filename.toLowerCase().endsWith('.json')) {
filename += '.json';
}
}
const p = await app.graphToPrompt();
const json = JSON.stringify(p.workflow, 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: filename,
style: {display: 'none'},
parent: document.body,
});
a.click();
setTimeout(function() {
a.remove();
window.URL.revokeObjectURL(url);
}, 0);
};
saveFunctionSwitch = (newOne) => {
// for ignore the first call
if (this.originalSaveEventsRef === null) {
return;
}
let handler = null;
// remove all event listeners
const clone = this.saveButtonRef.cloneNode(true);
if (newOne) {
handler = this.saveFunctionNewHandler;
} else {
handler = this.saveFunctionOldHandler;
}
handler && clone.addEventListener('click', handler);
this.saveButtonRef.replaceWith(clone);
};
}
const crystoolsSave = new CrystoolsSave();
app.registerExtension({
name: crystoolsSave.idExtensionName,
setup: crystoolsSave.setup.bind(crystoolsSave),
})