diff --git a/.config/.last_opt_in_prompt.yaml b/.config/.last_opt_in_prompt.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0967ef424bce6791893e9a57bb952f80fd536e93 --- /dev/null +++ b/.config/.last_opt_in_prompt.yaml @@ -0,0 +1 @@ +{} diff --git a/.config/.last_survey_prompt.yaml b/.config/.last_survey_prompt.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed6da4cde3490492b0f22b426d868c20a1a8a7af --- /dev/null +++ b/.config/.last_survey_prompt.yaml @@ -0,0 +1 @@ +last_prompt_time: 1787578073.1355083 diff --git a/.config/.last_update_check.json b/.config/.last_update_check.json new file mode 100644 index 0000000000000000000000000000000000000000..d40bb6e63e0e7309a0321334cf6e39e254ef6406 --- /dev/null +++ b/.config/.last_update_check.json @@ -0,0 +1 @@ +{"last_update_check_time": 1787578074.3213105, "last_update_check_revision": 20260814074256, "notifications": [], "last_nag_times": {}} \ No newline at end of file diff --git a/.config/active_config b/.config/active_config new file mode 100644 index 0000000000000000000000000000000000000000..331d858ce9b12fa6720414196a9dd6e0b6a0faaa --- /dev/null +++ b/.config/active_config @@ -0,0 +1 @@ +default \ No newline at end of file diff --git a/.config/config_sentinel b/.config/config_sentinel new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/.config/configurations/config_default b/.config/configurations/config_default new file mode 100644 index 0000000000000000000000000000000000000000..ee06685b6841afd85a59e8ea5bc7ee8a27d6fe74 --- /dev/null +++ b/.config/configurations/config_default @@ -0,0 +1,6 @@ +[component_manager] +disable_update_check = true + +[compute] +gce_metadata_read_timeout_sec = 0 + diff --git a/.config/default_configs.db b/.config/default_configs.db new file mode 100644 index 0000000000000000000000000000000000000000..e8a2c56e9e0369b0e66531a0ddfec7c2b10a73ee Binary files /dev/null and b/.config/default_configs.db differ diff --git a/.config/gce b/.config/gce new file mode 100644 index 0000000000000000000000000000000000000000..c1f22fbc23bb6ee67824843d6685826db10313d3 --- /dev/null +++ b/.config/gce @@ -0,0 +1 @@ +False \ No newline at end of file diff --git a/.config/hidden_gcloud_config_universe_descriptor_data_cache_configs.db b/.config/hidden_gcloud_config_universe_descriptor_data_cache_configs.db new file mode 100644 index 0000000000000000000000000000000000000000..285224b1b8eac03cfb63b9479efca1f68b6b7db5 Binary files /dev/null and b/.config/hidden_gcloud_config_universe_descriptor_data_cache_configs.db differ diff --git a/.config/logs/2026.08.24/13.27.25.202777.log b/.config/logs/2026.08.24/13.27.25.202777.log new file mode 100644 index 0000000000000000000000000000000000000000..2323b9a293bc1a0491b89bbd0f41f3e010abb31e --- /dev/null +++ b/.config/logs/2026.08.24/13.27.25.202777.log @@ -0,0 +1,819 @@ +2026-08-24 13:27:25,204 DEBUG root Failed to read GCE cache file: [Errno 2] No such file or directory: '/content/.config/gce' +2026-08-24 13:27:43,229 DEBUG root Failed to check metadata server: +2026-08-24 13:27:43,231 DEBUG root Loaded Command Group: ['gcloud', 'components'] +2026-08-24 13:27:43,234 DEBUG root Loaded Command Group: ['gcloud', 'components', 'update'] +2026-08-24 13:27:43,236 DEBUG root Running [gcloud.components.update] with arguments: [--compile-python: "True", --quiet: "True", COMPONENT-IDS:6: "['core', 'gcloud-deps', 'bq', 'gcloud', 'gcloud-crc32c', 'gsutil']"] +2026-08-24 13:27:43,237 INFO ___FILE_ONLY___ Beginning update. This process may take several minutes. + +2026-08-24 13:27:43,263 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,266 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,268 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:43,279 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components-2.json HTTP/1.1" 200 28475 +2026-08-24 13:27:43,292 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,293 INFO ___FILE_ONLY___ +Your current Google Cloud CLI version is: 581.0.0 + +2026-08-24 13:27:43,293 INFO ___FILE_ONLY___ Installing components from version: 581.0.0 + +2026-08-24 13:27:43,293 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,293 DEBUG root Chosen display Format:table[box,title="These components will be removed."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:43,294 DEBUG root Chosen display Format:table[box,title="These components will be updated."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:43,294 DEBUG root Chosen display Format:table[box,title="These components will be installed."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:43,327 INFO ___FILE_ONLY___ ┌─────────────────────────────────────────────────────────────────────────────┐ +2026-08-24 13:27:43,327 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,327 INFO ___FILE_ONLY___ │ These components will be installed. │ +2026-08-24 13:27:43,327 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ ├─────────────────────────────────────────────────────┬────────────┬──────────┤ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ │ Name │ Version │ Size │ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ ├─────────────────────────────────────────────────────┼────────────┼──────────┤ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ BigQuery Command Line Tool +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ 2.1.37 +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ 2.2 MiB +2026-08-24 13:27:43,328 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ BigQuery Command Line Tool (Platform Specific) +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ 2.1.32 +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,329 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ Bundled Python 3.14 (Platform Specific) +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ 3.14.6 +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ 33.0 MiB +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ Cloud Storage Command Line Tool +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,330 INFO ___FILE_ONLY___ 5.37 +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ 12.4 MiB +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ Cloud Storage Command Line Tool (Platform Specific) +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ 5.37 +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,331 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ Default set of gcloud commands (Platform Specific) +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ 2026.07.10 +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ Google Cloud CLI Core Libraries (Platform Specific) +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ 2026.06.05 +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,332 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ Google Cloud CRC32C Hash Tool (Platform Specific) +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ 1.0.0 +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ 1.5 MiB +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,333 INFO ___FILE_ONLY___ gcloud cli dependencies (Platform Specific) +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ 2021.04.16 +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ └─────────────────────────────────────────────────────┴────────────┴──────────┘ +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,334 INFO ___FILE_ONLY___ + +2026-08-24 13:27:43,335 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,336 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,337 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:43,352 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/RELEASE_NOTES HTTP/1.1" 200 399308 +2026-08-24 13:27:43,838 INFO ___FILE_ONLY___ For the latest full release notes, please visit: + https://cloud.google.com/sdk/release_notes + + +2026-08-24 13:27:43,839 INFO ___FILE_ONLY___ Performing in place update... + + +2026-08-24 13:27:43,841 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:43,842 INFO ___FILE_ONLY___ ╠═ Downloading: BigQuery Command Line Tool ═╣ + +2026-08-24 13:27:43,842 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:43,843 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,844 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,844 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:43,901 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-bq-20260814074256.tar.gz HTTP/1.1" 200 2286040 +2026-08-24 13:27:43,927 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,927 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,927 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,928 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,929 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,930 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,931 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,932 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:43,933 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:43,935 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:43,935 INFO ___FILE_ONLY___ ╠═ Downloading: BigQuery Command Line Tool (Platform Spe... ═╣ + +2026-08-24 13:27:43,935 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:43,936 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,937 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,938 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:43,990 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-bq-nix-20260605120704.tar.gz HTTP/1.1" 200 1948 +2026-08-24 13:27:43,991 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:43,991 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:43,993 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:43,993 INFO ___FILE_ONLY___ ╠═ Downloading: Bundled Python 3.14 ═╣ + +2026-08-24 13:27:43,993 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:43,993 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:43,994 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:43,995 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:43,996 INFO ___FILE_ONLY___ ╠═ Downloading: Bundled Python 3.14 (Platform Specific) ═╣ + +2026-08-24 13:27:43,996 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:43,997 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,998 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:43,998 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,018 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-bundled-python3-unix-linux-x86_64-20260731054104.tar.gz HTTP/1.1" 200 34630708 +2026-08-24 13:27:44,156 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,157 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,157 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,158 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,159 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,160 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,161 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,161 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,162 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,163 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,164 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,165 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,165 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,166 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,167 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,168 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,169 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,169 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,170 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,171 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,172 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,173 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,174 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,175 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,176 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,176 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,177 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,178 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,179 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,179 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,180 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,181 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,182 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,183 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,183 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,184 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,185 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,186 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,186 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,187 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,188 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,189 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,189 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,190 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,191 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,192 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,192 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,193 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,194 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,195 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,195 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,196 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,197 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,198 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,198 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,199 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,200 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,201 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,201 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,202 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,202 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,204 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,204 INFO ___FILE_ONLY___ ╠═ Downloading: Cloud Storage Command Line Tool ═╣ + +2026-08-24 13:27:44,205 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,206 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,207 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,207 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,223 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-gsutil-20260501041631.tar.gz HTTP/1.1" 200 12967034 +2026-08-24 13:27:44,262 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,263 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,263 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,264 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,264 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,264 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,265 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,265 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,266 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,266 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,266 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,267 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,267 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,267 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,268 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,268 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,269 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,269 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,269 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,270 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,270 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,271 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,271 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,271 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,272 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,272 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,272 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,273 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,273 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,274 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,274 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,274 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,275 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,275 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,275 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,276 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,276 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,276 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,277 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,277 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,278 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,278 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,278 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,279 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,279 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,279 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,280 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,280 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,280 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,281 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,281 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,282 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,282 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,282 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,283 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,283 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,284 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,284 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,284 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,285 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,285 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,287 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,287 INFO ___FILE_ONLY___ ╠═ Downloading: Cloud Storage Command Line Tool (Platfor... ═╣ + +2026-08-24 13:27:44,287 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,288 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,289 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,290 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,299 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-gsutil-nix-20260605120704.tar.gz HTTP/1.1" 200 1963 +2026-08-24 13:27:44,299 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,299 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,301 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,301 INFO ___FILE_ONLY___ ╠═ Downloading: Default set of gcloud commands ═╣ + +2026-08-24 13:27:44,301 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,302 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,302 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,303 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,303 INFO ___FILE_ONLY___ ╠═ Downloading: Default set of gcloud commands (Platform... ═╣ + +2026-08-24 13:27:44,303 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,304 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,305 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,306 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,316 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-gcloud-linux-x86_64-20260710150251.tar.gz HTTP/1.1" 200 99 +2026-08-24 13:27:44,317 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,317 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,319 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,319 INFO ___FILE_ONLY___ ╠═ Downloading: Google Cloud CLI Core Libraries (Platfor... ═╣ + +2026-08-24 13:27:44,319 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,320 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,321 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,322 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,369 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-core-nix-20260605120704.tar.gz HTTP/1.1" 200 2342 +2026-08-24 13:27:44,369 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,370 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,372 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,372 INFO ___FILE_ONLY___ ╠═ Downloading: Google Cloud CRC32C Hash Tool ═╣ + +2026-08-24 13:27:44,372 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,372 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,372 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,374 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,374 INFO ___FILE_ONLY___ ╠═ Downloading: Google Cloud CRC32C Hash Tool (Platform ... ═╣ + +2026-08-24 13:27:44,374 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,375 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,376 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,377 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,393 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-gcloud-crc32c-linux-x86_64-20260717053915.tar.gz HTTP/1.1" 200 1610486 +2026-08-24 13:27:44,404 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,404 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,404 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,405 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,407 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,409 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,410 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,411 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,413 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,413 INFO ___FILE_ONLY___ ╠═ Downloading: gcloud cli dependencies (Platform Specific) ═╣ + +2026-08-24 13:27:44,414 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,414 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,415 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:44,416 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:44,429 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-gcloud-deps-linux-x86_64-20210416153011.tar.gz HTTP/1.1" 200 104 +2026-08-24 13:27:44,430 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,430 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,432 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,432 INFO ___FILE_ONLY___ ╠═ Installing: BigQuery Command Line Tool ═╣ + +2026-08-24 13:27:44,432 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,506 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,509 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,511 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,514 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,516 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,518 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,520 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,523 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,526 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,528 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,530 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,532 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,534 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,537 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,539 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,542 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,544 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,546 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,549 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,551 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,554 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,556 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,558 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,560 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,562 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,564 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,566 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,568 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,570 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,572 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,574 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,575 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,577 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,580 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,582 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,584 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,587 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,590 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,592 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,597 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,601 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,604 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,612 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,614 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,617 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,621 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,623 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,626 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,629 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,631 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,633 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,635 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,638 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,639 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,642 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,644 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,646 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,649 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,651 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,653 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:44,653 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,659 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,659 INFO ___FILE_ONLY___ ╠═ Installing: BigQuery Command Line Tool (Platform Spec... ═╣ + +2026-08-24 13:27:44,659 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,660 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,660 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,663 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,663 INFO ___FILE_ONLY___ ╠═ Installing: Bundled Python 3.14 ═╣ + +2026-08-24 13:27:44,663 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:44,664 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:44,664 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:44,666 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:44,666 INFO ___FILE_ONLY___ ╠═ Installing: Bundled Python 3.14 (Platform Specific) ═╣ + +2026-08-24 13:27:44,666 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:45,472 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,489 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,509 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,538 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,588 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,605 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,621 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,635 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,653 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,673 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,692 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,707 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,784 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,906 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,920 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,942 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,958 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,976 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:45,992 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,006 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,024 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,043 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,064 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,075 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,085 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,096 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,106 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,116 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,126 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,137 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,147 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,162 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,178 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,188 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,198 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,209 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,220 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,230 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,241 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,251 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,262 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,274 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,284 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,297 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,308 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,319 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,329 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,340 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,351 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,362 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,373 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,384 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,396 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,408 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,420 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,432 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,446 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,463 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,477 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,606 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:46,606 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:46,636 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:46,636 INFO ___FILE_ONLY___ ╠═ Installing: Cloud Storage Command Line Tool ═╣ + +2026-08-24 13:27:46,636 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:46,992 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,002 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,012 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,022 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,031 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,060 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,072 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,085 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,098 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,112 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,127 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,137 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,148 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,157 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,166 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,183 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,195 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,204 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,215 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,225 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,234 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,245 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,255 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,266 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,276 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,286 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,296 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,309 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,323 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,334 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,345 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,362 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,376 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,392 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,406 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,419 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,428 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,439 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,470 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,482 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,492 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,502 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,511 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,521 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,531 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,540 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,549 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,558 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,567 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,579 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,593 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,605 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,617 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,629 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,640 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,657 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,676 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,702 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,719 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,737 INFO ___FILE_ONLY___ ═ +2026-08-24 13:27:47,738 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,765 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,765 INFO ___FILE_ONLY___ ╠═ Installing: Cloud Storage Command Line Tool (Platform... ═╣ + +2026-08-24 13:27:47,765 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,766 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:47,766 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,770 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,770 INFO ___FILE_ONLY___ ╠═ Installing: Default set of gcloud commands ═╣ + +2026-08-24 13:27:47,770 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,773 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:47,774 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,775 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,775 INFO ___FILE_ONLY___ ╠═ Installing: Default set of gcloud commands (Platform ... ═╣ + +2026-08-24 13:27:47,775 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,776 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:47,776 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,781 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,781 INFO ___FILE_ONLY___ ╠═ Installing: Google Cloud CLI Core Libraries (Platform... ═╣ + +2026-08-24 13:27:47,781 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,782 INFO ___FILE_ONLY___ ══════════════════════════════ +2026-08-24 13:27:47,782 INFO ___FILE_ONLY___ ══════════════════════════════ +2026-08-24 13:27:47,782 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,788 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,788 INFO ___FILE_ONLY___ ╠═ Installing: Google Cloud CRC32C Hash Tool ═╣ + +2026-08-24 13:27:47,788 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,791 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:47,791 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,793 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,793 INFO ___FILE_ONLY___ ╠═ Installing: Google Cloud CRC32C Hash Tool (Platform S... ═╣ + +2026-08-24 13:27:47,793 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,824 INFO ___FILE_ONLY___ ══════════════════════════════ +2026-08-24 13:27:47,824 INFO ___FILE_ONLY___ ══════════════════════════════ +2026-08-24 13:27:47,824 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,830 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:47,830 INFO ___FILE_ONLY___ ╠═ Installing: gcloud cli dependencies (Platform Specific) ═╣ + +2026-08-24 13:27:47,830 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:47,831 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:47,831 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:47,836 DEBUG root Updating notification cache... +2026-08-24 13:27:47,836 INFO ___FILE_ONLY___ + +2026-08-24 13:27:47,838 INFO ___FILE_ONLY___ Performing post processing steps... +2026-08-24 13:27:47,839 DEBUG root Executing command: ['/tools/google-cloud-sdk/bin/gcloud', 'components', 'post-process'] +2026-08-24 13:27:53,016 DEBUG ___FILE_ONLY___ +2026-08-24 13:27:53,016 DEBUG ___FILE_ONLY___ +2026-08-24 13:27:53,131 INFO root descriptor_list: [{'universeDomain': 'googleapis.com', 'universeShortName': '', 'authenticationDomain': 'auth.cloud.google.com', 'projectPrefix': '', 'cloudWebDomain': 'cloud.google.com', 'documentationDomain': 'cloud.google.com', 'version': '1.0.0', 'state': 'primary', 'artifactRegistryDomain': 'pkg.dev'}] +2026-08-24 13:27:53,132 INFO ___FILE_ONLY___ +Update done! + + +2026-08-24 13:27:53,134 DEBUG root Chosen display Format:none +2026-08-24 13:27:53,135 INFO root Display format: "none" diff --git a/.config/logs/2026.08.24/13.27.48.254038.log b/.config/logs/2026.08.24/13.27.48.254038.log new file mode 100644 index 0000000000000000000000000000000000000000..b2e4a454ec418f4955c76f8f1ce1ba3c745af57d --- /dev/null +++ b/.config/logs/2026.08.24/13.27.48.254038.log @@ -0,0 +1,5 @@ +2026-08-24 13:27:48,254 DEBUG root Loaded Command Group: ['gcloud', 'components'] +2026-08-24 13:27:48,255 DEBUG root Loaded Command Group: ['gcloud', 'components', 'post_process'] +2026-08-24 13:27:48,257 DEBUG root Running [gcloud.components.post-process] with arguments: [] +2026-08-24 13:27:52,894 DEBUG root Chosen display Format:none +2026-08-24 13:27:52,894 INFO root Display format: "none" diff --git a/.config/logs/2026.08.24/13.27.53.584308.log b/.config/logs/2026.08.24/13.27.53.584308.log new file mode 100644 index 0000000000000000000000000000000000000000..cce270cb6a8f27a4bc63562f458cc7b8987087a0 --- /dev/null +++ b/.config/logs/2026.08.24/13.27.53.584308.log @@ -0,0 +1,164 @@ +2026-08-24 13:27:53,584 DEBUG root Loaded Command Group: ['gcloud', 'components'] +2026-08-24 13:27:53,611 DEBUG root Loaded Command Group: ['gcloud', 'components', 'update'] +2026-08-24 13:27:53,612 DEBUG root Running [gcloud.components.update] with arguments: [--quiet: "True", COMPONENT-IDS:8: "['gcloud', 'core', 'bq', 'gsutil', 'compute', 'preview', 'alpha', 'beta']"] +2026-08-24 13:27:53,613 DEBUG root On GCE from disk cache: False +2026-08-24 13:27:53,613 INFO ___FILE_ONLY___ Beginning update. This process may take several minutes. + +2026-08-24 13:27:53,614 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:53,616 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:53,617 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:53,628 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components-2.json HTTP/1.1" 200 28475 +2026-08-24 13:27:53,636 WARNING root Component [compute] no longer exists. +2026-08-24 13:27:53,637 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,637 INFO ___FILE_ONLY___ +Your current Google Cloud CLI version is: 581.0.0 + +2026-08-24 13:27:53,637 INFO ___FILE_ONLY___ Installing components from version: 581.0.0 + +2026-08-24 13:27:53,637 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,637 DEBUG root Chosen display Format:table[box,title="These components will be removed."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:53,638 DEBUG root Chosen display Format:table[box,title="These components will be updated."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:53,638 DEBUG root Chosen display Format:table[box,title="These components will be installed."](details.display_name:label=Name:align=left,version.version_string:label=Version:align=right,data.size.size(zero="",min=1048576):label=Size:align=right) +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ ┌────────────────────────────────────────────────┐ +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ │ These components will be installed. │ +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ ├─────────────────────────┬────────────┬─────────┤ +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,653 INFO ___FILE_ONLY___ │ Name │ Version │ Size │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ ├─────────────────────────┼────────────┼─────────┤ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ gcloud Alpha Commands +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ 2026.08.14 +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ gcloud Beta Commands +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ 2026.08.14 +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,654 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ gcloud Preview Commands +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ 2026.08.14 +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ < 1 MiB +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ │ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ └─────────────────────────┴────────────┴─────────┘ +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,655 INFO ___FILE_ONLY___ + +2026-08-24 13:27:53,656 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:53,657 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:53,658 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:53,673 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/RELEASE_NOTES HTTP/1.1" 200 399308 +2026-08-24 13:27:54,157 INFO ___FILE_ONLY___ For the latest full release notes, please visit: + https://cloud.google.com/sdk/release_notes + + +2026-08-24 13:27:54,158 INFO ___FILE_ONLY___ Performing in place update... + + +2026-08-24 13:27:54,160 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,160 INFO ___FILE_ONLY___ ╠═ Downloading: gcloud Alpha Commands ═╣ + +2026-08-24 13:27:54,160 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,161 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,162 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,162 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:54,224 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-alpha-20260814074256.tar.gz HTTP/1.1" 200 761 +2026-08-24 13:27:54,225 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,225 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,227 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,227 INFO ___FILE_ONLY___ ╠═ Downloading: gcloud Beta Commands ═╣ + +2026-08-24 13:27:54,227 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,228 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,229 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,229 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:54,239 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-beta-20260814074256.tar.gz HTTP/1.1" 200 758 +2026-08-24 13:27:54,239 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,239 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,241 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,242 INFO ___FILE_ONLY___ ╠═ Downloading: gcloud Preview Commands ═╣ + +2026-08-24 13:27:54,242 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,242 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,243 DEBUG root On GCE from memory cache: False +2026-08-24 13:27:54,244 DEBUG urllib3.connectionpool Starting new HTTPS connection (1): dl.google.com:443 +2026-08-24 13:27:54,300 DEBUG urllib3.connectionpool https://dl.google.com:443 "GET /dl/cloudsdk/channels/rapid/components/google-cloud-sdk-preview-20260814074256.tar.gz HTTP/1.1" 200 782 +2026-08-24 13:27:54,301 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,301 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,303 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,303 INFO ___FILE_ONLY___ ╠═ Installing: gcloud Alpha Commands ═╣ + +2026-08-24 13:27:54,303 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,304 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,304 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,310 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,310 INFO ___FILE_ONLY___ ╠═ Installing: gcloud Beta Commands ═╣ + +2026-08-24 13:27:54,310 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,311 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,311 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,314 INFO ___FILE_ONLY___ ╔════════════════════════════════════════════════════════════╗ + +2026-08-24 13:27:54,314 INFO ___FILE_ONLY___ ╠═ Installing: gcloud Preview Commands ═╣ + +2026-08-24 13:27:54,315 INFO ___FILE_ONLY___ ╚ +2026-08-24 13:27:54,315 INFO ___FILE_ONLY___ ════════════════════════════════════════════════════════════ +2026-08-24 13:27:54,315 INFO ___FILE_ONLY___ ╝ + +2026-08-24 13:27:54,321 DEBUG root Updating notification cache... +2026-08-24 13:27:54,321 INFO ___FILE_ONLY___ + +2026-08-24 13:27:54,323 INFO ___FILE_ONLY___ Performing post processing steps... +2026-08-24 13:27:54,324 DEBUG root Executing command: ['/tools/google-cloud-sdk/bin/gcloud', 'components', 'post-process'] +2026-08-24 13:27:59,763 DEBUG ___FILE_ONLY___ +2026-08-24 13:27:59,763 DEBUG ___FILE_ONLY___ +2026-08-24 13:27:59,844 INFO root descriptor_list: [{'universeDomain': 'googleapis.com', 'universeShortName': '', 'authenticationDomain': 'auth.cloud.google.com', 'projectPrefix': '', 'cloudWebDomain': 'cloud.google.com', 'documentationDomain': 'cloud.google.com', 'version': '1.0.0', 'state': 'primary', 'artifactRegistryDomain': 'pkg.dev'}] +2026-08-24 13:27:59,844 INFO ___FILE_ONLY___ +Update done! + + +2026-08-24 13:27:59,846 DEBUG root Chosen display Format:none +2026-08-24 13:27:59,846 INFO root Display format: "none" diff --git a/.config/logs/2026.08.24/13.27.54.687874.log b/.config/logs/2026.08.24/13.27.54.687874.log new file mode 100644 index 0000000000000000000000000000000000000000..698132a42c435e976e191ab473f660183f50016c --- /dev/null +++ b/.config/logs/2026.08.24/13.27.54.687874.log @@ -0,0 +1,5 @@ +2026-08-24 13:27:54,688 DEBUG root Loaded Command Group: ['gcloud', 'components'] +2026-08-24 13:27:54,689 DEBUG root Loaded Command Group: ['gcloud', 'components', 'post_process'] +2026-08-24 13:27:54,691 DEBUG root Running [gcloud.components.post-process] with arguments: [] +2026-08-24 13:27:59,682 DEBUG root Chosen display Format:none +2026-08-24 13:27:59,682 INFO root Display format: "none" diff --git a/.config/logs/2026.08.24/13.28.00.267545.log b/.config/logs/2026.08.24/13.28.00.267545.log new file mode 100644 index 0000000000000000000000000000000000000000..7047711555e19a93c78270ca250a5861c206dd9d --- /dev/null +++ b/.config/logs/2026.08.24/13.28.00.267545.log @@ -0,0 +1,8 @@ +2026-08-24 13:28:00,270 DEBUG root Loaded Command Group: ['gcloud', 'config'] +2026-08-24 13:28:00,340 DEBUG root Loaded Command Group: ['gcloud', 'config', 'set'] +2026-08-24 13:28:00,342 DEBUG root Running [gcloud.config.set] with arguments: [SECTION/PROPERTY: "component_manager/disable_update_check", VALUE: "true"] +2026-08-24 13:28:00,342 INFO ___FILE_ONLY___ Updated property [component_manager/disable_update_check]. + +2026-08-24 13:28:00,343 DEBUG root Chosen display Format:default +2026-08-24 13:28:00,343 INFO root Display format: "default" +2026-08-24 13:28:00,347 DEBUG root SDK update checks are disabled. diff --git a/.config/logs/2026.08.24/13.28.00.789021.log b/.config/logs/2026.08.24/13.28.00.789021.log new file mode 100644 index 0000000000000000000000000000000000000000..f389f49c4767a9d5f66202bdeffb249f7f3336df --- /dev/null +++ b/.config/logs/2026.08.24/13.28.00.789021.log @@ -0,0 +1,8 @@ +2026-08-24 13:28:00,792 DEBUG root Loaded Command Group: ['gcloud', 'config'] +2026-08-24 13:28:00,854 DEBUG root Loaded Command Group: ['gcloud', 'config', 'set'] +2026-08-24 13:28:00,856 DEBUG root Running [gcloud.config.set] with arguments: [SECTION/PROPERTY: "compute/gce_metadata_read_timeout_sec", VALUE: "0"] +2026-08-24 13:28:00,856 INFO ___FILE_ONLY___ Updated property [compute/gce_metadata_read_timeout_sec]. + +2026-08-24 13:28:00,857 DEBUG root Chosen display Format:default +2026-08-24 13:28:00,857 INFO root Display format: "default" +2026-08-24 13:28:00,861 DEBUG root SDK update checks are disabled. diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..bac1a5cac25f4a94b5cdce060be0e063fdec57fd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,16 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/base[[:space:]]model[[:space:]]image.png filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/buildings[[:space:]]ff.png filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/buildings.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/distilled[[:space:]]image.png filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/dubit_input.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/hdr_input_video.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/ingredients_input.jpg filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/inpainting_input.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/instant_shave_input.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/motion_track_input.jpg filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/outpainting_input.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/example_workflows/assets/spatial_upscale_4x_input.mp4 filter=lfs diff=lfs merge=lfs -text +1/custom_nodes/ComfyUI-LTXVideo/gemma_configs/tokenizer.json filter=lfs diff=lfs merge=lfs -text diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/.github/workflows/publish.yml b/1/custom_nodes/ComfyUI-Custom-Scripts/.github/workflows/publish.yml new file mode 100644 index 0000000000000000000000000000000000000000..c9c70bf7f47b9e294ac2436b8fe2a2b8878bc106 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/.github/workflows/publish.yml @@ -0,0 +1,25 @@ +name: Publish to Comfy registry +on: + workflow_dispatch: + push: + branches: + - main + paths: + - "pyproject.toml" + +permissions: + issues: write + +jobs: + publish-node: + name: Publish Custom Node to registry + runs-on: ubuntu-latest + if: ${{ github.repository_owner == 'pythongosssss' }} + steps: + - name: Check out code + uses: actions/checkout@v4 + - name: Publish Custom Node + uses: Comfy-Org/publish-node-action@v1 + with: + ## Add your own personal access token to your Github Repository secrets and reference it here. + personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/.gitignore b/1/custom_nodes/ComfyUI-Custom-Scripts/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..8d303a4effdf5bf2a332042b2cb31a77589ab333 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/.gitignore @@ -0,0 +1,5 @@ +__pycache__ +pysssss.json +user/autocomplete.txt +web/js/assets/favicon.user.ico +web/js/assets/favicon-active.user.ico \ No newline at end of file diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/LICENSE b/1/custom_nodes/ComfyUI-Custom-Scripts/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..acf31806a2507192169eca2137ea9ceb7685f51c --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 pythongosssss + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/README.md b/1/custom_nodes/ComfyUI-Custom-Scripts/README.md new file mode 100644 index 0000000000000000000000000000000000000000..690bfe1c46018bdd63385abf77a58d226388623f --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/README.md @@ -0,0 +1,160 @@ +# ComfyUI-Custom-Scripts + +### ⚠️ While these extensions work for the most part, i'm very busy at the moment and so unable to keep on top of everything here, thanks for your patience! + +# Installation + +1. Clone the repository: +`git clone https://github.com/pythongosssss/ComfyUI-Custom-Scripts.git` +to your ComfyUI `custom_nodes` directory + + The script will then automatically install all custom scripts and nodes. + It will attempt to use symlinks and junctions to prevent having to copy files and keep them up to date. + +- For uninstallation: + - Delete the cloned repo in `custom_nodes` + - Ensure `web/extensions/pysssss/CustomScripts` has also been removed + +# Update +1. Navigate to the cloned repo e.g. `custom_nodes/ComfyUI-Custom-Scripts` +2. `git pull` + +# Features + +## Autocomplete +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/b5971135-414f-4f4e-a6cf-2650dc01085f) +Provides embedding and custom word autocomplete. You can view embedding details by clicking on the info icon on the list. +Define your list of custom words via the settings. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/160ef61c-7d7e-49d0-b60f-5a1501b74c9d) +You can quickly default to danbooru tags using the Load button, or load/manage other custom word lists. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/cc180b35-5f45-442f-9285-3ddf3fa320d0) + +## Auto Arrange Graph +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/04b06081-ca6f-4c0f-8584-d0a157c36747) +Adds a menu option to auto arrange the graph in order of execution, this makes very wide graphs! + +## Always Snap to Grid +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/66f36d1f-e579-4959-9880-9a9624922e3a) +Adds a setting to make moving nodes always snap to grid. + +## [Testing] "Better" Loader Lists +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/664caa71-f25f-4a96-a04a-1466d6b2b8b4) +Adds custom Lora and Checkpoint loader nodes, these have the ability to show preview images, just place a png or jpg next to the file and it'll display in the list on hover (e.g. sdxl.safetensors and sdxl.png). +Optionally enable subfolders via the settings: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/e15b5e83-4f9d-4d57-8324-742bedf75439) +Adds an "examples" widget to load sample prompts, triggerwords, etc: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ad1751e4-4c85-42e7-9490-e94fb1cbc8e7) +These should be stored in a folder matching the name of the model, e.g. if it is `loras/add_detail.safetensors` put your files in as `loras/add_detail/*.txt` +To quickly save a generated image as the preview to use for the model, you can right click on an image on a node, and select Save as Preview and choose the model to save the preview for: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/9fa8e9db-27b3-45cb-85c2-0860a238fd3a) + +## Checkpoint/LoRA/Embedding Info +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/6b67bf40-ee17-4fa6-a0c1-7947066bafc2) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/32405df6-b367-404f-a5df-2d4347089a9e) +Adds "View Info" menu option to view details about the selected LoRA or Checkpoint. To view embedding details, click the info button when using embedding autocomplete. + +## Constrain Image +Adds a node for resizing an image to a max & min size optionally cropping if required. + +## Custom Colors +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/fa7883f3-f81c-49f6-9ab6-9526e4debab6) +Adds a custom color picker to nodes & groups + +## Favicon Status +![image](https://user-images.githubusercontent.com/125205205/230171227-31f061a6-6324-4976-bed9-723a87500cf3.png) +![image](https://user-images.githubusercontent.com/125205205/230171445-c7202a45-b511-4d69-87fa-945ad44c063f.png) +Adds a favicon and title to the window, favicon changes color while generating and the window title includes the number of prompts in the queue + +## Image Feed +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/caea0d48-85b9-4ca9-9771-5c795db35fbc) +Adds a panel showing images that have been generated in the current session, you can control the direction that images are added and the position of the panel via the ComfyUI settings screen and the size of the panel and the images via the sliders at the top of the panel. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ca093d38-41a3-4647-9223-5bd0b9ee4f1e) + +## KSampler (Advanced) denoise helper +Provides a simple method to set custom denoise on the advanced sampler +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/42946bd8-0078-4c7a-bfe9-7adb1382b5e2) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7cfccb22-f155-4848-934b-a2b2a6efe16f) + +## Math Expression +Allows for evaluating complex expressions using values from the graph. You can input `INT`, `FLOAT`, `IMAGE` and `LATENT` values. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/1593edde-67b8-45d8-88cb-e75f52dba039) +Other nodes values can be referenced via the `Node name for S&R` via the `Properties` menu item on a node, or the node title. +Supported operators: `+ - * /` (basic ops) `//` (floor division) `**` (power) `^` (xor) `%` (mod) +Supported functions `floor(num, dp?)` `floor(num)` `ceil(num)` `randomint(min,max)` +If using a `LATENT` or `IMAGE` you can get the dimensions using `a.width` or `a.height` where `a` is the input name. + +## Node Finder +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/177d2b67-acbc-4ec3-ab31-7c295a98c194) +Adds a menu item for following/jumping to the executing node, and a menu to quickly go to a node of a specific type. + +## Preset Text +![image](https://user-images.githubusercontent.com/125205205/230173939-08459efc-785b-46da-93d1-b02f0300c6f4.png) +Adds a node that lets you save and use text presets (e.g. for your 'normal' negatives) + +## Quick Nodes +![image](https://user-images.githubusercontent.com/125205205/230174266-5232831a-a03b-4bf7-bc8b-c45466a0bc64.png) +Adds various menu items to some nodes for quickly setting up common parts of graphs + +## Play Sound +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/9bcf9fb3-5898-4432-a974-fb1e17d3b7e8) +Plays a sound when the node is executed, either after each prompt or only when the queue is empty for queuing multiple prompts. +You can customize the sound by replacing the mp3 file `ComfyUI/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/notify.mp3` + +## System Notification +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/30354775/993fd783-5cd6-4779-aa97-173bc06cc405) +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/30354775/e45227fb-5714-4f45-b96b-6601902ef6e2) + +Sends a system notification via the browser when the node is executed, either after each prompt or only when the queue is empty for queuing multiple prompts. + +## [WIP] Repeater +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/ec0dac25-14e4-4d44-b975-52193656709d) +Node allows you to either create a list of N repeats of the input node, or create N outputs from the input node. +You can optionally decide if you want to reuse the input node, or create a new instance each time (e.g. a Checkpoint Loader would want to be re-used, but a random number would want to be unique) +TODO: Type safety on the wildcard outputs to require match with input + +## Show Text +![image](https://user-images.githubusercontent.com/125205205/230174888-c004fd48-da78-4de9-81c2-93a866fcfcd1.png) +Takes input from a node that produces a string and displays it, useful for things like interrogator, prompt generators, etc. + +## Show Image on Menu +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/b6ab58f2-583b-448c-bcfc-f93f5cdab0fc) +Shows the current generating image on the menu at the bottom, you can disable this via the settings menu. + +## String Function +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/01107137-8a93-4765-bae0-fcc110a09091) +Supports appending and replacing text +`tidy_tags` will add commas between parts when in `append` mode. +`replace` mode supports regex replace by using `/your regex here/` and you can reference capturing groups using `\number` e.g. `\1` + +## Touch Support +Provides basic support for touch screen devices, its not perfect but better than nothing + +## Widget Defaults +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/3d675032-2b19-4da8-a7d7-fa2d7c555daa) +Allows you to specify default values for widgets when adding new nodes, the values are configured via the settings menu +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7b57a3d8-98d3-46e9-9b33-6645c0da41e7) + +## Workflows +Adds options to the menu for saving + loading workflows: +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/7b5a3012-4c59-47c6-8eea-85cf534403ea) + +## Workflow Images +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/06453fd2-c020-46ee-a7db-2b8bf5bcba7e) +Adds menu options for importing/exporting the graph as SVG and PNG showing a view of the nodes + +## (Testing) Reroute Primitive +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/8b870eef-d572-43f9-b394-cfa7abbd2f98) Provides a node that allows rerouting primitives. +The node can also be collapsed to a single point that you can drag around. +![image](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/assets/125205205/a9bd0112-cf8f-44f3-af6d-f9a8fed152a7) +Warning: Don't use normal reroutes or primitives with these nodes, it isn't tested and this node replaces their functionality. + +
+
+ + +## WD14 Tagger +Moved to: https://github.com/pythongosssss/ComfyUI-WD14-Tagger + +## ~~Lock Nodes & Groups~~ +This is now a standard feature of ComfyUI +~~Adds a lock option to nodes & groups that prevents you from moving them until unlocked~~ diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/__init__.py b/1/custom_nodes/ComfyUI-Custom-Scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ae43dd2090ce782074bf72f2b7f49ad28dff1a5c --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/__init__.py @@ -0,0 +1,25 @@ +import importlib.util +import glob +import os +import sys +from .pysssss import init, get_ext_dir + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + +if init(): + py = get_ext_dir("py") + files = glob.glob(os.path.join(py, "*.py"), recursive=False) + for file in files: + name = os.path.splitext(file)[0] + spec = importlib.util.spec_from_file_location(name, file) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: + NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS) + if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None: + NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS) + +WEB_DIRECTORY = "./web" +__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/autocomplete.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/autocomplete.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac6a0524823d13849b6cbe02efedc7bffea8f38 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/autocomplete.py @@ -0,0 +1,29 @@ +from server import PromptServer +from aiohttp import web +import os +import folder_paths + +dir = os.path.abspath(os.path.join(__file__, "../../user")) +if not os.path.exists(dir): + os.mkdir(dir) +file = os.path.join(dir, "autocomplete.txt") + + +@PromptServer.instance.routes.get("/pysssss/autocomplete") +async def get_autocomplete(request): + if os.path.isfile(file): + return web.FileResponse(file) + return web.Response(status=404) + + +@PromptServer.instance.routes.post("/pysssss/autocomplete") +async def update_autocomplete(request): + with open(file, "w", encoding="utf-8") as f: + f.write(await request.text()) + return web.Response(status=200) + + +@PromptServer.instance.routes.get("/pysssss/loras") +async def get_loras(request): + loras = folder_paths.get_filename_list("loras") + return web.json_response(list(map(lambda a: os.path.splitext(a)[0], loras))) diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/better_combos.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/better_combos.py new file mode 100644 index 0000000000000000000000000000000000000000..d31043b0afdb8943409f3d97adbdde2db9dc38ee --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/better_combos.py @@ -0,0 +1,172 @@ +import glob +import os +from nodes import LoraLoader, CheckpointLoaderSimple +import folder_paths +from server import PromptServer +from folder_paths import get_directory_by_type +from aiohttp import web +import shutil + + +@PromptServer.instance.routes.get("/pysssss/view/{name}") +async def view(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + image_path = folder_paths.get_full_path( + type, name) + if not image_path: + return web.Response(status=404) + + filename = os.path.basename(image_path) + return web.FileResponse(image_path, headers={"Content-Disposition": f"filename=\"{filename}\""}) + + +@PromptServer.instance.routes.post("/pysssss/save/{name}") +async def save_preview(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + body = await request.json() + + dir = get_directory_by_type(body.get("type", "output")) + subfolder = body.get("subfolder", "") + full_output_folder = os.path.join(dir, os.path.normpath(subfolder)) + + filepath = os.path.join(full_output_folder, body.get("filename", "")) + + if os.path.commonpath((dir, os.path.abspath(filepath))) != dir: + return web.Response(status=400) + + image_path = folder_paths.get_full_path(type, name) + image_path = os.path.splitext( + image_path)[0] + os.path.splitext(filepath)[1] + + shutil.copyfile(filepath, image_path) + + return web.json_response({ + "image": type + "/" + os.path.basename(image_path) + }) + + +@PromptServer.instance.routes.get("/pysssss/examples/{name}") +async def get_examples(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + file_path_no_ext = os.path.splitext(file_path)[0] + examples = [] + + if os.path.isdir(file_path_no_ext): + examples += sorted(map(lambda t: os.path.relpath(t, file_path_no_ext), + glob.glob(file_path_no_ext + "/*.txt"))) + + if os.path.isfile(file_path_no_ext + ".txt"): + examples += ["notes"] + + return web.json_response(examples) + + +@PromptServer.instance.routes.post("/pysssss/examples/{name}") +async def save_example(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + body = await request.json() + example_name = body["name"] + example = body["example"] + + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + if not example_name.endswith(".txt"): + example_name += ".txt" + + file_path_no_ext = os.path.splitext(file_path)[0] + example_file = os.path.join(file_path_no_ext, example_name) + if not os.path.exists(file_path_no_ext): + os.mkdir(file_path_no_ext) + with open(example_file, 'w', encoding='utf8') as f: + f.write(example) + + return web.Response(status=201) + + +@PromptServer.instance.routes.get("/pysssss/images/{type}") +async def get_images(request): + type = request.match_info["type"] + names = folder_paths.get_filename_list(type) + + images = {} + for item_name in names: + file_name = os.path.splitext(item_name)[0] + file_path = folder_paths.get_full_path(type, item_name) + + if file_path is None: + continue + + file_path_no_ext = os.path.splitext(file_path)[0] + + for ext in ["png", "jpg", "jpeg", "preview.png", "preview.jpeg"]: + if os.path.isfile(file_path_no_ext + "." + ext): + images[item_name] = f"{type}/{file_name}.{ext}" + break + + return web.json_response(images) + + +class LoraLoaderWithImages(LoraLoader): + RETURN_TYPES = (*LoraLoader.RETURN_TYPES, "STRING",) + RETURN_NAMES = (*getattr(LoraLoader, "RETURN_NAMES", + LoraLoader.RETURN_TYPES), "example") + + @classmethod + def INPUT_TYPES(s): + types = super().INPUT_TYPES() + types["optional"] = {"prompt": ("STRING", {"hidden": True})} + return types + + def load_lora(self, **kwargs): + prompt = kwargs.pop("prompt", "") + return (*super().load_lora(**kwargs), prompt) + + +class CheckpointLoaderSimpleWithImages(CheckpointLoaderSimple): + RETURN_TYPES = (*CheckpointLoaderSimple.RETURN_TYPES, "STRING",) + RETURN_NAMES = (*getattr(CheckpointLoaderSimple, "RETURN_NAMES", + CheckpointLoaderSimple.RETURN_TYPES), "example") + + @classmethod + def INPUT_TYPES(s): + types = super().INPUT_TYPES() + types["optional"] = {"prompt": ("STRING", {"hidden": True})} + return types + + def load_checkpoint(self, **kwargs): + prompt = kwargs.pop("prompt", "") + return (*super().load_checkpoint(**kwargs), prompt) + + +NODE_CLASS_MAPPINGS = { + "LoraLoader|pysssss": LoraLoaderWithImages, + "CheckpointLoader|pysssss": CheckpointLoaderSimpleWithImages, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LoraLoader|pysssss": "Lora Loader 🐍", + "CheckpointLoader|pysssss": "Checkpoint Loader 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image.py new file mode 100644 index 0000000000000000000000000000000000000000..1c768893c5ed5c1cb1247bca77414dc8762d3fde --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image.py @@ -0,0 +1,71 @@ +import torch +import numpy as np +from PIL import Image + +class ConstrainImage: + """ + A node that constrains an image to a maximum and minimum size while maintaining aspect ratio. + """ + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "max_width": ("INT", {"default": 1024, "min": 0}), + "max_height": ("INT", {"default": 1024, "min": 0}), + "min_width": ("INT", {"default": 0, "min": 0}), + "min_height": ("INT", {"default": 0, "min": 0}), + "crop_if_required": (["yes", "no"], {"default": "no"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "constrain_image" + CATEGORY = "image" + OUTPUT_IS_LIST = (True,) + + def constrain_image(self, images, max_width, max_height, min_width, min_height, crop_if_required): + crop_if_required = crop_if_required == "yes" + results = [] + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)).convert("RGB") + + current_width, current_height = img.size + aspect_ratio = current_width / current_height + + constrained_width = min(max(current_width, min_width), max_width) + constrained_height = min(max(current_height, min_height), max_height) + + if constrained_width / constrained_height > aspect_ratio: + constrained_width = max(int(constrained_height * aspect_ratio), min_width) + if crop_if_required: + constrained_height = int(current_height / (current_width / constrained_width)) + else: + constrained_height = max(int(constrained_width / aspect_ratio), min_height) + if crop_if_required: + constrained_width = int(current_width / (current_height / constrained_height)) + + resized_image = img.resize((constrained_width, constrained_height), Image.LANCZOS) + + if crop_if_required and (constrained_width > max_width or constrained_height > max_height): + left = max((constrained_width - max_width) // 2, 0) + top = max((constrained_height - max_height) // 2, 0) + right = min(constrained_width, max_width) + left + bottom = min(constrained_height, max_height) + top + resized_image = resized_image.crop((left, top, right, bottom)) + + resized_image = np.array(resized_image).astype(np.float32) / 255.0 + resized_image = torch.from_numpy(resized_image)[None,] + results.append(resized_image) + + return (results,) + +NODE_CLASS_MAPPINGS = { + "ConstrainImage|pysssss": ConstrainImage, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ConstrainImage|pysssss": "Constrain Image 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image_for_video.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image_for_video.py new file mode 100644 index 0000000000000000000000000000000000000000..91c0c502b8d8f6202d96a26b045e393b4552fc8e --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/constrain_image_for_video.py @@ -0,0 +1,72 @@ +import torch +import numpy as np +from PIL import Image + +class ConstrainImageforVideo: + """ + A node that constrains an image to a maximum and minimum size while maintaining aspect ratio. + """ + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "images": ("IMAGE",), + "max_width": ("INT", {"default": 1024, "min": 0}), + "max_height": ("INT", {"default": 1024, "min": 0}), + "min_width": ("INT", {"default": 0, "min": 0}), + "min_height": ("INT", {"default": 0, "min": 0}), + "crop_if_required": (["yes", "no"], {"default": "no"}), + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("IMAGE",) + FUNCTION = "constrain_image_for_video" + CATEGORY = "image" + + def constrain_image_for_video(self, images, max_width, max_height, min_width, min_height, crop_if_required): + crop_if_required = crop_if_required == "yes" + results = [] + for image in images: + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)).convert("RGB") + + current_width, current_height = img.size + aspect_ratio = current_width / current_height + + constrained_width = max(min(current_width, min_width), max_width) + constrained_height = max(min(current_height, min_height), max_height) + + if constrained_width / constrained_height > aspect_ratio: + constrained_width = max(int(constrained_height * aspect_ratio), min_width) + if crop_if_required: + constrained_height = int(current_height / (current_width / constrained_width)) + else: + constrained_height = max(int(constrained_width / aspect_ratio), min_height) + if crop_if_required: + constrained_width = int(current_width / (current_height / constrained_height)) + + resized_image = img.resize((constrained_width, constrained_height), Image.LANCZOS) + + if crop_if_required and (constrained_width > max_width or constrained_height > max_height): + left = max((constrained_width - max_width) // 2, 0) + top = max((constrained_height - max_height) // 2, 0) + right = min(constrained_width, max_width) + left + bottom = min(constrained_height, max_height) + top + resized_image = resized_image.crop((left, top, right, bottom)) + + resized_image = np.array(resized_image).astype(np.float32) / 255.0 + resized_image = torch.from_numpy(resized_image)[None,] + results.append(resized_image) + all_images = torch.cat(results, dim=0) + + return (all_images, all_images.size(0),) + +NODE_CLASS_MAPPINGS = { + "ConstrainImageforVideo|pysssss": ConstrainImageforVideo, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ConstrainImageforVideo|pysssss": "Constrain Image for Video 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/math_expression.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/math_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..4a41655b6876a077338040b0099c4d4e8c9dbcd2 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/math_expression.py @@ -0,0 +1,252 @@ +import ast +import math +import random +import operator as op + +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + +operators = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.truediv, + ast.FloorDiv: op.floordiv, + ast.Pow: op.pow, + ast.BitXor: op.xor, + ast.USub: op.neg, + ast.Mod: op.mod, + ast.BitAnd: op.and_, + ast.BitOr: op.or_, + ast.Invert: op.invert, + ast.And: lambda a, b: 1 if a and b else 0, + ast.Or: lambda a, b: 1 if a or b else 0, + ast.Not: lambda a: 0 if a else 1, + ast.RShift: op.rshift, + ast.LShift: op.lshift +} + +# TODO: restructure args to provide more info, generate hint based on args to save duplication +functions = { + "round": { + "args": (1, 2), + "call": lambda a, b = None: round(a, b), + "hint": "number, dp? = 0" + }, + "ceil": { + "args": (1, 1), + "call": lambda a: math.ceil(a), + "hint": "number" + }, + "floor": { + "args": (1, 1), + "call": lambda a: math.floor(a), + "hint": "number" + }, + "min": { + "args": (2, None), + "call": lambda *args: min(*args), + "hint": "...numbers" + }, + "max": { + "args": (2, None), + "call": lambda *args: max(*args), + "hint": "...numbers" + }, + "randomint": { + "args": (2, 2), + "call": lambda a, b: random.randint(a, b), + "hint": "min, max" + }, + "randomchoice": { + "args": (2, None), + "call": lambda *args: random.choice(args), + "hint": "...numbers" + }, + "sqrt": { + "args": (1, 1), + "call": lambda a: math.sqrt(a), + "hint": "number" + }, + "int": { + "args": (1, 1), + "call": lambda a = None: int(a), + "hint": "number" + }, + "iif": { + "args": (3, 3), + "call": lambda a, b, c = None: b if a else c, + "hint": "value, truepart, falsepart" + }, +} + +autocompleteWords = list({ + "text": x, + "value": f"{x}()", + "showValue": False, + "hint": f"{functions[x]['hint']}", + "caretOffset": -1 +} for x in functions.keys()) + + +class MathExpression: + + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "expression": ("STRING", {"multiline": True, "dynamicPrompts": False, "pysssss.autocomplete": { + "words": autocompleteWords, + "separator": "" + }}), + }, + "optional": { + "a": (any, ), + "b": (any,), + "c": (any, ), + }, + "hidden": {"extra_pnginfo": "EXTRA_PNGINFO", + "prompt": "PROMPT"}, + } + + RETURN_TYPES = ("INT", "FLOAT", ) + FUNCTION = "evaluate" + CATEGORY = "utils" + OUTPUT_NODE = True + + @classmethod + def IS_CHANGED(s, expression, **kwargs): + if "random" in expression: + return float("nan") + return expression + + def get_widget_value(self, extra_pnginfo, prompt, node_name, widget_name): + workflow = extra_pnginfo["workflow"] if "workflow" in extra_pnginfo else { "nodes": [] } + node_id = None + for node in workflow["nodes"]: + name = node["type"] + if "properties" in node: + if "Node name for S&R" in node["properties"]: + name = node["properties"]["Node name for S&R"] + if name == node_name: + node_id = node["id"] + break + if "title" in node: + name = node["title"] + if name == node_name: + node_id = node["id"] + break + if node_id is not None: + values = prompt[str(node_id)] + if "inputs" in values: + if widget_name in values["inputs"]: + value = values["inputs"][widget_name] + if isinstance(value, list): + raise ValueError("Converted widgets are not supported via named reference, use the inputs instead.") + return value + raise NameError(f"Widget not found: {node_name}.{widget_name}") + raise NameError(f"Node not found: {node_name}.{widget_name}") + + def get_size(self, target, property): + if isinstance(target, dict) and "samples" in target: + # Latent + if property == "width": + return target["samples"].shape[3] * 8 + return target["samples"].shape[2] * 8 + else: + # Image + if property == "width": + return target.shape[2] + return target.shape[1] + + def evaluate(self, expression, prompt, extra_pnginfo={}, a=None, b=None, c=None): + expression = expression.replace('\n', ' ').replace('\r', '') + node = ast.parse(expression, mode='eval').body + + lookup = {"a": a, "b": b, "c": c} + + def eval_op(node, l, r): + l = eval_expr(l) + r = eval_expr(r) + l = l if isinstance(l, int) else float(l) + r = r if isinstance(r, int) else float(r) + return operators[type(node.op)](l, r) + + def eval_expr(node): + if isinstance(node, ast.Constant) or isinstance(node, ast.Num): + return node.n + elif isinstance(node, ast.BinOp): + return eval_op(node, node.left, node.right) + elif isinstance(node, ast.BoolOp): + return eval_op(node, node.values[0], node.values[1]) + elif isinstance(node, ast.UnaryOp): + return operators[type(node.op)](eval_expr(node.operand)) + elif isinstance(node, ast.Attribute): + if node.value.id in lookup: + if node.attr == "width" or node.attr == "height": + return self.get_size(lookup[node.value.id], node.attr) + + return self.get_widget_value(extra_pnginfo, prompt, node.value.id, node.attr) + elif isinstance(node, ast.Name): + if node.id in lookup: + val = lookup[node.id] + if isinstance(val, (int, float, complex)): + return val + else: + raise TypeError( + f"Compex types (LATENT/IMAGE) need to reference their width/height, e.g. {node.id}.width") + raise NameError(f"Name not found: {node.id}") + elif isinstance(node, ast.Call): + if node.func.id in functions: + fn = functions[node.func.id] + l = len(node.args) + if l < fn["args"][0] or (fn["args"][1] is not None and l > fn["args"][1]): + if fn["args"][1] is None: + toErr = " or more" + else: + toErr = f" to {fn['args'][1]}" + raise SyntaxError( + f"Invalid function call: {node.func.id} requires {fn['args'][0]}{toErr} arguments") + args = [] + for arg in node.args: + args.append(eval_expr(arg)) + return fn["call"](*args) + raise NameError(f"Invalid function call: {node.func.id}") + elif isinstance(node, ast.Compare): + l = eval_expr(node.left) + r = eval_expr(node.comparators[0]) + if isinstance(node.ops[0], ast.Eq): + return 1 if l == r else 0 + if isinstance(node.ops[0], ast.NotEq): + return 1 if l != r else 0 + if isinstance(node.ops[0], ast.Gt): + return 1 if l > r else 0 + if isinstance(node.ops[0], ast.GtE): + return 1 if l >= r else 0 + if isinstance(node.ops[0], ast.Lt): + return 1 if l < r else 0 + if isinstance(node.ops[0], ast.LtE): + return 1 if l <= r else 0 + raise NotImplementedError( + "Operator " + node.ops[0].__class__.__name__ + " not supported.") + else: + raise TypeError(node) + + r = eval_expr(node) + return {"ui": {"value": [r]}, "result": (int(r), float(r),)} + + +NODE_CLASS_MAPPINGS = { + "MathExpression|pysssss": MathExpression, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "MathExpression|pysssss": "Math Expression 🐍", +} + diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/model_info.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/model_info.py new file mode 100644 index 0000000000000000000000000000000000000000..b360bafb35fdfc25dd94902076fab6baa39ee23c --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/model_info.py @@ -0,0 +1,115 @@ +import hashlib +import json +from aiohttp import web +from server import PromptServer +import folder_paths +import os + + +def get_metadata(filepath): + with open(filepath, "rb") as file: + # https://github.com/huggingface/safetensors#format + # 8 bytes: N, an unsigned little-endian 64-bit integer, containing the size of the header + header_size = int.from_bytes(file.read(8), "little", signed=False) + + if header_size <= 0: + raise BufferError("Invalid header size") + + header = file.read(header_size) + if header_size <= 0: + raise BufferError("Invalid header") + + header_json = json.loads(header) + return header_json["__metadata__"] if "__metadata__" in header_json else None + + +@PromptServer.instance.routes.post("/pysssss/metadata/notes/{name}") +async def save_notes(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = None + if type == "embeddings" or type == "loras": + name = name.lower() + files = folder_paths.get_filename_list(type) + for f in files: + lower_f = f.lower() + if lower_f == name: + file_path = folder_paths.get_full_path(type, f) + else: + n = os.path.splitext(f)[0].lower() + if n == name: + file_path = folder_paths.get_full_path(type, f) + + if file_path is not None: + break + else: + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + file_no_ext = os.path.splitext(file_path)[0] + info_file = file_no_ext + ".txt" + with open(info_file, "w") as f: + f.write(await request.text()) + + return web.Response(status=200) + + +@PromptServer.instance.routes.get("/pysssss/metadata/{name}") +async def load_metadata(request): + name = request.match_info["name"] + pos = name.index("/") + type = name[0:pos] + name = name[pos+1:] + + file_path = None + if type == "embeddings" or type == "loras": + name = name.lower() + files = folder_paths.get_filename_list(type) + for f in files: + lower_f = f.lower() + if lower_f == name: + file_path = folder_paths.get_full_path(type, f) + else: + n = os.path.splitext(f)[0].lower() + if n == name: + file_path = folder_paths.get_full_path(type, f) + + if file_path is not None: + break + else: + file_path = folder_paths.get_full_path( + type, name) + if not file_path: + return web.Response(status=404) + + try: + meta = get_metadata(file_path) + except: + meta = None + + if meta is None: + meta = {} + + file_no_ext = os.path.splitext(file_path)[0] + + info_file = file_no_ext + ".txt" + if os.path.isfile(info_file): + with open(info_file, "r") as f: + meta["pysssss.notes"] = f.read() + + hash_file = file_no_ext + ".sha256" + if os.path.isfile(hash_file): + with open(hash_file, "rt") as f: + meta["pysssss.sha256"] = f.read() + else: + with open(file_path, "rb") as f: + meta["pysssss.sha256"] = hashlib.sha256(f.read()).hexdigest() + with open(hash_file, "wt") as f: + f.write(meta["pysssss.sha256"]) + + return web.json_response(meta) diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/play_sound.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/play_sound.py new file mode 100644 index 0000000000000000000000000000000000000000..65f599d2680553a20031d81d1fdf161d73edefef --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/play_sound.py @@ -0,0 +1,42 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class PlaySound: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "any": (any, {}), + "mode": (["always", "on empty queue"], {}), + "volume": ("FLOAT", {"min": 0, "max": 1, "step": 0.1, "default": 0.5}), + "file": ("STRING", { "default": "notify.mp3" }) + }} + + FUNCTION = "nop" + INPUT_IS_LIST = True + OUTPUT_IS_LIST = (True,) + OUTPUT_NODE = True + RETURN_TYPES = (any,) + + CATEGORY = "utils" + + def IS_CHANGED(self, **kwargs): + return float("NaN") + + def nop(self, any, mode, volume, file): + return {"ui": {"a": []}, "result": (any,)} + + +NODE_CLASS_MAPPINGS = { + "PlaySound|pysssss": PlaySound, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "PlaySound|pysssss": "PlaySound 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/repeater.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/repeater.py new file mode 100644 index 0000000000000000000000000000000000000000..1d83c67e2132b9db708ef087ad788d22c58c80c2 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/repeater.py @@ -0,0 +1,46 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class Repeater: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "source": (any, {}), + "repeats": ("INT", {"min": 0, "max": 5000, "default": 2}), + "output": (["single", "multi"], {}), + "node_mode": (["reuse", "create"], {}), + }} + + RETURN_TYPES = (any,) + FUNCTION = "repeat" + OUTPUT_NODE = False + OUTPUT_IS_LIST = (True,) + + CATEGORY = "utils" + + def repeat(self, repeats, output, node_mode, **kwargs): + if output == "multi": + # Multi outputs are split to indiviual nodes on the frontend when serializing + return ([kwargs["source"]],) + elif node_mode == "reuse": + # When reusing we have a single input node, repeat that N times + return ([kwargs["source"]] * repeats,) + else: + # When creating new nodes, they'll be added dynamically when the graph is serialized + return ((list(kwargs.values())),) + + +NODE_CLASS_MAPPINGS = { + "Repeater|pysssss": Repeater, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "Repeater|pysssss": "Repeater 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/reroute_primitive.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/reroute_primitive.py new file mode 100644 index 0000000000000000000000000000000000000000..c22a7d1ef00eddfbde6185e702b6c3462521ccda --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/reroute_primitive.py @@ -0,0 +1,59 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class ReroutePrimitive: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {"value": (any, )}, + } + + @classmethod + def VALIDATE_INPUTS(s, **kwargs): + return True + + RETURN_TYPES = (any,) + FUNCTION = "route" + CATEGORY = "__hidden__" + + def route(self, value): + return (value,) + + +class MultiPrimitive: + @classmethod + def INPUT_TYPES(cls): + return { + "required": {}, + "optional": {"value": (any, )}, + } + + @classmethod + def VALIDATE_INPUTS(s, **kwargs): + return True + + RETURN_TYPES = (any,) + FUNCTION = "listify" + CATEGORY = "utils" + OUTPUT_IS_LIST = (True,) + + def listify(self, **kwargs): + return (list(kwargs.values()),) + + +NODE_CLASS_MAPPINGS = { + "ReroutePrimitive|pysssss": ReroutePrimitive, + # "MultiPrimitive|pysssss": MultiPrimitive, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ReroutePrimitive|pysssss": "Reroute Primitive 🐍", + # "MultiPrimitive|pysssss": "Multi Primitive 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/show_text.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/show_text.py new file mode 100644 index 0000000000000000000000000000000000000000..5a013a5bc7a82e29f38f35ff85dab827ba42a254 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/show_text.py @@ -0,0 +1,49 @@ +class ShowText: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "text": ("STRING", {"forceInput": True}), + }, + "hidden": { + "unique_id": "UNIQUE_ID", + "extra_pnginfo": "EXTRA_PNGINFO", + }, + } + + INPUT_IS_LIST = True + RETURN_TYPES = ("STRING",) + FUNCTION = "notify" + OUTPUT_NODE = True + OUTPUT_IS_LIST = (True,) + + CATEGORY = "utils" + + def notify(self, text, unique_id=None, extra_pnginfo=None): + if unique_id is not None and extra_pnginfo is not None: + if not isinstance(extra_pnginfo, list): + print("Error: extra_pnginfo is not a list") + elif ( + not isinstance(extra_pnginfo[0], dict) + or "workflow" not in extra_pnginfo[0] + ): + print("Error: extra_pnginfo[0] is not a dict or missing 'workflow' key") + else: + workflow = extra_pnginfo[0]["workflow"] + node = next( + (x for x in workflow["nodes"] if str(x["id"]) == str(unique_id[0])), + None, + ) + if node: + node["widgets_values"] = [text] + + return {"ui": {"text": text}, "result": (text,)} + + +NODE_CLASS_MAPPINGS = { + "ShowText|pysssss": ShowText, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "ShowText|pysssss": "Show Text 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/string_function.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/string_function.py new file mode 100644 index 0000000000000000000000000000000000000000..f502ba31f52720f019c9f1d155d17a9cb9e335f9 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/string_function.py @@ -0,0 +1,49 @@ +import re + +class StringFunction: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "action": (["append", "replace"], {}), + "tidy_tags": (["yes", "no"], {}), + }, + "optional": { + "text_a": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "text_b": ("STRING", {"multiline": True, "dynamicPrompts": False}), + "text_c": ("STRING", {"multiline": True, "dynamicPrompts": False}) + } + } + + RETURN_TYPES = ("STRING",) + FUNCTION = "exec" + CATEGORY = "utils" + OUTPUT_NODE = True + + def exec(self, action, tidy_tags, text_a="", text_b="", text_c=""): + tidy_tags = tidy_tags == "yes" + out = "" + if action == "append": + out = (", " if tidy_tags else "").join(filter(None, [text_a, text_b, text_c])) + else: + if text_c is None: + text_c = "" + if text_b.startswith("/") and text_b.endswith("/"): + regex = text_b[1:-1] + out = re.sub(regex, text_c, text_a) + else: + out = text_a.replace(text_b, text_c) + if tidy_tags: + out = re.sub(r"\s{2,}", " ", out) + out = out.replace(" ,", ",") + out = re.sub(r",{2,}", ",", out) + out = out.strip() + return {"ui": {"text": (out,)}, "result": (out,)} + +NODE_CLASS_MAPPINGS = { + "StringFunction|pysssss": StringFunction, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "StringFunction|pysssss": "String Function 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/system_notification.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/system_notification.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a52c14773ff86bbb3b29c6405a05238d8b46eb --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/system_notification.py @@ -0,0 +1,41 @@ +# Hack: string type that is always equal in not equal comparisons +class AnyType(str): + def __ne__(self, __value: object) -> bool: + return False + + +# Our any instance wants to be a wildcard string +any = AnyType("*") + + +class SystemNotification: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "message": ("STRING", {"default": "Your notification has triggered."}), + "any": (any, {}), + "mode": (["always", "on empty queue"], {}), + }} + + FUNCTION = "nop" + INPUT_IS_LIST = True + OUTPUT_IS_LIST = (True,) + OUTPUT_NODE = True + RETURN_TYPES = (any,) + + CATEGORY = "utils" + + def IS_CHANGED(self, **kwargs): + return float("NaN") + + def nop(self, any, message, mode): + return {"ui": {"message": message, "mode": mode}, "result": (any,)} + + +NODE_CLASS_MAPPINGS = { + "SystemNotification|pysssss": SystemNotification, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "SystemNotification|pysssss": "SystemNotification 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/text_files.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/text_files.py new file mode 100644 index 0000000000000000000000000000000000000000..42de6d71a375b7e5169f868f789c254b4f6c2cd9 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/text_files.py @@ -0,0 +1,204 @@ +import os +import folder_paths +import json +from server import PromptServer +import glob +from aiohttp import web + + +def get_allowed_dirs(): + dir = os.path.abspath(os.path.join(__file__, "../../user")) + file = os.path.join(dir, "text_file_dirs.json") + with open(file, "r") as f: + return json.loads(f.read()) + + +def get_valid_dirs(): + return get_allowed_dirs().keys() + + +def get_dir_from_name(name): + dirs = get_allowed_dirs() + if name not in dirs: + raise KeyError(name + " dir not found") + + path = dirs[name] + path = path.replace("$input", folder_paths.get_input_directory()) + path = path.replace("$output", folder_paths.get_output_directory()) + path = path.replace("$temp", folder_paths.get_temp_directory()) + return path + + +def is_child_dir(parent_path, child_path): + parent_path = os.path.abspath(parent_path) + child_path = os.path.abspath(child_path) + return os.path.commonpath([parent_path]) == os.path.commonpath([parent_path, child_path]) + + +def get_real_path(dir): + dir = dir.replace("/**/", "/") + dir = os.path.abspath(dir) + dir = os.path.split(dir)[0] + return dir + + +@PromptServer.instance.routes.get("/pysssss/text-file/{name}") +async def get_files(request): + name = request.match_info["name"] + dir = get_dir_from_name(name) + recursive = "/**/" in dir + # Ugh cant use root_path on glob... lazy hack.. + pre = get_real_path(dir) + + files = list(map(lambda t: os.path.relpath(t, pre), + glob.glob(dir, recursive=recursive))) + + if len(files) == 0: + files = ["[none]"] + return web.json_response(files) + + +def get_file(root_dir, file): + if file == "[none]" or not file or not file.strip(): + raise ValueError("No file") + + root_dir = get_dir_from_name(root_dir) + root_dir = get_real_path(root_dir) + if not os.path.exists(root_dir): + os.mkdir(root_dir) + full_path = os.path.join(root_dir, file) + + file_dir = os.path.dirname(full_path) + if file_dir and not os.path.exists(file_dir): + os.makedirs(file_dir, exist_ok=True) + + if not is_child_dir(root_dir, full_path): + raise ReferenceError() + + return full_path + + +class TextFileNode: + RETURN_TYPES = ("STRING",) + CATEGORY = "utils" + + @classmethod + def VALIDATE_INPUTS(self, root_dir, file, **kwargs): + if file == "[none]" or not file or not file.strip(): + return True + get_file(root_dir, file) + return True + + def load_text(self, **kwargs): + self.file = get_file(kwargs["root_dir"], kwargs["file"]) + with open(self.file, "r") as f: + return (f.read(), ) + + +class LoadText(TextFileNode): + @classmethod + def IS_CHANGED(self, **kwargs): + return os.path.getmtime(self.file) + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "root_dir": (list(get_valid_dirs()), {}), + "file": (["[none]"], { + "pysssss.binding": [{ + "source": "root_dir", + "callback": [{ + "type": "set", + "target": "$this.disabled", + "value": True + }, { + "type": "fetch", + "url": "/pysssss/text-file/{$source.value}", + "then": [{ + "type": "set", + "target": "$this.options.values", + "value": "$result" + }, { + "type": "validate-combo" + }, { + "type": "set", + "target": "$this.disabled", + "value": False + }] + }], + }] + }) + }, + } + + FUNCTION = "load_text" + + +class SaveText(TextFileNode): + OUTPUT_NODE = True + + @classmethod + def IS_CHANGED(self, **kwargs): + return float("nan") + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "root_dir": (list(get_valid_dirs()), {}), + "file": ("STRING", {"default": "file.txt"}), + "append": (["append", "overwrite", "new only"], {}), + "insert": ("BOOLEAN", { + "default": True, "label_on": "new line", "label_off": "none", + "pysssss.binding": [{ + "source": "append", + "callback": [{ + "type": "if", + "condition": [{ + "left": "$source.value", + "op": "eq", + "right": '"append"' + }], + "true": [{ + "type": "set", + "target": "$this.disabled", + "value": False + }], + "false": [{ + "type": "set", + "target": "$this.disabled", + "value": True + }], + }] + }] + }), + "text": ("STRING", {"forceInput": True, "multiline": True}) + }, + } + + FUNCTION = "write_text" + + def write_text(self, **kwargs): + self.file = get_file(kwargs["root_dir"], kwargs["file"]) + if kwargs["append"] == "new only" and os.path.exists(self.file): + raise FileExistsError( + self.file + " already exists and 'new only' is selected.") + with open(self.file, "a+" if kwargs["append"] == "append" else "w") as f: + is_append = f.tell() != 0 + if is_append and kwargs["insert"]: + f.write("\n") + f.write(kwargs["text"]) + + return super().load_text(**kwargs) + + +NODE_CLASS_MAPPINGS = { + "LoadText|pysssss": LoadText, + "SaveText|pysssss": SaveText, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + "LoadText|pysssss": "Load Text 🐍", + "SaveText|pysssss": "Save Text 🐍", +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/py/workflows.py b/1/custom_nodes/ComfyUI-Custom-Scripts/py/workflows.py new file mode 100644 index 0000000000000000000000000000000000000000..233e8c84ce490a1fd2a51e603b9836d869dc0262 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/py/workflows.py @@ -0,0 +1,61 @@ +from server import PromptServer +from aiohttp import web +import os +import inspect +import json +import importlib +import sys +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) +import pysssss + +root_directory = os.path.dirname(inspect.getfile(PromptServer)) +workflows_directory = os.path.join(root_directory, "pysssss-workflows") +workflows_directory = pysssss.get_config_value( + "workflows.directory", workflows_directory) +if not os.path.isabs(workflows_directory): + workflows_directory = os.path.abspath(os.path.join(root_directory, workflows_directory)) + +NODE_CLASS_MAPPINGS = {} +NODE_DISPLAY_NAME_MAPPINGS = {} + + +@PromptServer.instance.routes.get("/pysssss/workflows") +async def get_workflows(request): + files = [] + for dirpath, directories, file in os.walk(workflows_directory): + for file in file: + if (file.endswith(".json")): + files.append(os.path.relpath(os.path.join( + dirpath, file), workflows_directory)) + return web.json_response(list(map(lambda f: os.path.splitext(f)[0].replace("\\", "/"), files))) + + +@PromptServer.instance.routes.get("/pysssss/workflows/{name:.+}") +async def get_workflow(request): + file = os.path.abspath(os.path.join( + workflows_directory, request.match_info["name"] + ".json")) + if os.path.commonpath([file, workflows_directory]) != workflows_directory: + return web.Response(status=403) + + return web.FileResponse(file) + + +@PromptServer.instance.routes.post("/pysssss/workflows") +async def save_workflow(request): + json_data = await request.json() + file = os.path.abspath(os.path.join( + workflows_directory, json_data["name"] + ".json")) + if os.path.commonpath([file, workflows_directory]) != workflows_directory: + 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) diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/pyproject.toml b/1/custom_nodes/ComfyUI-Custom-Scripts/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..b34f8cfc4a4af33575586c2c11313bdd34d1dfee --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/pyproject.toml @@ -0,0 +1,13 @@ +[project] +name = "comfyui-custom-scripts" +description = "Enhancements & experiments for ComfyUI, mostly focusing on UI features" +version = "1.2.5" +license = { file = "LICENSE" } + +[project.urls] +Repository = "https://github.com/pythongosssss/ComfyUI-Custom-Scripts" + +[tool.comfy] +PublisherId = "pythongosssss" +DisplayName = "ComfyUI-Custom-Scripts" +Icon = "" diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.default.json b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.default.json new file mode 100644 index 0000000000000000000000000000000000000000..6ca06420135d024f925a0d70d5dd0328c69b271e --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.default.json @@ -0,0 +1,4 @@ +{ + "name": "CustomScripts", + "logging": false +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.example.json b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.example.json new file mode 100644 index 0000000000000000000000000000000000000000..251e3c720067fc06b4458db51cb8c12182c05dee --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.example.json @@ -0,0 +1,7 @@ +{ + "name": "CustomScripts", + "logging": false, + "workflows": { + "directory": "C:\\ComfyUI-Workflows" + } +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.py b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.py new file mode 100644 index 0000000000000000000000000000000000000000..b1024f5a220779239bdadc56aaf7b9431cfa77cc --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/pysssss.py @@ -0,0 +1,300 @@ +import asyncio +import os +import json +import shutil +import inspect +import aiohttp +from server import PromptServer +from tqdm import tqdm + +config = None + + +def is_logging_enabled(): + config = get_extension_config() + if "logging" not in config: + return False + return config["logging"] + + +def log(message, type=None, always=False, name=None): + if not always and not is_logging_enabled(): + return + + if type is not None: + message = f"[{type}] {message}" + + if name is None: + name = get_extension_config()["name"] + + print(f"(pysssss:{name}) {message}") + + +def get_ext_dir(subpath=None, mkdir=False): + dir = os.path.dirname(__file__) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_comfy_dir(subpath=None, mkdir=False): + dir = os.path.dirname(inspect.getfile(PromptServer)) + if subpath is not None: + dir = os.path.join(dir, subpath) + + dir = os.path.abspath(dir) + + if mkdir and not os.path.exists(dir): + os.makedirs(dir) + return dir + + +def get_web_ext_dir(): + config = get_extension_config() + name = config["name"] + dir = get_comfy_dir("web/extensions/pysssss") + if not os.path.exists(dir): + os.makedirs(dir) + dir = os.path.join(dir, name) + return dir + + +def get_extension_config(reload=False): + global config + if reload == False and config is not None: + return config + + config_path = get_ext_dir("pysssss.json") + default_config_path = get_ext_dir("pysssss.default.json") + if not os.path.exists(config_path): + if os.path.exists(default_config_path): + shutil.copy(default_config_path, config_path) + if not os.path.exists(config_path): + log(f"Failed to create config at {config_path}", type="ERROR", always=True, name="???") + print(f"Extension path: {get_ext_dir()}") + return {"name": "Unknown", "version": -1} + + else: + log("Missing pysssss.default.json, this extension may not work correctly. Please reinstall the extension.", + type="ERROR", always=True, name="???") + print(f"Extension path: {get_ext_dir()}") + return {"name": "Unknown", "version": -1} + + with open(config_path, "r") as f: + config = json.loads(f.read()) + return config + + +def link_js(src, dst): + src = os.path.abspath(src) + dst = os.path.abspath(dst) + if os.name == "nt": + try: + import _winapi + _winapi.CreateJunction(src, dst) + return True + except: + pass + try: + os.symlink(src, dst) + return True + except: + import logging + logging.exception('') + return False + + +def is_junction(path): + if os.name != "nt": + return False + try: + return bool(os.readlink(path)) + except OSError: + return False + + +def install_js(): + src_dir = get_ext_dir("web/js") + if not os.path.exists(src_dir): + log("No JS") + return + + should_install = should_install_js() + if should_install: + log("it looks like you're running an old version of ComfyUI that requires manual setup of web files, it is recommended you update your installation.", "warning", True) + dst_dir = get_web_ext_dir() + linked = os.path.islink(dst_dir) or is_junction(dst_dir) + if linked or os.path.exists(dst_dir): + if linked: + if should_install: + log("JS already linked") + else: + os.unlink(dst_dir) + log("JS unlinked, PromptServer will serve extension") + elif not should_install: + shutil.rmtree(dst_dir) + log("JS deleted, PromptServer will serve extension") + return + + if not should_install: + log("JS skipped, PromptServer will serve extension") + return + + if link_js(src_dir, dst_dir): + log("JS linked") + return + + log("Copying JS files") + shutil.copytree(src_dir, dst_dir, dirs_exist_ok=True) + + +def should_install_js(): + return not hasattr(PromptServer.instance, "supports") or "custom_nodes_from_web" not in PromptServer.instance.supports + + +def init(check_imports=None): + log("Init") + + if check_imports is not None: + import importlib.util + for imp in check_imports: + spec = importlib.util.find_spec(imp) + if spec is None: + log(f"{imp} is required, please check requirements are installed.", + type="ERROR", always=True) + return False + + install_js() + return True + + +def get_async_loop(): + loop = None + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + return loop + + +def get_http_session(): + loop = get_async_loop() + return aiohttp.ClientSession(loop=loop) + + +async def download(url, stream, update_callback=None, session=None): + close_session = False + if session is None: + close_session = True + session = get_http_session() + try: + async with session.get(url) as response: + size = int(response.headers.get('content-length', 0)) or None + + with tqdm( + unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1], total=size, + ) as progressbar: + perc = 0 + async for chunk in response.content.iter_chunked(2048): + stream.write(chunk) + progressbar.update(len(chunk)) + if update_callback is not None and progressbar.total is not None and progressbar.total != 0: + last = perc + perc = round(progressbar.n / progressbar.total, 2) + if perc != last: + last = perc + await update_callback(perc) + finally: + if close_session and session is not None: + await session.close() + + +async def download_to_file(url, destination, update_callback=None, is_ext_subpath=True, session=None): + if is_ext_subpath: + destination = get_ext_dir(destination) + with open(destination, mode='wb') as f: + download(url, f, update_callback, session) + + +def wait_for_async(async_fn, loop=None): + res = [] + + async def run_async(): + r = await async_fn() + res.append(r) + + if loop is None: + try: + loop = asyncio.get_event_loop() + except: + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + + loop.run_until_complete(run_async()) + + return res[0] + + +def update_node_status(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + PromptServer.instance.send_sync("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +async def update_node_status_async(client_id, node, text, progress=None): + if client_id is None: + client_id = PromptServer.instance.client_id + + if client_id is None: + return + + await PromptServer.instance.send("pysssss/update_status", { + "node": node, + "progress": progress, + "text": text + }, client_id) + + +def get_config_value(key, default=None, throw=False): + split = key.split(".") + obj = get_extension_config() + for s in split: + if s in obj: + obj = obj[s] + else: + if throw: + raise KeyError("Configuration key missing: " + key) + else: + return default + return obj + + +def is_inside_dir(root_dir, check_path): + root_dir = os.path.abspath(root_dir) + if not os.path.isabs(check_path): + check_path = os.path.abspath(os.path.join(root_dir, check_path)) + return os.path.commonpath([check_path, root_dir]) == root_dir + + +def get_child_dir(root_dir, child_path, throw_if_outside=True): + child_path = os.path.abspath(os.path.join(root_dir, child_path)) + if is_inside_dir(root_dir, child_path): + return child_path + if throw_if_outside: + raise NotADirectoryError( + "Saving outside the target folder is not allowed.") + return None diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/user/text_file_dirs.json b/1/custom_nodes/ComfyUI-Custom-Scripts/user/text_file_dirs.json new file mode 100644 index 0000000000000000000000000000000000000000..15adc2255e0109be7b860d591f54187520c673aa --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/user/text_file_dirs.json @@ -0,0 +1,5 @@ +{ + "input": "$input/**/*.txt", + "output": "$output/**/*.txt", + "temp": "$temp/**/*.txt" +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/canvas2svg.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/canvas2svg.js new file mode 100644 index 0000000000000000000000000000000000000000..03dc3923759ccbe8cf70eaab387b792cc0ba32ca --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/canvas2svg.js @@ -0,0 +1,1192 @@ +/*!! + * Canvas 2 Svg v1.0.19 + * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + * + * Author: + * Kerry Liu + * + * Copyright (c) 2014 Gliffy Inc. + */ + +;(function() { + "use strict"; + + var STYLES, ctx, CanvasGradient, CanvasPattern, namedEntities; + + //helper function to format a string + function format(str, args) { + var keys = Object.keys(args), i; + for (i=0; i 1) { + options = defaultOptions; + options.width = arguments[0]; + options.height = arguments[1]; + } else if( !o ) { + options = defaultOptions; + } else { + options = o; + } + + if(!(this instanceof ctx)) { + //did someone call this without new? + return new ctx(options); + } + + //setup options + this.width = options.width || defaultOptions.width; + this.height = options.height || defaultOptions.height; + this.enableMirroring = options.enableMirroring !== undefined ? options.enableMirroring : defaultOptions.enableMirroring; + + this.canvas = this; ///point back to this instance! + this.__document = options.document || document; + this.__canvas = this.__document.createElement("canvas"); + this.__ctx = this.__canvas.getContext("2d"); + + this.__setDefaultStyles(); + this.__stack = [this.__getStyleState()]; + this.__groupStack = []; + + //the root svg element + this.__root = this.__document.createElementNS("http://www.w3.org/2000/svg", "svg"); + this.__root.setAttribute("version", 1.1); + this.__root.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + this.__root.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); + this.__root.setAttribute("width", this.width); + this.__root.setAttribute("height", this.height); + + //make sure we don't generate the same ids in defs + this.__ids = {}; + + //defs tag + this.__defs = this.__document.createElementNS("http://www.w3.org/2000/svg", "defs"); + this.__root.appendChild(this.__defs); + + //also add a group child. the svg element can't use the transform attribute + this.__currentElement = this.__document.createElementNS("http://www.w3.org/2000/svg", "g"); + this.__root.appendChild(this.__currentElement); + }; + + + /** + * Creates the specified svg element + * @private + */ + ctx.prototype.__createElement = function (elementName, properties, resetFill) { + if (typeof properties === "undefined") { + properties = {}; + } + + var element = this.__document.createElementNS("http://www.w3.org/2000/svg", elementName), + keys = Object.keys(properties), i, key; + if(resetFill) { + //if fill or stroke is not specified, the svg element should not display. By default SVG's fill is black. + element.setAttribute("fill", "none"); + element.setAttribute("stroke", "none"); + } + for(i=0; i 0) { + var group = this.__createElement("g"); + parent.appendChild(group); + this.__currentElement = group; + } + + var transform = this.__currentElement.getAttribute("transform"); + if(transform) { + transform += " "; + } else { + transform = ""; + } + transform += t; + this.__currentElement.setAttribute("transform", transform); + }; + + /** + * scales the current element + */ + ctx.prototype.scale = function(x, y) { + if(y === undefined) { + y = x; + } + this.__addTransform(format("scale({x},{y})", {x:x, y:y})); + }; + + /** + * rotates the current element + */ + ctx.prototype.rotate = function(angle){ + var degrees = (angle * 180 / Math.PI); + this.__addTransform(format("rotate({angle},{cx},{cy})", {angle:degrees, cx:0, cy:0})); + }; + + /** + * translates the current element + */ + ctx.prototype.translate = function(x, y){ + this.__addTransform(format("translate({x},{y})", {x:x,y:y})); + }; + + /** + * applies a transform to the current element + */ + ctx.prototype.transform = function(a, b, c, d, e, f){ + this.__addTransform(format("matrix({a},{b},{c},{d},{e},{f})", {a:a, b:b, c:c, d:d, e:e, f:f})); + }; + + /** + * Create a new Path Element + */ + ctx.prototype.beginPath = function(){ + var path, parent; + + // Note that there is only one current default path, it is not part of the drawing state. + // See also: https://html.spec.whatwg.org/multipage/scripting.html#current-default-path + this.__currentDefaultPath = ""; + this.__currentPosition = {}; + + path = this.__createElement("path", {}, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(path); + this.__currentElement = path; + }; + + /** + * Helper function to apply currentDefaultPath to current path element + * @private + */ + ctx.prototype.__applyCurrentDefaultPath = function() { + if(this.__currentElement.nodeName === "path") { + var d = this.__currentDefaultPath; + this.__currentElement.setAttribute("d", d); + } else { + throw new Error("Attempted to apply path command to node " + this.__currentElement.nodeName); + } + }; + + /** + * Helper function to add path command + * @private + */ + ctx.prototype.__addPathCommand = function(command){ + this.__currentDefaultPath += " "; + this.__currentDefaultPath += command; + }; + + /** + * Adds the move command to the current path element, + * if the currentPathElement is not empty create a new path element + */ + ctx.prototype.moveTo = function(x,y){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + + // creates a new subpath with the given point + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + }; + + /** + * Closes the current path + */ + ctx.prototype.closePath = function(){ + this.__addPathCommand("Z"); + }; + + /** + * Adds a line to command + */ + ctx.prototype.lineTo = function(x, y){ + this.__currentPosition = {x: x, y: y}; + if (this.__currentDefaultPath.indexOf('M') > -1) { + this.__addPathCommand(format("L {x} {y}", {x:x, y:y})); + } else { + this.__addPathCommand(format("M {x} {y}", {x:x, y:y})); + } + }; + + /** + * Add a bezier command + */ + ctx.prototype.bezierCurveTo = function(cp1x, cp1y, cp2x, cp2y, x, y) { + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}", + {cp1x:cp1x, cp1y:cp1y, cp2x:cp2x, cp2y:cp2y, x:x, y:y})); + }; + + /** + * Adds a quadratic curve to command + */ + ctx.prototype.quadraticCurveTo = function(cpx, cpy, x, y){ + this.__currentPosition = {x: x, y: y}; + this.__addPathCommand(format("Q {cpx} {cpy} {x} {y}", {cpx:cpx, cpy:cpy, x:x, y:y})); + }; + + + /** + * Return a new normalized vector of given vector + */ + var normalize = function(vector) { + var len = Math.sqrt(vector[0] * vector[0] + vector[1] * vector[1]); + return [vector[0] / len, vector[1] / len]; + }; + + /** + * Adds the arcTo to the current path + * + * @see http://www.w3.org/TR/2015/WD-2dcontext-20150514/#dom-context-2d-arcto + */ + ctx.prototype.arcTo = function(x1, y1, x2, y2, radius) { + // Let the point (x0, y0) be the last point in the subpath. + var x0 = this.__currentPosition && this.__currentPosition.x; + var y0 = this.__currentPosition && this.__currentPosition.y; + + // First ensure there is a subpath for (x1, y1). + if (typeof x0 == "undefined" || typeof y0 == "undefined") { + return; + } + + // Negative values for radius must cause the implementation to throw an IndexSizeError exception. + if (radius < 0) { + throw new Error("IndexSizeError: The radius provided (" + radius + ") is negative."); + } + + // If the point (x0, y0) is equal to the point (x1, y1), + // or if the point (x1, y1) is equal to the point (x2, y2), + // or if the radius radius is zero, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + if (((x0 === x1) && (y0 === y1)) + || ((x1 === x2) && (y1 === y2)) + || (radius === 0)) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, if the points (x0, y0), (x1, y1), and (x2, y2) all lie on a single straight line, + // then the method must add the point (x1, y1) to the subpath, + // and connect that point to the previous point (x0, y0) by a straight line. + var unit_vec_p1_p0 = normalize([x0 - x1, y0 - y1]); + var unit_vec_p1_p2 = normalize([x2 - x1, y2 - y1]); + if (unit_vec_p1_p0[0] * unit_vec_p1_p2[1] === unit_vec_p1_p0[1] * unit_vec_p1_p2[0]) { + this.lineTo(x1, y1); + return; + } + + // Otherwise, let The Arc be the shortest arc given by circumference of the circle that has radius radius, + // and that has one point tangent to the half-infinite line that crosses the point (x0, y0) and ends at the point (x1, y1), + // and that has a different point tangent to the half-infinite line that ends at the point (x1, y1), and crosses the point (x2, y2). + // The points at which this circle touches these two lines are called the start and end tangent points respectively. + + // note that both vectors are unit vectors, so the length is 1 + var cos = (unit_vec_p1_p0[0] * unit_vec_p1_p2[0] + unit_vec_p1_p0[1] * unit_vec_p1_p2[1]); + var theta = Math.acos(Math.abs(cos)); + + // Calculate origin + var unit_vec_p1_origin = normalize([ + unit_vec_p1_p0[0] + unit_vec_p1_p2[0], + unit_vec_p1_p0[1] + unit_vec_p1_p2[1] + ]); + var len_p1_origin = radius / Math.sin(theta / 2); + var x = x1 + len_p1_origin * unit_vec_p1_origin[0]; + var y = y1 + len_p1_origin * unit_vec_p1_origin[1]; + + // Calculate start angle and end angle + // rotate 90deg clockwise (note that y axis points to its down) + var unit_vec_origin_start_tangent = [ + -unit_vec_p1_p0[1], + unit_vec_p1_p0[0] + ]; + // rotate 90deg counter clockwise (note that y axis points to its down) + var unit_vec_origin_end_tangent = [ + unit_vec_p1_p2[1], + -unit_vec_p1_p2[0] + ]; + var getAngle = function(vector) { + // get angle (clockwise) between vector and (1, 0) + var x = vector[0]; + var y = vector[1]; + if (y >= 0) { // note that y axis points to its down + return Math.acos(x); + } else { + return -Math.acos(x); + } + }; + var startAngle = getAngle(unit_vec_origin_start_tangent); + var endAngle = getAngle(unit_vec_origin_end_tangent); + + // Connect the point (x0, y0) to the start tangent point by a straight line + this.lineTo(x + unit_vec_origin_start_tangent[0] * radius, + y + unit_vec_origin_start_tangent[1] * radius); + + // Connect the start tangent point to the end tangent point by arc + // and adding the end tangent point to the subpath. + this.arc(x, y, radius, startAngle, endAngle); + }; + + /** + * Sets the stroke property on the current element + */ + ctx.prototype.stroke = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "fill stroke markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("stroke"); + }; + + /** + * Sets fill properties on the current element + */ + ctx.prototype.fill = function(){ + if(this.__currentElement.nodeName === "path") { + this.__currentElement.setAttribute("paint-order", "stroke fill markers"); + } + this.__applyCurrentDefaultPath(); + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Adds a rectangle to the path. + */ + ctx.prototype.rect = function(x, y, width, height){ + if(this.__currentElement.nodeName !== "path") { + this.beginPath(); + } + this.moveTo(x, y); + this.lineTo(x+width, y); + this.lineTo(x+width, y+height); + this.lineTo(x, y+height); + this.lineTo(x, y); + this.closePath(); + }; + + + /** + * adds a rectangle element + */ + ctx.prototype.fillRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("fill"); + }; + + /** + * Draws a rectangle with no fill + * @param x + * @param y + * @param width + * @param height + */ + ctx.prototype.strokeRect = function(x, y, width, height){ + var rect, parent; + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height + }, true); + parent = this.__closestGroupOrSvg(); + parent.appendChild(rect); + this.__currentElement = rect; + this.__applyStyleToCurrentElement("stroke"); + }; + + + /** + * Clear entire canvas: + * 1. save current transforms + * 2. remove all the childNodes of the root g element + */ + ctx.prototype.__clearCanvas = function() { + var current = this.__closestGroupOrSvg(), + transform = current.getAttribute("transform"); + var rootGroup = this.__root.childNodes[1]; + var childNodes = rootGroup.childNodes; + for (var i = childNodes.length - 1; i >= 0; i--) { + if (childNodes[i]) { + rootGroup.removeChild(childNodes[i]); + } + } + this.__currentElement = rootGroup; + //reset __groupStack as all the child group nodes are all removed. + this.__groupStack = []; + if (transform) { + this.__addTransform(transform); + } + }; + + /** + * "Clears" a canvas by just drawing a white rectangle in the current group. + */ + ctx.prototype.clearRect = function(x, y, width, height) { + //clear entire canvas + if (x === 0 && y === 0 && width === this.width && height === this.height) { + this.__clearCanvas(); + return; + } + var rect, parent = this.__closestGroupOrSvg(); + rect = this.__createElement("rect", { + x : x, + y : y, + width : width, + height : height, + fill : "#FFFFFF" + }, true); + parent.appendChild(rect); + }; + + /** + * Adds a linear gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createLinearGradient = function(x1, y1, x2, y2){ + var grad = this.__createElement("linearGradient", { + id : randomString(this.__ids), + x1 : x1+"px", + x2 : x2+"px", + y1 : y1+"px", + y2 : y2+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + }; + + /** + * Adds a radial gradient to a defs tag. + * Returns a canvas gradient object that has a reference to it's parent def + */ + ctx.prototype.createRadialGradient = function(x0, y0, r0, x1, y1, r1){ + var grad = this.__createElement("radialGradient", { + id : randomString(this.__ids), + cx : x1+"px", + cy : y1+"px", + r : r1+"px", + fx : x0+"px", + fy : y0+"px", + "gradientUnits" : "userSpaceOnUse" + }, false); + this.__defs.appendChild(grad); + return new CanvasGradient(grad, this); + + }; + + /** + * Parses the font string and returns svg mapping + * @private + */ + ctx.prototype.__parseFont = function() { + var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z]+?)\s*$/i; + var fontPart = regex.exec( this.font ); + var data = { + style : fontPart[1] || 'normal', + size : fontPart[4] || '10px', + family : fontPart[6] || 'sans-serif', + weight: fontPart[3] || 'normal', + decoration : fontPart[2] || 'normal', + href : null + }; + + //canvas doesn't support underline natively, but we can pass this attribute + if(this.__fontUnderline === "underline") { + data.decoration = "underline"; + } + + //canvas also doesn't support linking, but we can pass this as well + if(this.__fontHref) { + data.href = this.__fontHref; + } + + return data; + }; + + /** + * Helper to link text fragments + * @param font + * @param element + * @return {*} + * @private + */ + ctx.prototype.__wrapTextLink = function(font, element) { + if(font.href) { + var a = this.__createElement("a"); + a.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", font.href); + a.appendChild(element); + return a; + } + return element; + }; + + /** + * Fills or strokes text + * @param text + * @param x + * @param y + * @param action - stroke or fill + * @private + */ + ctx.prototype.__applyText = function(text, x, y, action) { + var font = this.__parseFont(), + parent = this.__closestGroupOrSvg(), + textElement = this.__createElement("text", { + "font-family" : font.family, + "font-size" : font.size, + "font-style" : font.style, + "font-weight" : font.weight, + "text-decoration" : font.decoration, + "x" : x, + "y" : y, + "text-anchor": getTextAnchor(this.textAlign), + "dominant-baseline": getDominantBaseline(this.textBaseline) + }, true); + + textElement.appendChild(this.__document.createTextNode(text)); + this.__currentElement = textElement; + this.__applyStyleToCurrentElement(action); + parent.appendChild(this.__wrapTextLink(font,textElement)); + }; + + /** + * Creates a text element + * @param text + * @param x + * @param y + */ + ctx.prototype.fillText = function(text, x, y){ + this.__applyText(text, x, y, "fill"); + }; + + /** + * Strokes text + * @param text + * @param x + * @param y + */ + ctx.prototype.strokeText = function(text, x, y){ + this.__applyText(text, x, y, "stroke"); + }; + + /** + * No need to implement this for svg. + * @param text + * @return {TextMetrics} + */ + ctx.prototype.measureText = function(text){ + this.__ctx.font = this.font; + return this.__ctx.measureText(text); + }; + + /** + * Arc command! + */ + ctx.prototype.arc = function(x, y, radius, startAngle, endAngle, counterClockwise) { + // in canvas no circle is drawn if no angle is provided. + if (startAngle === endAngle) { + return; + } + startAngle = startAngle % (2*Math.PI); + endAngle = endAngle % (2*Math.PI); + if(startAngle === endAngle) { + //circle time! subtract some of the angle so svg is happy (svg elliptical arc can't draw a full circle) + endAngle = ((endAngle + (2*Math.PI)) - 0.001 * (counterClockwise ? -1 : 1)) % (2*Math.PI); + } + var endX = x+radius*Math.cos(endAngle), + endY = y+radius*Math.sin(endAngle), + startX = x+radius*Math.cos(startAngle), + startY = y+radius*Math.sin(startAngle), + sweepFlag = counterClockwise ? 0 : 1, + largeArcFlag = 0, + diff = endAngle - startAngle; + + // https://github.com/gliffy/canvas2svg/issues/4 + if(diff < 0) { + diff += 2*Math.PI; + } + + if(counterClockwise) { + largeArcFlag = diff > Math.PI ? 0 : 1; + } else { + largeArcFlag = diff > Math.PI ? 1 : 0; + } + + this.lineTo(startX, startY); + this.__addPathCommand(format("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}", + {rx:radius, ry:radius, xAxisRotation:0, largeArcFlag:largeArcFlag, sweepFlag:sweepFlag, endX:endX, endY:endY})); + + this.__currentPosition = {x: endX, y: endY}; + }; + + /** + * Generates a ClipPath from the clip command. + */ + ctx.prototype.clip = function(){ + var group = this.__closestGroupOrSvg(), + clipPath = this.__createElement("clipPath"), + id = randomString(this.__ids), + newGroup = this.__createElement("g"); + + this.__applyCurrentDefaultPath(); + group.removeChild(this.__currentElement); + clipPath.setAttribute("id", id); + clipPath.appendChild(this.__currentElement); + + this.__defs.appendChild(clipPath); + + //set the clip path to this group + group.setAttribute("clip-path", format("url(#{id})", {id:id})); + + //clip paths can be scaled and transformed, we need to add another wrapper group to avoid later transformations + // to this path + group.appendChild(newGroup); + + this.__currentElement = newGroup; + + }; + + /** + * Draws a canvas, image or mock context to this canvas. + * Note that all svg dom manipulation uses node.childNodes rather than node.children for IE support. + * http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-drawimage + */ + ctx.prototype.drawImage = function(){ + //convert arguments to a real array + var args = Array.prototype.slice.call(arguments), + image=args[0], + dx, dy, dw, dh, sx=0, sy=0, sw, sh, parent, svg, defs, group, + currentElement, svgImage, canvas, context, id; + + if(args.length === 3) { + dx = args[1]; + dy = args[2]; + sw = image.width; + sh = image.height; + dw = sw; + dh = sh; + } else if(args.length === 5) { + dx = args[1]; + dy = args[2]; + dw = args[3]; + dh = args[4]; + sw = image.width; + sh = image.height; + } else if(args.length === 9) { + sx = args[1]; + sy = args[2]; + sw = args[3]; + sh = args[4]; + dx = args[5]; + dy = args[6]; + dw = args[7]; + dh = args[8]; + } else { + throw new Error("Inavlid number of arguments passed to drawImage: " + arguments.length); + } + + parent = this.__closestGroupOrSvg(); + currentElement = this.__currentElement; + var translateDirective = "translate(" + dx + ", " + dy + ")"; + if(image instanceof ctx) { + //canvas2svg mock canvas context. In the future we may want to clone nodes instead. + //also I'm currently ignoring dw, dh, sw, sh, sx, sy for a mock context. + svg = image.getSvg().cloneNode(true); + if (svg.childNodes && svg.childNodes.length > 1) { + defs = svg.childNodes[0]; + while(defs.childNodes.length) { + id = defs.childNodes[0].getAttribute("id"); + this.__ids[id] = id; + this.__defs.appendChild(defs.childNodes[0]); + } + group = svg.childNodes[1]; + if (group) { + //save original transform + var originTransform = group.getAttribute("transform"); + var transformDirective; + if (originTransform) { + transformDirective = originTransform+" "+translateDirective; + } else { + transformDirective = translateDirective; + } + group.setAttribute("transform", transformDirective); + parent.appendChild(group); + } + } + } else if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + //canvas or image + svgImage = this.__createElement("image"); + svgImage.setAttribute("width", dw); + svgImage.setAttribute("height", dh); + svgImage.setAttribute("preserveAspectRatio", "none"); + + if(sx || sy || sw !== image.width || sh !== image.height) { + //crop the image using a temporary canvas + canvas = this.__document.createElement("canvas"); + canvas.width = dw; + canvas.height = dh; + context = canvas.getContext("2d"); + context.drawImage(image, sx, sy, sw, sh, 0, 0, dw, dh); + image = canvas; + } + svgImage.setAttribute("transform", translateDirective); + svgImage.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + parent.appendChild(svgImage); + } + }; + + /** + * Generates a pattern tag + */ + ctx.prototype.createPattern = function(image, repetition){ + var pattern = this.__document.createElementNS("http://www.w3.org/2000/svg", "pattern"), id = randomString(this.__ids), + img; + pattern.setAttribute("id", id); + pattern.setAttribute("width", image.width); + pattern.setAttribute("height", image.height); + if(image.nodeName === "CANVAS" || image.nodeName === "IMG") { + img = this.__document.createElementNS("http://www.w3.org/2000/svg", "image"); + img.setAttribute("width", image.width); + img.setAttribute("height", image.height); + img.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", + image.nodeName === "CANVAS" ? image.toDataURL() : image.getAttribute("src")); + pattern.appendChild(img); + this.__defs.appendChild(pattern); + } else if(image instanceof ctx) { + pattern.appendChild(image.__root.childNodes[1]); + this.__defs.appendChild(pattern); + } + return new CanvasPattern(pattern, this); + }; + + ctx.prototype.setLineDash = function(dashArray) { + if (dashArray && dashArray.length > 0) { + this.lineDash = dashArray.join(","); + } else { + this.lineDash = null; + } + }; + + /** + * Not yet implemented + */ + ctx.prototype.drawFocusRing = function(){}; + ctx.prototype.createImageData = function(){}; + ctx.prototype.getImageData = function(){}; + ctx.prototype.putImageData = function(){}; + ctx.prototype.globalCompositeOperation = function(){}; + ctx.prototype.setTransform = function(){}; + + //add options for alternative namespace + if (typeof window === "object") { + window.C2S = ctx; + } + + // CommonJS/Browserify + if (typeof module === "object" && typeof module.exports === "object") { + module.exports = ctx; + } + +}()); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon-active.ico b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon-active.ico new file mode 100644 index 0000000000000000000000000000000000000000..64045ab56e87879adb039b1fdb0bbbe0462143e7 Binary files /dev/null and b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon-active.ico differ diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon.ico b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..08df2481551bb6903735fa69d658b5abfb0a5ae1 Binary files /dev/null and b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/favicon.ico differ diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/no-image.png b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/no-image.png new file mode 100644 index 0000000000000000000000000000000000000000..d0b58b2c9d3ad82a2a949933648f8691ff36ba84 Binary files /dev/null and b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/no-image.png differ diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/notify.mp3 b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/notify.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..5e3fdabbb12142dfa75702a0b0e0ca5e5425a7dd Binary files /dev/null and b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/assets/notify.mp3 differ diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/autocompleter.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/autocompleter.js new file mode 100644 index 0000000000000000000000000000000000000000..20d6920ec0e8138eb1e51e8dc65eaceb0707a248 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/autocompleter.js @@ -0,0 +1,602 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; +import { api } from "../../../scripts/api.js"; +import { $el, ComfyDialog } from "../../../scripts/ui.js"; +import { TextAreaAutoComplete } from "./common/autocomplete.js"; +import { ModelInfoDialog } from "./common/modelInfoDialog.js"; +import { LoraInfoDialog } from "./modelInfo.js"; + +function parseCSV(csvText) { + const rows = []; + const delimiter = ","; + const quote = '"'; + let currentField = ""; + let inQuotedField = false; + + function pushField() { + rows[rows.length - 1].push(currentField); + currentField = ""; + inQuotedField = false; + } + + rows.push([]); // Initialize the first row + + for (let i = 0; i < csvText.length; i++) { + const char = csvText[i]; + const nextChar = csvText[i + 1]; + + // Special handling for backslash escaped quotes + if (char === "\\" && nextChar === quote) { + currentField += quote; + i++; + } + + if (!inQuotedField) { + if (char === quote) { + inQuotedField = true; + } else if (char === delimiter) { + pushField(); + } else if (char === "\r" || char === "\n" || i === csvText.length - 1) { + pushField(); + if (nextChar === "\n") { + i++; // Handle Windows line endings (\r\n) + } + rows.push([]); // Start a new row + } else { + currentField += char; + } + } else { + if (char === quote && nextChar === quote) { + currentField += quote; + i++; // Skip the next quote + } else if (char === quote) { + inQuotedField = false; + } else if (char === "\r" || char === "\n" || i === csvText.length - 1) { + // Dont allow new lines in quoted text, assume its wrong + const parsed = parseCSV(currentField); + rows.pop(); + rows.push(...parsed); + inQuotedField = false; + currentField = ""; + rows.push([]); + } else { + currentField += char; + } + } + } + + if (currentField || csvText[csvText.length - 1] === ",") { + pushField(); + } + + // Remove the last row if it's empty + if (rows[rows.length - 1].length === 0) { + rows.pop(); + } + + return rows; +} + +async function getCustomWords() { + const resp = await api.fetchApi("/pysssss/autocomplete", { cache: "no-store" }); + if (resp.status === 200) { + return await resp.text(); + } + return undefined; +} + +async function addCustomWords(text) { + if (!text) { + text = await getCustomWords(); + } + if (text) { + TextAreaAutoComplete.updateWords( + "pysssss.customwords", + parseCSV(text).reduce((p, n) => { + let text; + let priority; + let value; + let num; + switch (n.length) { + case 0: + return; + case 1: + // Single word + text = n[0]; + break; + case 2: + // Word,[priority|alias] + num = +n[1]; + if (isNaN(num)) { + text = n[0] + "🔄️" + n[1]; + value = n[0]; + } else { + text = n[0]; + priority = num; + } + break; + case 4: + // a1111 csv format? + value = n[0]; + priority = +n[2]; + const aliases = n[3]?.trim(); + if (aliases && aliases !== "null") { // Weird null in an example csv, maybe they are JSON.parsing the last column? + const split = aliases.split(","); + for (const text of split) { + p[text] = { text, priority, value }; + } + } + text = value; + break; + default: + // Word,alias,priority + text = n[1]; + value = n[0]; + priority = +n[2]; + break; + } + p[text] = { text, priority, value }; + return p; + }, {}) + ); + } +} + +function toggleLoras() { + [TextAreaAutoComplete.globalWords, TextAreaAutoComplete.globalWordsExclLoras] = [ + TextAreaAutoComplete.globalWordsExclLoras, + TextAreaAutoComplete.globalWords, + ]; +} + +class EmbeddingInfoDialog extends ModelInfoDialog { + async addInfo() { + super.addInfo(); + const info = await this.addCivitaiInfo(); + if (info) { + $el("div", { + parent: this.content, + innerHTML: info.description, + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + } +} + +class CustomWordsDialog extends ComfyDialog { + async show() { + const text = await getCustomWords(); + this.words = $el("textarea", { + textContent: text, + style: { + width: "70vw", + height: "70vh", + }, + }); + + const input = $el("input", { + style: { + flex: "auto", + }, + value: + "https://gist.githubusercontent.com/pythongosssss/1d3efa6050356a08cea975183088159a/raw/a18fb2f94f9156cf4476b0c24a09544d6c0baec6/danbooru-tags.txt", + }); + + super.show( + $el( + "div", + { + style: { + display: "flex", + flexDirection: "column", + overflow: "hidden", + maxHeight: "100%", + }, + }, + [ + $el("h2", { + textContent: "Custom Autocomplete Words", + style: { + color: "#fff", + marginTop: 0, + textAlign: "center", + fontFamily: "sans-serif", + }, + }), + $el( + "div", + { + style: { + color: "#fff", + fontFamily: "sans-serif", + display: "flex", + alignItems: "center", + gap: "5px", + }, + }, + [ + $el("label", { textContent: "Load Custom List: " }), + input, + $el("button", { + textContent: "Load", + onclick: async () => { + try { + const res = await fetch(input.value); + if (res.status !== 200) { + throw new Error("Error loading: " + res.status + " " + res.statusText); + } + this.words.value = await res.text(); + } catch (error) { + alert("Error loading custom list, try manually copy + pasting the list"); + } + }, + }), + ] + ), + this.words, + ] + ) + ); + } + + createButtons() { + const btns = super.createButtons(); + const save = $el("button", { + type: "button", + textContent: "Save", + onclick: async (e) => { + try { + const res = await api.fetchApi("/pysssss/autocomplete", { method: "POST", body: this.words.value }); + if (res.status !== 200) { + throw new Error("Error saving: " + res.status + " " + res.statusText); + } + save.textContent = "Saved!"; + addCustomWords(this.words.value); + setTimeout(() => { + save.textContent = "Save"; + }, 500); + } catch (error) { + alert("Error saving word list!"); + console.error(error); + } + }, + }); + + btns.unshift(save); + return btns; + } +} + +const id = "pysssss.AutoCompleter"; + +app.registerExtension({ + name: id, + init() { + const STRING = ComfyWidgets.STRING; + const SKIP_WIDGETS = new Set(["ttN xyPlot.x_values", "ttN xyPlot.y_values"]); + ComfyWidgets.STRING = function (node, inputName, inputData) { + const r = STRING.apply(this, arguments); + + if (inputData[1]?.multiline) { + // Disabled on this input + const config = inputData[1]?.["pysssss.autocomplete"]; + if (config === false) return r; + + // In list of widgets to skip + const id = `${node.comfyClass}.${inputName}`; + if (SKIP_WIDGETS.has(id)) return r; + + let words; + let separator; + if (typeof config === "object") { + separator = config.separator; + words = {}; + if (config.words) { + // Custom wordlist, this will have been registered on setup + Object.assign(words, TextAreaAutoComplete.groups[node.comfyClass + "." + inputName] ?? {}); + } + + for (const item of config.groups ?? []) { + if (item === "*") { + // This widget wants all global words included + Object.assign(words, TextAreaAutoComplete.globalWords); + } else { + // This widget wants a specific group included + Object.assign(words, TextAreaAutoComplete.groups[item] ?? {}); + } + } + } + + new TextAreaAutoComplete(r.widget.inputEl ?? r.widget.element, words, separator); + } + + return r; + }; + + TextAreaAutoComplete.globalSeparator = localStorage.getItem(id + ".AutoSeparate") ?? ", "; + const enabledSetting = app.ui.settings.addSetting({ + id, + name: "🐍 Text Autocomplete", + defaultValue: true, + type: (name, setter, value) => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: name, + }), + ]), + $el("td", [ + $el( + "label", + { + textContent: "Enabled ", + style: { + display: "block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-"), + type: "checkbox", + checked: value, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.enabled = checked; + setter(checked); + }, + }), + ] + ), + $el( + "label.comfy-tooltip-indicator", + { + title: "This requires other ComfyUI nodes/extensions that support using LoRAs in the prompt.", + textContent: "Loras enabled ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.lorasEnabled, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.lorasEnabled = checked; + toggleLoras(); + localStorage.setItem(id + ".ShowLoras", TextAreaAutoComplete.lorasEnabled); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Auto-insert comma ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.globalSeparator, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.globalSeparator = checked ? ", " : ""; + localStorage.setItem(id + ".AutoSeparate", TextAreaAutoComplete.globalSeparator); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Replace _ with space ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.replacer, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.replacer = checked ? (v) => v.replaceAll("_", " ") : undefined; + localStorage.setItem(id + ".ReplaceUnderscore", checked); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Insert suggestion on: ", + style: { + display: "block", + }, + }, + [ + $el( + "label", + { + textContent: "Tab", + style: { + display: "block", + marginLeft: "20px", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.insertOnTab, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.insertOnTab = checked; + localStorage.setItem(id + ".InsertOnTab", checked); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Enter", + style: { + display: "block", + marginLeft: "20px", + }, + }, + [ + $el("input", { + type: "checkbox", + checked: !!TextAreaAutoComplete.insertOnEnter, + onchange: (event) => { + const checked = !!event.target.checked; + TextAreaAutoComplete.insertOnEnter = checked; + localStorage.setItem(id + ".InsertOnEnter", checked); + }, + }), + ] + ), + ] + ), + $el( + "label", + { + textContent: "Max suggestions: ", + style: { + display: "block", + }, + }, + [ + $el("input", { + type: "number", + value: +TextAreaAutoComplete.suggestionCount, + style: { + width: "80px" + }, + onchange: (event) => { + const value = +event.target.value; + TextAreaAutoComplete.suggestionCount = value;; + localStorage.setItem(id + ".SuggestionCount", TextAreaAutoComplete.suggestionCount); + }, + }), + ] + ), + $el("button", { + textContent: "Manage Custom Words", + onclick: () => { + try { + // Try closing old settings window + if (typeof app.ui.settings.element?.close === "function") { + app.ui.settings.element.close(); + } + } catch (error) { + } + try { + // Try closing new vue dialog + document.querySelector(".p-dialog-close-button").click(); + } catch (error) { + // Fallback to just hiding the element + app.ui.settings.element.style.display = "none"; + } + + new CustomWordsDialog().show(); + }, + style: { + fontSize: "14px", + display: "block", + marginTop: "5px", + }, + }), + ]), + ]); + }, + }); + + TextAreaAutoComplete.enabled = enabledSetting.value; + TextAreaAutoComplete.replacer = localStorage.getItem(id + ".ReplaceUnderscore") === "true" ? (v) => v.replaceAll("_", " ") : undefined; + TextAreaAutoComplete.insertOnTab = localStorage.getItem(id + ".InsertOnTab") !== "false"; + TextAreaAutoComplete.insertOnEnter = localStorage.getItem(id + ".InsertOnEnter") !== "false"; + TextAreaAutoComplete.lorasEnabled = localStorage.getItem(id + ".ShowLoras") === "true"; + TextAreaAutoComplete.suggestionCount = +localStorage.getItem(id + ".SuggestionCount") || 20; + }, + setup() { + async function addEmbeddings() { + const embeddings = await api.getEmbeddings(); + const words = {}; + words["embedding:"] = { text: "embedding:" }; + + for (const emb of embeddings) { + const v = `embedding:${emb}`; + words[v] = { + text: v, + info: () => new EmbeddingInfoDialog(emb).show("embeddings", emb), + use_replacer: false, + }; + } + + TextAreaAutoComplete.updateWords("pysssss.embeddings", words); + } + + async function addLoras() { + let loras; + try { + loras = LiteGraph.registered_node_types["LoraLoader"]?.nodeData.input.required.lora_name[0]; + } catch (error) {} + + if (!loras?.length) { + loras = await api.fetchApi("/pysssss/loras", { cache: "no-store" }).then((res) => res.json()); + } + + const words = {}; + words["lora:"] = { text: "lora:" }; + + for (const lora of loras) { + const v = ``; + words[v] = { + text: v, + info: () => new LoraInfoDialog(lora).show("loras", lora), + use_replacer: false, + }; + } + + TextAreaAutoComplete.updateWords("pysssss.loras", words); + } + + // store global words with/without loras + Promise.all([addEmbeddings(), addCustomWords()]) + .then(() => { + TextAreaAutoComplete.globalWordsExclLoras = Object.assign({}, TextAreaAutoComplete.globalWords); + }) + .then(addLoras) + .then(() => { + if (!TextAreaAutoComplete.lorasEnabled) { + toggleLoras(); // off by default + } + }); + }, + beforeRegisterNodeDef(_, def) { + // Process each input to see if there is a custom word list for + // { input: { required: { something: ["STRING", { "pysssss.autocomplete": ["groupid", ["custom", "words"] ] }] } } } + const inputs = { ...def.input?.required, ...def.input?.optional }; + for (const input in inputs) { + const config = inputs[input][1]?.["pysssss.autocomplete"]; + if (!config) continue; + if (typeof config === "object" && config.words) { + const words = {}; + for (const text of config.words || []) { + const obj = typeof text === "string" ? { text } : text; + words[obj.text] = obj; + } + TextAreaAutoComplete.updateWords(def.name + "." + input, words, false); + } + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/betterCombos.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/betterCombos.js new file mode 100644 index 0000000000000000000000000000000000000000..cbf0a0740471035dc1d1d4f14101c4888dd91c2a --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/betterCombos.js @@ -0,0 +1,534 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; +import { $el } from "../../../scripts/ui.js"; +import { api } from "../../../scripts/api.js"; + +const CHECKPOINT_LOADER = "CheckpointLoader|pysssss"; +const LORA_LOADER = "LoraLoader|pysssss"; +const IMAGE_WIDTH = 384; +const IMAGE_HEIGHT = 384; + +function getType(node) { + if (node.comfyClass === CHECKPOINT_LOADER) { + return "checkpoints"; + } + return "loras"; +} + +function getWidgetName(type) { + return type === "checkpoints" ? "ckpt_name" : "lora_name"; +} + +function encodeRFC3986URIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); +} + +const calculateImagePosition = (el, bodyRect) => { + let { top, left, right } = el.getBoundingClientRect(); + const { width: bodyWidth, height: bodyHeight } = bodyRect; + + const isSpaceRight = right + IMAGE_WIDTH <= bodyWidth; + if (isSpaceRight) { + left = right; + } else { + left -= IMAGE_WIDTH; + } + + top = top - IMAGE_HEIGHT / 2; + if (top + IMAGE_HEIGHT > bodyHeight) { + top = bodyHeight - IMAGE_HEIGHT; + } + if (top < 0) { + top = 0; + } + + return { left: Math.round(left), top: Math.round(top), isLeft: !isSpaceRight }; +}; + +function showImage(relativeToEl, imageEl) { + const bodyRect = document.body.getBoundingClientRect(); + if (!bodyRect) return; + + const { left, top, isLeft } = calculateImagePosition(relativeToEl, bodyRect); + + imageEl.style.left = `${left}px`; + imageEl.style.top = `${top}px`; + + if (isLeft) { + imageEl.classList.add("left"); + } else { + imageEl.classList.remove("left"); + } + + document.body.appendChild(imageEl); +} + +let imagesByType = {}; +const loadImageList = async (type) => { + imagesByType[type] = await (await api.fetchApi(`/pysssss/images/${type}`)).json(); +}; + +app.registerExtension({ + name: "pysssss.Combo++", + init() { + const displayOptions = { "List (normal)": 0, "Tree (subfolders)": 1, "Thumbnails (grid)": 2 }; + const displaySetting = app.ui.settings.addSetting({ + id: "pysssss.Combo++.Submenu", + name: "🐍 Lora & Checkpoint loader display mode", + defaultValue: 1, + type: "combo", + options: (value) => { + value = +value; + + return Object.entries(displayOptions).map(([k, v]) => ({ + value: v, + text: k, + selected: k === value, + })); + }, + }); + + $el("style", { + textContent: ` + .pysssss-combo-image { + position: absolute; + left: 0; + top: 0; + width: ${IMAGE_WIDTH}px; + height: ${IMAGE_HEIGHT}px; + object-fit: contain; + object-position: top left; + z-index: 9999; + } + .pysssss-combo-image.left { + object-position: top right; + } + .pysssss-combo-folder { opacity: 0.7 } + .pysssss-combo-folder-arrow { display: inline-block; width: 15px; } + .pysssss-combo-folder:hover { background-color: rgba(255, 255, 255, 0.1); } + .pysssss-combo-prefix { display: none } + + /* Special handling for when the filter input is populated to revert to normal */ + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-folder-contents { + display: block !important; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-folder { + display: none; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .pysssss-combo-prefix { + display: inline; + } + .litecontextmenu:has(input:not(:placeholder-shown)) .litemenu-entry { + padding-left: 2px !important; + } + + /* Grid mode */ + .pysssss-combo-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); + gap: 10px; + overflow-x: hidden; + max-width: 60vw; + } + .pysssss-combo-grid .comfy-context-menu-filter { + grid-column: 1 / -1; + position: sticky; + top: 0; + } + .pysssss-combo-grid .litemenu-entry { + word-break: break-word; + display: flex; + flex-direction: column; + justify-content: space-between; + align-items: center; + } + .pysssss-combo-grid .litemenu-entry:before { + content: ""; + display: block; + width: 100%; + height: 250px; + background-size: contain; + background-position: center; + background-repeat: no-repeat; + /* No-image image attribution: Picture icons created by Pixel perfect - Flaticon */ + background-image: var(--background-image, url(extensions/ComfyUI-Custom-Scripts/js/assets/no-image.png)); + } + + `, + parent: document.body, + }); + const p1 = loadImageList("checkpoints"); + const p2 = loadImageList("loras"); + + const refreshComboInNodes = app.refreshComboInNodes; + app.refreshComboInNodes = async function () { + const r = await Promise.all([ + refreshComboInNodes.apply(this, arguments), + loadImageList("checkpoints").catch(() => {}), + loadImageList("loras").catch(() => {}), + ]); + return r[0]; + }; + + const imageHost = $el("img.pysssss-combo-image"); + + const positionMenu = (menu, fillWidth) => { + // compute best position + let left = app.canvas.last_mouse[0] - 10; + let top = app.canvas.last_mouse[1] - 10; + + const body_rect = document.body.getBoundingClientRect(); + const root_rect = menu.getBoundingClientRect(); + + if (body_rect.width && left > body_rect.width - root_rect.width - 10) left = body_rect.width - root_rect.width - 10; + if (body_rect.height && top > body_rect.height - root_rect.height - 10) top = body_rect.height - root_rect.height - 10; + + menu.style.left = `${left}px`; + menu.style.top = `${top}px`; + if (fillWidth) { + menu.style.right = "10px"; + } + }; + + const updateMenu = async (menu, type) => { + try { + await p1; + await p2; + } catch (error) { + console.error(error); + console.error("Error loading pysssss.betterCombos data"); + } + + // Clamp max height so it doesn't overflow the screen + const position = menu.getBoundingClientRect(); + const maxHeight = window.innerHeight - position.top - 20; + menu.style.maxHeight = `${maxHeight}px`; + + const images = imagesByType[type]; + const items = menu.querySelectorAll(".litemenu-entry"); + + // Add image handler to items + const addImageHandler = (item) => { + const text = item.getAttribute("data-value").trim(); + if (images[text]) { + const textNode = document.createTextNode("*"); + item.appendChild(textNode); + + item.addEventListener( + "mouseover", + () => { + imageHost.src = `/pysssss/view/${encodeRFC3986URIComponent(images[text])}?${+new Date()}`; + document.body.appendChild(imageHost); + showImage(item, imageHost); + }, + { passive: true } + ); + item.addEventListener( + "mouseout", + () => { + imageHost.remove(); + }, + { passive: true } + ); + item.addEventListener( + "click", + () => { + imageHost.remove(); + }, + { passive: true } + ); + } + }; + + const createTree = () => { + // Create a map to store folder structures + const folderMap = new Map(); + const rootItems = []; + const splitBy = (navigator.platform || navigator.userAgent).includes("Win") ? /\/|\\/ : /\//; + const itemsSymbol = Symbol("items"); + + // First pass - organize items into folder structure + for (const item of items) { + const path = item.getAttribute("data-value").split(splitBy); + + // Remove path from visible text + item.textContent = path[path.length - 1]; + if (path.length > 1) { + // Add the prefix path back in so it can be filtered on + const prefix = $el("span.pysssss-combo-prefix", { + textContent: path.slice(0, -1).join("/") + "/", + }); + item.prepend(prefix); + } + + addImageHandler(item); + + if (path.length === 1) { + rootItems.push(item); + continue; + } + + // Temporarily remove the item from current position + item.remove(); + + // Create folder hierarchy + let currentLevel = folderMap; + for (let i = 0; i < path.length - 1; i++) { + const folder = path[i]; + if (!currentLevel.has(folder)) { + currentLevel.set(folder, new Map()); + } + currentLevel = currentLevel.get(folder); + } + + // Store the actual item in the deepest folder + if (!currentLevel.has(itemsSymbol)) { + currentLevel.set(itemsSymbol, []); + } + currentLevel.get(itemsSymbol).push(item); + } + + const createFolderElement = (name) => { + const folder = $el("div.litemenu-entry.pysssss-combo-folder", { + innerHTML: `▶ ${name}`, + style: { paddingLeft: "5px" }, + }); + return folder; + }; + + const insertFolderStructure = (parentElement, map, level = 0) => { + for (const [folderName, content] of map.entries()) { + if (folderName === itemsSymbol) continue; + + const folderElement = createFolderElement(folderName); + folderElement.style.paddingLeft = `${level * 10 + 5}px`; + parentElement.appendChild(folderElement); + + const childContainer = $el("div.pysssss-combo-folder-contents", { + style: { display: "none" }, + }); + + // Add items in this folder + const items = content.get(itemsSymbol) || []; + for (const item of items) { + item.style.paddingLeft = `${(level + 1) * 10 + 14}px`; + childContainer.appendChild(item); + } + + // Recursively add subfolders + insertFolderStructure(childContainer, content, level + 1); + parentElement.appendChild(childContainer); + + // Add click handler for folder + folderElement.addEventListener("click", (e) => { + e.stopPropagation(); + const arrow = folderElement.querySelector(".pysssss-combo-folder-arrow"); + const contents = folderElement.nextElementSibling; + if (contents.style.display === "none") { + contents.style.display = "block"; + arrow.textContent = "▼"; + } else { + contents.style.display = "none"; + arrow.textContent = "▶"; + } + }); + } + }; + + insertFolderStructure(items[0]?.parentElement || menu, folderMap); + positionMenu(menu); + }; + + const addImageData = (item) => { + const text = item.getAttribute("data-value").trim(); + if (images[text]) { + item.style.setProperty("--background-image", `url(/pysssss/view/${encodeRFC3986URIComponent(images[text])})`); + } + }; + + if (displaySetting.value === 1 || displaySetting.value === true) { + createTree(); + } else if (displaySetting.value === 2) { + menu.classList.add("pysssss-combo-grid"); + + for (const item of items) { + addImageData(item); + } + positionMenu(menu, true); + } else { + for (const item of items) { + addImageHandler(item); + } + } + }; + + const mutationObserver = new MutationObserver((mutations) => { + const node = app.canvas.current_node; + + if (!node || (node.comfyClass !== LORA_LOADER && node.comfyClass !== CHECKPOINT_LOADER)) { + return; + } + + for (const mutation of mutations) { + for (const removed of mutation.removedNodes) { + if (removed.classList?.contains("litecontextmenu")) { + imageHost.remove(); + } + } + + for (const added of mutation.addedNodes) { + if (added.classList?.contains("litecontextmenu")) { + const overWidget = app.canvas.getWidgetAtCursor(); + const type = getType(node); + if (overWidget?.name === getWidgetName(type)) { + requestAnimationFrame(() => { + // Bad hack to prevent showing on right click menu by checking for the filter input + if (!added.querySelector(".comfy-context-menu-filter")) return; + updateMenu(added, type); + }); + } + return; + } + } + } + }); + mutationObserver.observe(document.body, { childList: true, subtree: false }); + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + const isCkpt = nodeData.name === CHECKPOINT_LOADER; + const isLora = nodeData.name === LORA_LOADER; + if (isCkpt || isLora) { + const onAdded = nodeType.prototype.onAdded; + nodeType.prototype.onAdded = function () { + onAdded?.apply(this, arguments); + const { widget: exampleList } = ComfyWidgets["COMBO"](this, "example", [[""], {}], app); + this.widgets.find((w) => w.name === "prompt").computeSize = () => [0, -4]; + let exampleWidget; + + const get = async (route, suffix) => { + const url = encodeRFC3986URIComponent(`${getType(nodeType)}${suffix || ""}`); + return await api.fetchApi(`/pysssss/${route}/${url}`); + }; + + const getExample = async () => { + if (exampleList.value === "[none]") { + if (exampleWidget) { + exampleWidget.inputEl.remove(); + exampleWidget = null; + this.widgets.length -= 1; + } + return; + } + + const v = this.widgets[0].value; + const pos = v.lastIndexOf("."); + const name = v.substr(0, pos); + let exampleName = exampleList.value; + let viewPath = `/${name}`; + if (exampleName === "notes") { + viewPath += ".txt"; + } else { + viewPath += `/${exampleName}`; + } + const example = await (await get("view", viewPath)).text(); + if (!exampleWidget) { + exampleWidget = ComfyWidgets["STRING"](this, "prompt", ["STRING", { multiline: true }], app).widget; + exampleWidget.inputEl.readOnly = true; + exampleWidget.inputEl.style.opacity = 0.6; + } + exampleWidget.value = example; + }; + + const exampleCb = exampleList.callback; + exampleList.callback = function () { + getExample(); + return exampleCb?.apply(this, arguments) ?? exampleList.value; + }; + + const listExamples = async () => { + exampleList.disabled = true; + exampleList.options.values = ["[none]"]; + exampleList.value = "[none]"; + let examples = []; + if (this.widgets[0].value) { + try { + examples = await (await get("examples", `/${this.widgets[0].value}`)).json(); + } catch (error) {} + } + exampleList.options.values = ["[none]", ...examples]; + exampleList.value = exampleList.options.values[+!!examples.length]; + exampleList.callback(); + exampleList.disabled = !examples.length; + app.graph.setDirtyCanvas(true, true); + }; + + // Expose function to update examples + nodeType.prototype["pysssss.updateExamples"] = listExamples; + + const modelWidget = this.widgets[0]; + const modelCb = modelWidget.callback; + let prev = undefined; + modelWidget.callback = function () { + let ret = modelCb?.apply(this, arguments) ?? modelWidget.value; + if (typeof ret === "object" && "content" in ret) { + ret = ret.content; + modelWidget.value = ret; + } + let v = ret; + if (prev !== v) { + listExamples(); + prev = v; + } + return ret; + }; + setTimeout(() => { + modelWidget.callback(); + }, 30); + }; + } + + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + if (this.imgs) { + // If this node has images then we add an open in new tab item + let img; + if (this.imageIndex != null) { + // An image is selected so select that + img = this.imgs[this.imageIndex]; + } else if (this.overIndex != null) { + // No image is selected but one is hovered + img = this.imgs[this.overIndex]; + } + if (img) { + const nodes = app.graph._nodes.filter((n) => n.comfyClass === LORA_LOADER || n.comfyClass === CHECKPOINT_LOADER); + if (nodes.length) { + options.unshift({ + content: "Save as Preview", + submenu: { + options: nodes.map((n) => ({ + content: n.widgets[0].value, + callback: async () => { + const url = new URL(img.src); + await api.fetchApi("/pysssss/save/" + encodeRFC3986URIComponent(`${getType(n)}/${n.widgets[0].value}`), { + method: "POST", + body: JSON.stringify({ + filename: url.searchParams.get("filename"), + subfolder: url.searchParams.get("subfolder"), + type: url.searchParams.get("type"), + }), + headers: { + "content-type": "application/json", + }, + }); + loadImageList(getType(n)); + }, + })), + }, + }); + } + } + } + return getExtraMenuOptions?.apply(this, arguments); + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.css b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.css new file mode 100644 index 0000000000000000000000000000000000000000..1f371d6203a94202c48c851a3321c7e423de477b --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.css @@ -0,0 +1,62 @@ +.pysssss-autocomplete { + color: var(--descrip-text); + background-color: var(--comfy-menu-bg); + position: absolute; + font-family: sans-serif; + box-shadow: 3px 3px 8px rgba(0, 0, 0, 0.4); + z-index: 9999; + overflow: auto; +} + +.pysssss-autocomplete-item { + cursor: pointer; + padding: 3px 7px; + display: flex; + border-left: 3px solid transparent; + align-items: center; +} + +.pysssss-autocomplete-item--selected { + border-left-color: dodgerblue; +} + +.pysssss-autocomplete-highlight { + font-weight: bold; + text-decoration: underline; + text-decoration-color: dodgerblue; +} + +.pysssss-autocomplete-pill { + margin-left: auto; + font-size: 10px; + color: #fff; + padding: 2px 4px 2px 14px; + position: relative; +} + +.pysssss-autocomplete-pill::after { + content: ""; + display: block; + background: rgba(255, 255, 255, 0.25); + width: calc(100% - 10px); + height: 100%; + position: absolute; + left: 10px; + top: 0; + border-radius: 5px; +} + +.pysssss-autocomplete-pill + .pysssss-autocomplete-pill { + margin-left: 0; +} + +.pysssss-autocomplete-item-info { + margin-left: auto; + transition: filter 0.2s; + will-change: filter; + text-decoration: none; + padding-left: 10px; +} +.pysssss-autocomplete-item-info:hover { + filter: invert(1); +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.js new file mode 100644 index 0000000000000000000000000000000000000000..ac5fb1d006bad80c67870655ccfc82a120ddc4a7 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/autocomplete.js @@ -0,0 +1,692 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +/* + https://github.com/component/textarea-caret-position + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const getCaretCoordinates = (function () { + // We'll copy the properties below into the mirror div. + // Note that some browsers, such as Firefox, do not concatenate properties + // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), + // so we have to list every single property explicitly. + var properties = [ + "direction", // RTL support + "boxSizing", + "width", // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does + "height", + "overflowX", + "overflowY", // copy the scrollbar for IE + + "borderTopWidth", + "borderRightWidth", + "borderBottomWidth", + "borderLeftWidth", + "borderStyle", + + "paddingTop", + "paddingRight", + "paddingBottom", + "paddingLeft", + + // https://developer.mozilla.org/en-US/docs/Web/CSS/font + "fontStyle", + "fontVariant", + "fontWeight", + "fontStretch", + "fontSize", + "fontSizeAdjust", + "lineHeight", + "fontFamily", + + "textAlign", + "textTransform", + "textIndent", + "textDecoration", // might not make a difference, but better be safe + + "letterSpacing", + "wordSpacing", + + "tabSize", + "MozTabSize", + ]; + + var isBrowser = typeof window !== "undefined"; + var isFirefox = isBrowser && window.mozInnerScreenX != null; + + return function getCaretCoordinates(element, position, options) { + if (!isBrowser) { + throw new Error("textarea-caret-position#getCaretCoordinates should only be called in a browser"); + } + + var debug = (options && options.debug) || false; + if (debug) { + var el = document.querySelector("#input-textarea-caret-position-mirror-div"); + if (el) el.parentNode.removeChild(el); + } + + // The mirror div will replicate the textarea's style + var div = document.createElement("div"); + div.id = "input-textarea-caret-position-mirror-div"; + document.body.appendChild(div); + + var style = div.style; + var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 + var isInput = element.nodeName === "INPUT"; + + // Default textarea styles + style.whiteSpace = "pre-wrap"; + if (!isInput) style.wordWrap = "break-word"; // only for textarea-s + + // Position off-screen + style.position = "absolute"; // required to return coordinates properly + if (!debug) style.visibility = "hidden"; // not 'display: none' because we want rendering + + // Transfer the element's properties to the div + properties.forEach(function (prop) { + if (isInput && prop === "lineHeight") { + // Special case for s because text is rendered centered and line height may be != height + if (computed.boxSizing === "border-box") { + var height = parseInt(computed.height); + var outerHeight = + parseInt(computed.paddingTop) + + parseInt(computed.paddingBottom) + + parseInt(computed.borderTopWidth) + + parseInt(computed.borderBottomWidth); + var targetHeight = outerHeight + parseInt(computed.lineHeight); + if (height > targetHeight) { + style.lineHeight = height - outerHeight + "px"; + } else if (height === targetHeight) { + style.lineHeight = computed.lineHeight; + } else { + style.lineHeight = 0; + } + } else { + style.lineHeight = computed.height; + } + } else { + style[prop] = computed[prop]; + } + }); + + if (isFirefox) { + // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 + if (element.scrollHeight > parseInt(computed.height)) style.overflowY = "scroll"; + } else { + style.overflow = "hidden"; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' + } + + div.textContent = element.value.substring(0, position); + // The second special handling for input type="text" vs textarea: + // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 + if (isInput) div.textContent = div.textContent.replace(/\s/g, "\u00a0"); + + var span = document.createElement("span"); + // Wrapping must be replicated *exactly*, including when a long word gets + // onto the next line, with whitespace at the end of the line before (#7). + // The *only* reliable way to do that is to copy the *entire* rest of the + // textarea's content into the created at the caret position. + // For inputs, just '.' would be enough, but no need to bother. + span.textContent = element.value.substring(position) || "."; // || because a completely empty faux span doesn't render at all + div.appendChild(span); + + var coordinates = { + top: span.offsetTop + parseInt(computed["borderTopWidth"]), + left: span.offsetLeft + parseInt(computed["borderLeftWidth"]), + height: parseInt(computed["lineHeight"]), + }; + + if (debug) { + span.style.backgroundColor = "#aaa"; + } else { + document.body.removeChild(div); + } + + return coordinates; + }; +})(); + +/* + Key functions from: + https://github.com/yuku/textcomplete + © Yuku Takahashi - This software is licensed under the MIT license. + + The MIT License (MIT) + + Copyright (c) 2015 Jonathan Ong me@jongleberry.com + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +const CHAR_CODE_ZERO = "0".charCodeAt(0); +const CHAR_CODE_NINE = "9".charCodeAt(0); + +class TextAreaCaretHelper { + constructor(el, getScale) { + this.el = el; + this.getScale = getScale; + } + + #calculateElementOffset() { + const rect = this.el.getBoundingClientRect(); + const owner = this.el.ownerDocument; + if (owner == null) { + throw new Error("Given element does not belong to document"); + } + const { defaultView, documentElement } = owner; + if (defaultView == null) { + throw new Error("Given element does not belong to window"); + } + const offset = { + top: rect.top + defaultView.pageYOffset, + left: rect.left + defaultView.pageXOffset, + }; + if (documentElement) { + offset.top -= documentElement.clientTop; + offset.left -= documentElement.clientLeft; + } + return offset; + } + + #isDigit(charCode) { + return CHAR_CODE_ZERO <= charCode && charCode <= CHAR_CODE_NINE; + } + + #getLineHeightPx() { + const computedStyle = getComputedStyle(this.el); + const lineHeight = computedStyle.lineHeight; + // If the char code starts with a digit, it is either a value in pixels, + // or unitless, as per: + // https://drafts.csswg.org/css2/visudet.html#propdef-line-height + // https://drafts.csswg.org/css2/cascade.html#computed-value + if (this.#isDigit(lineHeight.charCodeAt(0))) { + const floatLineHeight = parseFloat(lineHeight); + // In real browsers the value is *always* in pixels, even for unit-less + // line-heights. However, we still check as per the spec. + return this.#isDigit(lineHeight.charCodeAt(lineHeight.length - 1)) + ? floatLineHeight * parseFloat(computedStyle.fontSize) + : floatLineHeight; + } + // Otherwise, the value is "normal". + // If the line-height is "normal", calculate by font-size + return this.#calculateLineHeightPx(this.el.nodeName, computedStyle); + } + + /** + * Returns calculated line-height of the given node in pixels. + */ + #calculateLineHeightPx(nodeName, computedStyle) { + const body = document.body; + if (!body) return 0; + + const tempNode = document.createElement(nodeName); + tempNode.innerHTML = " "; + Object.assign(tempNode.style, { + fontSize: computedStyle.fontSize, + fontFamily: computedStyle.fontFamily, + padding: "0", + position: "absolute", + }); + body.appendChild(tempNode); + + // Make sure textarea has only 1 row + if (tempNode instanceof HTMLTextAreaElement) { + tempNode.rows = 1; + } + + // Assume the height of the element is the line-height + const height = tempNode.offsetHeight; + body.removeChild(tempNode); + + return height; + } + + getCursorOffset() { + const scale = this.getScale(); + const elOffset = this.#calculateElementOffset(); + const elScroll = this.#getElScroll(); + const cursorPosition = this.#getCursorPosition(); + const lineHeight = this.#getLineHeightPx(); + const top = elOffset.top - (elScroll.top * scale) + (cursorPosition.top + lineHeight) * scale; + const left = elOffset.left - elScroll.left + cursorPosition.left; + const clientTop = this.el.getBoundingClientRect().top; + if (this.el.dir !== "rtl") { + return { top, left, lineHeight, clientTop }; + } else { + const right = document.documentElement ? document.documentElement.clientWidth - left : 0; + return { top, right, lineHeight, clientTop }; + } + } + + #getElScroll() { + return { top: this.el.scrollTop, left: this.el.scrollLeft }; + } + + #getCursorPosition() { + return getCaretCoordinates(this.el, this.el.selectionEnd); + } + + getBeforeCursor() { + return this.el.selectionStart !== this.el.selectionEnd ? null : this.el.value.substring(0, this.el.selectionEnd); + } + + getAfterCursor() { + return this.el.value.substring(this.el.selectionEnd); + } + + insertAtCursor(value, offset, finalOffset) { + if (this.el.selectionStart != null) { + const startPos = this.el.selectionStart; + const endPos = this.el.selectionEnd; + + // Move selection to beginning of offset + this.el.selectionStart = this.el.selectionStart + offset; + + // Using execCommand to support undo, but since it's officially + // 'deprecated' we need a backup solution, but it won't support undo :( + let pasted = true; + try { + if (!document.execCommand("insertText", false, value)) { + pasted = false; + } + } catch (e) { + console.error("Error caught during execCommand:", e); + pasted = false; + } + + if (!pasted) { + console.error( + "execCommand unsuccessful; not supported. Adding text manually, no undo support."); + textarea.setRangeText(modifiedText, this.el.selectionStart, this.el.selectionEnd, 'end'); + } + + this.el.selectionEnd = this.el.selectionStart = startPos + value.length + offset + (finalOffset ?? 0); + } else { + // Using execCommand to support undo, but since it's officially + // 'deprecated' we need a backup solution, but it won't support undo :( + let pasted = true; + try { + if (!document.execCommand("insertText", false, value)) { + pasted = false; + } + } catch (e) { + console.error("Error caught during execCommand:", e); + pasted = false; + } + + if (!pasted) { + console.error( + "execCommand unsuccessful; not supported. Adding text manually, no undo support."); + this.el.value += value; + } + } + } +} + +/*********************/ + +/** + * @typedef {{ + * text: string, + * priority?: number, + * info?: Function, + * hint?: string, + * showValue?: boolean, + * caretOffset?: number + * }} AutoCompleteEntry + */ +export class TextAreaAutoComplete { + static globalSeparator = ""; + static enabled = true; + static insertOnTab = true; + static insertOnEnter = true; + static replacer = undefined; + static lorasEnabled = false; + static suggestionCount = 20; + + /** @type {Record>} */ + static groups = {}; + /** @type {Set} */ + static globalGroups = new Set(); + /** @type {Record} */ + static globalWords = {}; + /** @type {Record} */ + static globalWordsExclLoras = {}; + + /** @type {HTMLTextAreaElement} */ + el; + + /** @type {Record} */ + overrideWords; + overrideSeparator = ""; + + get words() { + return this.overrideWords ?? TextAreaAutoComplete.globalWords; + } + + get separator() { + return this.overrideSeparator ?? TextAreaAutoComplete.globalSeparator; + } + + /** + * @param {HTMLTextAreaElement} el + */ + constructor(el, words = null, separator = null) { + this.el = el; + this.helper = new TextAreaCaretHelper(el, () => app.canvas.ds.scale); + this.dropdown = $el("div.pysssss-autocomplete"); + this.overrideWords = words; + this.overrideSeparator = separator; + + this.#setup(); + } + + #setup() { + this.el.addEventListener("keydown", this.#keyDown.bind(this)); + this.el.addEventListener("keypress", this.#keyPress.bind(this)); + this.el.addEventListener("keyup", this.#keyUp.bind(this)); + this.el.addEventListener("click", this.#hide.bind(this)); + this.el.addEventListener("blur", () => setTimeout(() => this.#hide(), 150)); + } + + /** + * @param {KeyboardEvent} e + */ + #keyDown(e) { + if (!TextAreaAutoComplete.enabled) return; + + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "ArrowUp": + e.preventDefault(); + if (this.selected.index) { + this.#setSelected(this.currentWords[this.selected.index - 1].wordInfo); + } else { + this.#setSelected(this.currentWords[this.currentWords.length - 1].wordInfo); + } + break; + case "ArrowDown": + e.preventDefault(); + if (this.selected.index === this.currentWords.length - 1) { + this.#setSelected(this.currentWords[0].wordInfo); + } else { + this.#setSelected(this.currentWords[this.selected.index + 1].wordInfo); + } + break; + case "Tab": + if (TextAreaAutoComplete.insertOnTab) { + this.#insertItem(); + e.preventDefault(); + } + break; + } + } + } + + /** + * @param {KeyboardEvent} e + */ + #keyPress(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Enter": + if (!e.ctrlKey) { + if (TextAreaAutoComplete.insertOnEnter) { + this.#insertItem(); + e.preventDefault(); + } + } + break; + } + } + + if (!e.defaultPrevented) { + this.#update(); + } + } + + #keyUp(e) { + if (!TextAreaAutoComplete.enabled) return; + if (this.dropdown.parentElement) { + // We are visible + switch (e.key) { + case "Escape": + e.preventDefault(); + this.#hide(); + break; + } + } else if (e.key.length > 1 && e.key != "Delete" && e.key != "Backspace") { + return; + } + if (!e.defaultPrevented) { + this.#update(); + } + } + + #setSelected(item) { + if (this.selected) { + this.selected.el.classList.remove("pysssss-autocomplete-item--selected"); + } + + this.selected = item; + this.selected.el.classList.add("pysssss-autocomplete-item--selected"); + } + + #insertItem() { + if (!this.selected) return; + this.selected.el.click(); + } + + #getFilteredWords(term) { + term = term.toLocaleLowerCase(); + + const priorityMatches = []; + const prefixMatches = []; + const includesMatches = []; + for (const word of Object.keys(this.words)) { + const lowerWord = word.toLocaleLowerCase(); + if (lowerWord === term) { + // Dont include exact matches + continue; + } + + const pos = lowerWord.indexOf(term); + if (pos === -1) { + // No match + continue; + } + + const wordInfo = this.words[word]; + if (wordInfo.priority) { + priorityMatches.push({ pos, wordInfo }); + } else if (pos) { + includesMatches.push({ pos, wordInfo }); + } else { + prefixMatches.push({ pos, wordInfo }); + } + } + + priorityMatches.sort( + (a, b) => + b.wordInfo.priority - a.wordInfo.priority || + a.wordInfo.text.length - b.wordInfo.text.length || + a.wordInfo.text.localeCompare(b.wordInfo.text) + ); + + const top = priorityMatches.length * 0.2; + return priorityMatches.slice(0, top).concat(prefixMatches, priorityMatches.slice(top), includesMatches).slice(0, TextAreaAutoComplete.suggestionCount); + } + + #update() { + let before = this.helper.getBeforeCursor(); + if (before?.length) { + const m = before.match(/([^,;"|{}()\n]+)$/); + if (m) { + before = m[0] + .replace(/^\s+/, "") + .replace(/\s/g, "_") || null; + } else { + before = null; + } + } + + if (!before) { + this.#hide(); + return; + } + + this.currentWords = this.#getFilteredWords(before); + if (!this.currentWords.length) { + this.#hide(); + return; + } + + this.dropdown.style.display = ""; + + let hasSelected = false; + const items = this.currentWords.map(({ wordInfo, pos }, i) => { + const parts = [ + $el("span", { + textContent: wordInfo.text.substr(0, pos), + }), + $el("span.pysssss-autocomplete-highlight", { + textContent: wordInfo.text.substr(pos, before.length), + }), + $el("span", { + textContent: wordInfo.text.substr(pos + before.length), + }), + ]; + + if (wordInfo.hint) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.hint, + }) + ); + } + + if (wordInfo.priority) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.priority, + }) + ); + } + + if (wordInfo.value && wordInfo.text !== wordInfo.value && wordInfo.showValue !== false) { + parts.push( + $el("span.pysssss-autocomplete-pill", { + textContent: wordInfo.value, + }) + ); + } + + if (wordInfo.info) { + parts.push( + $el("a.pysssss-autocomplete-item-info", { + textContent: "ℹ️", + title: "View info...", + onclick: (e) => { + e.stopPropagation(); + wordInfo.info(); + e.preventDefault(); + }, + }) + ); + } + const item = $el( + "div.pysssss-autocomplete-item", + { + onclick: () => { + this.el.focus(); + let value = wordInfo.value ?? wordInfo.text; + const use_replacer = wordInfo.use_replacer ?? true; + if (TextAreaAutoComplete.replacer && use_replacer) { + value = TextAreaAutoComplete.replacer(value); + } + value = this.#escapeParentheses(value); + + const afterCursor = this.helper.getAfterCursor(); + const shouldAddSeparator = !afterCursor.trim().startsWith(this.separator.trim()); + this.helper.insertAtCursor( + value + (shouldAddSeparator ? this.separator : ''), + -before.length, + wordInfo.caretOffset + ); + setTimeout(() => { + this.#update(); + }, 150); + }, + }, + parts + ); + + if (wordInfo === this.selected) { + hasSelected = true; + } + + wordInfo.index = i; + wordInfo.el = item; + + return item; + }); + + this.#setSelected(hasSelected ? this.selected : this.currentWords[0].wordInfo); + this.dropdown.replaceChildren(...items); + + if (!this.dropdown.parentElement) { + document.body.append(this.dropdown); + } + + const position = this.helper.getCursorOffset(); + this.dropdown.style.left = (position.left ?? 0) + "px"; + this.dropdown.style.top = (position.top ?? 0) + "px"; + this.dropdown.style.maxHeight = (window.innerHeight - position.top) + "px"; + } + + #escapeParentheses(text) { + return text.replace(/\(/g, '\\(').replace(/\)/g, '\\)'); + } + + #hide() { + this.selected = null; + this.dropdown.remove(); + } + + static updateWords(id, words, addGlobal = true) { + const isUpdate = id in TextAreaAutoComplete.groups; + TextAreaAutoComplete.groups[id] = words; + if (addGlobal) { + TextAreaAutoComplete.globalGroups.add(id); + } + + if (isUpdate) { + // Remerge all words + TextAreaAutoComplete.globalWords = Object.assign( + {}, + ...Object.keys(TextAreaAutoComplete.groups) + .filter((k) => TextAreaAutoComplete.globalGroups.has(k)) + .map((k) => TextAreaAutoComplete.groups[k]) + ); + } else if (addGlobal) { + // Just insert the new words + Object.assign(TextAreaAutoComplete.globalWords, words); + } + } +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/binding.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/binding.js new file mode 100644 index 0000000000000000000000000000000000000000..7533e7e5e93beee798123a8ed84d36a50d2a4702 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/binding.js @@ -0,0 +1,244 @@ +// @ts-check +// @ts-ignore +import { ComfyWidgets } from "../../../../scripts/widgets.js"; +// @ts-ignore +import { api } from "../../../../scripts/api.js"; +// @ts-ignore +import { app } from "../../../../scripts/app.js"; + +const PathHelper = { + get(obj, path) { + if (typeof path !== "string") { + // Hardcoded value + return path; + } + + if (path[0] === '"' && path[path.length - 1] === '"') { + // Hardcoded string + return JSON.parse(path); + } + + // Evaluate the path + path = path.split(".").filter(Boolean); + for (const p of path) { + const k = isNaN(+p) ? p : +p; + obj = obj[k]; + } + + return obj; + }, + set(obj, path, value) { + // https://stackoverflow.com/a/54733755 + if (Object(obj) !== obj) return obj; // When obj is not an object + // If not yet an array, get the keys from the string-path + if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []; + path.slice(0, -1).reduce( + ( + a, + c, + i // Iterate all of them except the last one + ) => + Object(a[c]) === a[c] // Does the key exist and is its value an object? + ? // Yes: then follow that path + a[c] + : // No: create the key. Is the next key a potential array-index? + (a[c] = + Math.abs(path[i + 1]) >> 0 === +path[i + 1] + ? [] // Yes: assign a new array object + : {}), // No: assign a new plain object + obj + )[path[path.length - 1]] = value; // Finally assign the value to the last key + return obj; // Return the top-level object to allow chaining + }, +}; + +/*** + @typedef { { + left: string; + op: "eq" | "ne", + right: string + } } IfCondition + + @typedef { { + type: "if", + condition: Array, + true?: Array, + false?: Array + } } IfCallback + + @typedef { { + type: "fetch", + url: string, + then: Array + } } FetchCallback + + @typedef { { + type: "set", + target: string, + value: string + } } SetCallback + + @typedef { { + type: "validate-combo", + } } ValidateComboCallback + + @typedef { IfCallback | FetchCallback | SetCallback | ValidateComboCallback } BindingCallback + + @typedef { { + source: string, + callback: Array + } } Binding +***/ + +/** + * @param {IfCondition} condition + */ +function evaluateCondition(condition, state) { + const left = PathHelper.get(state, condition.left); + const right = PathHelper.get(state, condition.right); + + let r; + if (condition.op === "eq") { + r = left === right; + } else { + r = left !== right; + } + + return r; +} + +/** + * @type { Record) => Promise> } + */ +const callbacks = { + /** + * @param {IfCallback} cb + */ + async if(cb, state) { + // For now only support ANDs + let success = true; + for (const condition of cb.condition) { + const r = evaluateCondition(condition, state); + if (!r) { + success = false; + break; + } + } + + for (const m of cb[success + ""] ?? []) { + await invokeCallback(m, state); + } + }, + /** + * @param {FetchCallback} cb + */ + async fetch(cb, state) { + const url = cb.url.replace(/\{([^\}]+)\}/g, (m, v) => { + return PathHelper.get(state, v); + }); + const res = await (await api.fetchApi(url)).json(); + state["$result"] = res; + for (const m of cb.then) { + await invokeCallback(m, state); + } + }, + /** + * @param {SetCallback} cb + */ + async set(cb, state) { + const value = PathHelper.get(state, cb.value); + PathHelper.set(state, cb.target, value); + }, + async "validate-combo"(cb, state) { + const w = state["$this"]; + const valid = w.options.values.includes(w.value); + if (!valid) { + w.value = w.options.values[0]; + } + }, +}; + +async function invokeCallback(callback, state) { + if (callback.type in callbacks) { + // @ts-ignore + await callbacks[callback.type](callback, state); + } else { + console.warn( + "%c[🐍 pysssss]", + "color: limegreen", + `[binding ${state.$node.comfyClass}.${state.$this.name}]`, + "unsupported binding callback type:", + callback.type + ); + } +} + +app.registerExtension({ + name: "pysssss.Binding", + beforeRegisterNodeDef(node, nodeData) { + const hasBinding = (v) => { + if (!v) return false; + return Object.values(v).find((c) => c[1]?.["pysssss.binding"]); + }; + const inputs = { ...nodeData.input?.required, ...nodeData.input?.optional }; + if (hasBinding(inputs)) { + const onAdded = node.prototype.onAdded; + node.prototype.onAdded = function () { + const r = onAdded?.apply(this, arguments); + + for (const widget of this.widgets || []) { + const bindings = inputs[widget.name][1]?.["pysssss.binding"]; + if (!bindings) continue; + + for (const binding of bindings) { + /** + * @type {import("../../../../../web/types/litegraph.d.ts").IWidget} + */ + const source = this.widgets.find((w) => w.name === binding.source); + if (!source) { + console.warn( + "%c[🐍 pysssss]", + "color: limegreen", + `[binding ${node.comfyClass}.${widget.name}]`, + "unable to find source binding widget:", + binding.source, + binding + ); + continue; + } + + let lastValue; + async function valueChanged() { + const state = { + $this: widget, + $source: source, + $node: node, + }; + + for (const callback of binding.callback) { + await invokeCallback(callback, state); + } + + app.graph.setDirtyCanvas(true, false); + } + + const cb = source.callback; + source.callback = function () { + const v = cb?.apply(this, arguments) ?? source.value; + if (v !== lastValue) { + lastValue = v; + valueChanged(); + } + return v; + }; + + lastValue = source.value; + valueChanged(); + } + } + + return r; + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.css b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.css new file mode 100644 index 0000000000000000000000000000000000000000..c4307fd0a201f6ae396e0cb9e2b5e00dba8fc285 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.css @@ -0,0 +1,102 @@ +.pysssss-lightbox { + width: 100vw; + height: 100vh; + position: fixed; + top: 0; + left: 0; + z-index: 1001; + background: rgba(0, 0, 0, 0.6); + display: flex; + align-items: center; + transition: opacity 0.2s; +} + +.pysssss-lightbox-prev, +.pysssss-lightbox-next { + height: 60px; + display: flex; + align-items: center; +} + +.pysssss-lightbox-prev:after, +.pysssss-lightbox-next:after { + border-style: solid; + border-width: 0.25em 0.25em 0 0; + display: inline-block; + height: 0.45em; + left: 0.15em; + position: relative; + top: 0.15em; + transform: rotate(-135deg) scale(0.75); + vertical-align: top; + width: 0.45em; + padding: 10px; + font-size: 20px; + margin: 0 10px 0 20px; + transition: color 0.2s; + flex-shrink: 0; + content: ""; +} + +.pysssss-lightbox-next:after { + transform: rotate(45deg) scale(0.75); + margin: 0 20px 0 0px; +} + +.pysssss-lightbox-main { + display: grid; + flex: auto; + place-content: center; + text-align: center; +} + +.pysssss-lightbox-link { + display: flex; + justify-content: center; + align-items: center; + position: relative; +} + +.pysssss-lightbox .lds-ring { + position: absolute; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); +} + +.pysssss-lightbox-img { + max-height: 90vh; + max-width: calc(100vw - 130px); + height: auto; + object-fit: contain; + border: 3px solid white; + border-radius: 4px; + transition: opacity 0.2s; + user-select: none; +} + +.pysssss-lightbox-img:hover { + border-color: dodgerblue; +} + +.pysssss-lightbox-close { + font-size: 80px; + line-height: 1ch; + height: 1ch; + width: 1ch; + position: absolute; + right: 10px; + top: 10px; + padding: 5px; +} + +.pysssss-lightbox-close:after { + content: "\00d7"; +} + +.pysssss-lightbox-close:hover, +.pysssss-lightbox-prev:hover, +.pysssss-lightbox-next:hover { + color: dodgerblue; + cursor: pointer; +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.js new file mode 100644 index 0000000000000000000000000000000000000000..5c9079067f6fd26ab8e392e55add76d52a885858 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/lightbox.js @@ -0,0 +1,149 @@ +import { $el } from "../../../../scripts/ui.js"; +import { addStylesheet, getUrl, loadImage } from "./utils.js"; +import { createSpinner } from "./spinner.js"; + +addStylesheet(getUrl("lightbox.css", import.meta.url)); + +const $$el = (tag, name, ...args) => { + if (name) name = "-" + name; + return $el(tag + ".pysssss-lightbox" + name, ...args); +}; + +const ani = async (a, t, b) => { + a(); + await new Promise((r) => setTimeout(r, t)); + b(); +}; + +export class Lightbox { + constructor() { + this.el = $$el("div", "", { + parent: document.body, + onclick: (e) => { + e.stopImmediatePropagation(); + this.close(); + }, + style: { + display: "none", + opacity: 0, + }, + }); + this.closeBtn = $$el("div", "close", { + parent: this.el, + }); + this.prev = $$el("div", "prev", { + parent: this.el, + onclick: (e) => { + this.update(-1); + e.stopImmediatePropagation(); + }, + }); + this.main = $$el("div", "main", { + parent: this.el, + }); + this.next = $$el("div", "next", { + parent: this.el, + onclick: (e) => { + this.update(1); + e.stopImmediatePropagation(); + }, + }); + this.link = $$el("a", "link", { + parent: this.main, + target: "_blank", + }); + this.spinner = createSpinner(); + this.link.appendChild(this.spinner); + this.img = $$el("img", "img", { + style: { + opacity: 0, + }, + parent: this.link, + onclick: (e) => { + e.stopImmediatePropagation(); + }, + onwheel: (e) => { + if (!(e instanceof WheelEvent) || e.ctrlKey) { + return; + } + const direction = Math.sign(e.deltaY); + this.update(direction); + }, + }); + } + + close() { + ani( + () => (this.el.style.opacity = 0), + 200, + () => (this.el.style.display = "none") + ); + } + + async show(images, index) { + this.images = images; + this.index = index || 0; + await this.update(0); + } + + async update(shift) { + if (shift < 0 && this.index <= 0) { + return; + } + if (shift > 0 && this.index >= this.images.length - 1) { + return; + } + this.index += shift; + + this.prev.style.visibility = this.index ? "unset" : "hidden"; + this.next.style.visibility = this.index === this.images.length - 1 ? "hidden" : "unset"; + + const img = this.images[this.index]; + this.el.style.display = "flex"; + this.el.clientWidth; // Force a reflow + this.el.style.opacity = 1; + this.img.style.opacity = 0; + this.spinner.style.display = "inline-block"; + try { + await loadImage(img); + } catch (err) { + console.error('failed to load image', img, err); + } + this.spinner.style.display = "none"; + this.link.href = img; + this.img.src = img; + this.img.style.opacity = 1; + } + + async updateWithNewImage(img, feedDirection) { + // No-op if lightbox is not open + if (this.el.style.display === "none" || this.el.style.opacity === "0") return; + + // Ensure currently shown image does not change + const [method, shift] = feedDirection === "newest first" ? ["unshift", 1] : ["push", 0]; + this.images[method](img); + await this.update(shift); + } +} + +export const lightbox = new Lightbox(); + +addEventListener('keydown', (event) => { + if (lightbox.el.style.display === 'none') { + return; + } + const { key } = event; + switch (key) { + case 'ArrowLeft': + case 'a': + lightbox.update(-1); + break; + case 'ArrowRight': + case 'd': + lightbox.update(1); + break; + case 'Escape': + lightbox.close(); + break; + } +}); \ No newline at end of file diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.css b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.css new file mode 100644 index 0000000000000000000000000000000000000000..a5b9f627fc348ca17db78e5b28bc43a86e46560a --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.css @@ -0,0 +1,119 @@ +.pysssss-model-info { + color: white; + font-family: sans-serif; + max-width: 90vw; +} +.pysssss-model-content { + display: flex; + flex-direction: column; + overflow: hidden; +} +.pysssss-model-info h2 { + text-align: center; + margin: 0 0 10px 0; +} +.pysssss-model-info p { + margin: 5px 0; +} +.pysssss-model-info a { + color: dodgerblue; +} +.pysssss-model-info a:hover { + text-decoration: underline; +} +.pysssss-model-tags-list { + display: flex; + flex-wrap: wrap; + list-style: none; + gap: 10px; + max-height: 200px; + overflow: auto; + margin: 10px 0; + padding: 0; +} +.pysssss-model-tag { + background-color: rgb(128, 213, 247); + color: #000; + display: flex; + align-items: center; + gap: 5px; + border-radius: 5px; + padding: 2px 5px; + cursor: pointer; +} +.pysssss-model-tag--selected span::before { + content: "✅"; + position: absolute; + background-color: dodgerblue; + left: 0; + top: 0; + right: 0; + bottom: 0; + text-align: center; +} +.pysssss-model-tag:hover { + outline: 2px solid dodgerblue; +} +.pysssss-model-tag p { + margin: 0; +} +.pysssss-model-tag span { + text-align: center; + border-radius: 5px; + background-color: dodgerblue; + color: #fff; + padding: 2px; + position: relative; + min-width: 20px; + overflow: hidden; +} + +.pysssss-model-metadata .comfy-modal-content { + max-width: 100%; +} +.pysssss-model-metadata label { + margin-right: 1ch; + color: #ccc; +} + +.pysssss-model-metadata span { + color: dodgerblue; +} + +.pysssss-preview { + max-width: 50%; + margin-left: 10px; + position: relative; +} +.pysssss-preview img { + max-height: 300px; +} +.pysssss-preview button { + position: absolute; + font-size: 12px; + bottom: 10px; + right: 10px; +} +.pysssss-preview button+button { + bottom: 34px; +} + +.pysssss-preview button.pysssss-preview-nav { + bottom: unset; + right: 30px; + top: 10px; + font-size: 14px; + line-height: 14px; +} + +.pysssss-preview button.pysssss-preview-nav+.pysssss-preview-nav { + right: 10px; +} +.pysssss-model-notes { + background-color: rgba(0, 0, 0, 0.25); + padding: 5px; + margin-top: 5px; +} +.pysssss-model-notes:empty { + display: none; +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.js new file mode 100644 index 0000000000000000000000000000000000000000..032767da17bfc12f60ac8c6f926d8366a3b436e6 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/modelInfoDialog.js @@ -0,0 +1,358 @@ +import { $el, ComfyDialog } from "../../../../scripts/ui.js"; +import { api } from "../../../../scripts/api.js"; +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +class MetadataDialog extends ComfyDialog { + constructor() { + super(); + + this.element.classList.add("pysssss-model-metadata"); + } + show(metadata) { + super.show( + $el( + "div", + Object.keys(metadata).map((k) => + $el("div", [ + $el("label", { textContent: k }), + $el("span", { textContent: typeof metadata[k] === "object" ? JSON.stringify(metadata[k]) : metadata[k] }), + ]) + ) + ) + ); + } +} + +export class ModelInfoDialog extends ComfyDialog { + constructor(name, node) { + super(); + this.name = name; + this.node = node; + this.element.classList.add("pysssss-model-info"); + } + + get customNotes() { + return this.metadata["pysssss.notes"]; + } + + set customNotes(v) { + this.metadata["pysssss.notes"] = v; + } + + get hash() { + return this.metadata["pysssss.sha256"]; + } + + async show(type, value) { + this.type = type; + + const req = api.fetchApi("/pysssss/metadata/" + encodeURIComponent(`${type}/${value}`)); + this.info = $el("div", { style: { flex: "auto" } }); + this.img = $el("img", { style: { display: "none" } }); + this.imgWrapper = $el("div.pysssss-preview", [this.img]); + this.main = $el("main", { style: { display: "flex" } }, [this.info, this.imgWrapper]); + this.content = $el("div.pysssss-model-content", [$el("h2", { textContent: this.name }), this.main]); + + const loading = $el("div", { textContent: "ℹ️ Loading...", parent: this.content }); + + super.show(this.content); + + this.metadata = await (await req).json(); + this.viewMetadata.style.cursor = this.viewMetadata.style.opacity = ""; + this.viewMetadata.removeAttribute("disabled"); + + loading.remove(); + this.addInfo(); + } + + createButtons() { + const btns = super.createButtons(); + this.viewMetadata = $el("button", { + type: "button", + textContent: "View raw metadata", + disabled: "disabled", + style: { + opacity: 0.5, + cursor: "not-allowed", + }, + onclick: (e) => { + if (this.metadata) { + new MetadataDialog().show(this.metadata); + } + }, + }); + + btns.unshift(this.viewMetadata); + return btns; + } + + getNoteInfo() { + function parseNote() { + if (!this.customNotes) return []; + + let notes = []; + // Extract links from notes + const r = new RegExp("(\\bhttps?:\\/\\/[^\\s]+)", "g"); + let end = 0; + let m; + do { + m = r.exec(this.customNotes); + let pos; + let fin = 0; + if (m) { + pos = m.index; + fin = m.index + m[0].length; + } else { + pos = this.customNotes.length; + } + + let pre = this.customNotes.substring(end, pos); + if (pre) { + pre = pre.replaceAll("\n", "
"); + notes.push( + $el("span", { + innerHTML: pre, + }) + ); + } + if (m) { + notes.push( + $el("a", { + href: m[0], + textContent: m[0], + target: "_blank", + }) + ); + } + + end = fin; + } while (m); + return notes; + } + + let textarea; + let notesContainer; + const editText = "✏️ Edit"; + const edit = $el("a", { + textContent: editText, + href: "#", + style: { + float: "right", + color: "greenyellow", + textDecoration: "none", + }, + onclick: async (e) => { + e.preventDefault(); + + if (textarea) { + this.customNotes = textarea.value; + + const resp = await api.fetchApi("/pysssss/metadata/notes/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: this.customNotes, + }); + + if (resp.status !== 200) { + console.error(resp); + alert(`Error saving notes (${req.status}) ${req.statusText}`); + return; + } + + e.target.textContent = editText; + textarea.remove(); + textarea = null; + + notesContainer.replaceChildren(...parseNote.call(this)); + this.node?.["pysssss.updateExamples"]?.(); + } else { + e.target.textContent = "💾 Save"; + textarea = $el("textarea", { + style: { + width: "100%", + minWidth: "200px", + minHeight: "50px", + }, + textContent: this.customNotes, + }); + e.target.after(textarea); + notesContainer.replaceChildren(); + textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px"; + } + }, + }); + + notesContainer = $el("div.pysssss-model-notes", parseNote.call(this)); + return $el( + "div", + { + style: { display: "contents" }, + }, + [edit, notesContainer] + ); + } + + addInfo() { + const usageHint = this.metadata["modelspec.usage_hint"]; + if (usageHint) { + this.addInfoEntry("Usage Hint", usageHint); + } + this.addInfoEntry("Notes", this.getNoteInfo()); + } + + addInfoEntry(name, value) { + return $el( + "p", + { + parent: this.info, + }, + [ + typeof name === "string" ? $el("label", { textContent: name + ": " }) : name, + typeof value === "string" ? $el("span", { textContent: value }) : value, + ] + ); + } + + async getCivitaiDetails() { + const req = await fetch("https://civitai.com/api/v1/model-versions/by-hash/" + this.hash); + if (req.status === 200) { + return await req.json(); + } else if (req.status === 404) { + throw new Error("Model not found"); + } else { + throw new Error(`Error loading info (${req.status}) ${req.statusText}`); + } + } + + addCivitaiInfo() { + const promise = this.getCivitaiDetails(); + const content = $el("span", { textContent: "ℹ️ Loading..." }); + + this.addInfoEntry( + $el("label", [ + $el("img", { + style: { + width: "18px", + position: "relative", + top: "3px", + margin: "0 5px 0 0", + }, + src: "https://civitai.com/favicon.ico", + }), + $el("span", { textContent: "Civitai: " }), + ]), + content + ); + + return promise + .then((info) => { + content.replaceChildren( + $el("a", { + href: "https://civitai.com/models/" + info.modelId, + textContent: "View " + info.model.name, + target: "_blank", + }) + ); + + const allPreviews = info.images?.filter((i) => i.type === "image"); + const previews = allPreviews?.filter((i) => i.nsfwLevel <= ModelInfoDialog.nsfwLevel); + if (previews?.length) { + let previewIndex = 0; + let preview; + const updatePreview = () => { + preview = previews[previewIndex]; + this.img.src = preview.url; + }; + + updatePreview(); + this.img.style.display = ""; + + this.img.title = `${previews.length} previews.`; + if (allPreviews.length !== previews.length) { + this.img.title += ` ${allPreviews.length - previews.length} images hidden due to NSFW level.`; + } + + this.imgSave = $el("button", { + textContent: "Use as preview", + parent: this.imgWrapper, + onclick: async () => { + // Convert the preview to a blob + const blob = await (await fetch(this.img.src)).blob(); + + // Store it in temp + const name = "temp_preview." + new URL(this.img.src).pathname.split(".")[1]; + const body = new FormData(); + body.append("image", new File([blob], name)); + body.append("overwrite", "true"); + body.append("type", "temp"); + + const resp = await api.fetchApi("/upload/image", { + method: "POST", + body, + }); + + if (resp.status !== 200) { + console.error(resp); + alert(`Error saving preview (${req.status}) ${req.statusText}`); + return; + } + + // Use as preview + await api.fetchApi("/pysssss/save/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: JSON.stringify({ + filename: name, + type: "temp", + }), + headers: { + "content-type": "application/json", + }, + }); + app.refreshComboInNodes(); + }, + }); + + $el("button", { + textContent: "Show metadata", + parent: this.imgWrapper, + onclick: async () => { + if (preview.meta && Object.keys(preview.meta).length) { + new MetadataDialog().show(preview.meta); + } else { + alert("No image metadata found"); + } + }, + }); + + const addNavButton = (icon, direction) => { + $el("button.pysssss-preview-nav", { + textContent: icon, + parent: this.imgWrapper, + onclick: async () => { + previewIndex += direction; + if (previewIndex < 0) { + previewIndex = previews.length - 1; + } else if (previewIndex >= previews.length) { + previewIndex = 0; + } + updatePreview(); + }, + }); + }; + + if (previews.length > 1) { + addNavButton("‹", -1); + addNavButton("›", 1); + } + } else if (info.images?.length) { + $el("span", { style: { opacity: 0.6 }, textContent: "⚠️ All images hidden due to NSFW level setting.", parent: this.imgWrapper }); + } + + return info; + }) + .catch((err) => { + content.textContent = "⚠️ " + err.message; + }); + } +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.css b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.css new file mode 100644 index 0000000000000000000000000000000000000000..cfb7a0d961de791e721f5351476a0d014285736e --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.css @@ -0,0 +1,35 @@ +.pysssss-lds-ring { + display: inline-block; + position: absolute; + width: 80px; + height: 80px; +} +.pysssss-lds-ring div { + box-sizing: border-box; + display: block; + position: absolute; + width: 64px; + height: 64px; + margin: 8px; + border: 5px solid #fff; + border-radius: 50%; + animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; + border-color: #fff transparent transparent transparent; +} +.pysssss-lds-ring div:nth-child(1) { + animation-delay: -0.45s; +} +.pysssss-lds-ring div:nth-child(2) { + animation-delay: -0.3s; +} +.pysssss-lds-ring div:nth-child(3) { + animation-delay: -0.15s; +} +@keyframes lds-ring { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.js new file mode 100644 index 0000000000000000000000000000000000000000..407599017aab85cddf6edab18afe91c3013c3cf0 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/spinner.js @@ -0,0 +1,9 @@ +import { addStylesheet } from "./utils.js"; + +addStylesheet(import.meta.url); + +export function createSpinner() { + const div = document.createElement("div"); + div.innerHTML = `
`; + return div.firstElementChild; +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/utils.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..cd7539d449a2ac85672fb36da4be725f352b86f8 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/common/utils.js @@ -0,0 +1,30 @@ +import { $el } from "../../../../scripts/ui.js"; + +export function addStylesheet(url) { + if (url.endsWith(".js")) { + url = url.substr(0, url.length - 2) + "css"; + } + $el("link", { + parent: document.head, + rel: "stylesheet", + type: "text/css", + href: url.startsWith("http") ? url : getUrl(url), + }); +} + +export function getUrl(path, baseUrl) { + if (baseUrl) { + return new URL(path, baseUrl).toString(); + } else { + return new URL("../" + path, import.meta.url).toString(); + } +} + +export async function loadImage(url) { + return new Promise((res, rej) => { + const img = new Image(); + img.onload = res; + img.onerror = rej; + img.src = url; + }); +} diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/contextMenuHook.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/contextMenuHook.js new file mode 100644 index 0000000000000000000000000000000000000000..0fd35b41a4a4f6b7110c417d76235e07b22e7ce4 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/contextMenuHook.js @@ -0,0 +1,90 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.ContextMenuHook", + init() { + const getOrSet = (target, name, create) => { + if (name in target) return target[name]; + return (target[name] = create()); + }; + const symbol = getOrSet(window, "__pysssss__", () => Symbol("__pysssss__")); + const store = getOrSet(window, symbol, () => ({})); + const contextMenuHook = getOrSet(store, "contextMenuHook", () => ({})); + for (const e of ["ctor", "preAddItem", "addItem"]) { + if (!contextMenuHook[e]) { + contextMenuHook[e] = []; + } + } + + // Big ol' hack to get allow customizing the context menu + // Replace the addItem function with our own that wraps the context of "this" with a proxy + // That proxy then replaces the constructor with another proxy + // That proxy then calls the custom ContextMenu that supports filters + const ctorProxy = new Proxy(LiteGraph.ContextMenu, { + construct(target, args) { + return new LiteGraph.ContextMenu(...args); + }, + }); + + function triggerCallbacks(name, getArgs, handler) { + const callbacks = contextMenuHook[name]; + if (callbacks && callbacks instanceof Array) { + for (const cb of callbacks) { + const r = cb(...getArgs()); + handler?.call(this, r); + } + } else { + console.warn("[pysssss 🐍]", `invalid ${name} callbacks`, callbacks, name in contextMenuHook); + } + } + + const addItem = LiteGraph.ContextMenu.prototype.addItem; + LiteGraph.ContextMenu.prototype.addItem = function () { + const proxy = new Proxy(this, { + get(target, prop) { + if (prop === "constructor") { + return ctorProxy; + } + return target[prop]; + }, + }); + proxy.__target__ = this; + + let el; + let args = arguments; + triggerCallbacks( + "preAddItem", + () => [el, this, args], + (r) => { + if (r !== undefined) el = r; + } + ); + + if (el === undefined) { + el = addItem.apply(proxy, arguments); + } + + triggerCallbacks( + "addItem", + () => [el, this, args], + (r) => { + if (r !== undefined) el = r; + } + ); + return el; + }; + + // We also need to patch the ContextMenu constructor to unwrap the parent else it fails a LiteGraph type check + const ctxMenu = LiteGraph.ContextMenu; + LiteGraph.ContextMenu = function (values, options) { + if (options?.parentMenu) { + if (options.parentMenu.__target__) { + options.parentMenu = options.parentMenu.__target__; + } + } + + triggerCallbacks("ctor", () => [values, options]); + return ctxMenu.call(this, values, options); + }; + LiteGraph.ContextMenu.prototype = ctxMenu.prototype; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/customColors.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/customColors.js new file mode 100644 index 0000000000000000000000000000000000000000..2b0fefca7aa86b48d4e81126a6549e4b5fe16505 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/customColors.js @@ -0,0 +1,98 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +const colorShade = (col, amt) => { + col = col.replace(/^#/, ""); + if (col.length === 3) col = col[0] + col[0] + col[1] + col[1] + col[2] + col[2]; + + let [r, g, b] = col.match(/.{2}/g); + [r, g, b] = [parseInt(r, 16) + amt, parseInt(g, 16) + amt, parseInt(b, 16) + amt]; + + r = Math.max(Math.min(255, r), 0).toString(16); + g = Math.max(Math.min(255, g), 0).toString(16); + b = Math.max(Math.min(255, b), 0).toString(16); + + const rr = (r.length < 2 ? "0" : "") + r; + const gg = (g.length < 2 ? "0" : "") + g; + const bb = (b.length < 2 ? "0" : "") + b; + + return `#${rr}${gg}${bb}`; +}; + +app.registerExtension({ + name: "pysssss.CustomColors", + setup() { + let picker; + let activeNode; + const onMenuNodeColors = LGraphCanvas.onMenuNodeColors; + LGraphCanvas.onMenuNodeColors = function (value, options, e, menu, node) { + const r = onMenuNodeColors.apply(this, arguments); + requestAnimationFrame(() => { + const menus = document.querySelectorAll(".litecontextmenu"); + for (let i = menus.length - 1; i >= 0; i--) { + if (menus[i].firstElementChild.textContent.includes("No color") || menus[i].firstElementChild.value?.content?.includes("No color")) { + $el( + "div.litemenu-entry.submenu", + { + parent: menus[i], + $: (el) => { + el.onclick = () => { + LiteGraph.closeAllContextMenus(); + if (!picker) { + picker = $el("input", { + type: "color", + parent: document.body, + style: { + display: "none", + }, + }); + picker.onchange = () => { + if (activeNode) { + const fApplyColor = function(node){ + if (picker.value) { + if (node.constructor === LiteGraph.LGraphGroup) { + node.color = picker.value; + } else { + node.color = colorShade(picker.value, 20); + node.bgcolor = picker.value; + } + } + } + const graphcanvas = LGraphCanvas.active_canvas; + if (!graphcanvas.selected_nodes || Object.keys(graphcanvas.selected_nodes).length <= 1){ + fApplyColor(activeNode); + } else { + for (let i in graphcanvas.selected_nodes) { + fApplyColor(graphcanvas.selected_nodes[i]); + } + } + + activeNode.setDirtyCanvas(true, true); + } + }; + } + activeNode = null; + picker.value = node.bgcolor; + activeNode = node; + picker.click(); + }; + }, + }, + [ + $el("span", { + style: { + paddingLeft: "4px", + display: "block", + }, + textContent: "🎨 Custom", + }), + ] + ); + break; + } + } + }); + return r; + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/faviconStatus.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/faviconStatus.js new file mode 100644 index 0000000000000000000000000000000000000000..3dcd196bcbc83082144faef0d247ef5eac3d668c --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/faviconStatus.js @@ -0,0 +1,58 @@ +import { api } from "../../../scripts/api.js"; +import { app } from "../../../scripts/app.js"; + +// Simple script that adds the current queue size to the window title +// Adds a favicon that changes color while active + +app.registerExtension({ + name: "pysssss.FaviconStatus", + async setup() { + let link = document.querySelector("link[rel~='icon']"); + if (!link) { + link = document.createElement("link"); + link.rel = "icon"; + document.head.appendChild(link); + } + + const getUrl = (active, user) => new URL(`assets/favicon${active ? "-active" : ""}${user ? ".user" : ""}.ico`, import.meta.url); + const testUrl = async (active) => { + const url = getUrl(active, true); + const r = await fetch(url, { + method: "HEAD", + }); + if (r.status === 200) { + return url; + } + return getUrl(active, false); + }; + const activeUrl = await testUrl(true); + const idleUrl = await testUrl(false); + + let executing = false; + const update = () => (link.href = executing ? activeUrl : idleUrl); + + for (const e of ["execution_start", "progress"]) { + api.addEventListener(e, () => { + executing = true; + update(); + }); + } + + api.addEventListener("executing", ({ detail }) => { + // null will be sent when it's finished + executing = !!detail; + update(); + }); + + api.addEventListener("status", ({ detail }) => { + let title = "ComfyUI"; + if (detail && detail.exec_info.queue_remaining) { + title = `(${detail.exec_info.queue_remaining}) ${title}`; + } + document.title = title; + update(); + executing = false; + }); + update(); + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/graphArrange.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/graphArrange.js new file mode 100644 index 0000000000000000000000000000000000000000..8f25e241a2b91a01ca95a376385bdbe572994752 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/graphArrange.js @@ -0,0 +1,91 @@ +import { app } from "../../../scripts/app.js"; + +app.registerExtension({ + name: "pysssss.GraphArrange", + setup(app) { + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + options.push({ content: "Arrange (float left)", callback: () => graph.arrange() }); + options.push({ + content: "Arrange (float right)", + callback: () => { + (function () { + var margin = 50; + var layout; + + const nodes = this.computeExecutionOrder(false, true); + const columns = []; + + // Find node first use + for (let i = nodes.length - 1; i >= 0; i--) { + const node = nodes[i]; + let max = null; + for (const out of node.outputs || []) { + if (out.links) { + for (const link of out.links) { + const outNode = app.graph.getNodeById(app.graph.links[link].target_id); + if (!outNode) continue; + var l = outNode._level - 1; + if (max === null) max = l; + else if (l < max) max = l; + } + } + } + if (max != null) node._level = max; + } + + for (let i = 0; i < nodes.length; ++i) { + const node = nodes[i]; + const col = node._level || 1; + if (!columns[col]) { + columns[col] = []; + } + columns[col].push(node); + } + + let x = margin; + + for (let i = 0; i < columns.length; ++i) { + const column = columns[i]; + if (!column) { + continue; + } + column.sort((a, b) => { + var as = !(a.type === "SaveImage" || a.type === "PreviewImage"); + var bs = !(b.type === "SaveImage" || b.type === "PreviewImage"); + var r = as - bs; + if (r === 0) r = (a.inputs?.length || 0) - (b.inputs?.length || 0); + if (r === 0) r = (a.outputs?.length || 0) - (b.outputs?.length || 0); + return r; + }); + let max_size = 100; + let y = margin + LiteGraph.NODE_TITLE_HEIGHT; + for (let j = 0; j < column.length; ++j) { + const node = column[j]; + node.pos[0] = layout == LiteGraph.VERTICAL_LAYOUT ? y : x; + node.pos[1] = layout == LiteGraph.VERTICAL_LAYOUT ? x : y; + const max_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 1 : 0; + if (node.size[max_size_index] > max_size) { + max_size = node.size[max_size_index]; + } + const node_size_index = layout == LiteGraph.VERTICAL_LAYOUT ? 0 : 1; + y += node.size[node_size_index] + margin + LiteGraph.NODE_TITLE_HEIGHT + j; + } + + // Right align in column + for (let j = 0; j < column.length; ++j) { + const node = column[j]; + node.pos[0] += max_size - node.size[0]; + } + x += max_size + margin; + } + + this.setDirtyCanvas(true, true); + }).apply(app.graph); + }, + }); + return options; + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/imageFeed.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/imageFeed.js new file mode 100644 index 0000000000000000000000000000000000000000..4afdc066b023a43dccaf91884c8910b1fc470961 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/imageFeed.js @@ -0,0 +1,604 @@ +import { api } from "../../../scripts/api.js"; +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; +import { lightbox } from "./common/lightbox.js"; + +$el("style", { + textContent: ` + .pysssss-image-feed { + position: absolute; + background: var(--comfy-menu-bg); + color: var(--fg-color); + z-index: 99; + font-family: sans-serif; + font-size: 12px; + display: flex; + flex-direction: column; + } + div > .pysssss-image-feed { + position: static; + } + .pysssss-image-feed--top, .pysssss-image-feed--bottom { + width: 100vw; + min-height: 30px; + max-height: calc(var(--max-size, 20) * 1vh); + } + .pysssss-image-feed--top { + top: 0; + } + .pysssss-image-feed--bottom { + bottom: 0; + flex-direction: column-reverse; + padding-top: 5px; + } + .pysssss-image-feed--left, .pysssss-image-feed--right { + top: 0; + height: 100vh; + min-width: 200px; + max-width: calc(var(--max-size, 10) * 1vw); + } + .comfyui-body-left .pysssss-image-feed--left, .comfyui-body-right .pysssss-image-feed--right { + height: 100%; + } + .pysssss-image-feed--left { + left: 0; + } + .pysssss-image-feed--right { + right: 0; + } + + .pysssss-image-feed--left .pysssss-image-feed-menu, .pysssss-image-feed--right .pysssss-image-feed-menu { + flex-direction: column; + } + + .pysssss-image-feed-menu { + position: relative; + flex: 0 1 min-content; + display: flex; + gap: 5px; + padding: 5px; + justify-content: space-between; + } + .pysssss-image-feed-btn-group { + align-items: stretch; + display: flex; + gap: .5rem; + flex: 0 1 fit-content; + justify-content: flex-end; + } + .pysssss-image-feed-btn { + background-color:var(--comfy-input-bg); + border-radius:5px; + border:2px solid var(--border-color); + color: var(--fg-color); + cursor:pointer; + display:inline-block; + flex: 0 1 fit-content; + text-decoration:none; + } + .pysssss-image-feed-btn.sizing-btn:checked { + filter: invert(); + } + .pysssss-image-feed-btn.clear-btn { + padding: 5px 20px; + } + .pysssss-image-feed-btn.hide-btn { + padding: 5px; + aspect-ratio: 1 / 1; + } + .pysssss-image-feed-btn:hover { + filter: brightness(1.2); + } + .pysssss-image-feed-btn:active { + position:relative; + top:1px; + } + + .pysssss-image-feed-menu section { + border-radius: 5px; + background: rgba(0,0,0,0.6); + padding: 0 5px; + display: flex; + gap: 5px; + align-items: center; + position: relative; + } + .pysssss-image-feed-menu section span { + white-space: nowrap; + } + .pysssss-image-feed-menu section input { + flex: 1 1 100%; + background: rgba(0,0,0,0.6); + border-radius: 5px; + overflow: hidden; + z-index: 100; + } + + .sizing-menu { + position: relative; + } + + .size-controls-flyout { + position: absolute; + transform: scaleX(0%); + transition: 200ms ease-out; + transition-delay: 500ms; + z-index: 101; + width: 300px; + } + + .sizing-menu:hover .size-controls-flyout { + transform: scale(1, 1); + transition: 200ms linear; + transition-delay: 0; + } + .pysssss-image-feed--bottom .size-controls-flyout { + transform: scale(1,0); + transform-origin: bottom; + bottom: 0; + left: 0; + } + .pysssss-image-feed--top .size-controls-flyout { + transform: scale(1,0); + transform-origin: top; + top: 0; + left: 0; + } + .pysssss-image-feed--left .size-controls-flyout { + transform: scale(0, 1); + transform-origin: left; + top: 0; + left: 0; + } + .pysssss-image-feed--right .size-controls-flyout { + transform: scale(0, 1); + transform-origin: right; + top: 0; + right: 0; + } + + .pysssss-image-feed-menu > * { + min-height: 24px; + } + .pysssss-image-feed-list { + flex: 1 1 auto; + overflow-y: auto; + display: grid; + align-items: center; + justify-content: center; + gap: 4px; + grid-auto-rows: min-content; + grid-template-columns: repeat(var(--img-sz, 3), 1fr); + transition: 100ms linear; + scrollbar-gutter: stable both-edges; + padding: 5px; + background: var(--comfy-input-bg); + border-radius: 5px; + margin: 5px; + margin-top: 0px; + } + .pysssss-image-feed-list:empty { + display: none; + } + .pysssss-image-feed-list div { + height: 100%; + text-align: center; + } + .pysssss-image-feed-list::-webkit-scrollbar { + background: var(--comfy-input-bg); + border-radius: 5px; + } + .pysssss-image-feed-list::-webkit-scrollbar-thumb { + background:var(--comfy-menu-bg); + border: 5px solid transparent; + border-radius: 8px; + background-clip: content-box; + } + .pysssss-image-feed-list::-webkit-scrollbar-thumb:hover { + background: var(--border-color); + background-clip: content-box; + } + .pysssss-image-feed-list img { + object-fit: var(--img-fit, contain); + max-width: 100%; + max-height: calc(var(--max-size) * 1vh); + border-radius: 4px; + } + .pysssss-image-feed-list img:hover { + filter: brightness(1.2); + }`, + parent: document.body, +}); + +app.registerExtension({ + name: "pysssss.ImageFeed", + async setup() { + let visible = true; + const seenImages = new Map(); + const showButton = $el("button.comfy-settings-btn", { + textContent: "🖼️", + style: { + right: "16px", + cursor: "pointer", + display: "none", + }, + }); + let showMenuButton; + if (!app.menu?.element.style.display && app.menu?.settingsGroup) { + showMenuButton = new (await import("../../../scripts/ui/components/button.js")).ComfyButton({ + icon: "image-multiple", + action: () => showButton.click(), + tooltip: "Show Image Feed 🐍", + content: "Show Image Feed 🐍", + }); + showMenuButton.enabled = false; + showMenuButton.element.style.display = "none"; + app.menu.settingsGroup.append(showMenuButton); + } + + const getVal = (n, d) => { + const v = localStorage.getItem("pysssss.ImageFeed." + n); + if (v && !isNaN(+v)) { + return v; + } + return d; + }; + + const saveVal = (n, v) => { + localStorage.setItem("pysssss.ImageFeed." + n, v); + }; + + const imageFeed = $el("div.pysssss-image-feed"); + const imageList = $el("div.pysssss-image-feed-list"); + + function updateMenuParent(location) { + if (showMenuButton) { + const el = document.querySelector(".comfyui-body-" + location); + if (!el) return; + el.append(imageFeed); + } else { + if (!imageFeed.parent) { + document.body.append(imageFeed); + } + } + } + + const feedLocation = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Location", + name: "🐍 Image Feed Location", + defaultValue: "bottom", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + textContent: "🐍 Image Feed Location:", + }), + ]), + $el("td", [ + $el( + "select", + { + style: { + fontSize: "14px", + }, + oninput: (e) => { + feedLocation.value = e.target.value; + imageFeed.className = `pysssss-image-feed pysssss-image-feed--${feedLocation.value}`; + updateMenuParent(feedLocation.value); + saveVal("Location", feedLocation.value); + window.dispatchEvent(new Event("resize")); + }, + }, + ["left", "top", "right", "bottom", "hidden"].map((m) => + $el("option", { + value: m, + textContent: m, + selected: feedLocation.value === m, + }) + ) + ), + ]), + ]); + }, + onChange(value) { + if (value === "hidden") { + imageFeed.remove(); + if (showMenuButton) { + requestAnimationFrame(() => { + showMenuButton.element.style.display = "none"; + }); + } + showButton.style.display = "none"; + } else { + showMenuButton.element.style.display = "unset"; + showButton.style.display = visible ? "none" : "unset"; + imageFeed.className = `pysssss-image-feed pysssss-image-feed--${value}`; + updateMenuParent(value); + } + }, + }); + + const feedDirection = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Direction", + name: "🐍 Image Feed Direction", + defaultValue: "newest first", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + textContent: "🐍 Image Feed Direction:", + }), + ]), + $el("td", [ + $el( + "select", + { + style: { + fontSize: "14px", + }, + oninput: (e) => { + feedDirection.value = e.target.value; + imageList.replaceChildren(...[...imageList.childNodes].reverse()); + }, + }, + ["newest first", "oldest first"].map((m) => + $el("option", { + value: m, + textContent: m, + selected: feedDirection.value === m, + }) + ) + ), + ]), + ]); + }, + }); + + const deduplicateFeed = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.Deduplication", + name: "🐍 Image Feed Deduplication", + tooltip: `Ensures unique images in the image feed but at the cost of CPU-bound performance impact \ +(from hundreds of milliseconds to seconds per image, depending on byte size). For workflows that produce duplicate images, turning this setting on may yield overall client-side performance improvements \ +by reducing the number of images in the feed. + +Recommended: "enabled (max performance)" uness images are erroneously deduplicated.`, + defaultValue: 0, + type: "combo", + options: (value) => { + let dedupeOptions = { disabled: 0, "enabled (slow)": 1, "enabled (performance)": 0.5, "enabled (max performance)": 0.25 }; + return Object.entries(dedupeOptions).map(([k, v]) => ({ + value: v, + text: k, + selected: k === value, + })); + }, + }); + + const maxImages = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.MaxImages", + name: "🐍 Image Feed Max Images", + tooltip: `Limits the number of images in the feed to a maximum, removing the oldest images as new ones are added.`, + defaultValue: 0, + type: "number", + }); + + const saveNodeOnly = app.ui.settings.addSetting({ + id: "pysssss.ImageFeed.SaveNodeOnly", + name: "🐍 Image Feed Display 'SaveImage' Only", + tooltip: `Only show images from 'SaveImage' nodes. This prevents 'PreviewImage' node outputs from appearing in the feed.`, + defaultValue: false, + type: "boolean", + }); + + const clearButton = $el("button.pysssss-image-feed-btn.clear-btn", { + textContent: "Clear", + onclick: () => { + imageList.replaceChildren(); + window.dispatchEvent(new Event("resize")); + }, + }); + + const hideButton = $el("button.pysssss-image-feed-btn.hide-btn", { + textContent: "❌", + onclick: () => { + imageFeed.style.display = "none"; + showButton.style.display = feedLocation.value === "hidden" ? "none" : "unset"; + if (showMenuButton) { + showMenuButton.enabled = true; + showMenuButton.element.style.display = ""; + } + saveVal("Visible", 0); + visible = false; + window.dispatchEvent(new Event("resize")); + }, + }); + + let columnInput; + function updateColumnCount(v) { + columnInput.parentElement.title = `Controls the number of columns in the feed (${v} columns).\nClick label to set custom value.`; + imageFeed.style.setProperty("--img-sz", v); + saveVal("ImageSize", v); + columnInput.max = Math.max(10, v, columnInput.max); + columnInput.value = v; + window.dispatchEvent(new Event("resize")); + } + + function addImageToFeed(href) { + const method = feedDirection.value === "newest first" ? "prepend" : "append"; + + if (maxImages.value > 0 && imageList.children.length >= maxImages.value) { + imageList.children[method === "prepend" ? imageList.children.length - 1 : 0].remove(); + } + + imageList[method]( + $el("div", [ + $el( + "a", + { + target: "_blank", + href, + onclick: (e) => { + const imgs = [...imageList.querySelectorAll("img")].map((img) => img.getAttribute("src")); + lightbox.show(imgs, imgs.indexOf(href)); + e.preventDefault(); + }, + }, + [$el("img", { src: href })] + ), + ]) + ); + // If lightbox is open, update it with new image + lightbox.updateWithNewImage(href, feedDirection.value); + } + + imageFeed.append( + $el("div.pysssss-image-feed-menu", [ + $el("section.sizing-menu", {}, [ + $el("label.size-control-handle", { textContent: "↹ Resize Feed" }), + $el("div.size-controls-flyout", {}, [ + $el("section.size-control.feed-size-control", {}, [ + $el("span", { + textContent: "Feed Size...", + }), + $el("input", { + type: "range", + min: 10, + max: 80, + oninput: (e) => { + e.target.parentElement.title = `Controls the maximum size of the image feed panel (${e.target.value}vh)`; + imageFeed.style.setProperty("--max-size", e.target.value); + saveVal("FeedSize", e.target.value); + window.dispatchEvent(new Event("resize")); + }, + $: (el) => { + requestAnimationFrame(() => { + el.value = getVal("FeedSize", 25); + el.oninput({ target: el }); + }); + }, + }), + ]), + $el("section.size-control.image-size-control", {}, [ + $el("a", { + textContent: "Column count...", + style: { + cursor: "pointer", + textDecoration: "underline", + }, + onclick: () => { + const v = +prompt("Enter custom column count", 20); + if (!isNaN(v)) { + updateColumnCount(v); + } + }, + }), + $el("input", { + type: "range", + min: 1, + max: 10, + step: 1, + oninput: (e) => { + updateColumnCount(e.target.value); + }, + $: (el) => { + columnInput = el; + requestAnimationFrame(() => { + updateColumnCount(getVal("ImageSize", 4)); + }); + }, + }), + ]), + ]), + ]), + $el("div.pysssss-image-feed-btn-group", {}, [clearButton, hideButton]), + ]), + imageList + ); + showButton.onclick = () => { + imageFeed.style.display = "flex"; + showButton.style.display = "none"; + if (showMenuButton) { + showMenuButton.enabled = false; + showMenuButton.element.style.display = "none"; + } + + saveVal("Visible", 1); + visible = true; + window.dispatchEvent(new Event("resize")); + }; + document.querySelector(".comfy-settings-btn").after(showButton); + window.dispatchEvent(new Event("resize")); + + if (!+getVal("Visible", 1)) { + hideButton.onclick(); + } + + api.addEventListener("executed", ({ detail }) => { + if (visible && detail?.output?.images) { + if (detail.node?.includes?.(":")) { + // Ignore group nodes + const n = app.graph.getNodeById(detail.node.split(":")[0]); + if (n?.getInnerNodes) return; + } + + // Apply "Display Save Image Node Only" filter if setting is enabled + const nodeName = detail.node?.split(":")?.[0]; + if (nodeName) { + const node = app.graph.getNodeById(nodeName); + + if (saveNodeOnly.value && node?.type !== "SaveImage") return; + } + + for (const src of detail.output.images) { + const href = `./view?filename=${encodeURIComponent(src.filename)}&type=${src.type}& + subfolder=${encodeURIComponent(src.subfolder)}&t=${+new Date()}`; + + // deduplicateFeed.value is essentially the scaling factor used for image hashing + // but when deduplication is disabled, this value is "0" + if (deduplicateFeed.value > 0) { + // deduplicate by ignoring images with the same filename/type/subfolder + const fingerprint = JSON.stringify({ filename: src.filename, type: src.type, subfolder: src.subfolder }); + if (seenImages.has(fingerprint)) { + // NOOP: image is a duplicate + } else { + seenImages.set(fingerprint, true); + let img = $el("img", { src: href }); + img.onerror = () => { + // fall back to default behavior + addImageToFeed(href); + }; + img.onload = () => { + // redraw the image onto a canvas to strip metadata (resize if performance mode) + let imgCanvas = document.createElement("canvas"); + let imgScalar = deduplicateFeed.value; + imgCanvas.width = imgScalar * img.width; + imgCanvas.height = imgScalar * img.height; + + let imgContext = imgCanvas.getContext("2d"); + imgContext.drawImage(img, 0, 0, imgCanvas.width, imgCanvas.height); + const data = imgContext.getImageData(0, 0, imgCanvas.width, imgCanvas.height); + + // calculate fast hash of the image data + let hash = 0; + for (const b of data.data) { + hash = (hash << 5) - hash + b; + } + + // add image to feed if we've never seen the hash before + if (seenImages.has(hash)) { + // NOOP: image is a duplicate + } else { + // if we got to here, then the image is unique--so add to feed + seenImages.set(hash, true); + addImageToFeed(href); + } + }; + } + } else { + addImageToFeed(href); + } + } + } + }); + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/kSamplerAdvDenoise.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/kSamplerAdvDenoise.js new file mode 100644 index 0000000000000000000000000000000000000000..7b92d4f1d6596a6d9679d3ef4c7dffe9ea297327 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/kSamplerAdvDenoise.js @@ -0,0 +1,54 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.KSamplerAdvDenoise", + async beforeRegisterNodeDef(nodeType) { + // Add menu options to conver to/from widgets + const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = origGetExtraMenuOptions?.apply?.(this, arguments); + + let stepsWidget = null; + let startAtWidget = null; + let endAtWidget = null; + for (const w of this.widgets || []) { + if (w.name === "steps") { + stepsWidget = w; + } else if (w.name === "start_at_step") { + startAtWidget = w; + } else if (w.name === "end_at_step") { + endAtWidget = w; + } + } + + if (stepsWidget && startAtWidget && endAtWidget) { + options.push( + { + content: "Set Denoise", + callback: () => { + const steps = +prompt("How many steps do you want?", 15); + if (isNaN(steps)) { + return; + } + const denoise = +prompt("How much denoise? (0-1)", 0.5); + if (isNaN(denoise)) { + return; + } + + stepsWidget.value = Math.floor(steps / Math.max(0, Math.min(1, denoise))); + stepsWidget.callback?.(stepsWidget.value); + + startAtWidget.value = stepsWidget.value - steps; + startAtWidget.callback?.(startAtWidget.value); + + endAtWidget.value = stepsWidget.value; + endAtWidget.callback?.(endAtWidget.value); + }, + }, + null + ); + } + + return r; + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/linkRenderMode.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/linkRenderMode.js new file mode 100644 index 0000000000000000000000000000000000000000..010de6ee1085e3fbb4e5b3d3a381e38e261b53c7 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/linkRenderMode.js @@ -0,0 +1,57 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +const id = "pysssss.LinkRenderMode"; +const ext = { + name: id, + async setup(app) { + if (app.extensions.find((ext) => ext.name === "Comfy.LinkRenderMode")) { + console.log("%c[🐍 pysssss]", "color: limegreen", "Skipping LinkRenderMode as core extension found"); + return; + } + const setting = app.ui.settings.addSetting({ + id, + name: "🐍 Link Render Mode", + defaultValue: 2, + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: "🐍 Link Render Mode:", + }), + ]), + $el("td", [ + $el( + "select", + { + textContent: "Manage", + style: { + fontSize: "14px", + }, + oninput: (e) => { + setting.value = e.target.value; + app.canvas.links_render_mode = +e.target.value; + app.graph.setDirtyCanvas(true, true); + }, + }, + LiteGraph.LINK_RENDER_MODES.map((m, i) => + $el("option", { + value: i, + textContent: m, + selected: i == app.canvas.links_render_mode, + }) + ) + ), + ]), + ]); + }, + onChange(value) { + app.canvas.links_render_mode = +value; + app.graph.setDirtyCanvas(true); + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/mathExpression.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/mathExpression.js new file mode 100644 index 0000000000000000000000000000000000000000..d0dde50ec2fa00a556b56baa17ec2be340035ef3 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/mathExpression.js @@ -0,0 +1,44 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +app.registerExtension({ + name: "pysssss.MathExpression", + init() { + const STRING = ComfyWidgets.STRING; + ComfyWidgets.STRING = function (node, inputName, inputData) { + const r = STRING.apply(this, arguments); + r.widget.dynamicPrompts = inputData?.[1].dynamicPrompts; + return r; + }; + }, + beforeRegisterNodeDef(nodeType) { + if (nodeType.comfyClass === "MathExpression|pysssss") { + const onDrawForeground = nodeType.prototype.onDrawForeground; + + nodeType.prototype.onNodeCreated = function() { + // These are typed as any to bypass backend validation + // update frontend to restrict types + for(const input of this.inputs) { + input.type = "INT,FLOAT,IMAGE,LATENT"; + } + } + + nodeType.prototype.onDrawForeground = function (ctx) { + const r = onDrawForeground?.apply?.(this, arguments); + + const v = app.nodeOutputs?.[this.id + ""]; + if (!this.flags.collapsed && v) { + const text = v.value[0] + ""; + ctx.save(); + ctx.font = "bold 12px sans-serif"; + ctx.fillStyle = "dodgerblue"; + const sz = ctx.measureText(text); + ctx.fillText(text, this.size[0] - sz.width - 5, LiteGraph.NODE_SLOT_HEIGHT * 3); + ctx.restore(); + } + + return r; + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/middleClickAddDefaultNode.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/middleClickAddDefaultNode.js new file mode 100644 index 0000000000000000000000000000000000000000..43f944f2835f56357b7701c2ef987261ceff9a8b --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/middleClickAddDefaultNode.js @@ -0,0 +1,49 @@ +import { app } from "../../../scripts/app.js"; + +const id = "pysssss.MiddleClickAddDefaultNode"; +const ext = { + name: id, + async setup(app) { + app.ui.settings.addSetting({ + id, + name: "🐍 Middle click slot to add", + defaultValue: "Reroute", + type: "combo", + options: (value) => + [ + ...Object.keys(LiteGraph.registered_node_types) + .filter((k) => k.includes("Reroute")) + .sort((a, b) => { + if (a === "Reroute") return -1; + if (b === "Reroute") return 1; + return a.localeCompare(b); + }), + "[None]", + ].map((m) => ({ + value: m, + text: m, + selected: !value ? m === "[None]" : m === value, + })), + onChange(value) { + const enable = value && value !== "[None]"; + if (value === true) { + value = "Reroute"; + } + LiteGraph.middle_click_slot_add_default_node = enable; + if (enable) { + for (const arr of Object.values(LiteGraph.slot_types_default_in).concat( + Object.values(LiteGraph.slot_types_default_out) + )) { + const idx = arr.indexOf(value); + if (idx !== 0) { + arr.splice(idx, 1); + } + arr.unshift(value); + } + } + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/modelInfo.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/modelInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..b5db20a113fdb8f75b820306985fbf743e5f6bcc --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/modelInfo.js @@ -0,0 +1,412 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; +import { ModelInfoDialog } from "./common/modelInfoDialog.js"; + +const MAX_TAGS = 500; +const NsfwLevel = { + PG: 1, + PG13: 2, + R: 4, + X: 8, + XXX: 16, + Blocked: 32, +}; + +export class LoraInfoDialog extends ModelInfoDialog { + getTagFrequency() { + if (!this.metadata.ss_tag_frequency) return []; + + const datasets = JSON.parse(this.metadata.ss_tag_frequency); + const tags = {}; + for (const setName in datasets) { + const set = datasets[setName]; + for (const t in set) { + if (t in tags) { + tags[t] += set[t]; + } else { + tags[t] = set[t]; + } + } + } + + return Object.entries(tags).sort((a, b) => b[1] - a[1]); + } + + getResolutions() { + let res = []; + if (this.metadata.ss_bucket_info) { + const parsed = JSON.parse(this.metadata.ss_bucket_info); + if (parsed?.buckets) { + for (const { resolution, count } of Object.values(parsed.buckets)) { + res.push([count, `${resolution.join("x")} * ${count}`]); + } + } + } + res = res.sort((a, b) => b[0] - a[0]).map((a) => a[1]); + let r = this.metadata.ss_resolution; + if (r) { + const s = r.split(","); + const w = s[0].replace("(", ""); + const h = s[1].replace(")", ""); + res.push(`${w.trim()}x${h.trim()} (Base res)`); + } else if ((r = this.metadata["modelspec.resolution"])) { + res.push(r + " (Base res"); + } + if (!res.length) { + res.push("⚠️ Unknown"); + } + return res; + } + + getTagList(tags) { + return tags.map((t) => + $el( + "li.pysssss-model-tag", + { + dataset: { + tag: t[0], + }, + $: (el) => { + el.onclick = () => { + el.classList.toggle("pysssss-model-tag--selected"); + }; + }, + }, + [ + $el("p", { + textContent: t[0], + }), + $el("span", { + textContent: t[1], + }), + ] + ) + ); + } + + addTags() { + let tags = this.getTagFrequency(); + if (!tags?.length) { + tags = this.metadata["modelspec.tags"]?.split(",").map((t) => [t.trim(), 1]); + } + let hasMore; + if (tags?.length) { + const c = tags.length; + let list; + if (c > MAX_TAGS) { + tags = tags.slice(0, MAX_TAGS); + hasMore = $el("p", [ + $el("span", { textContent: `⚠️ Only showing first ${MAX_TAGS} tags ` }), + $el("a", { + href: "#", + textContent: `Show all ${c}`, + onclick: () => { + list.replaceChildren(...this.getTagList(this.getTagFrequency())); + hasMore.remove(); + }, + }), + ]); + } + list = $el("ol.pysssss-model-tags-list", this.getTagList(tags)); + this.tags = $el("div", [list]); + } else { + this.tags = $el("p", { textContent: "⚠️ No tag frequency metadata found" }); + } + + this.content.append(this.tags); + + if (hasMore) { + this.content.append(hasMore); + } + } + + addExample(title, value, name) { + const textArea = $el("textarea", { + textContent: value, + style: { + whiteSpace: "pre-wrap", + margin: "10px 0", + color: "#fff", + background: "#222", + padding: "5px", + borderRadius: "5px", + maxHeight: "250px", + overflow: "auto", + display: "block", + border: "none", + width: "calc(100% - 10px)", + }, + }); + $el( + "p", + { + parent: this.content, + textContent: `${title}: `, + }, + [ + textArea, + $el("button", { + onclick: async () => { + await this.saveAsExample(textArea.value, `${name}.txt`); + }, + textContent: "Save as Example", + style: { + fontSize: "14px", + }, + }), + $el("hr"), + ] + ); + } + + async addInfo() { + this.addInfoEntry("Name", this.metadata.ss_output_name || "⚠️ Unknown"); + this.addInfoEntry("Base Model", this.metadata.ss_sd_model_name || "⚠️ Unknown"); + this.addInfoEntry("Clip Skip", this.metadata.ss_clip_skip || "⚠️ Unknown"); + + this.addInfoEntry( + "Resolution", + $el( + "select", + this.getResolutions().map((r) => $el("option", { textContent: r })) + ) + ); + + super.addInfo(); + const p = this.addCivitaiInfo(); + this.addTags(); + + const info = await p; + this.addExample("Trained Words", info?.trainedWords?.join(", ") ?? "", "trainedwords"); + + const triggerPhrase = this.metadata["modelspec.trigger_phrase"]; + if (triggerPhrase) { + this.addExample("Trigger Phrase", triggerPhrase, "triggerphrase"); + } + + $el("div", { + parent: this.content, + innerHTML: info?.description ?? this.metadata["modelspec.description"] ?? "[No description provided]", + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + + async saveAsExample(example, name = "example.txt") { + if (!example.length) { + return; + } + try { + name = prompt("Enter example name", name); + if (!name) return; + + await api.fetchApi("/pysssss/examples/" + encodeURIComponent(`${this.type}/${this.name}`), { + method: "POST", + body: JSON.stringify({ + name, + example, + }), + headers: { + "content-type": "application/json", + }, + }); + this.node?.["pysssss.updateExamples"]?.(); + alert("Saved!"); + } catch (error) { + console.error(error); + alert("Error saving: " + error); + } + } + + createButtons() { + const btns = super.createButtons(); + function tagsToCsv(tags) { + return tags.map((el) => el.dataset.tag).join(", "); + } + function copyTags(e, tags) { + const textarea = $el("textarea", { + parent: document.body, + style: { + position: "fixed", + }, + textContent: tagsToCsv(tags), + }); + textarea.select(); + try { + document.execCommand("copy"); + if (!e.target.dataset.text) { + e.target.dataset.text = e.target.textContent; + } + e.target.textContent = "Copied " + tags.length + " tags"; + setTimeout(() => { + e.target.textContent = e.target.dataset.text; + }, 1000); + } catch (ex) { + prompt("Copy to clipboard: Ctrl+C, Enter", text); + } finally { + document.body.removeChild(textarea); + } + } + + btns.unshift( + $el("button", { + type: "button", + textContent: "Save Selected as Example", + onclick: async (e) => { + const tags = tagsToCsv([...this.tags.querySelectorAll(".pysssss-model-tag--selected")]); + await this.saveAsExample(tags); + }, + }), + $el("button", { + type: "button", + textContent: "Copy Selected", + onclick: (e) => { + copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag--selected")]); + }, + }), + $el("button", { + type: "button", + textContent: "Copy All", + onclick: (e) => { + copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag")]); + }, + }) + ); + + return btns; + } +} + +class CheckpointInfoDialog extends ModelInfoDialog { + async addInfo() { + super.addInfo(); + const info = await this.addCivitaiInfo(); + if (info) { + this.addInfoEntry("Base Model", info.baseModel || "⚠️ Unknown"); + + $el("div", { + parent: this.content, + innerHTML: info.description, + style: { + maxHeight: "250px", + overflow: "auto", + }, + }); + } + } +} + +const lookups = {}; + +function addInfoOption(node, type, infoClass, widgetNamePattern, opts) { + const widgets = widgetNamePattern + ? node.widgets.filter((w) => w.name === widgetNamePattern || w.name.match(`^${widgetNamePattern}$`)) + : [node.widgets[0]]; + for (const widget of widgets) { + let value = widget.value; + if (value?.content) { + value = value.content; + } + if (!value || value === "None") { + return; + } + let optName; + const split = value.split(/[.\\/]/); + optName = split[split.length - 2]; + opts.push({ + content: optName, + callback: async () => { + new infoClass(value, node).show(type, value); + }, + }); + } +} + +function addTypeOptions(node, typeName, options) { + const type = typeName.toLowerCase() + "s"; + const values = lookups[typeName][node.type]; + if (!values) return; + + const widgets = Object.keys(values); + const cls = type === "loras" ? LoraInfoDialog : CheckpointInfoDialog; + + const opts = []; + for (const w of widgets) { + addInfoOption(node, type, cls, w, opts); + } + + if (!opts.length) return; + + if (opts.length === 1) { + opts[0].content = `View ${typeName} info...`; + options.unshift(opts[0]); + } else { + options.unshift({ + title: `View ${typeName} info...`, + has_submenu: true, + submenu: { + options: opts, + }, + }); + } +} + +app.registerExtension({ + name: "pysssss.ModelInfo", + setup() { + const addSetting = (type, defaultValue) => { + app.ui.settings.addSetting({ + id: `pysssss.ModelInfo.${type}Nodes`, + name: `🐍 Model Info - ${type} Nodes/Widgets`, + type: "text", + defaultValue, + tooltip: `Comma separated list of NodeTypeName or NodeTypeName.WidgetName that contain ${type} node names that should have the View Info option available.\nIf no widget name is specifed the first widget will be used. Regex matches (e.g. NodeName..*lora_\\d+) are supported in the widget name.`, + onChange(value) { + lookups[type] = value.split(",").reduce((p, n) => { + n = n.trim(); + const pos = n.indexOf("."); + const split = pos === -1 ? [n] : [n.substring(0, pos), n.substring(pos + 1)]; + p[split[0]] ??= {}; + p[split[0]][split[1] ?? ""] = true; + return p; + }, {}); + }, + }); + }; + addSetting( + "Lora", + ["LoraLoader.lora_name", "LoraLoader|pysssss", "LoraLoaderModelOnly.lora_name", "LoRA Stacker.lora_name.*"].join(",") + ); + addSetting( + "Checkpoint", + ["CheckpointLoader.ckpt_name", "CheckpointLoaderSimple", "CheckpointLoader|pysssss", "Efficient Loader", "Eff. Loader SDXL"].join(",") + ); + + app.ui.settings.addSetting({ + id: `pysssss.ModelInfo.NsfwLevel`, + name: `🐍 Model Info - Image Preview Max NSFW Level`, + type: "combo", + defaultValue: "PG13", + options: Object.keys(NsfwLevel), + tooltip: `Hides preview images that are tagged as a higher NSFW level`, + onChange(value) { + ModelInfoDialog.nsfwLevel = NsfwLevel[value] ?? NsfwLevel.PG; + }, + }); + }, + beforeRegisterNodeDef(nodeType) { + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + if (this.widgets) { + for (const type in lookups) { + addTypeOptions(this, type, options); + } + } + + return getExtraMenuOptions?.apply(this, arguments); + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/nodeFinder.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/nodeFinder.js new file mode 100644 index 0000000000000000000000000000000000000000..d3727724b4ad09454aa77736115d81d6426be9ef --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/nodeFinder.js @@ -0,0 +1,82 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; + +// Adds a menu option to toggle follow the executing node +// Adds a menu option to go to the currently executing node +// Adds a menu option to go to a node by type + +app.registerExtension({ + name: "pysssss.NodeFinder", + setup() { + let followExecution = false; + + const centerNode = (id) => { + if (!followExecution || !id) return; + const node = app.graph.getNodeById(id); + if (!node) return; + app.canvas.centerOnNode(node); + }; + + api.addEventListener("executing", ({ detail }) => centerNode(detail)); + + // Add canvas menu options + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + options.push(null, { + content: followExecution ? "Stop following execution" : "Follow execution", + callback: () => { + if ((followExecution = !followExecution)) { + centerNode(app.runningNodeId); + } + }, + }); + if (app.runningNodeId) { + options.push({ + content: "Show executing node", + callback: () => { + const node = app.graph.getNodeById(app.runningNodeId); + if (!node) return; + app.canvas.centerOnNode(node); + }, + }); + } + + const nodes = app.graph._nodes; + const types = nodes.reduce((p, n) => { + if (n.type in p) { + p[n.type].push(n); + } else { + p[n.type] = [n]; + } + return p; + }, {}); + options.push({ + content: "Go to node", + has_submenu: true, + submenu: { + options: Object.keys(types) + .sort() + .map((t) => ({ + content: t, + has_submenu: true, + submenu: { + options: types[t] + .sort((a, b) => { + return a.pos[0] - b.pos[0]; + }) + .map((n) => ({ + content: `${n.getTitle()} - #${n.id} (${n.pos[0]}, ${n.pos[1]})`, + callback: () => { + app.canvas.centerOnNode(n); + }, + })), + }, + })), + }, + }); + + return options; + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/playSound.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/playSound.js new file mode 100644 index 0000000000000000000000000000000000000000..de71058989079786807ad4b66ca6853c4b0b0ac7 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/playSound.js @@ -0,0 +1,36 @@ +import { app } from "../../../scripts/app.js"; + +app.registerExtension({ + name: "pysssss.PlaySound", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "PlaySound|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = async function () { + onExecuted?.apply(this, arguments); + if (this.widgets[0].value === "on empty queue") { + if (app.ui.lastQueueSize !== 0) { + await new Promise((r) => setTimeout(r, 500)); + } + if (app.ui.lastQueueSize !== 0) { + return; + } + } + let file = this.widgets[2].value; + if (!file) { + file = "notify.mp3"; + } + if (!file.startsWith("http")) { + if (!file.includes("/")) { + file = "assets/" + file; + } + file = new URL(file, import.meta.url) + } + + const url = new URL(file); + const audio = new Audio(url); + audio.volume = this.widgets[1].value; + audio.play(); + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/presetText.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/presetText.js new file mode 100644 index 0000000000000000000000000000000000000000..472f11bef9caa382703f6144c32d48c647b2443d --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/presetText.js @@ -0,0 +1,257 @@ +import { app } from "../../../scripts/app.js"; + +// Allows you to manage preset tags for e.g. common negative prompt +// Also performs replacements on any text field e.g. allowing you to use preset text in CLIP Text encode fields + +let replaceRegex; +const id = "pysssss.PresetText.Presets"; +const MISSING = Symbol(); + +const getPresets = () => { + let items; + try { + items = JSON.parse(localStorage.getItem(id)); + } catch (error) {} + if (!items || !items.length) { + items = [{ name: "default negative", value: "worst quality" }]; + } + return items; +}; + +let presets = getPresets(); + +app.registerExtension({ + name: "pysssss.PresetText", + setup() { + app.ui.settings.addSetting({ + id: "pysssss.PresetText.ReplacementRegex", + name: "🐍 Preset Text Replacement Regex", + type: "text", + defaultValue: "(?:^|[^\\w])(?@(?[\\w-]+))", + tooltip: + "The regex should return two named capture groups: id (the name of the preset text to use), replace (the matched text to replace)", + attrs: { + style: { + fontFamily: "monospace", + }, + }, + onChange(value) { + if (!value) { + replaceRegex = null; + return; + } + try { + replaceRegex = new RegExp(value, "g"); + } catch (error) { + alert("Error creating regex for preset text replacement, no replacements will be performed."); + replaceRegex = null; + } + }, + }); + + const drawNodeWidgets = LGraphCanvas.prototype.drawNodeWidgets + LGraphCanvas.prototype.drawNodeWidgets = function(node) { + const c = LiteGraph.WIDGET_BGCOLOR; + try { + if(node[MISSING]) { + LiteGraph.WIDGET_BGCOLOR = "red" + } + return drawNodeWidgets.apply(this, arguments); + } finally { + LiteGraph.WIDGET_BGCOLOR = c; + } + } + }, + registerCustomNodes() { + class PresetTextNode extends LiteGraph.LGraphNode { + constructor() { + super(); + this.title = "Preset Text 🐍"; + this.isVirtualNode = true; + this.serialize_widgets = true; + this.addOutput("text", "STRING"); + + const widget = this.addWidget("combo", "value", presets[0].name, () => {}, { + values: presets.map((p) => p.name), + }); + this.addWidget("button", "Manage", "Manage", () => { + const container = document.createElement("div"); + Object.assign(container.style, { + display: "grid", + gridTemplateColumns: "1fr 1fr", + gap: "10px", + }); + + const addNew = document.createElement("button"); + addNew.textContent = "Add New"; + addNew.classList.add("pysssss-presettext-addnew"); + Object.assign(addNew.style, { + fontSize: "13px", + gridColumn: "1 / 3", + color: "dodgerblue", + width: "auto", + textAlign: "center", + }); + addNew.onclick = () => { + addRow({ name: "", value: "" }); + }; + container.append(addNew); + + function addRow(p) { + const name = document.createElement("input"); + const nameLbl = document.createElement("label"); + name.value = p.name; + nameLbl.textContent = "Name:"; + nameLbl.append(name); + + const value = document.createElement("input"); + const valueLbl = document.createElement("label"); + value.value = p.value; + valueLbl.textContent = "Value:"; + valueLbl.append(value); + + addNew.before(nameLbl, valueLbl); + } + for (const p of presets) { + addRow(p); + } + + const help = document.createElement("span"); + help.textContent = "To remove a preset set the name or value to blank"; + help.style.gridColumn = "1 / 3"; + container.append(help); + + dialog.show(""); + dialog.textElement.append(container); + }); + + const dialog = new app.ui.dialog.constructor(); + dialog.element.classList.add("comfy-settings"); + + const closeButton = dialog.element.querySelector("button"); + closeButton.textContent = "CANCEL"; + const saveButton = document.createElement("button"); + saveButton.textContent = "SAVE"; + saveButton.onclick = function () { + const inputs = dialog.element.querySelectorAll("input"); + const p = []; + for (let i = 0; i < inputs.length; i += 2) { + const n = inputs[i]; + const v = inputs[i + 1]; + if (!n.value.trim() || !v.value.trim()) { + continue; + } + p.push({ name: n.value, value: v.value }); + } + + widget.options.values = p.map((p) => p.name); + if (!widget.options.values.includes(widget.value)) { + widget.value = widget.options.values[0]; + } + + presets = p; + localStorage.setItem(id, JSON.stringify(presets)); + + dialog.close(); + }; + + closeButton.before(saveButton); + + this.applyToGraph = function (workflow) { + // For each output link copy our value over the original widget value + if (this.outputs[0].links && this.outputs[0].links.length) { + for (const l of this.outputs[0].links) { + const link_info = app.graph.links[l]; + const outNode = app.graph.getNodeById(link_info.target_id); + const outIn = outNode && outNode.inputs && outNode.inputs[link_info.target_slot]; + if (outIn.widget) { + const w = outNode.widgets.find((w) => w.name === outIn.widget.name); + if (!w) continue; + const preset = presets.find((p) => p.name === widget.value); + if (!preset) { + this[MISSING] = true; + app.graph.setDirtyCanvas(true, true); + const msg = `Preset text '${widget.value}' not found. Please fix this and queue again.`; + throw new Error(msg); + } + delete this[MISSING]; + w.value = preset.value; + } + } + } + }; + } + } + + LiteGraph.registerNodeType( + "PresetText|pysssss", + Object.assign(PresetTextNode, { + title: "Preset Text 🐍", + }) + ); + + PresetTextNode.category = "utils"; + }, + nodeCreated(node) { + if (node.widgets) { + // Locate dynamic prompt text widgets + const widgets = node.widgets.filter((n) => n.type === "customtext" || n.type === "text"); + for (const widget of widgets) { + const callbacks = [ + () => { + let prompt = widget.value; + if (replaceRegex && typeof prompt.replace !== 'undefined') { + prompt = prompt.replace(replaceRegex, (match, p1, p2, index, text, groups) => { + if (!groups.replace || !groups.id) return match; // No match, bad regex? + + const preset = presets.find((p) => p.name.replaceAll(/\s/g, "-") === groups.id); + if (!preset) return match; // Invalid name + + const pos = match.indexOf(groups.replace); + return match.substring(0, pos) + preset.value; + }); + } + return prompt; + }, + ]; + let inheritedSerializeValue = widget.serializeValue || null; + + let called = false; + const serializeValue = async (workflowNode, widgetIndex) => { + const origWidgetValue = widget.value; + if (called) return origWidgetValue; + called = true; + + let allCallbacks = [...callbacks]; + if (inheritedSerializeValue) { + allCallbacks.push(inheritedSerializeValue) + } + let valueIsUndefined = false; + + for (const cb of allCallbacks) { + let value = await cb(workflowNode, widgetIndex); + // Need to check the callback return value before it is set on widget.value as it coerces it to a string (even for undefined) + if (value === undefined) valueIsUndefined = true; + widget.value = value; + } + + const prompt = valueIsUndefined ? undefined : widget.value; + widget.value = origWidgetValue; + + called = false; + + return prompt; + }; + + Object.defineProperty(widget, "serializeValue", { + get() { + return serializeValue; + }, + set(cb) { + inheritedSerializeValue = cb; + }, + }); + } + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/quickNodes.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/quickNodes.js new file mode 100644 index 0000000000000000000000000000000000000000..a52581b32ed9cc6af01f016774518d17693b2132 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/quickNodes.js @@ -0,0 +1,196 @@ +import { app } from "../../../scripts/app.js"; + +// Adds a bunch of context menu entries for quickly adding common steps + +function addMenuHandler(nodeType, cb) { + const getOpts = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function () { + const r = getOpts.apply(this, arguments); + cb.apply(this, arguments); + return r; + }; +} + +function getOrAddVAELoader(node) { + let vaeNode = app.graph._nodes.find((n) => n.type === "VAELoader"); + if (!vaeNode) { + vaeNode = addNode("VAELoader", node); + } + return vaeNode; +} + +function addNode(name, nextTo, options) { + options = { select: true, shiftY: 0, before: false, ...(options || {}) }; + const node = LiteGraph.createNode(name); + app.graph.add(node); + node.pos = [ + options.before ? nextTo.pos[0] - node.size[0] - 30 : nextTo.pos[0] + nextTo.size[0] + 30, + nextTo.pos[1] + options.shiftY, + ]; + if (options.select) { + app.canvas.selectNode(node, false); + } + return node; +} + +app.registerExtension({ + name: "pysssss.QuickNodes", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.input && nodeData.input.required) { + const keys = Object.keys(nodeData.input.required); + for (let i = 0; i < keys.length; i++) { + if (nodeData.input.required[keys[i]][0] === "VAE") { + addMenuHandler(nodeType, function (_, options) { + options.unshift({ + content: "Use VAE", + callback: () => { + getOrAddVAELoader(this).connect(0, this, i); + }, + }); + }); + break; + } + } + } + + if (nodeData.name === "KSampler") { + addMenuHandler(nodeType, function (_, options) { + options.unshift( + { + content: "Add Blank Input", + callback: () => { + const imageNode = addNode("EmptyLatentImage", this, { before: true }); + imageNode.connect(0, this, 3); + }, + }, + { + content: "Add Hi-res Fix", + callback: () => { + const upscaleNode = addNode("LatentUpscale", this); + this.connect(0, upscaleNode, 0); + + const sampleNode = addNode("KSampler", upscaleNode); + + for (let i = 0; i < 3; i++) { + const l = this.getInputLink(i); + if (l) { + app.graph.getNodeById(l.origin_id).connect(l.origin_slot, sampleNode, i); + } + } + + upscaleNode.connect(0, sampleNode, 3); + }, + }, + { + content: "Add 2nd Pass", + callback: () => { + const upscaleNode = addNode("LatentUpscale", this); + this.connect(0, upscaleNode, 0); + + const ckptNode = addNode("CheckpointLoaderSimple", this); + const sampleNode = addNode("KSampler", ckptNode); + + const positiveLink = this.getInputLink(1); + const negativeLink = this.getInputLink(2); + const positiveNode = positiveLink + ? app.graph.add(app.graph.getNodeById(positiveLink.origin_id).clone()) + : addNode("CLIPTextEncode"); + const negativeNode = negativeLink + ? app.graph.add(app.graph.getNodeById(negativeLink.origin_id).clone()) + : addNode("CLIPTextEncode"); + + ckptNode.connect(0, sampleNode, 0); + ckptNode.connect(1, positiveNode, 0); + ckptNode.connect(1, negativeNode, 0); + positiveNode.connect(0, sampleNode, 1); + negativeNode.connect(0, sampleNode, 2); + upscaleNode.connect(0, sampleNode, 3); + }, + }, + { + content: "Add Save Image", + callback: () => { + const decodeNode = addNode("VAEDecode", this); + this.connect(0, decodeNode, 0); + + getOrAddVAELoader(decodeNode).connect(0, decodeNode, 1); + + const saveNode = addNode("SaveImage", decodeNode); + decodeNode.connect(0, saveNode, 0); + }, + } + ); + }); + } + + if (nodeData.name === "CheckpointLoaderSimple") { + addMenuHandler(nodeType, function (_, options) { + options.unshift({ + content: "Add Clip Skip", + callback: () => { + const clipSkipNode = addNode("CLIPSetLastLayer", this); + const clipLinks = this.outputs[1].links ? this.outputs[1].links.map((l) => ({ ...graph.links[l] })) : []; + + this.disconnectOutput(1); + this.connect(1, clipSkipNode, 0); + + for (const clipLink of clipLinks) { + clipSkipNode.connect(0, clipLink.target_id, clipLink.target_slot); + } + }, + }); + }); + } + + if ( + nodeData.name === "CheckpointLoaderSimple" || + nodeData.name === "CheckpointLoader" || + nodeData.name === "CheckpointLoader|pysssss" || + nodeData.name === "LoraLoader" || + nodeData.name === "LoraLoader|pysssss" + ) { + addMenuHandler(nodeType, function (_, options) { + function addLora(type) { + const loraNode = addNode(type, this); + + const modelLinks = this.outputs[0].links ? this.outputs[0].links.map((l) => ({ ...graph.links[l] })) : []; + const clipLinks = this.outputs[1].links ? this.outputs[1].links.map((l) => ({ ...graph.links[l] })) : []; + + this.disconnectOutput(0); + this.disconnectOutput(1); + + this.connect(0, loraNode, 0); + this.connect(1, loraNode, 1); + + for (const modelLink of modelLinks) { + loraNode.connect(0, modelLink.target_id, modelLink.target_slot); + } + + for (const clipLink of clipLinks) { + loraNode.connect(1, clipLink.target_id, clipLink.target_slot); + } + } + options.unshift( + { + content: "Add LoRA", + callback: () => addLora.call(this, "LoraLoader"), + }, + { + content: "Add 🐍 LoRA", + callback: () => addLora.call(this, "LoraLoader|pysssss"), + }, + { + content: "Add Prompts", + callback: () => { + const positiveNode = addNode("CLIPTextEncode", this); + const negativeNode = addNode("CLIPTextEncode", this, { shiftY: positiveNode.size[1] + 30 }); + + this.connect(1, positiveNode, 0); + this.connect(1, negativeNode, 0); + }, + } + ); + }); + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/repeater.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/repeater.js new file mode 100644 index 0000000000000000000000000000000000000000..23432c4d4fa89f899312a7fa4bd83a04c635a6b5 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/repeater.js @@ -0,0 +1,123 @@ +import { app } from "../../../scripts/app.js"; + +const REPEATER = "Repeater|pysssss"; + +app.registerExtension({ + name: "pysssss.Repeater", + init() { + const graphToPrompt = app.graphToPrompt; + app.graphToPrompt = async function () { + const res = await graphToPrompt.apply(this, arguments); + + const id = Date.now() + "_"; + let u = 0; + + let newNodes = {}; + const newRepeaters = {}; + for (const nodeId in res.output) { + let output = res.output[nodeId]; + if (output.class_type === REPEATER) { + const isMulti = output.inputs.output === "multi"; + if (output.inputs.node_mode === "create") { + // We need to clone the input for every repeat + const orig = res.output[output.inputs.source[0]]; + if (isMulti) { + if (!newRepeaters[nodeId]) { + newRepeaters[nodeId] = []; + newRepeaters[nodeId][output.inputs.repeats - 1] = nodeId; + } + } + for (let i = 0; i < output.inputs.repeats - 1; i++) { + const clonedInputId = id + ++u; + + if (isMulti) { + // If multi create we need to clone the repeater too + newNodes[clonedInputId] = structuredClone(orig); + + output = structuredClone(output); + + const clonedRepeaterId = id + ++u; + newNodes[clonedRepeaterId] = output; + output.inputs["source"][0] = clonedInputId; + + newRepeaters[nodeId][i] = clonedRepeaterId; + } else { + newNodes[clonedInputId] = orig; + } + output.inputs[clonedInputId] = [clonedInputId, output.inputs.source[1]]; + } + } else if (isMulti) { + newRepeaters[nodeId] = Array(output.inputs.repeats).fill(nodeId); + } + } + } + + Object.assign(res.output, newNodes); + newNodes = {}; + + for (const nodeId in res.output) { + const output = res.output[nodeId]; + for (const k in output.inputs) { + const v = output.inputs[k]; + if (v instanceof Array) { + const repeaterId = v[0]; + const source = newRepeaters[repeaterId]; + if (source) { + v[0] = source.pop(); + v[1] = 0; + } + } + } + } + + // Object.assign(res.output, newNodes); + + return res; + }; + }, + beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === REPEATER) { + const SETUP_OUTPUTS = Symbol(); + nodeType.prototype[SETUP_OUTPUTS] = function (repeats) { + if (repeats == null) { + repeats = this.widgets[0].value; + } + while (this.outputs.length > repeats) { + this.removeOutput(repeats); + } + const id = Date.now() + "_"; + let u = 0; + while (this.outputs.length < repeats) { + this.addOutput(id + ++u, "*", { label: "*" }); + } + }; + + const onAdded = nodeType.prototype.onAdded; + nodeType.prototype.onAdded = function () { + const self = this; + const repeatsCb = this.widgets[0].callback; + this.widgets[0].callback = async function () { + const v = (await repeatsCb?.apply(this, arguments)) ?? this.value; + if (self.widgets[1].value === "multi") { + self[SETUP_OUTPUTS](v); + } + return v; + }; + + const outputCb = this.widgets[1].callback; + this.widgets[1].callback = async function () { + const v = (await outputCb?.apply(this, arguments)) ?? this.value; + if (v === "single") { + self.outputs[0].shape = 6; + self[SETUP_OUTPUTS](1); + } else { + delete self.outputs[0].shape; + self[SETUP_OUTPUTS](); + } + return v; + }; + return onAdded?.apply(this, arguments); + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/reroutePrimitive.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/reroutePrimitive.js new file mode 100644 index 0000000000000000000000000000000000000000..7b934d717073b3b4dc210a48356580c615802375 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/reroutePrimitive.js @@ -0,0 +1,348 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +const REROUTE_PRIMITIVE = "ReroutePrimitive|pysssss"; +const MULTI_PRIMITIVE = "MultiPrimitive|pysssss"; +const LAST_TYPE = Symbol("LastType"); + +app.registerExtension({ + name: "pysssss.ReroutePrimitive", + init() { + // On graph configure, fire onGraphConfigured to create widgets + const graphConfigure = LGraph.prototype.configure; + LGraph.prototype.configure = function () { + const r = graphConfigure.apply(this, arguments); + for (const n of app.graph._nodes) { + if (n.type === REROUTE_PRIMITIVE) { + n.onGraphConfigured(); + } + } + + return r; + }; + + // Hide this node as it is no longer supported + const getNodeTypesCategories = LiteGraph.getNodeTypesCategories; + LiteGraph.getNodeTypesCategories = function() { + return getNodeTypesCategories.apply(this, arguments).filter(c => !c.startsWith("__hidden__")); + } + + const graphToPrompt = app.graphToPrompt; + app.graphToPrompt = async function () { + const res = await graphToPrompt.apply(this, arguments); + + const multiOutputs = []; + for (const nodeId in res.output) { + const output = res.output[nodeId]; + if (output.class_type === MULTI_PRIMITIVE) { + multiOutputs.push({ id: nodeId, inputs: output.inputs }); + } + } + + function permute(outputs) { + function generatePermutations(inputs, currentIndex, currentPermutation, result) { + if (currentIndex === inputs.length) { + result.push({ ...currentPermutation }); + return; + } + + const input = inputs[currentIndex]; + + for (const k in input) { + currentPermutation[currentIndex] = input[k]; + generatePermutations(inputs, currentIndex + 1, currentPermutation, result); + } + } + + const inputs = outputs.map((output) => output.inputs); + const result = []; + const current = new Array(inputs.length); + + generatePermutations(inputs, 0, current, result); + + return outputs.map((output, index) => ({ + ...output, + inputs: result.reduce((p, permutation) => { + const count = Object.keys(p).length; + p["value" + (count || "")] = permutation[index]; + return p; + }, {}), + })); + } + + const permutations = permute(multiOutputs); + for (let i = 0; i < permutations.length; i++) { + res.output[multiOutputs[i].id].inputs = permutations[i].inputs; + } + + return res; + }; + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + function addOutputHandler() { + // Finds the first non reroute output node down the chain + nodeType.prototype.getFirstReroutedOutput = function (slot) { + if (nodeData.name === MULTI_PRIMITIVE) { + slot = 0; + } + const links = this.outputs[slot].links; + if (!links) return null; + + const search = []; + for (const l of links) { + const link = app.graph.links[l]; + if (!link) continue; + + const node = app.graph.getNodeById(link.target_id); + if (node.type !== REROUTE_PRIMITIVE && node.type !== MULTI_PRIMITIVE) { + return { node, link }; + } + search.push({ node, link }); + } + + for (const { link, node } of search) { + const r = node.getFirstReroutedOutput(link.target_slot); + if (r) { + return r; + } + } + }; + } + + if (nodeData.name === REROUTE_PRIMITIVE) { + const configure = nodeType.prototype.configure || LGraphNode.prototype.configure; + const onConnectionsChange = nodeType.prototype.onConnectionsChange; + const onAdded = nodeType.prototype.onAdded; + + nodeType.title_mode = LiteGraph.NO_TITLE; + + function hasAnyInput(node) { + for (const input of node.inputs) { + if (input.link) { + return true; + } + } + return false; + } + + // Remove input text + nodeType.prototype.onAdded = function () { + onAdded?.apply(this, arguments); + this.inputs[0].label = ""; + this.outputs[0].label = "value"; + this.setSize(this.computeSize()); + }; + + // Restore any widgets + nodeType.prototype.onGraphConfigured = function () { + if (hasAnyInput(this)) return; + + const outputNode = this.getFirstReroutedOutput(0); + if (outputNode) { + this.checkPrimitiveWidget(outputNode); + } + }; + + // Check if we need to create (or remove) a widget on the node + nodeType.prototype.checkPrimitiveWidget = function ({ node, link }) { + let widgetType = link.type; + let targetLabel = widgetType; + const input = node.inputs[link.target_slot]; + if (input.widget?.config?.[0] instanceof Array) { + targetLabel = input.widget.name; + widgetType = "COMBO"; + } + + if (widgetType in ComfyWidgets) { + if (!this.widgets?.length) { + let v; + if (this.widgets_values?.length) { + v = this.widgets_values[0]; + } + let config = [link.type, {}]; + if (input.widget?.config) { + config = input.widget.config; + } + const { widget } = ComfyWidgets[widgetType](this, "value", config, app); + if (v !== undefined && (!this[LAST_TYPE] || this[LAST_TYPE] === widgetType)) { + widget.value = v; + } + this[LAST_TYPE] = widgetType; + } + } else if (this.widgets) { + this.widgets.length = 0; + } + + return targetLabel; + }; + + // Finds all input nodes from the current reroute + nodeType.prototype.getReroutedInputs = function (slot) { + let nodes = [{ node: this }]; + let node = this; + while (node?.type === REROUTE_PRIMITIVE) { + const input = node.inputs[slot]; + if (input.link) { + const link = app.graph.links[input.link]; + node = app.graph.getNodeById(link.origin_id); + slot = link.origin_slot; + nodes.push({ + node, + link, + }); + } else { + node = null; + } + } + + return nodes; + }; + + addOutputHandler(); + + // Update the type of all reroutes in a chain + nodeType.prototype.changeRerouteType = function (slot, type, label) { + const color = LGraphCanvas.link_type_colors[type]; + const output = this.outputs[slot]; + this.inputs[slot].label = " "; + output.label = label || (type === "*" ? "value" : type); + output.type = type; + + // Process all linked outputs + for (const linkId of output.links || []) { + const link = app.graph.links[linkId]; + if (!link) continue; + link.color = color; + const node = app.graph.getNodeById(link.target_id); + if (node.changeRerouteType) { + // Recursively update reroutes + node.changeRerouteType(link.target_slot, type, label); + } else { + // Validate links to 'real' nodes + const theirType = node.inputs[link.target_slot].type; + if (theirType !== type && theirType !== "*") { + node.disconnectInput(link.target_slot); + } + } + } + + if (this.inputs[slot].link) { + const link = app.graph.links[this.inputs[slot].link]; + if (link) link.color = color; + } + }; + + // Override configure so we can flag that we are configuring to avoid link validation breaking + let configuring = false; + nodeType.prototype.configure = function () { + configuring = true; + const r = configure?.apply(this, arguments); + configuring = false; + + return r; + }; + + Object.defineProperty(nodeType, "title_mode", { + get() { + return app.canvas.current_node?.widgets?.length ? LiteGraph.NORMAL_TITLE : LiteGraph.NO_TITLE; + }, + }); + + nodeType.prototype.onConnectionsChange = function (type, _, connected, link_info) { + // If configuring treat everything as OK as links may not be set by litegraph yet + if (configuring) return; + + const isInput = type === LiteGraph.INPUT; + const slot = isInput ? link_info.target_slot : link_info.origin_slot; + + let targetLabel = null; + let targetNode = null; + let targetType = "*"; + let targetSlot = slot; + + const inputPath = this.getReroutedInputs(slot); + const rootInput = inputPath[inputPath.length - 1]; + const outputNode = this.getFirstReroutedOutput(slot); + if (rootInput.node.type === REROUTE_PRIMITIVE) { + // Our input node is a reroute, so see if we have an output + if (outputNode) { + targetType = outputNode.link.type; + } else if (rootInput.node.widgets) { + rootInput.node.widgets.length = 0; + } + targetNode = rootInput; + targetSlot = rootInput.link?.target_slot ?? slot; + } else { + // We have a real input, so we want to use that type + targetNode = inputPath[inputPath.length - 2]; + targetType = rootInput.node.outputs[rootInput.link.origin_slot].type; + targetSlot = rootInput.link.target_slot; + } + + if (this.widgets && inputPath.length > 1) { + // We have an input node so remove our widget + this.widgets.length = 0; + } + + if (outputNode && rootInput.node.checkPrimitiveWidget) { + // We have an output, check if we need to create a widget + targetLabel = rootInput.node.checkPrimitiveWidget(outputNode); + } + + // Trigger an update of the type to all child nodes + targetNode.node.changeRerouteType(targetSlot, targetType, targetLabel); + + return onConnectionsChange?.apply(this, arguments); + }; + + // When collapsed fix the size to just the dot + const computeSize = nodeType.prototype.computeSize || LGraphNode.prototype.computeSize; + nodeType.prototype.computeSize = function () { + const r = computeSize.apply(this, arguments); + if (this.flags?.collapsed) { + return [1, 25]; + } else if (this.widgets?.length) { + return r; + } else { + let w = 75; + if (this.outputs?.[0]?.label) { + const t = LiteGraph.NODE_TEXT_SIZE * this.outputs[0].label.length * 0.6 + 30; + if (t > w) { + w = t; + } + } + return [w, r[1]]; + } + }; + + // On collapse shrink the node to just a dot + const collapse = nodeType.prototype.collapse || LGraphNode.prototype.collapse; + nodeType.prototype.collapse = function () { + collapse.apply(this, arguments); + this.setSize(this.computeSize()); + requestAnimationFrame(() => { + this.setDirtyCanvas(true, true); + }); + }; + + // Shift the bounding area up slightly as LiteGraph miscalculates it for collapsed nodes + nodeType.prototype.onBounding = function (area) { + if (this.flags?.collapsed) { + area[1] -= 15; + } + }; + } else if (nodeData.name === MULTI_PRIMITIVE) { + addOutputHandler(); + nodeType.prototype.onConnectionsChange = function (type, _, connected, link_info) { + for (let i = 0; i < this.inputs.length - 1; i++) { + if (!this.inputs[i].link) { + this.removeInput(i--); + } + } + if (this.inputs[this.inputs.length - 1].link) { + this.addInput("v" + +new Date(), this.inputs[0].type).label = "value"; + } + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showImageOnMenu.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showImageOnMenu.js new file mode 100644 index 0000000000000000000000000000000000000000..4fed9de92e333270f1c2066e7667e34fd40e539b --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showImageOnMenu.js @@ -0,0 +1,81 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; + +const id = "pysssss.ShowImageOnMenu"; +const ext = { + name: id, + async setup(app) { + let enabled = true; + let nodeId = null; + const img = $el("img", { + style: { + width: "100%", + height: "150px", + objectFit: "contain", + }, + }); + const link = $el( + "a", + { + style: { + width: "100%", + height: "150px", + marginTop: "10px", + order: 100, // Place this item last (until someone else has a higher order) + display: "none", + }, + href: "#", + onclick: (e) => { + e.stopPropagation(); + e.preventDefault(); + const node = app.graph.getNodeById(nodeId); + if (!node) return; + app.canvas.centerOnNode(node); + app.canvas.setZoom(1); + }, + }, + [img] + ); + + app.ui.menuContainer.append(link); + + const show = (src, node) => { + img.src = src; + nodeId = Number(node); + link.style.display = "unset"; + }; + + api.addEventListener("executed", ({ detail }) => { + if (!enabled) return; + const images = detail?.output?.images; + if (!images || !images.length) return; + const format = app.getPreviewFormatParam(); + const src = [ + `./view?filename=${encodeURIComponent(images[0].filename)}`, + `type=${images[0].type}`, + `subfolder=${encodeURIComponent(images[0].subfolder)}`, + `t=${+new Date()}${format}`,].join('&'); + show(src, detail.node); + }); + + api.addEventListener("b_preview", ({ detail }) => { + if (!enabled) return; + show(URL.createObjectURL(detail), app.runningNodeId); + }); + + app.ui.settings.addSetting({ + id, + name: "🐍 Show Image On Menu", + defaultValue: true, + type: "boolean", + onChange(value) { + enabled = value; + + if (!enabled) link.style.display = "none"; + }, + }); + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showText.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showText.js new file mode 100644 index 0000000000000000000000000000000000000000..464fd404632397e26c2af1d2297970da6c726920 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/showText.js @@ -0,0 +1,78 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +// Displays input text on a node + +// TODO: This should need to be so complicated. Refactor at some point. + +app.registerExtension({ + name: "pysssss.ShowText", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "ShowText|pysssss") { + function populate(text) { + if (this.widgets) { + // On older frontend versions there is a hidden converted-widget + const isConvertedWidget = +!!this.inputs?.[0].widget; + for (let i = isConvertedWidget; i < this.widgets.length; i++) { + this.widgets[i].onRemove?.(); + } + this.widgets.length = isConvertedWidget; + } + + const v = [...text]; + if (!v[0]) { + v.shift(); + } + for (let list of v) { + // Force list to be an array, not sure why sometimes it is/isn't + if (!(list instanceof Array)) list = [list]; + for (const l of list) { + const w = ComfyWidgets["STRING"](this, "text_" + this.widgets?.length ?? 0, ["STRING", { multiline: true }], app).widget; + w.inputEl.readOnly = true; + w.inputEl.style.opacity = 0.6; + w.value = l; + } + } + + requestAnimationFrame(() => { + const sz = this.computeSize(); + if (sz[0] < this.size[0]) { + sz[0] = this.size[0]; + } + if (sz[1] < this.size[1]) { + sz[1] = this.size[1]; + } + this.onResize?.(sz); + app.graph.setDirtyCanvas(true, false); + }); + } + + // When the node is executed we will be sent the input text, display this in the widget + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + populate.call(this, message.text); + }; + + const VALUES = Symbol(); + const configure = nodeType.prototype.configure; + nodeType.prototype.configure = function () { + // Store unmodified widget values as they get removed on configure by new frontend + this[VALUES] = arguments[0]?.widgets_values; + return configure?.apply(this, arguments); + }; + + const onConfigure = nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure = function () { + onConfigure?.apply(this, arguments); + const widgets_values = this[VALUES]; + if (widgets_values?.length) { + // In newer frontend there seems to be a delay in creating the initial widget + requestAnimationFrame(() => { + populate.call(this, widgets_values.slice(+(widgets_values.length > 1 && this.inputs?.[0].widget))); + }); + } + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGrid.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGrid.js new file mode 100644 index 0000000000000000000000000000000000000000..07d5aa8c7bec97e2e14a8470fc8df2e82c14c39d --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGrid.js @@ -0,0 +1,73 @@ +import { app } from "../../../scripts/app.js"; + +let setting; +const id = "pysssss.SnapToGrid"; + +/** Wraps the provided function call to set/reset shiftDown when setting is enabled. */ +function wrapCallInSettingCheck(fn) { + if (setting?.value) { + const shift = app.shiftDown; + app.shiftDown = true; + const r = fn(); + app.shiftDown = shift; + return r; + } + return fn(); +} + +const ext = { + name: id, + init() { + setting = app.ui.settings.addSetting({ + id, + name: "🐍 Always snap to grid", + defaultValue: false, + type: "boolean", + onChange(value) { + app.canvas.align_to_grid = value; + }, + }); + + // We need to register our hooks after the core snap to grid extension runs + // Do this from the graph configure function so we still get onNodeAdded calls + const configure = LGraph.prototype.configure; + LGraph.prototype.configure = function () { + // Override drawNode to draw the drop position + const drawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function () { + wrapCallInSettingCheck(() => drawNode.apply(this, arguments)); + }; + + // Override node added to add a resize handler to force grid alignment + const onNodeAdded = app.graph.onNodeAdded; + app.graph.onNodeAdded = function (node) { + const r = onNodeAdded?.apply(this, arguments); + const onResize = node.onResize; + node.onResize = function () { + wrapCallInSettingCheck(() => onResize?.apply(this, arguments)); + }; + return r; + }; + + + const groupMove = LGraphGroup.prototype.move; + LGraphGroup.prototype.move = function(deltax, deltay, ignore_nodes) { + wrapCallInSettingCheck(() => groupMove.apply(this, arguments)); + } + + const canvasDrawGroups = LGraphCanvas.prototype.drawGroups; + LGraphCanvas.prototype.drawGroups = function (canvas, ctx) { + wrapCallInSettingCheck(() => canvasDrawGroups.apply(this, arguments)); + } + + const canvasOnGroupAdd = LGraphCanvas.onGroupAdd; + LGraphCanvas.onGroupAdd = function() { + wrapCallInSettingCheck(() => canvasOnGroupAdd.apply(this, arguments)); + } + + return configure.apply(this, arguments); + }; + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGridGuide.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGridGuide.js new file mode 100644 index 0000000000000000000000000000000000000000..54b2b739689d4f145398c794a38d1bb089ffceec --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/snapToGridGuide.js @@ -0,0 +1,163 @@ +import { app } from "../../../scripts/app.js"; +import { $el } from "../../../scripts/ui.js"; + +let guide_config; +const id = "pysssss.SnapToGrid.Guide"; +const guide_config_default = { + lines: { + enabled: false, + fillStyle: "rgba(255, 0, 0, 0.5)", + }, + block: { + enabled: false, + fillStyle: "rgba(0, 0, 255, 0.5)", + }, +} + +const ext = { + name: id, + init() { + if (localStorage.getItem(id) === null) { + localStorage.setItem(id, JSON.stringify(guide_config_default)); + } + guide_config = JSON.parse(localStorage.getItem(id)); + + app.ui.settings.addSetting({ + id, + name: "🐍 Display drag-and-drop guides", + type: (name, setter, value) => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: name, + }), + ]), + $el("td", [ + $el( + "label", + { + textContent: "Lines: ", + style: { + display: "inline-block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-") + "-line-text", + type: "text", + value: guide_config.lines.fillStyle, + onchange: (event) => { + guide_config.lines.fillStyle = event.target.value; + localStorage.setItem(id, JSON.stringify(guide_config)); + } + }), + $el("input", { + id: id.replaceAll(".", "-") + "-line-checkbox", + type: "checkbox", + checked: guide_config.lines.enabled, + onchange: (event) => { + guide_config.lines.enabled = !!event.target.checked; + localStorage.setItem(id, JSON.stringify(guide_config)); + }, + }), + ] + ), + $el( + "label", + { + textContent: "Block: ", + style: { + display: "inline-block", + }, + }, + [ + $el("input", { + id: id.replaceAll(".", "-") + "-block-text", + type: "text", + value: guide_config.block.fillStyle, + onchange: (event) => { + guide_config.block.fillStyle = event.target.value; + localStorage.setItem(id, JSON.stringify(guide_config)); + } + }), + $el("input", { + id: id.replaceAll(".", "-") + '-block-checkbox', + type: "checkbox", + checked: guide_config.block.enabled, + onchange: (event) => { + guide_config.block.enabled = !!event.target.checked; + localStorage.setItem(id, JSON.stringify(guide_config)); + }, + }), + ] + ), + ]), + ]); + } + }); + + const alwaysSnapToGrid = () => + app.ui.settings.getSettingValue("pysssss.SnapToGrid", /* default=*/ false); + const snapToGridEnabled = () => + app.shiftDown || alwaysSnapToGrid(); + + // Override drag-and-drop behavior to show orthogonal guide lines around selected node(s) and preview of where the node(s) will be placed + const origDrawNode = LGraphCanvas.prototype.drawNode; + LGraphCanvas.prototype.drawNode = function (node, ctx) { + const enabled = guide_config.lines.enabled || guide_config.block.enabled; + if (enabled && this.isDragging && node.id in this.selected_nodes && snapToGridEnabled()) { + // discretize the canvas into grid + let x = LiteGraph.CANVAS_GRID_SIZE * Math.round(node.pos[0] / LiteGraph.CANVAS_GRID_SIZE); + let y = LiteGraph.CANVAS_GRID_SIZE * Math.round(node.pos[1] / LiteGraph.CANVAS_GRID_SIZE); + + // calculate the width and height of the node + // (also need to shift the y position of the node, depending on whether the title is visible) + x -= node.pos[0]; + y -= node.pos[1]; + let w, h; + if (node.flags.collapsed) { + w = node._collapsed_width; + h = LiteGraph.NODE_TITLE_HEIGHT; + y -= LiteGraph.NODE_TITLE_HEIGHT; + } else { + w = node.size[0]; + h = node.size[1]; + let titleMode = node.constructor.title_mode; + if (titleMode !== LiteGraph.TRANSPARENT_TITLE && titleMode !== LiteGraph.NO_TITLE) { + h += LiteGraph.NODE_TITLE_HEIGHT; + y -= LiteGraph.NODE_TITLE_HEIGHT; + } + } + + // save the original fill style + const f = ctx.fillStyle; + + // draw preview for drag-and-drop (rectangle to show where the node will be placed) + if (guide_config.block.enabled) { + ctx.fillStyle = guide_config.block.fillStyle; + ctx.fillRect(x, y, w, h); + } + + // add guide lines around node (arbitrarily long enough to span most workflows) + if (guide_config.lines.enabled) { + const xd = 10000; + const yd = 10000; + const thickness = 3; + ctx.fillStyle = guide_config.lines.fillStyle; + ctx.fillRect(x - xd, y, 2*xd, thickness); + ctx.fillRect(x, y - yd, thickness, 2*yd); + ctx.fillRect(x - xd, y + h, 2*xd, thickness); + ctx.fillRect(x + w, y - yd, thickness, 2*yd); + } + + // restore the original fill style + ctx.fillStyle = f; + } + + return origDrawNode.apply(this, arguments); + }; + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/stringFunction.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/stringFunction.js new file mode 100644 index 0000000000000000000000000000000000000000..cc150dff04a2e94b9bc768f6331964c13a96ddbe --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/stringFunction.js @@ -0,0 +1,33 @@ +import { app } from "../../../scripts/app.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +// Displays input text on a node + +app.registerExtension({ + name: "pysssss.StringFunction", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "StringFunction|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = function (message) { + onExecuted?.apply(this, arguments); + + if (this.widgets) { + const pos = this.widgets.findIndex((w) => w.name === "result"); + if (pos !== -1) { + for (let i = pos; i < this.widgets.length; i++) { + this.widgets[i].onRemove?.(); + } + this.widgets.length = pos; + } + } + + const w = ComfyWidgets["STRING"](this, "result", ["STRING", { multiline: true }], app).widget; + w.inputEl.readOnly = true; + w.inputEl.style.opacity = 0.6; + w.value = message.text; + + this.onResize?.(this.size); + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/swapResolution.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/swapResolution.js new file mode 100644 index 0000000000000000000000000000000000000000..40f6dcc851780077c79e7e142fd0f97104e85a09 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/swapResolution.js @@ -0,0 +1,30 @@ +import { app } from "../../../scripts/app.js"; +app.registerExtension({ + name: "pysssss.SwapResolution", + async beforeRegisterNodeDef(nodeType, nodeData) { + const inputs = { ...nodeData.input?.required, ...nodeData.input?.optional }; + if (inputs.width && inputs.height) { + const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = origGetExtraMenuOptions?.apply?.(this, arguments); + + options.push( + { + content: "Swap width/height", + callback: () => { + const w = this.widgets.find((w) => w.name === "width"); + const h = this.widgets.find((w) => w.name === "height"); + const a = w.value; + w.value = h.value; + h.value = a; + app.graph.setDirtyCanvas(true); + }, + }, + null + ); + + return r; + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/systemNotification.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/systemNotification.js new file mode 100644 index 0000000000000000000000000000000000000000..803b8c90629f6722efd090e0bf5839e395c4402b --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/systemNotification.js @@ -0,0 +1,47 @@ +import { app } from "../../../scripts/app.js"; + +const notificationSetup = () => { + if (!("Notification" in window)) { + console.log("This browser does not support notifications."); + alert("This browser does not support notifications."); + return; + } + if (Notification.permission === "denied") { + console.log("Notifications are blocked. Please enable them in your browser settings."); + alert("Notifications are blocked. Please enable them in your browser settings."); + return; + } + if (Notification.permission !== "granted") { + Notification.requestPermission(); + } + return true; +}; + +app.registerExtension({ + name: "pysssss.SystemNotification", + async beforeRegisterNodeDef(nodeType, nodeData, app) { + if (nodeData.name === "SystemNotification|pysssss") { + const onExecuted = nodeType.prototype.onExecuted; + nodeType.prototype.onExecuted = async function ({ message, mode }) { + onExecuted?.apply(this, arguments); + + if (mode === "on empty queue") { + if (app.ui.lastQueueSize !== 0) { + await new Promise((r) => setTimeout(r, 500)); + } + if (app.ui.lastQueueSize !== 0) { + return; + } + } + if (!notificationSetup()) return; + const notification = new Notification("ComfyUI", { body: message ?? "Your notification has triggered." }); + }; + + const onNodeCreated = nodeType.prototype.onNodeCreated; + nodeType.prototype.onNodeCreated = function () { + onNodeCreated?.apply(this, arguments); + notificationSetup(); + }; + } + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/useNumberInputPrompt.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/useNumberInputPrompt.js new file mode 100644 index 0000000000000000000000000000000000000000..a92aa51095bc474b3cf80697aa238ad8814b4c3d --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/useNumberInputPrompt.js @@ -0,0 +1,36 @@ +import { app } from "../../../scripts/app.js"; + +const id = "pysssss.UseNumberInputPrompt"; +const ext = { + name: id, + async setup(app) { + const prompt = LGraphCanvas.prototype.prompt; + + const setting = app.ui.settings.addSetting({ + id, + name: "🐍 Use number input on value entry", + defaultValue: false, + type: "boolean", + }); + + LGraphCanvas.prototype.prompt = function () { + const dialog = prompt.apply(this, arguments); + if (setting.value && typeof arguments[1] === "number") { + // If this should be a number then update the imput + const input = dialog.querySelector("input"); + input.type = "number"; + + // Add constraints + const widget = app.canvas.node_widget?.[1]; + if (widget?.options) { + for (const prop of ["min", "max", "step"]) { + if (widget.options[prop]) input[prop] = widget.options[prop]; + } + } + } + return dialog; + }; + }, +}; + +app.registerExtension(ext); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/widgetDefaults.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/widgetDefaults.js new file mode 100644 index 0000000000000000000000000000000000000000..859749d16fda455bcdfb4a6fba89a7340c839183 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/widgetDefaults.js @@ -0,0 +1,297 @@ +import { app } from "../../../scripts/app.js"; +import { $el, ComfyDialog } from "../../../scripts/ui.js"; + +// Allows you to specify custom default values for any widget on any node + +const id = "pysssss.WidgetDefaults"; +const nodeDataKey = Symbol(); + +app.registerExtension({ + name: id, + beforeRegisterNodeDef(nodeType, nodeData) { + nodeType[nodeDataKey] = nodeData; + }, + setup() { + let defaults; + let regexDefaults; + let setting; + + const getNodeDefaults = (node, defaults) => { + const nodeDefaults = defaults[node.type] ?? {}; + const propSetBy = {}; + + Object.keys(regexDefaults) + .filter((r) => new RegExp(r).test(node.type)) + .reduce((p, n) => { + const props = regexDefaults[n]; + for (const k in props) { + // Use the longest matching key as its probably the most specific + if (!(k in nodeDefaults) || (k in propSetBy && n.length > propSetBy[k].length)) { + propSetBy[k] = n; + nodeDefaults[k] = props[k]; + } + } + return p; + }, nodeDefaults); + + return nodeDefaults; + }; + + const applyDefaults = (defaults) => { + for (const node of Object.values(LiteGraph.registered_node_types)) { + const nodeData = node[nodeDataKey]; + if (!nodeData) continue; + const nodeDefaults = getNodeDefaults(node, defaults); + if (!nodeDefaults) continue; + const inputs = { ...(nodeData.input?.required || {}), ...(nodeData.input?.optional || {}) }; + + for (const w in nodeDefaults) { + const widgetDef = inputs[w]; + if (widgetDef) { + let v = nodeDefaults[w]; + if (widgetDef[0] === "INT" || widgetDef[0] === "FLOAT") { + v = +v; + } + if (widgetDef[1]) { + widgetDef[1].default = v; + } else { + widgetDef[1] = { default: v }; + } + } + } + } + }; + + const getDefaults = () => { + let items; + regexDefaults = {}; + try { + items = JSON.parse(setting.value); + items = items.reduce((p, n) => { + if (n.node.startsWith("/") && n.node.endsWith("/")) { + const name = n.node.substring(1, n.node.length - 1); + try { + // Validate regex + new RegExp(name); + + if (!regexDefaults[name]) regexDefaults[name] = {}; + regexDefaults[name][n.widget] = n.value; + } catch (error) {} + } + + if (!p[n.node]) p[n.node] = {}; + p[n.node][n.widget] = n.value; + return p; + }, {}); + } catch (error) {} + if (!items) { + items = {}; + } + applyDefaults(items); + return items; + }; + + const onNodeAdded = app.graph.onNodeAdded; + app.graph.onNodeAdded = function (node) { + onNodeAdded?.apply?.(this, arguments); + + // See if we have any defaults for this type of node + const nodeDefaults = getNodeDefaults(node.constructor, defaults); + if (!nodeDefaults) return; + + // Dont run if they are pre-configured nodes from load/pastes + const stack = new Error().stack; + if (stack.includes("pasteFromClipboard") || stack.includes("loadGraphData")) { + return; + } + + for (const k in nodeDefaults) { + if (k.startsWith("property.")) { + const name = k.substring(9); + let v = nodeDefaults[k]; + // Special handling for some built in values + if (name in node || ["color", "bgcolor", "title"].includes(name)) { + node[name] = v; + } else { + // Try using the correct type + if (!node.properties) node.properties = {}; + if (typeof node.properties[name] === "number") v = +v; + else if (typeof node.properties[name] === "boolean") v = v === "true"; + else if (v === "true") v = true; + + node.properties[name] = v; + } + } + } + }; + + class WidgetDefaultsDialog extends ComfyDialog { + constructor() { + super(); + this.element.classList.add("comfy-manage-templates"); + this.grid = $el( + "div", + { + style: { + display: "grid", + gridTemplateColumns: "1fr auto auto auto", + gap: "5px", + }, + className: "pysssss-widget-defaults", + }, + [ + $el("label", { + textContent: "Node Class", + }), + $el("label", { + textContent: "Widget Name", + }), + $el("label", { + textContent: "Default Value", + }), + $el("label"), + (this.rows = $el("div", { + style: { + display: "contents", + }, + })), + ] + ); + } + + createButtons() { + const btns = super.createButtons(); + btns[0].textContent = "Cancel"; + btns.unshift( + $el("button", { + type: "button", + textContent: "Add New", + onclick: () => this.addRow(), + }), + $el("button", { + type: "button", + textContent: "Save", + onclick: () => this.save(), + }) + ); + return btns; + } + + addRow(node = "", widget = "", value = "") { + let nameInput; + this.rows.append( + $el( + "div", + { + style: { + display: "contents", + }, + className: "pysssss-widget-defaults-row", + }, + [ + $el("input", { + placeholder: "e.g. CheckpointLoaderSimple", + value: node, + }), + $el("input", { + placeholder: "e.g. ckpt_name", + value: widget, + $: (el) => (nameInput = el), + }), + $el("input", { + placeholder: "e.g. myBestModel.safetensors", + value, + }), + $el("button", { + textContent: "Delete", + style: { + fontSize: "12px", + color: "red", + fontWeight: "normal", + }, + onclick: (e) => { + nameInput.value = ""; + e.target.parentElement.style.display = "none"; + }, + }), + ] + ) + ); + } + + save() { + const rows = this.rows.children; + const items = []; + + for (const row of rows) { + const inputs = row.querySelectorAll("input"); + const node = inputs[0].value.trim(); + const widget = inputs[1].value.trim(); + const value = inputs[2].value; + if (node && widget) { + items.push({ node, widget, value }); + } + } + + setting.value = JSON.stringify(items); + defaults = getDefaults(); + + this.close(); + } + + show() { + this.rows.replaceChildren(); + for (const nodeName in defaults) { + const node = defaults[nodeName]; + for (const widgetName in node) { + this.addRow(nodeName, widgetName, node[widgetName]); + } + } + + this.addRow(); + super.show(this.grid); + } + } + + setting = app.ui.settings.addSetting({ + id, + name: "🐍 Widget Defaults", + type: () => { + return $el("tr", [ + $el("td", [ + $el("label", { + for: id.replaceAll(".", "-"), + textContent: "🐍 Widget & Property Defaults:", + }), + ]), + $el("td", [ + $el("button", { + textContent: "Manage", + onclick: () => { + try { + // Try closing old settings window + if (typeof app.ui.settings.element?.close === "function") { + app.ui.settings.element.close(); + } + } catch (error) {} + try { + // Try closing new vue dialog + document.querySelector(".p-dialog-close-button").click(); + } catch (error) { + // Fallback to just hiding the element + app.ui.settings.element.style.display = "none"; + } + const dialog = new WidgetDefaultsDialog(); + dialog.show(); + }, + style: { + fontSize: "14px", + }, + }), + ]), + ]); + }, + }); + defaults = getDefaults(); + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflowImage.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflowImage.js new file mode 100644 index 0000000000000000000000000000000000000000..ff19c6a040b302d94883ecba3ab6ede195069ecd --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflowImage.js @@ -0,0 +1,641 @@ +import { app } from "../../../scripts/app.js"; +import { importA1111 } from "../../../scripts/pnginfo.js"; +import { ComfyWidgets } from "../../../scripts/widgets.js"; + +let getDrawTextConfig = null; +let fileInput; + +class WorkflowImage { + static accept = ""; + + getBounds() { + // Calculate the min max bounds for the nodes on the graph + const bounds = app.graph._nodes.reduce( + (p, n) => { + if (n.pos[0] < p[0]) p[0] = n.pos[0]; + if (n.pos[1] < p[1]) p[1] = n.pos[1]; + const bounds = n.getBounding(); + const r = n.pos[0] + bounds[2]; + const b = n.pos[1] + bounds[3]; + if (r > p[2]) p[2] = r; + if (b > p[3]) p[3] = b; + return p; + }, + [99999, 99999, -99999, -99999] + ); + + bounds[0] -= 100; + bounds[1] -= 100; + bounds[2] += 100; + bounds[3] += 100; + return bounds; + } + + saveState() { + this.state = { + scale: app.canvas.ds.scale, + width: app.canvas.canvas.width, + height: app.canvas.canvas.height, + offset: app.canvas.ds.offset, + transform: app.canvas.canvas.getContext("2d").getTransform(), // Save the original transformation matrix + }; + } + + restoreState() { + app.canvas.ds.scale = this.state.scale; + app.canvas.canvas.width = this.state.width; + app.canvas.canvas.height = this.state.height; + app.canvas.ds.offset = this.state.offset; + app.canvas.canvas.getContext("2d").setTransform(this.state.transform); // Reapply the original transformation matrix + } + + updateView(bounds) { + const scale = window.devicePixelRatio || 1; + app.canvas.ds.scale = 1; + app.canvas.canvas.width = (bounds[2] - bounds[0]) * scale; + app.canvas.canvas.height = (bounds[3] - bounds[1]) * scale; + app.canvas.ds.offset = [-bounds[0], -bounds[1]]; + app.canvas.canvas.getContext("2d").setTransform(scale, 0, 0, scale, 0, 0); + } + + getDrawTextConfig(_, widget) { + return { + x: 10, + y: widget.last_y + 10, + resetTransform: false, + }; + } + + async export(includeWorkflow) { + // Save the current state of the canvas + this.saveState(); + // Update to render the whole workflow + this.updateView(this.getBounds()); + + // Flag that we are saving and render the canvas + getDrawTextConfig = this.getDrawTextConfig; + app.canvas.draw(true, true); + getDrawTextConfig = null; + + // Generate a blob of the image containing the workflow + const blob = await this.getBlob(includeWorkflow ? JSON.stringify(app.graph.serialize()) : undefined); + + // Restore initial state and redraw + this.restoreState(); + app.canvas.draw(true, true); + + // Download the generated image + this.download(blob); + } + + download(blob) { + const url = URL.createObjectURL(blob); + const a = document.createElement("a"); + Object.assign(a, { + href: url, + download: "workflow." + this.extension, + style: "display: none", + }); + document.body.append(a); + a.click(); + setTimeout(function () { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + + static import() { + if (!fileInput) { + fileInput = document.createElement("input"); + Object.assign(fileInput, { + type: "file", + style: "display: none", + onchange: () => { + app.handleFile(fileInput.files[0]); + }, + }); + document.body.append(fileInput); + } + fileInput.accept = WorkflowImage.accept; + fileInput.click(); + } +} + +class PngWorkflowImage extends WorkflowImage { + static accept = ".png,image/png"; + extension = "png"; + + n2b(n) { + return new Uint8Array([(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]); + } + + joinArrayBuffer(...bufs) { + const result = new Uint8Array(bufs.reduce((totalSize, buf) => totalSize + buf.byteLength, 0)); + bufs.reduce((offset, buf) => { + result.set(buf, offset); + return offset + buf.byteLength; + }, 0); + return result; + } + + crc32(data) { + const crcTable = + PngWorkflowImage.crcTable || + (PngWorkflowImage.crcTable = (() => { + let c; + const crcTable = []; + for (let n = 0; n < 256; n++) { + c = n; + for (let k = 0; k < 8; k++) { + c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + } + crcTable[n] = c; + } + return crcTable; + })()); + let crc = 0 ^ -1; + for (let i = 0; i < data.byteLength; i++) { + crc = (crc >>> 8) ^ crcTable[(crc ^ data[i]) & 0xff]; + } + return (crc ^ -1) >>> 0; + } + + async getBlob(workflow) { + return new Promise((r) => { + app.canvasEl.toBlob(async (blob) => { + if (workflow) { + // If we have a workflow embed it in the PNG + const buffer = await blob.arrayBuffer(); + const typedArr = new Uint8Array(buffer); + const view = new DataView(buffer); + + const data = new TextEncoder().encode(`tEXtworkflow\0${workflow}`); + const chunk = this.joinArrayBuffer(this.n2b(data.byteLength - 4), data, this.n2b(this.crc32(data))); + + const sz = view.getUint32(8) + 20; + const result = this.joinArrayBuffer(typedArr.subarray(0, sz), chunk, typedArr.subarray(sz)); + + blob = new Blob([result], { type: "image/png" }); + } + + r(blob); + }); + }); + } +} + +class DataReader { + /** @type {DataView} */ + view; + /** @type {boolean | undefined} */ + littleEndian; + offset = 0; + + /** + * @param {DataView} view + */ + constructor(view) { + this.view = view; + } + + /** + * Reads N bytes and increments the offset + * @param {1 | 2 | 4 | 8} size + */ + read(size, signed = false, littleEndian = undefined) { + const v = this.peek(size, signed, littleEndian); + this.offset += size; + return v; + } + + /** + * Reads N bytes + * @param {1 | 2 | 4 | 8} size + */ + peek(size, signed = false, littleEndian = undefined) { + this.view.getBigInt64; + let m = ""; + if (size === 8) m += "Big"; + m += signed ? "Int" : "Uint"; + m += size * 8; + m = "get" + m; + if (!this.view[m]) { + throw new Error("Method not found: " + m); + } + + return this.view[m](this.offset, littleEndian == null ? this.littleEndian : littleEndian); + } + + /** + * Seeks to the specified position or by the number of bytes specified relative to the current offset + * @param {number} pos + * @param {boolean} relative + */ + seek(pos, relative = true) { + if (relative) { + this.offset += pos; + } else { + this.offset = pos; + } + } +} + +class Tiff { + /** @type {DataReader} */ + #reader; + #start; + + readExif(reader) { + const TIFF_MARKER = 0x2a; + const EXIF_IFD = 0x8769; + + this.#reader = reader; + this.#start = this.#reader.offset; + this.#readEndianness(); + + if (!this.#reader.read(2) === TIFF_MARKER) { + throw new Error("Invalid TIFF: Marker not found."); + } + + const dirOffset = this.#reader.read(4); + this.#reader.seek(this.#start + dirOffset, false); + + for (const t of this.#readTags()) { + if (t.id === EXIF_IFD) { + return this.#readExifTag(t); + } + } + throw new Error("No EXIF: TIFF Exif IFD tag not found"); + } + + #readUserComment(tag) { + this.#reader.seek(this.#start + tag.offset, false); + const encoding = this.#reader.read(8); + if (encoding !== 0x45444f43494e55n) { + throw new Error("Unable to read non-Unicode data"); + } + const decoder = new TextDecoder("utf-16be"); + return decoder.decode(new DataView(this.#reader.view.buffer, this.#reader.offset, tag.count - 8)); + } + + #readExifTag(exifTag) { + const EXIF_USER_COMMENT = 0x9286; + + this.#reader.seek(this.#start + exifTag.offset, false); + for (const t of this.#readTags()) { + if (t.id === EXIF_USER_COMMENT) { + return this.#readUserComment(t); + } + } + throw new Error("No embedded data: UserComment Exif tag not found"); + } + + *#readTags() { + const count = this.#reader.read(2); + for (let i = 0; i < count; i++) { + yield { + id: this.#reader.read(2), + type: this.#reader.read(2), + count: this.#reader.read(4), + offset: this.#reader.read(4), + }; + } + } + + #readEndianness() { + const II = 0x4949; + const MM = 0x4d4d; + const endianness = this.#reader.read(2); + if (endianness === II) { + this.#reader.littleEndian = true; + } else if (endianness === MM) { + this.#reader.littleEndian = false; + } else { + throw new Error("Invalid JPEG: Endianness marker not found."); + } + } +} + +class Jpeg { + /** @type {DataReader} */ + #reader; + + /** + * @param {ArrayBuffer} buffer + */ + readExif(buffer) { + const JPEG_MARKER = 0xffd8; + const EXIF_SIG = 0x45786966; + + this.#reader = new DataReader(new DataView(buffer)); + if (!this.#reader.read(2) === JPEG_MARKER) { + throw new Error("Invalid JPEG: SOI not found."); + } + + const app0 = this.#readAppMarkerId(); + if (app0 !== 0) { + throw new Error(`Invalid JPEG: APP0 not found [found: ${app0}].`); + } + + this.#consumeAppSegment(); + const app1 = this.#readAppMarkerId(); + if (app1 !== 1) { + throw new Error(`No EXIF: APP1 not found [found: ${app0}].`); + } + + // Skip size + this.#reader.seek(2); + + if (this.#reader.read(4) !== EXIF_SIG) { + throw new Error(`No EXIF: Invalid EXIF header signature.`); + } + if (this.#reader.read(2) !== 0) { + throw new Error(`No EXIF: Invalid EXIF header.`); + } + + return new Tiff().readExif(this.#reader); + } + + #readAppMarkerId() { + const APP0_MARKER = 0xffe0; + return this.#reader.read(2) - APP0_MARKER; + } + + #consumeAppSegment() { + this.#reader.seek(this.#reader.read(2) - 2); + } +} + +class SvgWorkflowImage extends WorkflowImage { + static accept = ".svg,image/svg+xml"; + extension = "svg"; + + static init() { + // Override file handling to allow drag & drop of SVG + const handleFile = app.handleFile; + app.handleFile = async function (file) { + if (file && (file.type === "image/svg+xml" || file.name?.endsWith(".svg"))) { + const reader = new FileReader(); + reader.onload = () => { + // Extract embedded workflow from desc tags + const descEnd = reader.result.lastIndexOf(""); + if (descEnd !== -1) { + const descStart = reader.result.lastIndexOf("", descEnd); + if (descStart !== -1) { + const json = reader.result.substring(descStart + 6, descEnd); + this.loadGraphData(JSON.parse(SvgWorkflowImage.unescapeXml(json))); + } + } + }; + reader.readAsText(file); + return; + } else if (file && (file.type === "image/jpeg" || file.name?.endsWith(".jpg") || file.name?.endsWith(".jpeg"))) { + if ( + await new Promise((resolve) => { + try { + // This shouldnt go in here but it's easier than refactoring handleFile + const reader = new FileReader(); + reader.onload = async () => { + try { + const value = new Jpeg().readExif(reader.result); + importA1111(app.graph, value); + resolve(true); + } catch (error) { + resolve(false); + } + }; + reader.onerror = () => resolve(false); + reader.readAsArrayBuffer(file); + } catch (error) { + resolve(false); + } + }) + ) { + return; + } + } + return handleFile.apply(this, arguments); + }; + } + + static escapeXml(unsafe) { + return unsafe.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); + } + + static unescapeXml(safe) { + return safe.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">"); + } + + getDrawTextConfig(_, widget) { + const domWrapper = widget.inputEl.closest(".dom-widget") ?? widget.inputEl; + return { + x: parseInt(domWrapper.style.left), + y: parseInt(domWrapper.style.top), + resetTransform: true, + }; + } + + saveState() { + super.saveState(); + this.state.ctx = app.canvas.ctx; + } + + restoreState() { + super.restoreState(); + app.canvas.ctx = this.state.ctx; + } + + updateView(bounds) { + super.updateView(bounds); + this.createSvgCtx(bounds); + } + + createSvgCtx(bounds) { + const ctx = this.state.ctx; + const svgCtx = (this.svgCtx = new C2S(bounds[2] - bounds[0], bounds[3] - bounds[1])); + svgCtx.canvas.getBoundingClientRect = function () { + return { width: svgCtx.width, height: svgCtx.height }; + }; + + // Override the c2s handling of images to draw images as canvases + const drawImage = svgCtx.drawImage; + svgCtx.drawImage = function (...args) { + const image = args[0]; + // If we are an image node and not a datauri then we need to replace with a canvas + // we cant convert to data uri here as it is an async process + if (image.nodeName === "IMG" && !image.src.startsWith("data:image/")) { + const canvas = document.createElement("canvas"); + canvas.width = image.width; + canvas.height = image.height; + const imgCtx = canvas.getContext("2d"); + imgCtx.drawImage(image, 0, 0); + args[0] = canvas; + } + + return drawImage.apply(this, args); + }; + + // Implement missing required functions + svgCtx.getTransform = function () { + return ctx.getTransform(); + }; + svgCtx.resetTransform = function () { + return ctx.resetTransform(); + }; + svgCtx.roundRect = svgCtx.rect; + app.canvas.ctx = svgCtx; + } + + getBlob(workflow) { + let svg = this.svgCtx.getSerializedSvg(true).replace("", `${SvgWorkflowImage.escapeXml(workflow)}`); + } + + return new Blob([svg], { type: "image/svg+xml" }); + } +} + +app.registerExtension({ + name: "pysssss.WorkflowImage", + init() { + // https://codepen.io/peterhry/pen/nbMaYg + function wrapText(context, text, x, y, maxWidth, lineHeight) { + var words = text.split(" "), + line = "", + i, + test, + metrics; + + for (i = 0; i < words.length; i++) { + test = words[i]; + metrics = context.measureText(test); + while (metrics.width > maxWidth) { + // Determine how much of the word will fit + test = test.substring(0, test.length - 1); + metrics = context.measureText(test); + } + if (words[i] != test) { + words.splice(i + 1, 0, words[i].substr(test.length)); + words[i] = test; + } + + test = line + words[i] + " "; + metrics = context.measureText(test); + + if (metrics.width > maxWidth && i > 0) { + context.fillText(line, x, y); + line = words[i] + " "; + y += lineHeight; + } else { + line = test; + } + } + + context.fillText(line, x, y); + } + + const stringWidget = ComfyWidgets.STRING; + // Override multiline string widgets to draw text using canvas while saving as svg + ComfyWidgets.STRING = function () { + const w = stringWidget.apply(this, arguments); + if (w.widget && w.widget.type === "customtext") { + const draw = w.widget.draw; + w.widget.draw = function (ctx) { + draw.apply(this, arguments); + const inputEl = this.inputEl ?? this.element; + if (!inputEl || inputEl.hidden) return; + + if (getDrawTextConfig) { + const config = getDrawTextConfig(ctx, this); + const t = ctx.getTransform(); + ctx.save(); + if (config.resetTransform) { + ctx.resetTransform(); + } + + const style = document.defaultView.getComputedStyle(inputEl, null); + const x = config.x; + const y = config.y; + const domWrapper = inputEl.closest(".dom-widget") ?? inputEl; + let w = parseInt(domWrapper.style.width); + if (w === 0) { + w = this.node.size[0] - 20; + } + const h = parseInt(domWrapper.style.height); + ctx.fillStyle = style.getPropertyValue("background-color"); + ctx.fillRect(x, y, w, h); + + ctx.fillStyle = style.getPropertyValue("color"); + ctx.font = style.getPropertyValue("font"); + + const line = t.d * 12; + const split = inputEl.value.split("\n"); + let start = y; + for (const l of split) { + start += line; + wrapText(ctx, l, x + 4, start, w, line); + } + + ctx.restore(); + } + }; + } + return w; + }; + }, + setup() { + const script = document.createElement("script"); + script.onload = function () { + const formats = [SvgWorkflowImage, PngWorkflowImage]; + for (const f of formats) { + f.init?.call(); + WorkflowImage.accept += (WorkflowImage.accept ? "," : "") + f.accept; + } + + // Add canvas menu options + const orig = LGraphCanvas.prototype.getCanvasMenuOptions; + LGraphCanvas.prototype.getCanvasMenuOptions = function () { + const options = orig.apply(this, arguments); + + options.push(null, { + content: "Workflow Image", + submenu: { + options: [ + { + content: "Import", + callback: () => { + WorkflowImage.import(); + }, + }, + { + content: "Export", + submenu: { + options: formats.flatMap((f) => [ + { + content: f.name.replace("WorkflowImage", "").toLocaleLowerCase(), + callback: () => { + new f().export(true); + }, + }, + { + content: f.name.replace("WorkflowImage", "").toLocaleLowerCase() + " (no embedded workflow)", + callback: () => { + new f().export(); + }, + }, + ]), + }, + }, + ], + }, + }); + return options; + }; + }; + + script.src = new URL(`assets/canvas2svg.js`, import.meta.url); + document.body.append(script); + }, +}); diff --git a/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflows.js b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflows.js new file mode 100644 index 0000000000000000000000000000000000000000..0225260ae7cc6b420c272ab3f54e389910a93815 --- /dev/null +++ b/1/custom_nodes/ComfyUI-Custom-Scripts/web/js/workflows.js @@ -0,0 +1,343 @@ +import { app } from "../../../scripts/app.js"; +import { api } from "../../../scripts/api.js"; +import { $el } from "../../../scripts/ui.js"; + +// Adds workflow management +// Original implementation by https://github.com/i-h4x +// Thanks for permission to reimplement as an extension + +const style = ` +#comfy-save-button, #comfy-load-button { + position: relative; + overflow: hidden; +} +.pysssss-workflow-arrow { + position: absolute; + top: 0; + bottom: 0; + right: 0; + font-size: 12px; + display: flex; + align-items: center; + width: 24px; + justify-content: center; + background: rgba(255,255,255,0.1); +} +.pysssss-workflow-arrow:after { + content: "▼"; +} +.pysssss-workflow-arrow:hover { + filter: brightness(1.6); + background-color: var(--comfy-menu-bg); +} +.pysssss-workflow-load .litemenu-entry:not(.has_submenu):before, +.pysssss-workflow-load ~ .litecontextmenu .litemenu-entry:not(.has_submenu):before { + content: "🎛️"; + padding-right: 5px; +} +.pysssss-workflow-load .litemenu-entry.has_submenu:before, +.pysssss-workflow-load ~ .litecontextmenu .litemenu-entry.has_submenu:before { + content: "📂"; + padding-right: 5px; + position: relative; + top: -1px; +} +.pysssss-workflow-popup ~ .litecontextmenu { + transform: scale(1.3); +} +`; + +async function getWorkflows() { + const response = await api.fetchApi("/pysssss/workflows", { cache: "no-store" }); + return await response.json(); +} + +async function getWorkflow(name) { + const response = await api.fetchApi(`/pysssss/workflows/${encodeURIComponent(name)}`, { cache: "no-store" }); + return await response.json(); +} + +async function saveWorkflow(name, workflow, overwrite) { + try { + const response = await api.fetchApi("/pysssss/workflows", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ name, workflow, overwrite }), + }); + if (response.status === 201) { + return true; + } + if (response.status === 409) { + return false; + } + throw new Error(response.statusText); + } catch (error) { + console.error(error); + } +} + +class PysssssWorkflows { + async load() { + this.workflows = await getWorkflows(); + if(this.workflows.length) { + this.workflows.sort(); + } + this.loadMenu.style.display = this.workflows.length ? "flex" : "none"; + } + + getMenuOptions(callback) { + const menu = []; + const directories = new Map(); + for (const workflow of this.workflows || []) { + const path = workflow.split("/"); + let parent = menu; + let currentPath = ""; + for (let i = 0; i < path.length - 1; i++) { + currentPath += "/" + path[i]; + let newParent = directories.get(currentPath); + if (!newParent) { + newParent = { + title: path[i], + has_submenu: true, + submenu: { + options: [], + }, + }; + parent.push(newParent); + newParent = newParent.submenu.options; + directories.set(currentPath, newParent); + } + parent = newParent; + } + parent.push({ + title: path[path.length - 1], + callback: () => callback(workflow), + }); + } + return menu; + } + + constructor() { + function addWorkflowMenu(type, getOptions) { + return $el("div.pysssss-workflow-arrow", { + parent: document.getElementById(`comfy-${type}-button`), + onclick: (e) => { + e.preventDefault(); + e.stopPropagation(); + + LiteGraph.closeAllContextMenus(); + const menu = new LiteGraph.ContextMenu( + getOptions(), + { + event: e, + scale: 1.3, + }, + window + ); + menu.root.classList.add("pysssss-workflow-popup"); + menu.root.classList.add(`pysssss-workflow-${type}`); + }, + }); + } + + this.loadMenu = addWorkflowMenu("load", () => + this.getMenuOptions(async (workflow) => { + const json = await getWorkflow(workflow); + app.loadGraphData(json); + }) + ); + addWorkflowMenu("save", () => { + return [ + { + title: "Save as", + callback: () => { + let filename = prompt("Enter filename", this.workflowName || "workflow"); + if (filename) { + if (!filename.toLowerCase().endsWith(".json")) { + filename += ".json"; + } + + this.workflowName = filename; + + 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: filename, + style: { display: "none" }, + parent: document.body, + }); + a.click(); + setTimeout(function () { + a.remove(); + window.URL.revokeObjectURL(url); + }, 0); + } + }, + }, + { + title: "Save to workflows", + callback: async () => { + const name = prompt("Enter filename", this.workflowName || "workflow"); + if (name) { + this.workflowName = name; + + const data = app.graph.serialize(); + if (!(await saveWorkflow(name, data))) { + if (confirm("A workspace with this name already exists, do you want to overwrite it?")) { + await saveWorkflow(name, app.graph.serialize(), true); + } else { + return; + } + } + await this.load(); + } + }, + }, + ]; + }); + this.load(); + + const handleFile = app.handleFile; + const self = this; + app.handleFile = function (file) { + if (file?.name?.endsWith(".json")) { + self.workflowName = file.name; + } else { + self.workflowName = null; + } + return handleFile.apply(this, arguments); + }; + } +} + +const refreshComboInNodes = app.refreshComboInNodes; +let workflows; + +async function sendToWorkflow(img, workflow) { + const graph = !workflow ? app.graph.serialize() : await getWorkflow(workflow); + const nodes = graph.nodes.filter((n) => n.type === "LoadImage"); + let targetNode; + if (nodes.length === 0) { + alert("To send the image to another workflow, that workflow must have a LoadImage node."); + return; + } else if (nodes.length > 1) { + targetNode = nodes.find((n) => n.title?.toLowerCase().includes("input")); + if (!targetNode) { + targetNode = nodes[0]; + alert( + "The target workflow has multiple LoadImage nodes, include 'input' in the name of the one you want to use. The first one will be used here." + ); + } + } else { + targetNode = nodes[0]; + } + + const blob = await (await fetch(img.src)).blob(); + const name = + (workflow || "sendtoworkflow").replace(/\//g, "_") + + "-" + + +new Date() + + new URLSearchParams(img.src.split("?")[1]).get("filename"); + const body = new FormData(); + body.append("image", new File([blob], name)); + + const resp = await api.fetchApi("/upload/image", { + method: "POST", + body, + }); + + if (resp.status === 200) { + await refreshComboInNodes.call(app); + targetNode.widgets_values[0] = name; + app.loadGraphData(graph); + app.graph.getNodeById(targetNode.id); + } else { + alert(resp.status + " - " + resp.statusText); + } +} + +app.registerExtension({ + name: "pysssss.Workflows", + init() { + $el("style", { + textContent: style, + parent: document.head, + }); + }, + + async refreshComboInNodes() { + workflows.load() + }, + + async setup() { + workflows = new PysssssWorkflows(); + + const comfyDefault = "[ComfyUI Default]"; + const defaultWorkflow = app.ui.settings.addSetting({ + id: "pysssss.Workflows.Default", + name: "🐍 Default Workflow", + defaultValue: comfyDefault, + type: "combo", + options: (value) => + [comfyDefault, ...workflows.workflows].map((m) => ({ + value: m, + text: m, + selected: m === value, + })), + }); + + document.getElementById("comfy-load-default-button").onclick = async function () { + if ( + localStorage["Comfy.Settings.Comfy.ConfirmClear"] === "false" || + confirm(`Load default workflow (${defaultWorkflow.value})?`) + ) { + if (defaultWorkflow.value === comfyDefault) { + app.loadGraphData(); + } else { + const json = await getWorkflow(defaultWorkflow.value); + app.loadGraphData(json); + } + } + }; + }, + async beforeRegisterNodeDef(nodeType, nodeData, app) { + const getExtraMenuOptions = nodeType.prototype.getExtraMenuOptions; + nodeType.prototype.getExtraMenuOptions = function (_, options) { + const r = getExtraMenuOptions?.apply?.(this, arguments); + let img; + if (this.imageIndex != null) { + // An image is selected so select that + img = this.imgs[this.imageIndex]; + } else if (this.overIndex != null) { + // No image is selected but one is hovered + img = this.imgs[this.overIndex]; + } + + if (img) { + let pos = options.findIndex((o) => o.content === "Save Image"); + if (pos === -1) { + pos = 0; + } else { + pos++; + } + + options.splice(pos, 0, { + content: "Send to workflow", + has_submenu: true, + submenu: { + options: [ + { callback: () => sendToWorkflow(img), title: "[Current workflow]" }, + ...workflows.getMenuOptions(sendToWorkflow.bind(null, img)), + ], + }, + }); + } + + return r; + }; + }, +}); diff --git a/1/custom_nodes/ComfyUI-LTXVideo/.gitattributes b/1/custom_nodes/ComfyUI-LTXVideo/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..7e0e7c8d270b417ea6bde84fdf2ca542bbd67b68 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/.gitattributes @@ -0,0 +1,10 @@ +**/*.png filter=lfs diff=lfs merge=lfs -text +**/*.mp4 filter=lfs diff=lfs merge=lfs -text +**/*.jpg filter=lfs diff=lfs merge=lfs -text + +example_workflows/low_level/end.jpg -filter -diff -merge -text +example_workflows/low_level/fox.jpg -filter -diff -merge -text +example_workflows/low_level/shrek2.jpg -filter -diff -merge -text +example_workflows/low_level/start.jpg -filter -diff -merge -text +example_workflows/tricks/shrek2.jpg -filter -diff -merge -text +example_workflows/tricks/shrek3.jpg -filter -diff -merge -text diff --git a/1/custom_nodes/ComfyUI-LTXVideo/.gitignore b/1/custom_nodes/ComfyUI-LTXVideo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..82f927558a3dff0ea8c20858856e70779fd02c93 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/.gitignore @@ -0,0 +1,162 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/1/custom_nodes/ComfyUI-LTXVideo/.pre-commit-config.yaml b/1/custom_nodes/ComfyUI-LTXVideo/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c0a6f724829c8a8e00185644c6ca4b4a61132c9 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/.pre-commit-config.yaml @@ -0,0 +1,28 @@ +# general formatting +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.6.0 + hooks: + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - id: requirements-txt-fixer + - id: check-added-large-files + - id: check-toml +# Isort (import sorting) +- repo: https://github.com/PyCQA/isort + rev: 5.13.2 + hooks: + - id: isort + args: [--profile, black] +# Black (code formatting) +- repo: https://github.com/psf/black + rev: 24.4.2 # Replace by any tag/version: https://github.com/psf/black/tags + hooks: + - id: black + language_version: python3.10 +# flake8 linter +- repo: https://github.com/charliermarsh/ruff-pre-commit + rev: 'v0.4.4' + hooks: + - id: ruff diff --git a/1/custom_nodes/ComfyUI-LTXVideo/LICENSE b/1/custom_nodes/ComfyUI-LTXVideo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..b0d79e2e318e8931fbdad112136372ec28603d2d --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/LICENSE @@ -0,0 +1,381 @@ + LTX-2 Community License Agreement + License date: January 5, 2026 + + +By using or distributing any portion or element of LTX-2, you agree +to be bound by this Agreement. + + 1. Definitions. + + "Agreement" means the terms and conditions for the license, use, + reproduction, and distribution of LTX-2 and the Complementary + Materials, as specified in this document. + + "Control" means the direct or indirect ownership of more than + fifty percent (50%) of the voting securities or other ownership + interests, or the power to direct the management and policies of + such Entity through voting rights, contract, or otherwise. + + "Data" means a collection of information and/or content extracted + from the dataset used with LTX-2, including to train, pretrain, + or otherwise evaluate LTX-2. The Data is not licensed under this + Agreement. + + "Derivatives of LTX-2" means all modifications to LTX-2, works + based on LTX-2, or any other model which is created or initialized + by transfer of patterns of the weights, parameters, activations or + output of LTX-2, to the other model, in order to cause the other + model to perform similarly to LTX-2, including – but not limited + to - distillation methods entailing the use of intermediate data + representations or methods based on the generation of synthetic + data by LTX-2 for training the other model. For clarity, Derivatives + of LTX-2 include: (i) any fine-tuned or adapted weights, parameters, + or checkpoints derived from LTX-2; (ii) derivative model architectures + that incorporate or are based upon LTX-2's architecture; and + (iii) any modified or extended versions of the Complementary + Materials. All intellectual property rights in Derivatives of LTX-2 + shall be subject to the terms of this Agreement, and you may not + claim exclusive ownership rights in any Derivatives of LTX-2 that + would restrict the rights granted herein. + + "Entity" means any individual, corporation, partnership, limited + liability company, or other legal entity. For purposes of this + Agreement, an Entity shall be deemed to include, on an aggregative + basis, all subsidiaries, affiliates, and other companies under + common Control with such Entity. When determining whether an Entity + meets any threshold under this Agreement (including revenue + thresholds), all subsidiaries, affiliates, and companies under + common Control shall be considered collectively. + + "Harm" includes but is not limited to physical, mental, + psychological, financial and reputational damage, pain, or loss. + + "Licensor" or "Lightricks" means the owner that is granting the + license under this Agreement. For the purposes of this Agreement, + the Licensor is Lightricks Ltd. + + "LTX-2" means the large language models, text/image/video/audio/3D + generation models, and multimodal large language models and their + software and algorithms, including trained model weights, parameters + (including optimizer states), machine-learning model code, + inference-enabling code, training-enabling code, fine-tuning + enabling code, accompanying source code, scripts, documentation, + tutorials, examples, and all other elements of the foregoing + distributed and made publicly available by Lightricks (including, + for example, at https://github.com/Lightricks/LTX-2) for the LTX-2 + model released on January 5, 2026. This license is applicable to + all LTX-2 versions released since January 5, 2026, and all future + releases of LTX-2 under this license. + + "Output" means the results of operating LTX-2 as embodied in + informational content resulting therefrom. + + "you" (or "your") means an individual or legal Entity licensing + LTX-2 in accordance with this Agreement and/or making use of LTX-2 + for whichever purpose and in any field of use, including usage of + LTX-2 in an end-use application - e.g. chatbot, translator, image + generator. + + 2. Grant of License. Subject to the terms and conditions of this + Agreement, you are granted a non-exclusive, worldwide, + non-transferable and royalty-free limited license under Licensor's + intellectual property or other rights owned by Licensor embodied + in LTX-2 to use, reproduce, prepare, distribute, publicly display, + publicly perform, sublicense, copy, create derivative works of, + and make modifications to LTX-2, for any purpose, subject to the + restrictions set forth in Attachment A; provided however, that + Entities with annual revenues of at least $10,000,000 (the + "Commercial Entities") are required to obtain a paid commercial + use license in order to use LTX-2 and Derivatives of LTX-2, + subject to the terms and provisions of a different license (the + "Commercial Use Agreement"), as will be provided by the Licensor. + Commercial Entities interested in such a commercial license are + required to [contact Licensor](https://ltx.io/model/licensing). + Any commercial use of LTX-2 or Derivatives of LTX-2 by the + Commercial Entities not in accordance with this Agreement and/or + the Commercial Use Agreement is strictly prohibited and shall be + deemed a material breach of this Agreement. Such material breach + will be subject, in addition to any license fees owed to Licensor + for the period such Commercial Entity used LTX-2 (as will be + determined by Licensor), to liquidated damages, which will be paid + to Licensor immediately upon demand, in an amount equal to double + the amount that would otherwise have been paid by you for the + relevant period of time. Such amount reflects a reasonable estimation + of the losses and administrative costs incurred due to such breach. + You agree and understand that this remedy does not limit the Licensor's + right to pursue other remedies available at law or equity. + + 3. Distribution and Redistribution. You may host for third parties + remote access purposes (e.g. software-as-a-service), reproduce + and distribute copies of LTX-2 or Derivatives of LTX-2 thereof in + any medium, with or without modifications, provided that you meet + the following conditions: + + (a) Use-based restrictions as referenced in paragraph 4 and all + provisions of Attachment A MUST be included as an enforceable + provision by you in any type of legal agreement (e.g. a + license) governing the use and/or distribution of LTX-2 or + Derivatives of LTX-2, and you shall give notice to subsequent + users you distribute to, that LTX-2 or Derivatives of LTX-2 + are subject to paragraph 4 and Attachment A in their entirety, + including all use restrictions and acceptable use policies; + + (b) You must provide any third party recipients of LTX-2 or + Derivatives of LTX-2 a copy of this Agreement, including all + attachments and use policies. Any Derivative of LTX-2 (as + defined in Section 1, including but not limited to fine-tuned + weights, modified training code, models trained on Outputs, or + any other derivative) must be distributed exclusively under + the terms of this Agreement with a complete copy of this + license included; + + (c) You must cause any modified files to carry prominent notices + stating that you changed the files; + + (d) You must retain all copyright, patent, trademark, and + attribution notices excluding those notices that do not + pertain to any part of LTX-2, Derivatives of LTX-2. + + You may add your own copyright statement to your modifications and + may provide additional or different license terms and conditions - + respecting paragraph 3(a) - for use, reproduction, or distribution + of your modifications, or for any such Derivatives of LTX-2 as a + whole, provided your use, reproduction, and distribution of LTX-2 + otherwise complies with the conditions stated in this Agreement, + and you provide a complete copy of this Agreement with any such + use, reproduction and distribution of LTX-2 and any Derivatives + thereof. + + 4. Use-based restrictions. The restrictions set forth in Attachment A + are considered Use-based restrictions. Therefore, you cannot use + LTX-2 and the Derivatives of LTX-2 in violation of the specified + restricted uses. You may use LTX-2 subject to this Agreement, + including only for lawful purposes and in accordance with the + Agreement. "Use" may include creating any content with, fine-tuning, + updating, running, training, evaluating and/or re-parametrizing + LTX-2. You shall require all of your users who use LTX-2 or a + Derivative of LTX-2 to comply with the terms of this paragraph 4. + + 5. The Output You Generate. Except as set forth herein, Licensor + claims no rights in the Output you generate using LTX-2. You are + accountable for input you insert into LTX-2, the Output you + generate and its subsequent uses. No use of the Output can + contravene any provision as stated in the Agreement. + + 6. Updates and Runtime Restrictions. To the maximum extent permitted + by law, Licensor reserves the right to restrict (remotely or + otherwise) usage of LTX-2 in violation of this Agreement, update + LTX-2 through electronic means, or modify the Output of LTX-2 + based on updates. You shall undertake reasonable efforts to use + the latest version of LTX-2. Any use of the non-current version + of LTX-2 is done solely at your risk. + + 7. Export Controls and Sanctions Compliance. You acknowledge that + LTX-2, Derivatives of LTX-2 may be subject to export control laws + and regulations, including but not limited to the U.S. Export + Administration Regulations and sanctions programs administered by + the Office of Foreign Assets Control (OFAC). You represent and + warrant that you and any users of LTX-2 are not (i) located in, + organized under the laws of, or ordinarily resident in any country + or territory subject to comprehensive sanctions; (ii) identified + on any U.S. government restricted party list, including the + Specially Designated Nationals and Blocked Persons List; or + (iii) otherwise prohibited from receiving LTX-2 under applicable + law. You shall not export, re-export, or transfer LTX-2, directly + or indirectly, in violation of any applicable export control or + sanctions laws or regulations. You agree to comply with all + applicable trade control laws and shall indemnify and hold + Licensor harmless from any claims arising from your failure to + comply with such laws. + + 8. Trademarks and related. Nothing in this Agreement permits you to + make use of Licensor's trademarks, trade names, logos or to + otherwise suggest endorsement or misrepresent the relationship + between the parties; and any rights not expressly granted herein + are reserved by the Licensor. + + 9. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides LTX-2 on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or + conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS + FOR A PARTICULAR PURPOSE. You are solely responsible for + determining the appropriateness of using or redistributing LTX-2 + and Derivatives of LTX-2 and assume any risks associated with + your exercise of permissions under this Agreement. + + 10. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall Licensor be liable + to you for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as + a result of this Agreement or out of the use or inability to use + LTX-2 (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if Licensor has been + advised of the possibility of such damages. + + 11. Accepting Warranty or Additional Liability. While redistributing + LTX-2 and Derivatives of LTX-2, you may, provided you do not + violate the terms of this Agreement, choose to offer and charge + a fee for, acceptance of support, warranty, indemnity, or other + liability obligations. However, in accepting such obligations, + you may act only on your own behalf and on your sole + responsibility, not on behalf of Licensor, and only if you agree + to indemnify, defend, and hold Licensor harmless for any liability + incurred by, or claims asserted against Licensor, by reason of + your accepting any such warranty or additional liability. + + 12. Governing Law. This Agreement and all relations, disputes, claims + and other matters arising hereunder (including non-contractual + disputes or claims) will be governed exclusively by, and construed + exclusively in accordance with, the laws of the State of New York. + To the extent permitted by law, choice of laws rules and the + United Nations Convention on Contracts for the International Sale + of Goods will not apply. For the purposes of adjudicating any + action or proceeding to enforce the terms of this Agreement, you + hereby irrevocably consent to the exclusive jurisdiction of, and + venue in, the federal and state courts located in the County of + New York within the State of New York. The prevailing party in + any claim or dispute between the parties under this Agreement + will be entitled to reimbursement of its reasonable attorneys' + fees and costs. You hereby waive the right to a trial by jury, + to participate in a class or representative action (including in + arbitration), or to combine individual proceedings in court or + in arbitration without the consent of all parties. + + 13. Term and Termination. This Agreement is effective upon your + acceptance and continues until terminated. Licensor may terminate + this Agreement immediately upon written notice to you if you + breach any provision of this Agreement, including but not limited + to violations of the use restrictions in Attachment A or + unauthorized commercial use. Upon termination: (a) all rights + granted to you under this Agreement will immediately cease; + (b) you must immediately cease all use of LTX-2 and Derivatives + of LTX-2; (c) you must delete or destroy all copies of LTX-2 + and Derivatives of LTX-2 in your possession or control; and + (d) you must notify any third parties to whom you distributed + LTX-2 or Derivatives of LTX-2 of the termination. Sections 8-13, + and Section 15 shall survive termination of this Agreement. + Termination does not relieve you of any obligations incurred + prior to termination, including payment obligations under + Section 2. In addition, if You commence a lawsuit or other + proceedings (including a cross-claim or counterclaim in a lawsuit) + against Licensor or any person or entity alleging that LTX-2 or + any Output, or any portion of any of the foregoing, infringe any + intellectual property or other right owned or licensable by you, + then all licenses granted to you under this Agreement shall + terminate as of the date such lawsuit or other proceeding is filed. + + 14. Disputes and Arbitration. All disputes arising in connection with + this Agreement shall be finally settled by arbitration under the + Rules of Arbitration of the International Chamber of Commerce + ("ICC Rules"), by one (1) arbitrator appointed in accordance with + the ICC Rules. The seat of arbitration shall be New York, NY, USA, + and the proceedings shall be conducted in English. The arbitrator + shall be empowered to grant any relief that a court could grant. + Judgment on the arbitration award may be entered by any court + having jurisdiction thereof. Each party waives its right to a + trial by jury and to participate in any class or representative + action. + + 15. If any provision of this Agreement is held to be + invalid, illegal + or unenforceable, the remaining provisions shall be unaffected + thereby and remain valid as if such provision had not been set + forth herein. + + END OF TERMS AND CONDITIONS + + ATTACHMENT A: Use Restrictions + + When using the Outputs, LTX-2 and any Derivatives thereof, you + will comply with the Acceptable Use Policy. In addition, you + agree not to use the Outputs, LTX-2 or its Derivatives in any + of the following ways: + + 1. In any way that violates any applicable national, federal, + state, local or international law or regulation; + + 2. For the purpose of exploiting, Harming or attempting to + exploit or Harm minors in any way; + + 3. To generate or disseminate false information and/or content + with the purpose of Harming others; + + 4. To generate or disseminate personal identifiable information + that can be used to Harm an individual; + + 5. To generate or disseminate information and/or content (e.g. + images, code, posts, articles), and place the information + and/or content in any context (e.g. bot generating tweets) + without expressly and intelligibly disclaiming that the + information and/or content is machine generated; + + 6. To defame, disparage or otherwise harass others; + + 7. To impersonate or attempt to impersonate (e.g. deepfakes) + others without their consent; + + 8. For fully automated decision making that adversely impacts an + individual's legal rights or otherwise creates or modifies a + binding, enforceable obligation; + + 9. For any use intended to or which has the effect of + discriminating against or Harming individuals or groups based + on online or offline social behavior or known or predicted + personal or personality characteristics; + + 10. To exploit any of the vulnerabilities of a specific group of + persons based on their age, social, physical or mental + characteristics, in order to materially distort the behavior + of a person pertaining to that group in a manner that causes + or is likely to cause that person or another person physical + or psychological Harm; + + 11. For any use intended to or which has the effect of + discriminating against individuals or groups based on legally + protected characteristics or categories; + + 12. To provide medical advice and medical results interpretation; + + 13. To generate or disseminate information for the purpose to be + used for administration of justice, law enforcement, + immigration or asylum processes, such as predicting an + individual will commit fraud/crime commitment (e.g. by text + profiling, drawing causal relationships between assertions + made in documents, indiscriminate and arbitrarily-targeted use); + + 14. To generate and/or disseminate malware (including – but not + limited to – ransomware) or any other content to be used for + the purpose of harming electronic systems; + + 15. To engage in, promote, incite, or facilitate discrimination + or other unlawful or harmful conduct in the provision of + employment, employment benefits, credit, housing, or other + essential goods and services; + + 16. To engage in, promote, incite, or facilitate the harassment, + abuse, threatening, or bullying of individuals or groups of + individuals; + + 17. For military, warfare, nuclear industries or applications, + weapons development, or any use in connection with activities + that may cause death, personal injury, or severe physical or + environmental damage; + + 18. For commercial use only: To train, improve, or fine-tune any + other machine learning model, artificial intelligence system, + or competing model, except for Derivatives of LTX-2 as + expressly permitted under this Agreement; + + 19. To circumvent, disable, or interfere with any technical + limitations, safety features, content filters, or use + restrictions implemented in LTX-2 by Licensor; + + 20. To use LTX-2 or Derivatives of LTX-2 in any product, service, + or application that directly competes with Licensor's + commercial products or services, or is designed to replace or + substitute Licensor's offerings in the market, without + obtaining a separate commercial license from Licensor. diff --git a/1/custom_nodes/ComfyUI-LTXVideo/README.md b/1/custom_nodes/ComfyUI-LTXVideo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..81b9e7e4935fe66f420a33f5b23ebb841dfef8f1 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/README.md @@ -0,0 +1,182 @@ +# ComfyUI-LTXVideo + +[![GitHub](https://img.shields.io/badge/LTX-Repo-blue?logo=github)](https://github.com/Lightricks/LTX-2) +[![Website](https://img.shields.io/badge/Website-LTX-181717?logo=google-chrome)](https://ltx.io/model) +[![Model](https://img.shields.io/badge/HuggingFace-Model-orange?logo=huggingface)](https://huggingface.co/Lightricks/LTX-2.3) +[![LTXV Trainer](https://img.shields.io/badge/LTX-Trainer%20Repo-9146FF)](https://github.com/Lightricks/LTX-2/tree/main/packages/ltx-trainer) +[![Demo](https://img.shields.io/badge/Demo-Try%20Now-brightgreen?logo=vercel)](https://app.ltx.studio/ltx-2-playground/i2v) +[![Paper](https://img.shields.io/badge/Paper-arXiv-B31B1B?logo=arxiv)](https://videos.ltx.io/LTX-2/grants/LTX_2_Technical_Report_compressed.pdf) +[![Discord](https://img.shields.io/badge/Join-Discord-5865F2?logo=discord)](https://discord.gg/ltxplatform) + + +A collection of powerful custom nodes that extend ComfyUI's capabilities for the LTX-2 video generation model. + +LTX-2 is built into ComfyUI core ([see it here](https://github.com/comfyanonymous/ComfyUI/tree/master/comfy/ldm/lightricks)), making it readily accessible to all ComfyUI users. This repository hosts additional nodes and workflows to help you get the most out of LTX-2's advanced features. + +**To learn more about LTX-2** See the [main LTX-2 repository](https://github.com/Lightricks/LTX-2) for model details and additional resources. + + +## Prerequisites +Before you begin using an LTX-2 workflow in ComfyUI, make sure you have: + +* ComfyUI installed (Download here](https://www.comfy.org/download) +* CUDA-compatible GPU with 32GB+ VRAM +* 100GB+ free disk space for models and cache + + +## Quick Start 🚀 + +We recommend using the LTX-2 workflows available in Comfy Manager. + +1. Open ComfyUI +2. Click the Manager button (or press Ctrl+M) +3. Select Install Custom Nodes +4. Search for “LTXVideo” +5. Click Install +6. Wait for installation to complete +7. Restart ComfyUI + +The nodes will appear in your node menu under the “LTXVideo” category. Required models will be downloaded on first use. + + +## Example Workflows + +The ComfyUI-LTXVideo installation includes several example workflows. +You can see them all at: +``` +ComfyUI/custom_nodes/ComfyUI-LTXVideo/example_workflows/ +``` + +LTX-2.3 Workflows: + +* [`Text/image to video full/distilled model; single stage`](./example_workflows/2.3/LTX-2.3_T2V_I2V_Single_Stage_Distilled_Full.json) +* [`Text/image to video distilled model; two stages (with upsampling)`](./example_workflows/2.3/LTX-2.3_T2V_I2V_Two_Stage_Distilled.json) +* [`IC-LoRA distilled model depth + human pose + edges`](./example_workflows/2.3/LTX-2.3_ICLoRA_Union_Control_Distilled.json) +* [`IC-LoRA distilled model I2V motion tracking`](./example_workflows/2.3/LTX-2.3_ICLoRA_Motion_Track_Distilled.json) +* [`IC-LoRA distilled model HDR`](./example_workflows/2.3/LTX-2.3_ICLoRA_HDR_Distilled.json) +* [`IC-LoRA distilled model Dub-It; two stages (with upsampling)`](./example_workflows/2.3/LTX-2.3_ICLoRA_DubIt_Two_Stage_Distilled.json) +* [`IC-LoRA distilled model pixel spatial upscaling`](./example_workflows/2.3/LTX-2.3_ICLoRA_Pixel_Spatial_Upscaler_Distilled.json) +* [`Text to audio distilled model; single stage`](./example_workflows/2.3/LTX-2.3_T2A_Single_Stage_Distilled.json) + +Older Workflows (LTX-2.0): + +* [`Text to video full model`](./example_workflows/2.0/LTX-2_T2V_Full_wLora.json) +* [`Text to video distilled model (Fast)`](./example_workflows/2.0/LTX-2_T2V_Distilled_wLora.json) +* [`Image to video full model`](./example_workflows/2.0/LTX-2_I2V_Full_wLora.json) +* [`Image to video distilled model (Fast)`](./example_workflows/2.0/LTX-2_I2V_Distilled_wLora.json) +* [`Video to video detailer`](./example_workflows/2.0/LTX-2_V2V_Detailer.json) +* [`IC-LoRA distilled model (depth + human pose + edges)`](./example_workflows/2.0/LTX-2_ICLoRA_All_Distilled.json) +* [`IC-LoRA distilled model with downscaled reference latents`](./example_workflows/2.0/LTX-2_ICLoRA_All_Distilled_ref0.5.json) + +## Union IC-LoRA Model + +We introduce a new **Union IC-LoRA** model that combines depth and edge (canny) control conditions into a single unified LoRA. + +### Key Features + +- **Unified Control**: A single LoRA that supports multiple control conditions (depth or edges). +- **Downsampled Latent Processing**: The union LoRA operates on a downsampled latent size, which reduces memory usage and significantly speeds up inference while maintaining quality. + +### How It Works + +The union LoRA is trained to understand and respond to both control signals (depth maps and edge maps) within a single model. The model learns to: + +1. **Parse multiple conditions**: Identify which control signals are present in the input +2. **Process at reduced resolution**: Work on downsampled latents to improve efficiency + +## HDR IC-LoRA + +We provide an **HDR IC-LoRA** that generates linear HDR video encoded in ARRI LogC3, enabling workflows that output high-dynamic-range content suitable for grading and EXR export. + +### Key Features + +- **Linear HDR output**: The LoRA produces frames in LogC3-compressed space; the `LTXVHDRDecodePostprocess` node decodes these back to linear HDR values. +- **SDR preview + raw HDR**: The node outputs both a Reinhard-tonemapped SDR preview and the raw linear HDR tensor for downstream use. +- **EXR export**: Optionally writes the linear HDR frames as a 16/32-bit EXR image sequence. To enable EXR writing, set `OPENCV_IO_ENABLE_OPENEXR=1` in the environment before starting ComfyUI. The exported EXR sequence is best viewed in [DJV](https://github.com/grizzlypeak3d/DJV) (or [DJV for macOS](https://djv.en.uptodown.com/mac/download)). + +## Dub-It IC-LoRA + +We provide a **Dub-It IC-LoRA** that dubs or rephrases speech in video. Given a source video and a text prompt containing the desired dialogue, it generates new lip movements and audio that match the target text while preserving the speaker's identity. + +### Key Features + +- **Multilingual dubbing**: Translate speech into another language - the model regenerates lips and audio to match. +- **Same-language rephrasing**: Change what the speaker says while keeping the original language. +- **Two-stage pipeline**: Stage 1 generates the video and audio at base resolution; Stage 2 upscales while freezing the audio. +- **Speaker identity preservation**: Reference audio tokens provide speaker context so the generated voice stays consistent. + +## Pixel Spatial Upscaler IC-LoRA + +We provide **Pixel Spatial Upscaler** IC-LoRAs that creatively upscale low-resolution video by synthesizing fine detail rather than simply interpolating pixels. Given a low-resolution reference clip, the model re-renders it at 2× or 4× resolution with generative spatial detail — making it a creative upsampler, not a pixel-accurate refiner. + +### Key Features + +- **2× and 4× variants**: Choose the 2× upscaler for moderate upscaling or the 4× upscaler for larger resolution jumps. +- **Generative detail synthesis**: The model synthesizes texture and structure from the reference rather than faithfully preserving every pixel. +- **Draft-then-upscale workflow**: Generate at a low base resolution (e.g. ~280p) to lock in composition and motion, then run the upscaler for the final high-resolution output. +- **Tunable fidelity**: LoRA strength, guidance, and step count control how closely the output follows the reference — lower values stay closer to the source; higher values allow more creative detail. + +## Text-to-Audio (T2A) + +LTX-2 is a single joint audio/video transformer, but it can generate audio on its own. The `LTXVAudioOnlyModel` node puts the model into audio-only mode for text-to-audio, with no video output. + +### Key Features + +- **Audio-only sampling**: The node sets the model's `run_vx`, `a2v_cross_attn` and `v2a_cross_attn` flags off, so the audio is denoised with no dependence on the video latent and the video stream is skipped. This matches the reference single-stage T2A pipeline's `video=None` behavior. +- **Minimal dummy video latent**: The model splits its input positionally into `[video, audio]`, so the sampler still needs a video latent at index 0. Use the `LTXVAudioOnlyEmptyVideoLatent` node (a fixed 64x64 single-frame placeholder, no params to tweak) joined with the audio latent via `LTXVConcatAVLatent`; with `LTXVAudioOnlyModel` active it is never attended to and adds negligible cost. +- **Audio decode**: `LTXVAudioVAEDecode` extracts the audio directly from the joint latent, then save it with a standard built-in audio node (for example `Save Audio (FLAC)`). + +## Required Models + +Download the following models: + +**LTX-2.3 Model Checkpoint** - Choose and download one of the models to `COMFYUI_ROOT_FOLDER/models/checkpoints` folder. + * [`ltx-2.3-22b-dev.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-22b-dev.safetensors) + * [`ltx-2.3-22b-distilled-1.1.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-22b-distilled-1.1.safetensors) + +**Spatial Upscaler** - Required for current two-stage pipeline implementations in this repository. Download to `COMFYUI_ROOT_FOLDER/models/latent_upscale_models` folder. + * [`ltx-2.3-spatial-upscaler-x2-1.1.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-spatial-upscaler-x2-1.1.safetensors) + * [`ltx-2.3-spatial-upscaler-x1.5-1.0.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-spatial-upscaler-x1.5-1.0.safetensors) + +**Temporal Upscaler** - Required for current two-stage pipeline implementations in this repository. Download to `COMFYUI_ROOT_FOLDER/models/latent_upscale_models` folder. + * [`ltx-2.3-temporal-upscaler-x2-1.0.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-temporal-upscaler-x2-1.0.safetensors) + +**Distilled LoRA** - Required for current two-stage pipeline implementations in this repository (except DistilledPipeline and ICLoraPipeline). Download to `COMFYUI_ROOT_FOLDER/models/loras` folder. + * [`ltx-2.3-22b-distilled-lora-384-1.1.safetensors`](https://huggingface.co/Lightricks/LTX-2.3/blob/main/ltx-2.3-22b-distilled-lora-384-1.1.safetensors) + +**Gemma Text Encoder** Download all files from the repository to `COMFYUI_ROOT_FOLDER/models/text_encoders/gemma-3-12b-it-qat-q4_0-unquantized`. + * [`Gemma 3`](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized) + +**LoRAs** Choose and download to `COMFYUI_ROOT_FOLDER/models/loras` folder. + * [`ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Union-Control/blob/main/ltx-2.3-22b-ic-lora-union-control-ref0.5.safetensors) + * [`ltx-2.3-22b-ic-lora-motion-track-control-ref0.5.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Motion-Track-Control/blob/main/ltx-2.3-22b-ic-lora-motion-track-control-ref0.5.safetensors) + * [`ltx-2.3-22b-ic-lora-hdr-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-HDR) + * [`ltx-2.3-22b-ic-lora-dubit-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-DubIt) + * [`ltx-2-19b-ic-lora-detailer.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-IC-LoRA-Detailer/blob/main/ltx-2-19b-ic-lora-detailer.safetensors) + * [`ltx-2-19b-ic-lora-pose-control.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-IC-LoRA-Pose-Control/blob/main/ltx-2-19b-ic-lora-pose-control.safetensors) + * [`ltx-2-19b-lora-camera-control-dolly-in.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In/blob/main/ltx-2-19b-lora-camera-control-dolly-in.safetensors) + * [`ltx-2-19b-lora-camera-control-dolly-left.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Left/blob/main/ltx-2-19b-lora-camera-control-dolly-left.safetensors) + * [`ltx-2-19b-lora-camera-control-dolly-out.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out/blob/main/ltx-2-19b-lora-camera-control-dolly-out.safetensors) + * [`ltx-2-19b-lora-camera-control-dolly-right.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Right/blob/main/ltx-2-19b-lora-camera-control-dolly-right.safetensors) + * [`ltx-2-19b-lora-camera-control-jib-down.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down/blob/main/ltx-2-19b-lora-camera-control-jib-down.safetensors) + * [`ltx-2-19b-lora-camera-control-jib-up.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up/blob/main/ltx-2-19b-lora-camera-control-jib-up.safetensors) + * [`ltx-2-19b-lora-camera-control-static.safetensors`](https://huggingface.co/Lightricks/LTX-2-19b-LoRA-Camera-Control-Static/blob/main/ltx-2-19b-lora-camera-control-static.safetensors) + * [`ltx-2.3-22b-ic-lora-instant-shave-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave/blob/main/ltx-2.3-22b-ic-lora-instant-shave-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-colorization-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Colorization/blob/main/ltx-2.3-22b-ic-lora-colorization-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-cross-eyed-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Cross-Eyed/blob/main/ltx-2.3-22b-ic-lora-cross-eyed-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-day-to-night-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Day-To-Night/blob/main/ltx-2.3-22b-ic-lora-day-to-night-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-deblur-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Deblur/blob/main/ltx-2.3-22b-ic-lora-deblur-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-decompression-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Decompression/blob/main/ltx-2.3-22b-ic-lora-decompression-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-in-outpainting-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-In-Outpainting/blob/main/ltx-2.3-22b-ic-lora-in-outpainting-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-water-simulation-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Water-Simulation/blob/main/ltx-2.3-22b-ic-lora-water-simulation-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Ingredients/blob/main/ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-pixel-spatial-upscaler-x4-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Pixel-Spatial-Upscaler/blob/main/ltx-2.3-22b-ic-lora-pixel-spatial-upscaler-x4-0.9.safetensors) + * [`ltx-2.3-22b-ic-lora-pixel-spatial-upscaler-x2-0.9.safetensors`](https://huggingface.co/Lightricks/LTX-2.3-22b-IC-LoRA-Pixel-Spatial-Upscaler/blob/main/ltx-2.3-22b-ic-lora-pixel-spatial-upscaler-x2-0.9.safetensors) + + +## Advanced Techniques + +### Low VRAM +* For systems with low VRAM you can use the model loader nodes from [low_vram_loaders.py](./low_vram_loaders.py). Those nodes ensure the correct order of execution and perform the model offloading such that generation fits in 32 GB VRAM. +* Use --reserve-vram ComfyUI parameter: `python -m main --reserve-vram 5` (or other number in GB). +* For complete information about using LTX-2 models, workflows, and nodes in ComfyUI, please visit our [Open Source documentation](https://docs.ltx.video/open-source-model/integration-tools/comfy-ui). diff --git a/1/custom_nodes/ComfyUI-LTXVideo/__init__.py b/1/custom_nodes/ComfyUI-LTXVideo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f921a3492098c541e473f6ab9a4560961fb129e --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/__init__.py @@ -0,0 +1,147 @@ +from .audio_only import LTXVAudioOnlyEmptyVideoLatent, LTXVAudioOnlyModel +from .conditioning_loader import LTXVLoadConditioning +from .conditioning_saver import LTXVSaveConditioning +from .decoder_noise import DecoderNoise +from .dynamic_conditioning import DynamicConditioning +from .easy_samplers import ( + LinearOverlapLatentTransition, + LTXVBaseSampler, + LTXVExtendSampler, + LTXVInContextSampler, + LTXVNormalizingSampler, +) +from .gemma_api_conditioning import GemmaAPITextEncode +from .gemma_encoder import LTXVGemmaCLIPModelLoader, LTXVGemmaEnhancePrompt +from .guide import LTXVAddGuideAdvanced, LTXVAddGuideAdvancedAttention +from .guiders import GuiderParametersNode, MultimodalGuiderNode +from .hdr import LTXVHDRDecodePostprocess +from .iclora import ( + LTXAddVideoICLoRAGuide, + LTXAddVideoICLoRAGuideAdvanced, + LTXICLoRALoaderModelOnly, + LTXVSetAudioRefTokens, +) +from .latent_norm import ( + LTXVAdainLatent, + LTXVPerStepAdainPatcher, + LTXVPerStepStatNormPatcher, + LTXVStatNormLatent, +) +from .latents import ( + LTXVAddLatentGuide, + LTXVImgToVideoConditionOnly, + LTXVSelectLatents, + LTXVSetVideoLatentNoiseMasks, +) +from .looping_sampler import LTXVLoopingSampler, MultiPromptProvider +from .low_vram_loaders import ( + LowVRAMAudioVAELoader, + LowVRAMCheckpointLoader, + LowVRAMLatentUpscaleModelLoader, +) +from .masks import LTXVPreprocessMasks +from .nodes_registry import NODE_CLASS_MAPPINGS as RUNTIME_NODE_CLASS_MAPPINGS +from .nodes_registry import ( + NODE_DISPLAY_NAME_MAPPINGS as RUNTIME_NODE_DISPLAY_NAME_MAPPINGS, +) +from .nodes_registry import NODES_DISPLAY_NAME_PREFIX, camel_case_to_spaces +from .prompt_enhancer_nodes import LTXVPromptEnhancer, LTXVPromptEnhancerLoader +from .pyramid_blending import LTXVLaplacianPyramidBlend +from .q8_nodes import LTXVQ8LoraModelLoader, LTXVQ8Patch +from .sparse_tracks import LTXVDrawTracks, LTXVSparseTrackEditor +from .stg import ( + LTXVApplySTG, + STGAdvancedPresetsNode, + STGGuiderAdvancedNode, + STGGuiderNode, +) +from .tiled_sampler import LTXVTiledSampler +from .tiled_vae_decode import LTXVTiledVAEDecode +from .tricks import NODE_CLASS_MAPPINGS as TRICKS_NODE_CLASS_MAPPINGS +from .tricks import NODE_DISPLAY_NAME_MAPPINGS as TRICKS_NODE_DISPLAY_NAME_MAPPINGS +from .utiltily_nodes import FloatToInt, ImageToCPU +from .vae_patcher import LTXVPatcherVAE +from .vanish_nodes import LTXVDilateVideoMask, LTXVInpaintPreprocess + +# Static node mappings, required for ComfyUI-Manager mapping to work +NODE_CLASS_MAPPINGS = { + "Set VAE Decoder Noise": DecoderNoise, + "LTXVLinearOverlapLatentTransition": LinearOverlapLatentTransition, + "LTXVAddGuideAdvanced": LTXVAddGuideAdvanced, + "LTXVAddGuideAdvancedAttention": LTXVAddGuideAdvancedAttention, + "LTXVAddLatentGuide": LTXVAddLatentGuide, + "LTXVAdainLatent": LTXVAdainLatent, + "LTXVImgToVideoConditionOnly": LTXVImgToVideoConditionOnly, + "LTXVPerStepAdainPatcher": LTXVPerStepAdainPatcher, + "LTXVApplySTG": LTXVApplySTG, + "LTXVBaseSampler": LTXVBaseSampler, + "LTXVInContextSampler": LTXVInContextSampler, + "LTXVExtendSampler": LTXVExtendSampler, + "LTXVNormalizingSampler": LTXVNormalizingSampler, + "LTXVPreprocessMasks": LTXVPreprocessMasks, + "LTXVPatcherVAE": LTXVPatcherVAE, + "LTXVPromptEnhancer": LTXVPromptEnhancer, + "LTXVPromptEnhancerLoader": LTXVPromptEnhancerLoader, + "LTXQ8Patch": LTXVQ8Patch, + "LTXVQ8LoraModelLoader": LTXVQ8LoraModelLoader, + "LTXVSelectLatents": LTXVSelectLatents, + "LTXVSetVideoLatentNoiseMasks": LTXVSetVideoLatentNoiseMasks, + "LTXVTiledSampler": LTXVTiledSampler, + "LTXVLoopingSampler": LTXVLoopingSampler, + "LTXVTiledVAEDecode": LTXVTiledVAEDecode, + "MultimodalGuider": MultimodalGuiderNode, + "GuiderParameters": GuiderParametersNode, + "STGAdvancedPresets": STGAdvancedPresetsNode, + "STGGuiderAdvanced": STGGuiderAdvancedNode, + "STGGuiderNode": STGGuiderNode, + "LTXVMultiPromptProvider": MultiPromptProvider, + "ImageToCPU": ImageToCPU, + "LTXFloatToInt": FloatToInt, + "LTXVStatNormLatent": LTXVStatNormLatent, + "LTXVPerStepStatNormPatcher": LTXVPerStepStatNormPatcher, + "LTXVGemmaCLIPModelLoader": LTXVGemmaCLIPModelLoader, + "LTXVGemmaEnhancePrompt": LTXVGemmaEnhancePrompt, + "GemmaAPITextEncode": GemmaAPITextEncode, + "DynamicConditioning": DynamicConditioning, + "LowVRAMCheckpointLoader": LowVRAMCheckpointLoader, + "LowVRAMAudioVAELoader": LowVRAMAudioVAELoader, + "LowVRAMLatentUpscaleModelLoader": LowVRAMLatentUpscaleModelLoader, + "LTXAddVideoICLoRAGuide": LTXAddVideoICLoRAGuide, + "LTXAddVideoICLoRAGuideAdvanced": LTXAddVideoICLoRAGuideAdvanced, + "LTXICLoRALoaderModelOnly": LTXICLoRALoaderModelOnly, + "LTXVSetAudioRefTokens": LTXVSetAudioRefTokens, + "LTXVLoadConditioning": LTXVLoadConditioning, + "LTXVSaveConditioning": LTXVSaveConditioning, + "LTXVDrawTracks": LTXVDrawTracks, + "LTXVSparseTrackEditor": LTXVSparseTrackEditor, + "LTXVDilateVideoMask": LTXVDilateVideoMask, + "LTXVInpaintPreprocess": LTXVInpaintPreprocess, + "LTXVLaplacianPyramidBlend": LTXVLaplacianPyramidBlend, + "LTXVHDRDecodePostprocess": LTXVHDRDecodePostprocess, + "LTXVAudioOnlyModel": LTXVAudioOnlyModel, + "LTXVAudioOnlyEmptyVideoLatent": LTXVAudioOnlyEmptyVideoLatent, +} + +# Consistent display names between static and dynamic node mappings in nodes_registry.py, +# to prevent ComfyUI initializing them with default display names. +NODE_DISPLAY_NAME_MAPPINGS = { + name: f"{NODES_DISPLAY_NAME_PREFIX} {camel_case_to_spaces(name)}" + for name in NODE_CLASS_MAPPINGS.keys() +} + +# Merge the node mappings from tricks into the main mappings +NODE_CLASS_MAPPINGS.update(TRICKS_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(TRICKS_NODE_DISPLAY_NAME_MAPPINGS) + +# Update with runtime mappings (these will override static mappings if there are any differences) +NODE_CLASS_MAPPINGS.update(RUNTIME_NODE_CLASS_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(RUNTIME_NODE_DISPLAY_NAME_MAPPINGS) + +WEB_DIRECTORY = "./web" + +# Export so that ComfyUI can pick them up. +__all__ = [ + "NODE_CLASS_MAPPINGS", + "NODE_DISPLAY_NAME_MAPPINGS", + "WEB_DIRECTORY", +] diff --git a/1/custom_nodes/ComfyUI-LTXVideo/audio_only.py b/1/custom_nodes/ComfyUI-LTXVideo/audio_only.py new file mode 100644 index 0000000000000000000000000000000000000000..7e224014758d4bbb19d45bec613dbdb1fc5ac5f5 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/audio_only.py @@ -0,0 +1,89 @@ +"""Audio-only (text-to-audio) mode for the LTX-2 audio/video model. + +The LTX-2 transformer in ComfyUI core (``comfy/ldm/lightricks/av_model.py``) +already supports an audio-only path: every block reads ``run_vx``, +``a2v_cross_attn`` and ``v2a_cross_attn`` from ``transformer_options`` and skips +the video self-attention/FFN and the audio<->video cross-attention when they are +``False``. These flags default to ``True``, so the model normally runs jointly. + +``LTXVAudioOnlyModel`` flips those flags, which is the equivalent of the +reference pipeline's ``video=None``: the audio is denoised with no dependence on +the video latent, and the video stream is skipped for speed. + +Note: the model splits its input positionally into ``[video, audio]``, so the +sampler still needs a (tiny) dummy video latent at index 0. Use +``LTXVAudioOnlyEmptyVideoLatent`` (a fixed 64x64 single-frame placeholder) joined +with the audio latent via ``LTXVConcatAVLatent``. With ``LTXVAudioOnlyModel`` +active that dummy video is never attended to. +""" + +import comfy.model_management +import torch +from comfy.model_patcher import ModelPatcher + +from .nodes_registry import comfy_node + + +@comfy_node(name="LTXVAudioOnlyModel") +class LTXVAudioOnlyModel: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ( + "MODEL", + { + "tooltip": "The LTX-2 audio/video model to run in audio-only mode." + }, + ), + }, + } + + RETURN_TYPES = ("MODEL",) + RETURN_NAMES = ("model",) + FUNCTION = "patch" + CATEGORY = "Lightricks/audio" + DESCRIPTION = ( + "Run the LTX-2 audio/video model in audio-only mode for text-to-audio. " + "Skips the video stream and disables the audio<->video cross-attention, so " + "the generated audio does not depend on the video latent. The sampler still " + "needs a minimal dummy video latent (EmptyLTXVLatentVideo at 64x64 length 1, " + "joined with LTXVConcatAVLatent); it is never attended to. Remove or bypass " + "this node to restore normal joint audio+video generation." + ) + + def patch(self, model: ModelPatcher): + new_model = model.clone() + transformer_options = new_model.model_options["transformer_options"] + transformer_options["run_vx"] = False + transformer_options["a2v_cross_attn"] = False + transformer_options["v2a_cross_attn"] = False + return (new_model,) + + +@comfy_node(name="LTXVAudioOnlyEmptyVideoLatent") +class LTXVAudioOnlyEmptyVideoLatent: + @classmethod + def INPUT_TYPES(s): + return {"required": {}} + + RETURN_TYPES = ("LATENT",) + RETURN_NAMES = ("latent",) + FUNCTION = "generate" + CATEGORY = "Lightricks/audio" + DESCRIPTION = ( + "Fixed minimal placeholder video latent for audio-only (text-to-audio) " + "generation - a single 64x64 frame. LTX-2 needs a video latent at input " + "index 0, but with LTXV Audio Only Model it is never attended to, so the " + "dimensions are fixed (and hidden) to avoid confusion. Join it with the " + "audio latent via LTXVConcatAVLatent." + ) + + def generate(self): + # LTX-2 video latent shape: (batch, 128 channels, frames, H/32, W/32). + # Fixed to batch 1, a single frame, 64x64 -> (1, 128, 1, 2, 2). + latent = torch.zeros( + [1, 128, 1, 2, 2], + device=comfy.model_management.intermediate_device(), + ) + return ({"samples": latent},) diff --git a/1/custom_nodes/ComfyUI-LTXVideo/conditioning_loader.py b/1/custom_nodes/ComfyUI-LTXVideo/conditioning_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..40d9be90f236e736dea506994631263aa0756441 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/conditioning_loader.py @@ -0,0 +1,82 @@ +import hashlib +from pathlib import Path +from typing import Any + +import folder_paths +import safetensors +import torch +from comfy_api.latest import io + +from .nodes_registry import comfy_node + + +@comfy_node(name="LTXVLoadConditioning") +class LTXVLoadConditioning(io.ComfyNode): + @classmethod + def define_schema(cls) -> io.Schema: + files = folder_paths.get_filename_list("embeddings") + if not files: + files = [""] + return io.Schema( + node_id="LTXVLoadConditioning", + display_name="🅛🅣🅧 LTXV Load Conditioning", + category="lightricks/LTXV", + inputs=[ + io.Combo.Input("file_name", options=sorted(files)), + io.Combo.Input("device", options=["cpu", "gpu"]), + ], + outputs=[ + io.Conditioning.Output(), + ], + ) + + @classmethod + def execute(cls, file_name: str, device: str) -> io.NodeOutput: + file_path = folder_paths.get_full_path("embeddings", file_name) + if not Path(file_path).exists(): + raise FileNotFoundError(f"Conditioning file not found: {file_path}") + + target_device = "cpu" + if device == "gpu": + target_device = "cuda" if torch.cuda.is_available() else "cpu" + + conditioning: list[list[Any]] = [] + + with safetensors.safe_open( + file_path, framework="pt", device=target_device + ) as f: + tensor_keys = [k for k in f.keys() if k.startswith("conditioning_data_")] + + for tensor_key in sorted(tensor_keys): + idx = tensor_key.replace("conditioning_data_", "") + tensor = f.get_tensor(tensor_key) + + options: dict[str, Any] = {} + mask_key = f"attention_mask_{idx}" + if mask_key in f.keys(): + options["attention_mask"] = f.get_tensor(mask_key) + + conditioning.append([tensor, options]) + + if not conditioning: + raise ValueError(f"No conditioning data found in file: {file_name}") + + return io.NodeOutput(conditioning) + + @classmethod + def fingerprint_inputs(cls, file_name: str, device: str) -> str: + file_path = folder_paths.get_full_path("embeddings", file_name) + with open(file_path, "rb") as f: + return hashlib.sha256(f.read()).hexdigest() + + @classmethod + def validate_inputs(cls, file_name: str, device: str) -> bool | str: + if not file_name: + return "No files found. Please save a conditioning first." + try: + file_path = folder_paths.get_full_path("embeddings", file_name) + if not Path(file_path).exists(): + return f"File not found: {file_name}" + except Exception: + return f"Invalid file: {file_name}" + return True diff --git a/1/custom_nodes/ComfyUI-LTXVideo/conditioning_saver.py b/1/custom_nodes/ComfyUI-LTXVideo/conditioning_saver.py new file mode 100644 index 0000000000000000000000000000000000000000..9a7bb8a5c46fade9045af56e3ffa977719f63a83 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/conditioning_saver.py @@ -0,0 +1,69 @@ +from datetime import datetime +from pathlib import Path + +import comfy.utils +import folder_paths +import torch +from comfy_api.latest import io, ui + +from .nodes_registry import comfy_node + + +@comfy_node(name="LTXVSaveConditioning") +class LTXVSaveConditioning(io.ComfyNode): + @classmethod + def define_schema(cls) -> io.Schema: + return io.Schema( + node_id="LTXVSaveConditioning", + display_name="🅛🅣🅧 LTXV Save Conditioning", + category="lightricks/LTXV", + inputs=[ + io.Conditioning.Input("conditioning"), + io.String.Input("filename", default="conditioning"), + io.Combo.Input("dtype", options=["bfloat16", "float16"]), + ], + is_output_node=True, + ) + + @classmethod + def execute(cls, conditioning: list, filename: str, dtype: str) -> io.NodeOutput: + if not conditioning or len(conditioning) == 0: + raise ValueError("Conditioning is empty") + + embeddings_folder = Path(folder_paths.get_folder_paths("embeddings")[0]) + embeddings_folder.mkdir(parents=True, exist_ok=True) + + sanitized_filename = "".join( + c for c in filename if c.isalnum() or c in ("_", "-", ".") + ) + if not sanitized_filename: + sanitized_filename = "conditioning" + + output_path = embeddings_folder / f"{sanitized_filename}.safetensors" + + target_dtype = torch.bfloat16 if dtype == "bfloat16" else torch.float16 + + tensors_to_save: dict[str, torch.Tensor] = {} + + for idx, (cond_tensor, cond_options) in enumerate(conditioning): + tensor_converted = cond_tensor.to(dtype=target_dtype).contiguous() + tensors_to_save[f"conditioning_data_{idx}"] = tensor_converted + + if "attention_mask" in cond_options: + mask = cond_options["attention_mask"].contiguous() + tensors_to_save[f"attention_mask_{idx}"] = mask + + metadata = { + "num_conditionings": str(len(conditioning)), + "dtype": dtype, + "created_at": str(datetime.now()), + } + + comfy.utils.save_torch_file( + tensors_to_save, str(output_path), metadata=metadata + ) + + file_size_mb = output_path.stat().st_size / (1024 * 1024) + return io.NodeOutput( + ui=ui.PreviewText(f"Saved: {output_path.name} ({file_size_mb:.2f} MB)") + ) diff --git a/1/custom_nodes/ComfyUI-LTXVideo/decoder_noise.py b/1/custom_nodes/ComfyUI-LTXVideo/decoder_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..4dff6f7fdfde501a456fea4ad685374adce06a67 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/decoder_noise.py @@ -0,0 +1,57 @@ +from copy import copy + +from .nodes_registry import comfy_node + + +@comfy_node(name="Set VAE Decoder Noise") +class DecoderNoise: + @classmethod + def INPUT_TYPES(cls): + return { + "required": { + "vae": ("VAE",), + "timestep": ( + "FLOAT", + { + "default": 0.05, + "min": 0.0, + "max": 1.0, + "step": 0.001, + "tooltip": "The timestep used for decoding the noise.", + }, + ), + "scale": ( + "FLOAT", + { + "default": 0.025, + "min": 0.0, + "max": 1.0, + "step": 0.001, + "tooltip": "The scale of the noise added to the decoder.", + }, + ), + "seed": ( + "INT", + { + "default": 42, + "min": 0, + "max": 0xFFFFFFFFFFFFFFFF, + "tooltip": "The random seed used for creating the noise.", + }, + ), + } + } + + FUNCTION = "add_noise" + RETURN_TYPES = ("VAE",) + CATEGORY = "lightricks/LTXV" + + def add_noise(self, vae, timestep, scale, seed): + result = copy(vae) + if hasattr(result, "first_stage_model"): + result.first_stage_model.decode_timestep = timestep + result.first_stage_model.decode_noise_scale = scale + result._decode_timestep = timestep + result.decode_noise_scale = scale + result.seed = seed + return (result,) diff --git a/1/custom_nodes/ComfyUI-LTXVideo/dynamic_conditioning.py b/1/custom_nodes/ComfyUI-LTXVideo/dynamic_conditioning.py new file mode 100644 index 0000000000000000000000000000000000000000..6b598d038543dd6fc512795f0a19c31e840f8dd2 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/dynamic_conditioning.py @@ -0,0 +1,57 @@ +import torch + +from .nodes_registry import comfy_node + + +@comfy_node(name="DynamicConditioning") +class DynamicConditioning: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL",), + "power": ("FLOAT", {"default": 1.3, "min": 1, "max": 2, "step": 0.01}), + "only_first_frame": ("BOOLEAN", {"default": True}), + } + } + + RETURN_TYPES = ("MODEL",) + FUNCTION = "apply" + CATEGORY = "lightricks/LTXV" + INIT = False + + def apply(self, model, power, only_first_frame): + self.only_first_frame = only_first_frame + self.power = power + model = model.clone() + model.set_model_denoise_mask_function(self.forward) + return (model,) + + def find_step(self, sigma: torch.Tensor, step_sigmas: torch.Tensor): + for i, step_sigma in enumerate(step_sigmas): + if step_sigma <= sigma: + return i + return len(step_sigmas) - 1 + + def forward( + self, sigma: torch.Tensor, denoise_mask: torch.Tensor, extra_options: dict + ): + model = extra_options["model"] + step_sigmas = extra_options["sigmas"] + step = self.find_step(sigma, step_sigmas) + # In order to apply power multiple times, this is the same as applying power number of times equal to step + power = self.power**step + denoise_mask = denoise_mask.clone() + if self.only_first_frame: + num_channels = model.model_patcher.model.diffusion_model.in_channels + denoise_mask[:, :num_channels, :1] **= power + else: + denoise_mask **= power + # make sure to update the denoise mask in the model, to get correct timestep values for all tokens + for k in model.conds: + if "positive" in k or "negative" in k: + for cond in model.conds[k]: + if "model_conds" in cond and "denoise_mask" in cond["model_conds"]: + cond["model_conds"]["denoise_mask"].cond = denoise_mask + # print(f"DynamicConditioning: power: {power}, step: {step}, sigma: {sigma}, step_sigmas: {step_sigmas}") + return denoise_mask diff --git a/1/custom_nodes/ComfyUI-LTXVideo/easy_samplers.py b/1/custom_nodes/ComfyUI-LTXVideo/easy_samplers.py new file mode 100644 index 0000000000000000000000000000000000000000..d44e77c7e0e13ce4fdbdf230ae4b6d0a7e223640 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/easy_samplers.py @@ -0,0 +1,1051 @@ +import copy + +import comfy +import comfy_extras +import nodes +import torch +from comfy.ldm.lightricks.av_model import LTXAVModel +from comfy.nested_tensor import NestedTensor +from comfy_api.latest import io +from comfy_extras.nodes_custom_sampler import SamplerCustomAdvanced, SplitSigmas +from comfy_extras.nodes_lt import EmptyLTXVLatentVideo, LTXVAddGuide, LTXVCropGuides + +from .guide import blur_internal +from .latent_norm import LTXVAdainLatent +from .latents import LTXVAddLatentGuide, LTXVSelectLatents +from .nodes_registry import comfy_node + + +def _get_raw_conds_from_guider(guider): + if not hasattr(guider, "raw_conds"): + if "negative" not in guider.original_conds: + # for BasicGuider + raise ValueError( + "Guider does not have negative conds, cannot use it as a guider." + ) + raw_pos = guider.original_conds["positive"] + positive = [[raw_pos[0]["cross_attn"], copy.deepcopy(raw_pos[0])]] + raw_neg = guider.original_conds["negative"] + negative = [[raw_neg[0]["cross_attn"], copy.deepcopy(raw_neg[0])]] + guider.raw_conds = (positive, negative) + return guider.raw_conds + + +@comfy_node( + name="LTXVBaseSampler", +) +class LTXVBaseSampler: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The diffusion model to use."}), + "vae": ("VAE", {"tooltip": "The VAE to use."}), + "width": ( + "INT", + { + "default": 768, + "min": 64, + "max": nodes.MAX_RESOLUTION, + "step": 32, + }, + ), + "height": ( + "INT", + { + "default": 512, + "min": 64, + "max": nodes.MAX_RESOLUTION, + "step": 32, + }, + ), + "num_frames": ( + "INT", + {"default": 97, "min": 1, "max": nodes.MAX_RESOLUTION, "step": 8}, + ), + "guider": ( + "GUIDER", + {"tooltip": "The guider to use, must be a STGGuiderAdvanced."}, + ), + "sampler": ("SAMPLER", {"tooltip": "The sampler to use."}), + "sigmas": ("SIGMAS", {"tooltip": "The sigmas to use."}), + "noise": ("NOISE", {"tooltip": "The noise to use for the sampling."}), + }, + "optional": { + "optional_cond_images": ( + "IMAGE", + {"tooltip": "The images to use for conditioning the sampling."}, + ), + "optional_cond_indices": ( + "STRING", + { + "tooltip": "The indices of the images to use for conditioning the sampling." + }, + ), + "strength": ( + "FLOAT", + { + "default": 0.9, + "min": 0, + "max": 1, + "tooltip": "The strength of the conditioning on the images.", + }, + ), + "crop": ( + ["center", "disabled"], + { + "default": "disabled", + "tooltip": "The crop mode to use for the images.", + }, + ), + "crf": ( + "INT", + { + "default": 35, + "min": 0, + "max": 100, + "tooltip": "The CRF value to use for preprocessing the images.", + }, + ), + "blur": ( + "INT", + { + "default": 0, + "min": 0, + "max": 10, + "tooltip": "The blur value to use for preprocessing the images.", + }, + ), + }, + } + + RETURN_TYPES = ("LATENT", "CONDITIONING", "CONDITIONING") + RETURN_NAMES = ("denoised", "positive", "negative") + FUNCTION = "sample" + CATEGORY = "sampling" + + def sample( + self, + model, + vae, + width, + height, + num_frames, + guider, + sampler, + sigmas, + noise, + optional_cond_images=None, + optional_cond_indices=None, + strength=0.9, + crop="disabled", + crf=35, + blur=0, + optional_negative_index_latents=None, + optional_negative_index=-1, + optional_negative_index_strength=1.0, + optional_initialization_latents=None, + guiding_start_step=0, + guiding_end_step=1000, + ): + guider = copy.copy(guider) + guider.original_conds = copy.deepcopy(guider.original_conds) + positive, negative = _get_raw_conds_from_guider(guider) + + if optional_cond_images is not None: + optional_cond_images = ( + comfy.utils.common_upscale( + optional_cond_images.movedim(-1, 1), + width, + height, + "bilinear", + crop=crop, + ) + .movedim(1, -1) + .clamp(0, 1) + ) + optional_cond_images = comfy_extras.nodes_lt.LTXVPreprocess.execute( + optional_cond_images, crf + )[0] + for i in range(optional_cond_images.shape[0]): + optional_cond_images[i] = blur_internal( + optional_cond_images[i].unsqueeze(0), blur + ) + + if optional_cond_indices is not None and optional_cond_images is not None: + optional_cond_indices = optional_cond_indices.split(",") + optional_cond_indices = [int(i) for i in optional_cond_indices] + assert len(optional_cond_indices) == len( + optional_cond_images + ), "Number of optional cond images must match number of optional cond indices" + + if optional_initialization_latents is None: + (latents,) = EmptyLTXVLatentVideo().execute(width, height, num_frames, 1) + else: + latents = optional_initialization_latents + + if optional_cond_images is not None and 0 in optional_cond_indices: + # apply classical i2v conditioning on the first frame + idx_0 = optional_cond_indices.index(0) + encode_pixels = optional_cond_images[idx_0 : idx_0 + 1, :, :, :3] + t = vae.encode(encode_pixels) + latents["samples"][:, :, : t.shape[2]] = t + + if "noise_mask" not in latents: + conditioning_latent_frames_mask = torch.ones( + (1, 1, latents["samples"].shape[2], 1, 1), + dtype=torch.float32, + device=latents["samples"].device, + ) + conditioning_latent_frames_mask[:, :, : t.shape[2]] = 1.0 - strength + latents["noise_mask"] = conditioning_latent_frames_mask + else: + latents["noise_mask"][:, :, : t.shape[2]] = 1.0 - strength + conditioning_latent_frames_mask = latents["noise_mask"] + else: + conditioning_latent_frames_mask = None + + high_sigmas, rest_sigmas = SplitSigmas().get_sigmas(sigmas, guiding_start_step) + middle_sigmas, low_sigmas = SplitSigmas().get_sigmas( + rest_sigmas, guiding_end_step - guiding_start_step + ) + + if len(high_sigmas) > 1: + print("Denoising with no conditioning on sigmas: ", high_sigmas) + (_, new_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=high_sigmas, + latent_image=latents, + ) + + if optional_cond_images is not None: + # add conditioning on keyframes with index > 0 + for cond_image, cond_idx in zip( + optional_cond_images, optional_cond_indices + ): + if cond_idx == 0: + # 0 is handled by classical i2v conditioning + continue + ( + positive, + negative, + latents, + ) = LTXVAddGuide.execute( + positive=positive, + negative=negative, + vae=vae, + latent=latents, + image=cond_image.unsqueeze(0), + frame_idx=cond_idx, + strength=strength, + ) + + if optional_negative_index_latents is not None: + ( + positive, + negative, + latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=latents, + guiding_latent=optional_negative_index_latents, + latent_idx=optional_negative_index, + strength=optional_negative_index_strength, + ) + + guider.set_conds(positive, negative) + + # Denoise the latent video + print("Denoising with conditioning on sigmas: ", middle_sigmas) + (output_latents, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=middle_sigmas, + latent_image=latents, + ) + + # Clean up guides if image conditioning was used + positive, negative, denoised_output_latents = LTXVCropGuides.execute( + positive=positive, + negative=negative, + latent=denoised_output_latents, + ) + + denoised_output_latents["noise_mask"] = conditioning_latent_frames_mask + + if len(low_sigmas) > 1: + print( + "Denoising with no conditioning but with classical i2v noise mask on sigmas: ", + low_sigmas, + ) + (_, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=low_sigmas, + latent_image=denoised_output_latents, + ) + + return (denoised_output_latents, positive, negative) + + +@comfy_node( + name="LTXVExtendSampler", +) +class LTXVExtendSampler: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The diffusion model to use."}), + "vae": ("VAE", {"tooltip": "The VAE to use."}), + "latents": ( + "LATENT", + {"tooltip": "The latents of the video to extend."}, + ), + "num_new_frames": ( + "INT", + { + "default": 80, + "min": -1, + "max": nodes.MAX_RESOLUTION, + "step": 1, + "tooltip": "If -1, the number of frames will be based on the number of frames in the optional_guiding_latents.", + }, + ), + "frame_overlap": ( + "INT", + { + "default": 16, + "min": 16, + "max": 128, + "step": 8, + "tooltip": "The overlap region to use for conditioning the new frames on the end of the provided latents.", + }, + ), + "guider": ( + "GUIDER", + {"tooltip": "The guider to use, must be a STGGuiderAdvanced."}, + ), + "sampler": ("SAMPLER", {"tooltip": "The sampler to use."}), + "sigmas": ("SIGMAS", {"tooltip": "The sigmas to use."}), + "noise": ("NOISE", {"tooltip": "The noise to use for the sampling."}), + "strength": ( + "FLOAT", + { + "default": 0.5, + "min": 0.0, + "max": 1.0, + "tooltip": "The strength of the conditioning on the overlapping latents, when using optional_guiding_latents.", + }, + ), + }, + "optional": { + "optional_guiding_latents": ( + "LATENT", + {"tooltip": "Optional latents to guide the sampling."}, + ), + "optional_cond_images": ( + "IMAGE", + {"tooltip": "The images to use for conditioning the sampling."}, + ), + "optional_cond_indices": ("STRING",), + "cond_image_strength": ( + "FLOAT", + { + "default": 1.0, + "min": 0.0, + "max": 1.0, + "tooltip": "The strength of the conditioning on the images.", + }, + ), + }, + } + + RETURN_TYPES = ("LATENT", "CONDITIONING", "CONDITIONING") + RETURN_NAMES = ("denoised_video", "positive", "negative") + FUNCTION = "sample" + CATEGORY = "sampling" + + def sample( + self, + model, + vae, + latents, + num_new_frames, + frame_overlap, + guider, + sampler, + sigmas, + noise, + strength=0.5, + guiding_strength=1.0, + cond_image_strength=1.0, + optional_guiding_latents=None, + optional_cond_images=None, + optional_cond_indices=None, + optional_reference_latents=None, + optional_initialization_latents=None, + adain_factor=0.0, + optional_negative_index_latents=None, + optional_negative_index=-1, + optional_negative_index_strength=1.0, + guiding_start_step=0, + guiding_end_step=1000, + normalize_per_frame=False, + ): + guider = copy.copy(guider) + guider.original_conds = copy.deepcopy(guider.original_conds) + + if optional_cond_indices is not None and optional_cond_images is not None: + optional_cond_indices = optional_cond_indices.split(",") + optional_cond_indices = [int(i) for i in optional_cond_indices] + assert len(optional_cond_indices) == len( + optional_cond_images + ), "Number of optional cond images must match number of optional cond indices" + + positive, negative = _get_raw_conds_from_guider(guider) + + samples = latents["samples"] + batch, channels, frames, height, width = samples.shape + time_scale_factor, width_scale_factor, height_scale_factor = ( + vae.downscale_index_formula + ) + overlap = frame_overlap // time_scale_factor + + if num_new_frames == -1 and optional_guiding_latents is not None: + num_new_frames = ( + optional_guiding_latents["samples"].shape[2] - overlap + ) * time_scale_factor + + (last_overlap_latents,) = LTXVSelectLatents().select_latents( + latents, -overlap, -1 + ) + + if optional_initialization_latents is None: + new_latents = EmptyLTXVLatentVideo.execute( + width=width * width_scale_factor, + height=height * height_scale_factor, + length=overlap * time_scale_factor + num_new_frames, + batch_size=1, + )[0] + else: + new_latents = optional_initialization_latents + + last_overlap_latents["samples"] = last_overlap_latents["samples"].to( + new_latents["samples"].device + ) + + ( + positive, + negative, + new_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=new_latents, + guiding_latent=last_overlap_latents, + latent_idx=0, + strength=strength, + ) + + high_sigmas, rest_sigmas = SplitSigmas().get_sigmas(sigmas, guiding_start_step) + middle_sigmas, low_sigmas = SplitSigmas().get_sigmas( + rest_sigmas, guiding_end_step - guiding_start_step + ) + + if optional_cond_images is not None: + print("Adding conditioning on keyframes") + for cond_image, cond_idx in zip( + optional_cond_images, optional_cond_indices + ): + if optional_guiding_latents is not None and cond_idx % 8 == 1: + raise ValueError( + f"Conditioning image index {cond_idx} (relative to the in the temporal chunk) is a multiple of 8 + 1," + "and guiding latents are used. Please provide other conditioning image indices" + ) + ( + positive, + negative, + new_latents, + ) = LTXVAddGuide.execute( + positive=positive, + negative=negative, + vae=vae, + latent=new_latents, + image=cond_image.unsqueeze(0), + frame_idx=cond_idx, + strength=cond_image_strength, + ) + + if len(high_sigmas) > 1: + guider.set_conds(positive, negative) + print("Denoising with overlap conditioning only on sigmas: ", high_sigmas) + (_, new_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=high_sigmas, + latent_image=new_latents, + ) + + if optional_guiding_latents is not None: + optional_guiding_latents = LTXVSelectLatents().select_latents( + optional_guiding_latents, overlap, -1 + )[0] + ( + positive, + negative, + new_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=new_latents, + guiding_latent=optional_guiding_latents, + latent_idx=last_overlap_latents["samples"].shape[2], + strength=guiding_strength, + ) + + if optional_negative_index_latents is not None: + ( + positive, + negative, + new_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=new_latents, + guiding_latent=optional_negative_index_latents, + latent_idx=optional_negative_index, + strength=optional_negative_index_strength, + ) + + guider.set_conds(positive, negative) + + # Denoise the latent video + print("Denoising with full conditioning on sigmas: ", middle_sigmas) + (output_latents, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=middle_sigmas, + latent_image=new_latents, + ) + + positive, negative, denoised_output_latents = LTXVCropGuides.execute( + positive=positive, + negative=negative, + latent=denoised_output_latents, + ) + + if len(low_sigmas) > 1: + ( + positive, + negative, + denoised_output_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=denoised_output_latents, + guiding_latent=last_overlap_latents, + latent_idx=0, + strength=strength, + ) + + if optional_cond_images is not None: + print("Adding conditioning on keyframes") + for cond_image, cond_idx in zip( + optional_cond_images, optional_cond_indices + ): + if optional_guiding_latents is not None and cond_idx % 8 == 1: + raise ValueError( + f"Conditioning image index {cond_idx} (relative to the in the temporal chunk) is a multiple of 8 + 1," + "and guiding latents are used. Please provide other conditioning image indices" + ) + ( + positive, + negative, + denoised_output_latents, + ) = LTXVAddGuide.execute( + positive=positive, + negative=negative, + vae=vae, + latent=denoised_output_latents, + image=cond_image.unsqueeze(0), + frame_idx=cond_idx, + strength=cond_image_strength, + ) + + guider.set_conds(positive, negative) + print( + "Denoising with overlap + keyframes conditioning only on sigmas: ", + low_sigmas, + ) + (_, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=low_sigmas, + latent_image=denoised_output_latents, + ) + positive, negative, denoised_output_latents = LTXVCropGuides.execute( + positive=positive, + negative=negative, + latent=denoised_output_latents, + ) + + if optional_reference_latents is not None: + denoised_output_latents = LTXVAdainLatent().batch_normalize( + latents=denoised_output_latents, + reference=optional_reference_latents, + factor=adain_factor, + per_frame=normalize_per_frame, + )[0] + + # drop first output latent as it's a reinterpreted 8-frame latent understood as a 1-frame latent + truncated_denoised_output_latents = LTXVSelectLatents().select_latents( + denoised_output_latents, 1, -1 + )[0] + + # Fuse new frames with old ones by calling LinearOverlapLatentTransition + (latents,) = LinearOverlapLatentTransition().process( + latents, truncated_denoised_output_latents, overlap - 1, axis=2 + ) + return (latents, positive, negative) + + +@comfy_node( + name="LTXVInContextSampler", +) +class LTXVInContextSampler: + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "vae": ("VAE", {"tooltip": "The VAE to use."}), + "guider": ( + "GUIDER", + {"tooltip": "The guider to use, must be a STGGuiderAdvanced."}, + ), + "sampler": ("SAMPLER", {"tooltip": "The sampler to use."}), + "sigmas": ("SIGMAS", {"tooltip": "The sigmas to use."}), + "noise": ("NOISE", {"tooltip": "The noise to use for the sampling."}), + "guiding_latents": ( + "LATENT", + { + "tooltip": "The latents to use for guiding the sampling, typically with an IC-LoRA." + }, + ), + }, + "optional": { + "optional_cond_images": ( + "IMAGE", + { + "tooltip": "The image to use for conditioning the sampling, if not provided, the sampling will be unconditioned (t2v setup). The image will be resized to the size of the first frame." + }, + ), + "num_frames": ( + "INT", + { + "default": -1, + "min": -1, + "max": 1000, + "step": 1, + "tooltip": "If -1, the number of frames will be based on the number of frames in the guiding_latents.", + }, + ), + }, + } + + RETURN_TYPES = ("LATENT", "CONDITIONING", "CONDITIONING") + RETURN_NAMES = ("denoised_video", "positive", "negative") + FUNCTION = "sample" + CATEGORY = "sampling" + + def sample( + self, + vae, + guider, + sampler, + sigmas, + noise, + guiding_latents, + optional_cond_images=None, + optional_cond_indices=None, + num_frames=0, + optional_initialization_latents=None, + optional_negative_index_latents=None, + optional_negative_index=-1, + optional_negative_index_strength=1.0, + cond_image_strength=1.0, + guiding_strength=1.0, + guiding_start_step=0, + guiding_end_step=1000, + ): + guider = copy.copy(guider) + guider.original_conds = copy.deepcopy(guider.original_conds) + if optional_cond_images is None: + optional_cond_indices = None + + if optional_cond_indices is not None and optional_cond_images is not None: + optional_cond_indices = optional_cond_indices.split(",") + optional_cond_indices = [int(i) for i in optional_cond_indices] + assert len(optional_cond_indices) == len( + optional_cond_images + ), "Number of optional cond images must match number of optional cond indices" + + positive, negative = _get_raw_conds_from_guider(guider) + + time_scale_factor, width_scale_factor, height_scale_factor = ( + vae.downscale_index_formula + ) + + batch, channels, frames, height, width = guiding_latents["samples"].shape + if num_frames != -1: + frames = (num_frames - 1) // time_scale_factor + 1 + + if optional_initialization_latents is not None: + new_latents = optional_initialization_latents + else: + new_latents = EmptyLTXVLatentVideo.execute( + width=width * width_scale_factor, + height=height * height_scale_factor, + length=(frames - 1) * time_scale_factor + 1, + batch_size=1, + )[0] + + high_sigmas, rest_sigmas = SplitSigmas().get_sigmas(sigmas, guiding_start_step) + middle_sigmas, low_sigmas = SplitSigmas().get_sigmas( + rest_sigmas, guiding_end_step - guiding_start_step + ) + + if len(high_sigmas) > 1: + print( + "Denoising with keyframes only [if available] on sigmas: ", + high_sigmas, + ) + (_, new_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=high_sigmas, + latent_image=new_latents, + ) + + if optional_cond_indices is not None and 0 in optional_cond_indices: + guiding_latents = LTXVSelectLatents().select_latents( + guiding_latents, 1, -1 + )[0] + skip_one_guiding_latent = True + else: + skip_one_guiding_latent = False + + print("Adding conditioning on guiding latents") + ( + positive, + negative, + new_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=new_latents, + guiding_latent=guiding_latents, + latent_idx=1 if skip_one_guiding_latent else 0, + strength=guiding_strength, + ) + if optional_cond_images is not None: + print("Adding conditioning on keyframes", optional_cond_indices) + for cond_image, cond_idx in zip( + optional_cond_images, optional_cond_indices + ): + if cond_idx % 8 == 1: + raise ValueError( + f"Conditioning image index {cond_idx} is a multiple of 8 + 1 and guiding latents are used. Please provide other cond image indices" + ) + ( + positive, + negative, + new_latents, + ) = LTXVAddGuide.execute( + positive=positive, + negative=negative, + vae=vae, + latent=new_latents, + image=cond_image.unsqueeze(0), + frame_idx=cond_idx, + strength=cond_image_strength, + ) + if optional_negative_index_latents is not None: + ( + positive, + negative, + new_latents, + ) = LTXVAddLatentGuide().generate( + vae=vae, + positive=positive, + negative=negative, + latent=new_latents, + guiding_latent=optional_negative_index_latents, + latent_idx=optional_negative_index, + strength=optional_negative_index_strength, + ) + + guider.set_conds(positive, negative) + + # Denoise the latent video + print("Denoising with full conditioning on sigmas: ", middle_sigmas) + (_, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=middle_sigmas, + latent_image=new_latents, + ) + + # Clean up guides if image conditioning was used + positive, negative, denoised_output_latents = LTXVCropGuides.execute( + positive=positive, + negative=negative, + latent=denoised_output_latents, + ) + + if len(low_sigmas) > 1: + guider.set_conds(positive, negative) + print( + "Denoising with keyframes only [if available] conditioning on sigmas: ", + low_sigmas, + ) + (_, denoised_output_latents) = SamplerCustomAdvanced().sample( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=low_sigmas, + latent_image=denoised_output_latents, + ) + positive, negative, denoised_output_latents = LTXVCropGuides.execute( + positive=positive, + negative=negative, + latent=denoised_output_latents, + ) + + return (denoised_output_latents, positive, negative) + + +@comfy_node(description="Linear transition with overlap") +class LinearOverlapLatentTransition: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "samples1": ("LATENT",), + "samples2": ("LATENT",), + "overlap": ("INT", {"default": 1, "min": 1, "max": 256}), + }, + "optional": { + "axis": ("INT", {"default": 0}), + }, + } + + RETURN_TYPES = ("LATENT",) + FUNCTION = "process" + + CATEGORY = "Lightricks/latent" + + def get_subbatch(self, samples): + s = samples.copy() + samples = s["samples"] + return samples + + def process(self, samples1, samples2, overlap, axis=0): + samples1 = self.get_subbatch(samples1) + samples2 = self.get_subbatch(samples2) + + # Create transition coefficients + alpha = torch.linspace(1, 0, overlap + 2)[1:-1].to(samples1.device) + + # Create shape for broadcasting based on the axis + shape = [1] * samples1.dim() + shape[axis] = alpha.size(0) + alpha = alpha.reshape(shape) + + # Create slices for the overlap regions + slice_all = [slice(None)] * samples1.dim() + slice_overlap1 = slice_all.copy() + slice_overlap1[axis] = slice(-overlap, None) + slice_overlap2 = slice_all.copy() + slice_overlap2[axis] = slice(0, overlap) + slice_rest1 = slice_all.copy() + slice_rest1[axis] = slice(None, -overlap) + slice_rest2 = slice_all.copy() + slice_rest2[axis] = slice(overlap, None) + + # Combine samples + parts = [ + samples1[tuple(slice_rest1)], + alpha * samples1[tuple(slice_overlap1)] + + (1 - alpha) * samples2[tuple(slice_overlap2)], + samples2[tuple(slice_rest2)], + ] + + combined_samples = torch.cat(parts, dim=axis) + combined_batch_index = torch.arange(0, combined_samples.shape[0]).to( + dtype=torch.float32 + ) + + return ( + { + "samples": combined_samples, + "batch_index": combined_batch_index, + }, + ) + + +@comfy_node(description="LTXV Normalizing Sampler") +class LTXVNormalizingSampler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LTXVNormalizingSampler", + category="utility", + inputs=[ + io.Noise.Input("noise"), + io.Guider.Input("guider"), + io.Sampler.Input("sampler"), + io.Sigmas.Input("sigmas"), + io.Latent.Input("latent_image"), + io.String.Input( + "video_normalization_factors", default="1,1,1,1,1,1,1,1" + ), + io.String.Input( + "audio_normalization_factors", default="1,1,0.25,1,1,0.25,1,1" + ), + ], + outputs=[ + io.Latent.Output(display_name="denoised_output"), + ], + ) + + @classmethod + def execute( + cls, + noise, + guider, + sampler, + sigmas, + latent_image, + video_normalization_factors, + audio_normalization_factors, + ) -> io.NodeOutput: + + if ( + guider.model_patcher.model.diffusion_model.__class__.__name__ + != "LTXAVModel" + ): + raise ValueError() + + ltxav: LTXAVModel = guider.model_patcher.model.diffusion_model + + video_normalization_factors = video_normalization_factors.split(",") + audio_normalization_factors = audio_normalization_factors.split(",") + video_normalization_factors = [ + float(factor) for factor in video_normalization_factors + ] + audio_normalization_factors = [ + float(factor) for factor in audio_normalization_factors + ] + + # Extend normalization factors to match the length of sigmas + sigmas_len = len(sigmas) - 1 + if len(video_normalization_factors) < sigmas_len: + if len(video_normalization_factors) > 0: + video_normalization_factors.extend( + [video_normalization_factors[-1]] + * (sigmas_len - len(video_normalization_factors)) + ) + if len(audio_normalization_factors) < sigmas_len: + if len(audio_normalization_factors) > 0: + audio_normalization_factors.extend( + [audio_normalization_factors[-1]] + * (sigmas_len - len(audio_normalization_factors)) + ) + + # Calculate indices where both normalization factors are not 1.0 + sampling_split_indices = [ + i + 1 + for i, (v, a) in enumerate( + zip(video_normalization_factors, audio_normalization_factors) + ) + if v != 1.0 or a != 1.0 + ] + print("Sampling split indices: %s" % sampling_split_indices, flush=True) + + # Split sigmas according to sampling_split_indices + def split_by_indices(arr, indices): + """ + Splits arr into chunks according to indices (split points). + Indices are treated as starting a new chunk at each index in the list. + """ + if not indices: + return [arr] + split_points = sorted(set(indices)) + chunks = [] + prev = 0 + for idx in split_points: + if prev < idx: + chunks.append(arr[prev : idx + 1]) + prev = idx + if prev < len(arr): + chunks.append(arr[prev:]) + return chunks + + sigmas_chunks = split_by_indices(sigmas, sampling_split_indices) + print("Sigmas chunks: %s" % sigmas_chunks, flush=True) + + i = 0 + for sigmas_chunk in sigmas_chunks: + i += len(sigmas_chunk) - 1 + print("Sampling with sigmas %s" % (sigmas_chunk), flush=True) + (_, latent_image) = SamplerCustomAdvanced().execute( + noise=noise, + guider=guider, + sampler=sampler, + sigmas=sigmas_chunk, + latent_image=latent_image, + ) + video_samples, audio_samples = ltxav.separate_audio_and_video_latents( + latent_image["samples"].tensors, + None, + ) + if i - 1 < len(video_normalization_factors) and i - 1 < len( + audio_normalization_factors + ): + video_samples = video_samples * video_normalization_factors[i - 1] + audio_samples = audio_samples * audio_normalization_factors[i - 1] + latent_image["samples"] = NestedTensor( + ltxav.recombine_audio_and_video_latents( + video_samples, audio_samples + ) + ) + print( + "After %d steps, the latent image was normalized by %f and %f" + % ( + i, + video_normalization_factors[i - 1], + audio_normalization_factors[i - 1], + ), + flush=True, + ) + + return io.NodeOutput(latent_image) diff --git a/1/custom_nodes/ComfyUI-LTXVideo/embeddings_connector.py b/1/custom_nodes/ComfyUI-LTXVideo/embeddings_connector.py new file mode 100644 index 0000000000000000000000000000000000000000..54f21eb525916ca94c79e44033a55898ad0c8b35 --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/embeddings_connector.py @@ -0,0 +1,473 @@ +import math +from typing import Optional + +import comfy.ldm.common_dit +import comfy.ops +import torch +from comfy.ldm.lightricks.model import ( + CrossAttention, + FeedForward, + LTXFrequenciesPrecision, + LTXRopeType, + generate_freq_grid_np, +) +from torch import nn + +try: + # New core (since ComfyUI PR #15056) replaced interleaved_freqs_cis/split_freqs_cis + # with a single freqs_cis_matrix helper. + from comfy.ldm.lightricks.model import freqs_cis_matrix + + _USE_FREQS_CIS_MATRIX = True +except ImportError: + # Legacy core: cos/sin freqs consumed as a (cos, sin, split) tuple. + from .rope_utils import interleaved_freqs_cis, split_freqs_cis + + _USE_FREQS_CIS_MATRIX = False + +from .pos_embedding_exp_values import POS_EMBEDDING_EXP_VALUES + + +class BasicTransformerBlock1D(nn.Module): + r""" + A basic Transformer block. + + Parameters: + + dim (`int`): The number of channels in the input and output. + num_attention_heads (`int`): The number of heads to use for multi-head attention. + attention_head_dim (`int`): The number of channels in each head. + dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use. + activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward. + attention_bias (: + obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter. + upcast_attention (`bool`, *optional*): + Whether to upcast the attention computation to float32. This is useful for mixed precision training. + norm_elementwise_affine (`bool`, *optional*, defaults to `True`): + Whether to use learnable elementwise affine parameters for normalization. + standardization_norm (`str`, *optional*, defaults to `"layer_norm"`): The type of pre-normalization to use. Can be `"layer_norm"` or `"rms_norm"`. + norm_eps (`float`, *optional*, defaults to 1e-5): Epsilon value for normalization layers. + qk_norm (`str`, *optional*, defaults to None): + Set to 'layer_norm' or `rms_norm` to perform query and key normalization. + final_dropout (`bool` *optional*, defaults to False): + Whether to apply a final dropout after the last feed-forward layer. + ff_inner_dim (`int`, *optional*): Dimension of the inner feed-forward layer. If not provided, defaults to `dim * 4`. + ff_bias (`bool`, *optional*, defaults to `True`): Whether to use bias in the feed-forward layer. + attention_out_bias (`bool`, *optional*, defaults to `True`): Whether to use bias in the attention output layer. + use_rope (`bool`, *optional*, defaults to `False`): Whether to use Rotary Position Embeddings (RoPE). + ffn_dim_mult (`int`, *optional*, defaults to 4): Multiplier for the inner dimension of the feed-forward layer. + """ + + def __init__( + self, + dim, + n_heads, + d_head, + context_dim=None, + attn_precision=None, + apply_gated_attention=False, + dtype=None, + device=None, + operations=None, + ): + super().__init__() + + # Define 3 blocks. Each block has its own normalization layer. + # 1. Self-Attn + self.attn1 = CrossAttention( + query_dim=dim, + heads=n_heads, + dim_head=d_head, + context_dim=None, + apply_gated_attention=apply_gated_attention, + dtype=dtype, + device=device, + operations=operations, + ) + + # 3. Feed-forward + self.ff = FeedForward( + dim, + dim_out=dim, + glu=True, + dtype=dtype, + device=device, + operations=operations, + ) + + def forward(self, hidden_states, attention_mask=None, pe=None) -> torch.FloatTensor: + + # Notice that normalization is always applied before the real computation in the following blocks. + + # 1. Normalization Before Self-Attention + norm_hidden_states = comfy.ldm.common_dit.rms_norm(hidden_states) + + norm_hidden_states = norm_hidden_states.squeeze(1) + + # 2. Self-Attention + attn_output = self.attn1(norm_hidden_states, mask=attention_mask, pe=pe) + + hidden_states = attn_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + # 3. Normalization before Feed-Forward + norm_hidden_states = comfy.ldm.common_dit.rms_norm(hidden_states) + + # 4. Feed-forward + ff_output = self.ff(norm_hidden_states) + + hidden_states = ff_output + hidden_states + if hidden_states.ndim == 4: + hidden_states = hidden_states.squeeze(1) + + return hidden_states + + +class Embeddings1DConnector(nn.Module): + _supports_gradient_checkpointing = True + + def __init__( + self, + in_channels=128, + cross_attention_dim=2048, + attention_head_dim=128, + num_attention_heads=30, + num_layers=2, + positional_embedding_theta=10000.0, + positional_embedding_max_pos=[1], + causal_temporal_positioning=False, + num_learnable_registers: Optional[int] = 128, + apply_gated_attention=False, + dtype=None, + device=None, + operations=None, + split_rope=False, + double_precision_rope=False, + **kwargs, + ): + super().__init__() + self.dtype = dtype + self.out_channels = in_channels + self.num_attention_heads = num_attention_heads + self.inner_dim = num_attention_heads * attention_head_dim + self.causal_temporal_positioning = causal_temporal_positioning + self.positional_embedding_theta = positional_embedding_theta + self.positional_embedding_max_pos = positional_embedding_max_pos + self.split_rope = split_rope + self.double_precision_rope = double_precision_rope + self.transformer_1d_blocks = nn.ModuleList( + [ + BasicTransformerBlock1D( + self.inner_dim, + num_attention_heads, + attention_head_dim, + context_dim=cross_attention_dim, + apply_gated_attention=apply_gated_attention, + dtype=dtype, + device=device, + operations=operations, + ) + for _ in range(num_layers) + ] + ) + + inner_dim = num_attention_heads * attention_head_dim + self.num_learnable_registers = num_learnable_registers + if self.num_learnable_registers: + self.learnable_registers = nn.Parameter( + torch.rand( + self.num_learnable_registers, inner_dim, dtype=dtype, device=device + ) + * 2.0 + - 1.0 + ) + + def get_fractional_positions(self, indices_grid): + fractional_positions = torch.stack( + [ + indices_grid[:, i] / self.positional_embedding_max_pos[i] + for i in range(1) + ], + dim=-1, + ) + return fractional_positions + + def precompute_freqs(self, indices_grid, spacing): + source_dtype = indices_grid.dtype + dtype = ( + torch.float32 + if source_dtype in (torch.bfloat16, torch.float16) + else source_dtype + ) + + fractional_positions = self.get_fractional_positions(indices_grid) + indices = ( + generate_freq_grid_np( + self.positional_embedding_theta, + indices_grid.shape[1], + self.inner_dim, + ) + if self.double_precision_rope + else self.generate_freq_grid(spacing, dtype, fractional_positions.device) + ).to(device=fractional_positions.device) + + if spacing == "exp_2": + freqs = ( + (indices * fractional_positions.unsqueeze(-1)) + .transpose(-1, -2) + .flatten(2) + ) + else: + freqs = ( + (indices * (fractional_positions.unsqueeze(-1) * 2 - 1)) + .transpose(-1, -2) + .flatten(2) + ) + return freqs + + def generate_freq_grid(self, spacing, dtype, device): + dim = self.inner_dim + theta = self.positional_embedding_theta + n_pos_dims = 1 + n_elem = 2 * n_pos_dims # 2 for cos and sin e.g. x 3 = 6 + start = 1 + end = theta + + if spacing == "exp": + # Workaround float precision issues when calculating positional embeddings exponents to ensure compatibility with JAX. + indices = torch.tensor(POS_EMBEDDING_EXP_VALUES, dtype=dtype, device=device) + elif spacing == "exp_2": + indices = 1.0 / theta ** (torch.arange(0, dim, n_elem, device=device) / dim) + indices = indices.to(dtype=dtype) + elif spacing == "linear": + indices = torch.linspace( + start, end, dim // n_elem, device=device, dtype=dtype + ) + elif spacing == "sqrt": + indices = torch.linspace( + start**2, end**2, dim // n_elem, device=device, dtype=dtype + ).sqrt() + + indices = indices * math.pi / 2 + + return indices + + def precompute_freqs_cis(self, indices_grid, spacing="exp"): + dim = self.inner_dim + n_elem = 2 # 2 because of cos and sin + freqs = self.precompute_freqs(indices_grid, spacing) + if self.split_rope: + expected_freqs = dim // 2 + current_freqs = freqs.shape[-1] + pad_size = expected_freqs - current_freqs + else: + pad_size = dim % n_elem + + if _USE_FREQS_CIS_MATRIX: + # New core takes (rotation_matrix, split_pe); let it build the matrix so + # this cannot drift from the transformer again. + return freqs_cis_matrix( + freqs, pad_size, self.split_rope, self.num_attention_heads, self.dtype + ) + + # Legacy core: returns (cos, sin, split_rope). + if self.split_rope: + cos_freq, sin_freq = split_freqs_cis( + freqs, pad_size, self.num_attention_heads + ) + else: + cos_freq, sin_freq = interleaved_freqs_cis(freqs, pad_size) + return cos_freq.to(self.dtype), sin_freq.to(self.dtype), self.split_rope + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + ): + """ + The [`Transformer2DModel`] forward method. + + Args: + hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous): + Input `hidden_states`. + indices_grid (`torch.LongTensor` of shape `(batch size, 3, num latent pixels)`): + attention_mask ( `torch.Tensor`, *optional*): + An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask + is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large + negative values to the attention scores corresponding to "discard" tokens. + Returns: + If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a + `tuple` where the first element is the sample tensor. + """ + # 1. Input + + if self.num_learnable_registers: + # replace all padded tokens with learnable registers + assert ( + hidden_states.shape[1] % self.num_learnable_registers == 0 + ), f"Hidden states sequence length {hidden_states.shape[1]} must be divisible by num_learnable_registers {self.num_learnable_registers}." + + num_registers_duplications = ( + hidden_states.shape[1] // self.num_learnable_registers + ) + learnable_registers = torch.tile( + self.learnable_registers, (num_registers_duplications, 1) + ).to(hidden_states.device) + + attention_mask_binary = ( + attention_mask.squeeze(1).squeeze(1).unsqueeze(-1) >= -9000.0 + ).int() + + non_zero_hidden_states = hidden_states[ + :, attention_mask_binary.squeeze().bool(), : + ] + non_zero_nums = non_zero_hidden_states.shape[1] + pad_length = hidden_states.shape[1] - non_zero_nums + adjusted_hidden_states = torch.nn.functional.pad( + non_zero_hidden_states, pad=(0, 0, 0, pad_length), value=0 + ) + flipped_mask = torch.flip(attention_mask_binary, dims=[1]) + hidden_states = ( + flipped_mask * adjusted_hidden_states + + (1 - flipped_mask) * learnable_registers + ) + + attention_mask = torch.full_like( + attention_mask, + 0.0, + dtype=attention_mask.dtype, + device=attention_mask.device, + ) + + indices_grid = torch.arange( + hidden_states.shape[1], dtype=torch.float32, device=hidden_states.device + ) + indices_grid = indices_grid[None, None, :] + freqs_cis = self.precompute_freqs_cis(indices_grid) + + # 2. Blocks + for block_idx, block in enumerate(self.transformer_1d_blocks): + hidden_states = block( + hidden_states, attention_mask=attention_mask, pe=freqs_cis + ) + + # 3. Output + # if self.output_scale is not None: + # hidden_states = hidden_states / self.output_scale + + hidden_states = comfy.ldm.common_dit.rms_norm(hidden_states) + + return hidden_states, attention_mask + + +# --------------------------------------------------------------------------- +# Loading helpers +# --------------------------------------------------------------------------- + +_PREFIX_BASE = "model.diffusion_model." + + +def load_embeddings_connector( + sd, + connector_prefix, + connector_config, + dtype=torch.bfloat16, + rope_type=LTXRopeType.INTERLEAVED, + frequencies_precision=LTXFrequenciesPrecision.FLOAT32, + pe_max_pos=None, +): + sd_connector = { + k[len(connector_prefix) :]: v + for k, v in sd.items() + if k.startswith(connector_prefix) + } + + if len(sd_connector) == 0: + return None + + operations = comfy.ops.pick_operations(dtype, dtype, disable_fast_fp8=True) + connector = Embeddings1DConnector( + num_attention_heads=connector_config["num_attention_heads"], + attention_head_dim=connector_config["attention_head_dim"], + num_layers=connector_config["num_layers"], + apply_gated_attention=connector_config.get("apply_gated_attention", False), + dtype=dtype, + operations=operations, + positional_embedding_max_pos=pe_max_pos if pe_max_pos is not None else [1], + split_rope=rope_type == LTXRopeType.SPLIT, + double_precision_rope=frequencies_precision == LTXFrequenciesPrecision.FLOAT64, + ) + connector.load_state_dict(sd_connector) + return connector + + +def load_video_embeddings_connector(sd, transformer_config, dtype=torch.bfloat16): + rope_type = LTXRopeType.from_dict(transformer_config) + frequencies_precision = LTXFrequenciesPrecision.from_dict(transformer_config) + pe_max_pos = transformer_config.get("connector_positional_embedding_max_pos", [1]) + + video_only_connector_prefix = f"{_PREFIX_BASE}embeddings_connector." + av_connector_prefix = f"{_PREFIX_BASE}video_embeddings_connector." + prefix = ( + av_connector_prefix + if f"{_PREFIX_BASE}audio_adaln_single.linear.weight" in sd + else video_only_connector_prefix + ) + + connector_config = { + "num_attention_heads": transformer_config.get( + "connector_num_attention_heads", 30 + ), + "attention_head_dim": transformer_config.get( + "connector_attention_head_dim", 128 + ), + "num_layers": transformer_config.get("connector_num_layers", 2), + "apply_gated_attention": transformer_config.get( + "connector_apply_gated_attention", False + ), + } + + return load_embeddings_connector( + sd, + prefix, + connector_config, + dtype, + rope_type, + frequencies_precision, + pe_max_pos, + ) + + +def load_audio_embeddings_connector(sd, transformer_config, dtype=torch.bfloat16): + rope_type = LTXRopeType.from_dict(transformer_config) + frequencies_precision = LTXFrequenciesPrecision.from_dict(transformer_config) + pe_max_pos = transformer_config.get("connector_positional_embedding_max_pos", [1]) + + connector_config = { + "num_attention_heads": transformer_config.get( + "audio_connector_num_attention_heads", + transformer_config.get("connector_num_attention_heads", 30), + ), + "attention_head_dim": transformer_config.get( + "audio_connector_attention_head_dim", + transformer_config.get("connector_attention_head_dim", 128), + ), + "num_layers": transformer_config.get( + "audio_connector_num_layers", + transformer_config.get("connector_num_layers", 2), + ), + "apply_gated_attention": transformer_config.get( + "connector_apply_gated_attention", False + ), + } + + return load_embeddings_connector( + sd, + f"{_PREFIX_BASE}audio_embeddings_connector.", + connector_config, + dtype, + rope_type, + frequencies_precision, + pe_max_pos, + ) diff --git a/1/custom_nodes/ComfyUI-LTXVideo/example_workflows/2.0/LTX-2_I2V_Distilled_wLora.json b/1/custom_nodes/ComfyUI-LTXVideo/example_workflows/2.0/LTX-2_I2V_Distilled_wLora.json new file mode 100644 index 0000000000000000000000000000000000000000..6bb986447bc42ac8a79f45bc614946ba61663e9d --- /dev/null +++ b/1/custom_nodes/ComfyUI-LTXVideo/example_workflows/2.0/LTX-2_I2V_Distilled_wLora.json @@ -0,0 +1,3282 @@ +{ + "id": "5775f45b-ae48-4889-b57c-dbdb70f74381", + "revision": 0, + "last_node_id": 5214, + "last_link_id": 13953, + "nodes": [ + { + "id": 5185, + "type": "EmptyImage", + "pos": [ + -2667.561287475645, + 6824.636229314792 + ], + "size": [ + 210, + 130 + ], + "flags": {}, + "order": 0, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "IMAGE", + "type": "IMAGE", + "links": [ + 13943 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.5.1", + "Node name for S&R": "EmptyImage" + }, + "widgets_values": [ + 1920, + 1088, + 1, + 0 + ] + }, + { + "id": 5186, + "type": "PrimitiveInt", + "pos": [ + -2669.265782707413, + 7006.326003754771 + ], + "size": [ + 210, + 82 + ], + "flags": {}, + "order": 1, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "INT", + "type": "INT", + "links": [ + 13944 + ] + } + ], + "title": "length", + "properties": { + "cnr_id": "comfy-core", + "ver": "0.5.1", + "Node name for S&R": "PrimitiveInt" + }, + "widgets_values": [ + 121, + "fixed" + ] + }, + { + "id": 5196, + "type": "CM_FloatToInt", + "pos": [ + -2673.4965346008653, + 7259.13385362648 + ], + "size": [ + 214.03773034527285, + 58 + ], + "flags": {}, + "order": 13, + "mode": 0, + "inputs": [ + { + "name": "a", + "type": "FLOAT", + "widget": { + "name": "a" + }, + "link": 13948 + } + ], + "outputs": [ + { + "name": "INT", + "type": "INT", + "links": [ + 13949 + ] + } + ], + "title": "Frame Rate", + "properties": { + "Node name for S&R": "CM_FloatToInt" + }, + "widgets_values": [ + 0 + ] + }, + { + "id": 5190, + "type": "CreateVideo", + "pos": [ + -1150.8629295969438, + 6768.122273238377 + ], + "size": [ + 210, + 78 + ], + "flags": {}, + "order": 20, + "mode": 0, + "inputs": [ + { + "name": "images", + "type": "IMAGE", + "link": 13930 + }, + { + "name": "audio", + "shape": 7, + "type": "AUDIO", + "link": 13931 + }, + { + "name": "fps", + "type": "FLOAT", + "widget": { + "name": "fps" + }, + "link": 13932 + } + ], + "outputs": [ + { + "name": "VIDEO", + "type": "VIDEO", + "links": [ + 13946 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.5.1", + "Node name for S&R": "CreateVideo" + }, + "widgets_values": [ + 30 + ] + }, + { + "id": 4958, + "type": "SaveVideo", + "pos": [ + -908.3162271395863, + 6765.627599904565 + ], + "size": [ + 632.4072425120453, + 817.489191202842 + ], + "flags": {}, + "order": 21, + "mode": 0, + "inputs": [ + { + "name": "video", + "type": "VIDEO", + "link": 13946 + } + ], + "outputs": [], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.5.1" + }, + "widgets_values": [ + "video/LTX-2", + "auto", + "auto" + ] + }, + { + "id": 5184, + "type": "PrimitiveFloat", + "pos": [ + -2674.0643381993596, + 7141.5495111297 + ], + "size": [ + 219.3647216161935, + 58 + ], + "flags": {}, + "order": 2, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "FLOAT", + "type": "FLOAT", + "links": [ + 13923, + 13932, + 13948 + ] + } + ], + "title": "Frame Rate", + "properties": { + "cnr_id": "comfy-core", + "ver": "0.5.1", + "Node name for S&R": "PrimitiveFloat" + }, + "widgets_values": [ + 24 + ] + }, + { + "id": 5176, + "type": "CheckpointLoaderSimple", + "pos": [ + -3163.6484542778676, + 6835.212679199566 + ], + "size": [ + 429.0602433593749, + 115.06840156250018 + ], + "flags": {}, + "order": 3, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 13934, + 13947 + ] + }, + { + "name": "CLIP", + "type": "CLIP", + "links": [] + }, + { + "name": "VAE", + "type": "VAE", + "links": [ + 13939 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.56", + "Node name for S&R": "CheckpointLoaderSimple" + }, + "widgets_values": [ + "ltx-2-19b-distilled.safetensors" + ] + }, + { + "id": 5188, + "type": "LTXVAudioVAELoader", + "pos": [ + -3153.75563617144, + 7313.4443822788235 + ], + "size": [ + 424.18031362607053, + 58 + ], + "flags": {}, + "order": 4, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "Audio VAE", + "type": "VAE", + "links": [ + 13935 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.64", + "Node name for S&R": "LTXVAudioVAELoader" + }, + "widgets_values": [ + "ltx-2-19b-distilled.safetensors" + ] + }, + { + "id": 5182, + "type": "LoraLoaderModelOnly", + "pos": [ + -1958.7895251485363, + 6623.839323304449 + ], + "size": [ + 210, + 82 + ], + "flags": {}, + "order": 14, + "mode": 4, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 13934 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 13941 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.68", + "Node name for S&R": "LoraLoaderModelOnly" + }, + "widgets_values": [ + "your_camera_lora.safetensors", + 1 + ] + }, + { + "id": 5183, + "type": "LoraLoaderModelOnly", + "pos": [ + -1740.2505912634988, + 6624.698937379894 + ], + "size": [ + 210, + 82 + ], + "flags": {}, + "order": 15, + "mode": 4, + "inputs": [ + { + "name": "model", + "type": "MODEL", + "link": 13947 + } + ], + "outputs": [ + { + "name": "MODEL", + "type": "MODEL", + "links": [ + 13936 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.68", + "Node name for S&R": "LoraLoaderModelOnly" + }, + "widgets_values": [ + "your_camera_lora.safetensors", + 1 + ] + }, + { + "id": 5174, + "type": "CLIPTextEncode", + "pos": [ + -1674.9082842387786, + 7164.805578586365 + ], + "size": [ + 307.2346496582031, + 76 + ], + "flags": { + "collapsed": true + }, + "order": 17, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 13924 + }, + { + "name": "text", + "type": "STRING", + "widget": { + "name": "text" + }, + "link": 13925 + } + ], + "outputs": [ + { + "name": "CONDITIONING", + "type": "CONDITIONING", + "slot_index": 0, + "links": [ + 13921, + 13950 + ] + } + ], + "title": "Enhanced Prompt (Positive)", + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.28", + "Node name for S&R": "CLIPTextEncode" + }, + "widgets_values": [ + "" + ], + "color": "#232", + "bgcolor": "#353" + }, + { + "id": 5173, + "type": "LTXVConditioning", + "pos": [ + -1670.0361297856184, + 7232.400593532743 + ], + "size": [ + 210, + 94 + ], + "flags": {}, + "order": 18, + "mode": 0, + "inputs": [ + { + "name": "positive", + "type": "CONDITIONING", + "link": 13921 + }, + { + "name": "negative", + "type": "CONDITIONING", + "link": 13950 + }, + { + "name": "frame_rate", + "type": "FLOAT", + "widget": { + "name": "frame_rate" + }, + "link": 13923 + } + ], + "outputs": [ + { + "name": "positive", + "type": "CONDITIONING", + "slot_index": 0, + "links": [ + 13937 + ] + }, + { + "name": "negative", + "type": "CONDITIONING", + "slot_index": 1, + "links": [ + 13938 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.3.28", + "Node name for S&R": "LTXVConditioning" + }, + "widgets_values": [ + 25 + ] + }, + { + "id": 5210, + "type": "LatentUpscaleModelLoader", + "pos": [ + -3139.869216300637, + 7005.9900104735725 + ], + "size": [ + 399.6787452278271, + 58 + ], + "flags": {}, + "order": 5, + "mode": 0, + "inputs": [], + "outputs": [ + { + "name": "LATENT_UPSCALE_MODEL", + "type": "LATENT_UPSCALE_MODEL", + "links": [ + 13953 + ] + } + ], + "properties": { + "cnr_id": "comfy-core", + "ver": "0.7.0", + "Node name for S&R": "LatentUpscaleModelLoader" + }, + "widgets_values": [ + "ltx-2-spatial-upscaler-x2-1.0.safetensors" + ] + }, + { + "id": 5213, + "type": "MarkdownNote", + "pos": [ + -2682.3402563401937, + 6633.478072231158 + ], + "size": [ + 240.16187366614236, + 98.41687371924309 + ], + "flags": { + "collapsed": false + }, + "order": 6, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "Video Size", + "properties": {}, + "widgets_values": [ + "Width & height settings must be divisible by 64. \nFrame count must be divisible by 8 + 1. \n\n\nRunning with invalid parameters **will not cause errors**. Instead, the flow will silently choose the closest valid parameters. " + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 5214, + "type": "MarkdownNote", + "pos": [ + -1985.053544501217, + 6321.755714756273 + ], + "size": [ + 469.5872194653941, + 209.10385276580928 + ], + "flags": { + "collapsed": false + }, + "order": 7, + "mode": 0, + "inputs": [], + "outputs": [], + "title": "LoRA", + "properties": {}, + "widgets_values": [ + "# Using LoRAs\n**Ctrl + B to enable**\n\nFor the camera LoRA we recommend setting strength = 1\n\nYou can use LTX [Ready to use camera LoRAs](https://huggingface.co/collections/Lightricks/ltx-2)\n\n\n\n\nUse a second LoRa only when the details are important in the LoRa. \n\n## Training\nWe have made available a full trainer to help you to train your own LoRA. You can [find it here](https://github.com/Lightricks/LTX-2)." + ], + "color": "#432", + "bgcolor": "#653" + }, + { + "id": 5192, + "type": "LTXVGemmaEnhancePrompt", + "pos": [ + -1661.3146912335997, + 7116.792700532783 + ], + "size": [ + 361.2680247659398, + 425.1336513712222 + ], + "flags": { + "collapsed": true + }, + "order": 16, + "mode": 0, + "inputs": [ + { + "name": "clip", + "type": "CLIP", + "link": 13926 + }, + { + "name": "image", + "shape": 7, + "type": "IMAGE", + "link": 13927 + }, + { + "name": "prompt", + "type": "STRING", + "widget": { + "name": "prompt" + }, + "link": 13928 + } + ], + "outputs": [ + { + "name": "enhanced_prompt", + "type": "STRING", + "links": [ + 13925 + ] + } + ], + "title": "Enhancer", + "properties": { + "Node name for S&R": "LTXVGemmaEnhancePrompt" + }, + "widgets_values": [ + "", + "You are a Creative Assistant writing concise, action-focused image-to-video prompts. Given an image (first frame) and user Raw Input Prompt, generate a prompt to guide video generation from that image.\n\n#### Guidelines:\n- Analyze the Image: Identify Subject, Setting, Elements, Style and Mood.\n- Follow user Raw Input Prompt: Include all requested motion, actions, camera movements, audio, and details. If in conflict with the image, prioritize user request while maintaining visual consistency (describe transition from image to user's scene).\n- Describe only changes from the image: Don't reiterate established visual details. Inaccurate descriptions may cause scene cuts.\n- Active language: Use present-progressive verbs (\"is walking,\" \"speaking\"). If no action specified, describe natural movements.\n- Chronological flow: Use temporal connectors (\"as,\" \"then,\" \"while\").\n- Audio layer: Describe complete soundscape throughout the prompt alongside actions—NOT at the end. Align audio intensity with action tempo. Include natural background audio, ambient sounds, effects, speech or music (when requested). Be specific (e.g., \"soft footsteps on tile\") not vague (e.g., \"ambient sound\").\n- Speech (only when requested): Provide exact words in quotes with character's visual/voice characteristics (e.g., \"The tall man speaks in a low, gravelly voice\"), language if not English and accent if relevant. If general conversation mentioned without text, generate contextual quoted dialogue. (i.e., \"The man is talking\" input -> the output should include exact spoken words, like: \"The man is talking in an excited voice saying: 'You won't believe what I just saw!' His hands gesture expressively as he speaks, eyebrows raised with enthusiasm. The ambient sound of a quiet room underscores his animated speech.\")\n- Style: Include visual style at beginning: \"Style: