Compare commits

...
Author SHA1 Message Date
Mel Massadian 43924f768b feat: use mtb three-view (wip) 2024-12-16 01:22:42 +01:00
Mel Massadian 5e8244fc92 fix: from merge
probably very broken still, untested
2024-12-16 01:19:16 +01:00
Mel Massadian c20da85e65 Merge branch 'main' into dev/uv-tools 2024-12-09 18:43:40 +01:00
Mel Massadian 8c629bee18 feat: ✨ add support for more formats (I/O sidebar) 2024-12-08 23:13:07 +01:00
Mel Massadian 50cb6f5ed6 chore: 🧹 bump minor 2024-12-08 19:34:26 +01:00
Mel Massadian e32d1e02df feat: ✨ add h264 compression node
recommended for i2i in ltx.
original code by [mix](https://github.com/XmYx)
2024-12-08 19:12:28 +01:00
Mel Massadian b0d52f7305 fix: 🐛 remove mtb sidebar
- The source for this is not yet in main... this file slipped
  in an earlier commit

fixes https://github.com/Comfy-Org/ComfyUI_frontend/issues/1834
2024-12-07 15:45:43 +01:00
Mel Massadian e17c6e29f5 docs: 📚 update wiki
pull wiki for documentation
2024-12-04 02:11:02 +01:00
Mel Massadian 27e03fa23e feat: ✨ add postshot nodes
basic wrapper of the cli the idea is to
queue Cog + Rotating loras -> Postshot

needs testing
2024-12-03 23:17:54 +01:00
Mel Massadian ec1cb1ac17 fix: 🐛 always enable the I/O sidebar
closes #214
2024-12-03 22:11:48 +01:00
d8ahazard 64634104a2 Use local import for Rembg
Rembg can sometimes cause *very* long load times on import (like 40s). Moving it to local doesn't fix the long import entirely, but it does prevent it causing ComfyUI from loading slowly.
2024-12-03 04:55:55 +01:00
Mel Massadian ecbb220de6 fix: 🐛 ui shifts on animation builder
finally updated to addDOMWidget
2024-11-20 23:03:00 +01:00
Mel Massadian cd9e614b1a feat: ✨ improve the I/O sidebar
- better options (sort, count)
- uses the new toast api instead of MTB.notify
2024-11-20 22:42:32 +01:00
Mel Massadian 9ccf572a15 chore: 🧹 add worktree to gitignores
for the experimental doc site at:
https://melmass.github.io/comfy_mtb/
2024-11-20 22:42:32 +01:00
Mel Massadian 74af5c6499 feat: ✨ add UpscaleBBoxBy 2024-11-20 22:42:32 +01:00
Mel Massadian caf0b39d8a chore 🧹: add deprecations and experimental 2024-11-20 22:42:32 +01:00
Mel Massadian e099d581a7 chore: 🧹 remove dupe code 2024-11-20 22:42:32 +01:00
Mel Massadian 22f7c30373 feat: ✨ simplified sidebar and backend
If you have a LoadImage selected,
clicking on images in the "input" mode will set the image on the
selected nodes
2024-11-20 22:42:32 +01:00
Mel Massadian 0133fb93bc feat: ✨ add Interpolate Condition 2024-11-20 22:42:32 +01:00
Mel Massadian cf7d30507e feat: ✨ dump of wip things... 2024-11-20 22:42:32 +01:00
Mel Massadian b6fa571fd2 fix: 🐛 category for settings 2024-11-20 21:41:57 +01:00
Mel Massadian f272526bfc fix: 🐛 new UI issues
- Fixes the "edit icon cannot be clicked"
- Changed the parser to add support for more non std markdown
- Markdown links now always open a new tab instead of replacing current
- New optional shiki support for code blocks (check #211 for details)
2024-11-20 21:41:57 +01:00
Mel Massadian 4e593bb30b feat: ✨ use the new parser for documentations
- might also fix #210
2024-11-20 21:41:57 +01:00
Mel Massadian 097ca33b8e feat: ✨ add @mtb/markdown-parser bundles
- the standard one is half the size of showdown
- the enhanced one (add shiki with most of its features) is 1.5mb
2024-11-20 21:41:57 +01:00
Mel Massadian 784fb0145b chore: 🧹 update externs
- remove showdown
- update dompurify
2024-11-20 21:41:57 +01:00
Chenlei Hu dbcca15a21 fix 🐛: input type on MTB_AnyToString (#204) 2024-10-10 02:13:13 +02:00
Mel Massadian bc41576fac docs 📚: fix wiki link
closes #202
2024-09-29 00:57:44 +02:00
Mel Massadian 8596b8184e fix: 🐛 disable old BOOL widget (legacy)
This can break if a pack declares a BOOL type

fixes #201
2024-09-27 13:33:01 +02:00
Mel Massadian 896a025006 feat: ✨ add VitMatte nodes
Basic implementation hardcoded for cuda
https://huggingface.co/melmass/pytorch-scripts
2024-09-22 00:16:23 +02:00
Mel Massadian 43092e44a4 fix: 🐛 pass ONNX providers explicitely
see #199
2024-09-08 19:58:35 +02:00
bymyself 80b5a0ca74 fix: 🐛 typo in mtb_widgets error catch (#197) 2024-09-05 14:50:48 +02:00
Mel Massadian 81b3bc1651 fix: 🐛 doc widget sidebar offset in the new ui 2024-08-18 14:26:02 +02:00
Mel Massadian a825504bdd chore: 🧹 add pathlibed inputs to utils 2024-08-18 14:07:42 +02:00
Mel Massadian 22190cd25e chore: 🧹 disable Constant
Removing as this doesn't work without my PR
2024-08-16 00:03:25 +02:00
Mel Massadian a976adbb39 chore: 🧹 new ui is default, flag for old ui 2024-08-16 00:02:18 +02:00
Mel Massadian 997d2fb13a fix: 🐛 don't fallback to eval
addresses legitimate concerns raised in #190
This limits the use a bit, SimpleMath from:
https://github.com/cubiq/ComfyUI_essentials
Is a better alternative
2024-08-08 22:34:03 +02:00
Mel Massadian f8829fcb37 chore: 🧹 add methods to shared 2024-08-08 16:57:10 +02:00
Mel Massadian 9651a70341 feat: ✨ add ColorCorrectGPU
Alternative to my ColorCorrect using only torch.
Also added Mask input for both (optional so this is not a breaking change)
2024-08-01 19:33:13 +02:00
Mel Massadian 57683c3c7d feat: ✨ add Swap FG/BG colors to MaskToImage 2024-08-01 18:38:58 +02:00
Mel Massadian f99f92e8f7 feat: ✨ add Extract coordinates
wip meant mainly for SAM2
2024-08-01 18:36:12 +02:00
Mel Massadian 5bc125d2f0 docs: 📚 remove link
still in issues
2024-08-01 17:32:23 +02:00
Mel Massadian c99b0812ab fix: 🐛 rework main utils
A whole gymnastic because comfy masks are (B,H,W).
maybe unsqueezing first is better but some nodes seems to still output
(B,H,W,C), IIRC there is an upstream PR about that
2024-08-01 17:31:18 +02:00
Mel Massadian 333f646ab1 docs: 📚 clean readme 2024-08-01 17:28:33 +02:00
Mel Massadian dbdf27664c chore: 🧹 add an old_ui flag to my launcher
this is dev related to easily test both UIs
see: https://github.com/melMass/CosyVoice-ComfyUI/commit/29510c36f0f8c1e4e5209148d14fe038947728c1
2024-07-31 04:59:36 +02:00
Mel Massadian 7d5569e5c1 chore: 🧹 move qrcode to his own file
Each files in `./nodes` can fail, but this means all nodes in the
file are skipped... `Generate` has "too important" nodes to fail
and doesn't require any extra dependencies.

This change allow qrcode to fail on its own
2024-07-31 04:59:17 +02:00
Mel Massadian 5681b464ad feat: ✨ add AudioCut
and make AudioSequence able to get negative "silence"
which would effectively "overlap" the joining sections
2024-07-31 04:42:40 +02:00
Mel Massadian 8d0fcee2f3 feat: ✨ add AudioStack
To stack/overlay audios.
2024-07-28 20:11:31 +02:00
Mel Massadian 1078fc6f0f feat: ✨ add AudioSequence node 2024-07-28 17:20:01 +02:00
Mel Massadian 821a0ef427 fix: 🐛 MaskToImage
also remove style debug
2024-07-07 20:40:18 +02:00
Mel Massadian 9007a70aa0 feat: ✨ add Split Bbox node 2024-07-06 18:30:14 +02:00
Mel Massadian 1a0ebd5173 feat: ✨ update lerp example 2024-07-06 18:26:45 +02:00
Mel Massadian 59608320c8 ⬆️ Bump version: 0.1.5 → 0.1.6 2024-07-03 18:16:37 +02:00
Mel Massadian d64fac4b74 fix: 🐛 menu callback issue
`+` on arrays returns a string in js...
2024-07-03 18:11:07 +02:00
Mel Massadian d687497d80 chore: 🧹 better classname extraction
Allow for consecutive uppercase letters:
- MTB_BatchFromHistoryV2 -> Batch From History V2
- MTB_CLIPInterpolate -> CLIP Interpolate
2024-07-03 16:00:48 +02:00
Mel Massadian d6343e1860 feat: ✨ add alpha channel support for faceswap/restore
Fixes #187
2024-07-03 15:59:09 +02:00
Mel Massadian 4eebdd8b8b ci: 🤖 limit release only to tags
I regularly need to push to main without needing to update
the extension's code / registry.
2024-07-02 13:14:00 +02:00
Mel Massadian 372e035686 Merge branch 'main' of https://github.com/melMass/comfy_mtb 2024-07-02 13:09:05 +02:00
Mel Massadian fb34671ee6 chore: 🧹 runner 2024-07-02 13:08:57 +02:00
Elthariel f25f6bdcd1 docs: 📚 Update requirements file in INSTALL.md (#186) 2024-06-26 15:05:45 +02:00
Mel Massadian f1b484617a ci: 🤖 only publish on tag
I can still autotag easily but it avoids bumping too much
versions to quickly
2024-06-22 20:17:14 +02:00
Mel Massadian 4507842a70 chore: 🧹 small fixes
- Handle image dimension mismatch in ConcatImages (Error,Smallest,Largest)
- typing
2024-06-22 20:13:59 +02:00
Mel Massadian e10faab458 ⬆️ Bump version: 0.1.4 → 0.1.5 2024-06-21 20:54:30 +02:00
Mel Massadian bb5682aa6d chore: 🧹 add fields for the registry 2024-06-21 20:48:55 +02:00
Mel Massadian 59612fd811 chore: 🧹 add pre-commit 2024-06-21 20:44:46 +02:00
Mel Massadian 30eb5b0091 chore 🧹: prepare for auto versioning 2024-06-21 19:55:50 +02:00
Mel Massadian 1edc2cd10d fix: 🐛 keep the last model match instead of first
See #184 for details
2024-06-21 19:53:25 +02:00
Mel Massadian fa3199be2b docs: 📚 update the wiki 2024-06-09 19:19:55 +02:00
Mel Massadian 43d65ae68c feat: ✨ add ModelPruner (wip) 2024-06-09 19:13:46 +02:00
Mel Massadian dfd17f6d78 chore: 🧹 migrate from poetry to setuptools 2024-06-09 15:23:07 +02:00
Mel Massadian 1070edd024 chore: 🧹 remove logs 2024-05-27 22:28:53 +02:00
Mel Massadian 9f0ed85cc1 Merge branch 'main' of https://github.com/melMass/comfy_mtb 2024-05-27 22:25:45 +02:00
Mel Massadian 35622e3a5e fix: 🐛 properly initialize the curve value
Also restored the old sorting logic adapted for Object
Closes #183

note: the ux is still bad and will improve
2024-05-27 22:25:28 +02:00
Mel Massadian 644371e5b5 chore: 🧹 add more pyproject meta 2024-05-21 12:51:40 +02:00
Mel Massadian f3d468cfc2 ci: 🤖 move at the proper location 2024-05-21 12:45:22 +02:00
haohaocreatesandMel Massadian 6cd448b026 ci: 🤖 add CI to publish to ComfyUI Registry (#182)
* publish-action
* feat ⚡:  rename token and add icons

---------

Co-authored-by: Mel Massadian <melmassadian@gmail.com>
2024-05-21 12:40:16 +02:00
haohaocreatesandMel Massadian 5951c90b10 chore: 🧹 add ComfyUI registry to pyproject.toml (#181)
* Add pyproject.toml for Custom Node Registry
* feat ⚡: add publisher id

---------

Co-authored-by: Mel Massadian <melmassadian@gmail.com>
2024-05-21 12:37:54 +02:00
bymyself 6abac2e470 feat: ✨ Use dynamic contrast in Color Correct (#180)
* Change contrast_adjustment_tensor method to change contrast dynamically
* Switch to Adobe RGB color space
2024-05-20 23:32:15 +02:00
Mel Massadian 01c73e1c5e feat ⚡: add more options to load image sequence 2024-05-17 17:35:53 +02:00
Mel Massadian 5060c56135 feat: ✨ StackImages add support for batch mismatch
Useful for comparing a static image with a batch of images
for instance.
2024-05-15 12:21:10 +02:00
bymyselfandMel Massadian acc2d687d5 fix: 🐛 ImageCompare improvements (#176)
* avoid unnecessary numpy conversion for diff and blend
* add support for Batch
* add support for input mismatch (RGB/RGBA)
* fixes #175 

---------

Co-authored-by: Mel Massadian <mel@melmassadian.com>
2024-05-14 21:16:56 +02:00
vxkj1211andMel Massadian 780c52f03a fix: 🐛 repetitive warning (#177)
Co-authored-by: Mel Massadian <mel@melmassadian.com>
2024-05-14 16:09:10 +02:00
Mel Massadian 2fe0859476 docs 📚: update wiki 2024-05-14 15:36:43 +02:00
Mel Massadian 1186239751 chore 🧹: use sections properly 2024-05-14 15:36:29 +02:00
Mel Massadian 96a0da9dbd chore: 🧹 update types 2024-05-10 20:30:46 +02:00
Mel Massadian f9d2ebf91d feat: ✨ add BatchFloatMath
Simple math operations on FLOATS (list of floats)
2024-05-07 23:42:02 +02:00
Mel Massadian 1b7ae27cc1 feat: ✨ add FLOATS to INTS
For using it with FrameInterpolation's new multiplier
2024-05-07 19:22:23 +02:00
Mel Massadian e312b02ad2 wip: 🚧 curve widget logic fixed
Most of the logic is fixed, but it still needs some UI/UX tweaks.
2024-05-07 18:40:12 +02:00
Mel Massadian 63ee25d001 feat: ✨ debug dict
it was only working on conditions
2024-05-07 18:36:56 +02:00
Mel Massadian 1caf7c18c3 feat: ✨ add Swap BG/FG color menu item 2024-05-07 08:29:57 +02:00
Mel Massadian 349a8524c6 fix: 🐛 add back was conversion node
To avoid breaking other worklfows
I thought this was now builtin WAS suite.
Fixes #172
2024-05-02 07:58:37 +02:00
Mel Massadian 15330eab65 fix: 🐛 drag lag on documentation resize handle 2024-04-28 16:54:42 +02:00
Mel Massadian 1571782d01 fix: 🐛 kwarg typo
floats vs float
2024-04-28 15:51:24 +02:00
Mel Massadian 5b4030288d fix: 🐛 seed of PlotBatchFloat
Also using random colors instead of mapped to
colormap, the values weren't distinct enough
2024-04-28 15:18:27 +02:00
Mel Massadian ab58c36212 feat: ✨ BatchFloatFit the batch version of FitNumber 2024-04-28 15:18:27 +02:00
Mel Massadian 5a0ef0dadd fix: 🐛 forceInput for FLOAT <-> FLOATS converters 2024-04-28 13:10:36 +02:00
Mel Massadian 967e72fc66 fix: 🐛 FLOAT always need options to be set
Fixes #171
2024-04-28 13:04:38 +02:00
Mel Massadian 78a86daaf7 feat: ✨ add FloatToFloats (the counterpart) 2024-04-27 21:11:53 +02:00
Mel Massadian bee3f47a14 fix: 🐛 remove doc if opened on node delete 2024-04-27 20:25:54 +02:00
Mel Massadian 2159395389 feat: ✨ add some FLOATS batch nodes
* TimeWrap
* Normalize
2024-04-27 19:47:45 +02:00
Mel Massadian b11346aba8 fix: 🐛 for documentation on HiDPI
thanks @kijai
2024-04-27 19:46:25 +02:00
Mel Massadian 30982fa488 fix: 🐛 never remove input 0 of dynamic inputs
If you reloaded a graph containing a node with dynamic inputs
but none connected the node would end up input-less
2024-04-27 16:29:34 +02:00
Mel Massadian 92b79906cd fix: 🐛 use the same fix as dynamicInputs for debug
i.e we don't auto delete inputs on disconnect, only on connect of
inputs
2024-04-27 14:58:50 +02:00
Mel Massadian 76f365b5ee fix: 🐛 missing numberInput
This is the first iteration of the "multi" number inputs.
The behaviour is based on Houdini number inputs
2024-04-27 14:16:07 +02:00
Mel Massadian da67e766c2 fix: 🐛 better curve 2024-04-27 04:08:09 +02:00
Mel Massadian 49cea8d945 docs: 📚 update wiki submodule 2024-04-27 01:17:25 +02:00
Mel Massadian b1d74adb15 fix: 🐛 prepend MTB_ to all classes
to avoid any future clash.
2024-04-27 01:13:32 +02:00
Mel Massadian 652ac3f3b9 fix: 🐛 dynamic connections 2024-04-26 21:11:32 +02:00
Mel Massadian 060e733605 Merge branch 'main' into fix/js-refactor 2024-04-25 22:19:28 +02:00
Mel Massadian eedbb4bc65 wip: 🚧 dump3 2024-04-25 22:08:25 +02:00
Mel Massadian fa2397585f wip: 🚧 dump 2024-04-25 21:56:59 +02:00
Mel Massadian 77348c4adb Merge branch 'main' into fix/js-refactor 2024-04-25 21:42:12 +02:00
Mel Massadian 0d0fb8e13a wip: 🚧 dump
js refactor start
2024-04-25 21:41:40 +02:00
Mel Massadian c9973e450d fix: 🐛 properly load image in threejs 2024-04-19 21:54:30 +02:00
Mel Massadian 2c581752e6 fix: 🐛 merge utils 2024-04-19 21:51:56 +02:00
Mel Massadian ee91e49cb0 Merge branch 'main' into dev/uv-tools 2024-04-18 15:37:20 +02:00
Mel Massadian 5abaa614d0 fix: 🐛 node_list LF 2024-04-09 02:31:45 +02:00
Mel Massadian 6ea0bf632d Merge branch 'main' into dev/uv-tools 2024-04-09 02:28:10 +02:00
Mel Massadian c66705507f fix: 🐛 utils LF 2024-04-09 02:28:02 +02:00
Mel Massadian 3f8beb8eea fix: 🐛 issues from merge
some might still remain, properly check it
2024-04-06 20:38:38 +02:00
Mel Massadian bf4d0528bc Merge branch 'main' into dev/uv-tools 2024-04-06 20:22:42 +02:00
Mel Massadian 28d874853e Merge branch 'main' into dev/uv-tools 2024-04-01 14:13:58 +02:00
Mel Massadian 8d5f05e4c1 chore: 🧹 local 2024-03-28 20:08:50 +01:00
Mel Massadian 7b291d51c6 Merge branch 'main' into dev/uv-tools
# Conflicts:
#	requirements.txt
2024-03-23 12:43:52 +01:00
Mel Massadian 1c53bb3fb7 fix: 🐛 import 2024-03-13 00:49:18 +01:00
Mel Massadian 802206bde8 fix: 🐛 from merge 2024-03-07 23:46:52 +01:00
Mel Massadian eada7f89fe Merge branch 'main' into dev/uv-tools 2024-03-07 21:30:56 +01:00
melMass 6a8463812d Merge branch 'main' into dev/uv-tools 2024-02-04 14:22:21 +01:00
melMass a91e976ef0 Merge branch 'main' into dev/uv-tools 2024-01-17 21:19:16 +01:00
melMass 4ca3d113fd chore: ✨ cleanups
not meant to be done in this branch but anyway...
2024-01-17 21:15:19 +01:00
melMass aad2d9a1cb feat: ✨ some geo utils 2024-01-05 18:20:12 +01:00
melMass 82da116a33 feat: 💄 GEOMETRY is now a dict
- For now only "mesh" and "material" keys are interopable from py <-> js
- Small fixes from merge (wip)
2023-12-26 00:44:08 +01:00
melMass 241c1a574b fix: 🐛 use relative paths 2023-12-25 18:48:33 +01:00
melMass faa2079fc7 Merge branch 'main' into dev/uv-tools 2023-12-25 18:40:33 +01:00
melMass 37150271e5 fix: 📝 update model list 2023-10-05 23:33:38 +02:00
melMass ac97010f2f fix: ⚡️ canvas size
something broke since the merge from master (camera matrix),
not sure why, this is a temp fix for it
2023-10-05 23:32:56 +02:00
melMass 69549988c5 Merge branch 'main' into dev/uv-tools 2023-10-05 22:27:26 +02:00
melMass 3ef0541584 fix: ✨ use relative imports as in main 2023-10-05 22:26:27 +02:00
melMass d720b8ae9f Merge branch 'main' into dev/uv-tools 2023-10-05 21:29:44 +02:00
melMass 7f46e985d5 Merge branch 'main' into dev/uv-tools 2023-08-15 20:23:32 +02:00
melMass d4cf5ad764 chore: 🚧 local changes 2023-08-15 20:12:46 +02:00
melMass 4fd8cf392c Merge branch 'main' into dev/uv-tools 2023-08-14 19:42:51 +02:00
melMass 347705c4c8 feat: 💄 update node list 2023-08-13 01:16:00 +02:00
melMass 6a2f5a9653 Merge branch 'main' into dev/uv-tools 2023-08-13 00:56:29 +02:00
melMass 18b5ad20da feat: 🔖 POC ThreeJS <-> Open3D 2023-08-13 00:55:57 +02:00
melMass f2202e870f Merge branch 'main' into dev/uv-tools 2023-08-13 00:44:03 +02:00
melMass 18e091fb8b fix: ✨ first version (a bit more than POC but not fully working 2023-08-13 00:05:57 +02:00
70 changed files with 10930 additions and 2777 deletions
+18
View File
@@ -0,0 +1,18 @@
name: 📦 Publish to Comfy registry
on:
workflow_dispatch:
push:
tags:
- '*'
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
steps:
- name: ♻️ Check out code
uses: actions/checkout@v4
- name: 📦 Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
personal_access_token: ${{ secrets.COMFY_REGISTRY_TOKEN }}
+3
View File
@@ -6,3 +6,6 @@ node_modules/
compose.yaml
comfy_mtb.wsb
Dockerfile
# I store the gh-pages worktrees (src & build) there
.worktrees
+8
View File
@@ -0,0 +1,8 @@
default_language_version:
python: python3.10
repos:
- repo: https://github.com/melmass/hooks
rev: e8c6c18175ed4f6e30f23991de7989411e09c73b
hooks:
- id: fix-trailing-whitespace
- id: bump-version
-93
View File
@@ -1,93 +0,0 @@
# 安装
- [安装](#安装)
- [自动安装(推荐)](#自动安装推荐)
- [ComfyUI 管理器](#comfyui-管理器)
- [虚拟环境](#虚拟环境)
- [模型下载](#模型下载)
- [网络扩展](#网络扩展)
- [旧的安装方法 (MANUAL)](#旧的安装方法-manual)
- [依赖关系](#依赖关系)
### 自动安装(推荐)
### ComfyUI 管理器
从 0.1.0 版开始,该扩展将使用 [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager) 进行安装,这对处理各种环境下的各种安装问题大有帮助。
### 虚拟环境
还有一种试验性的单行安装方法,即在 ComfyUI 根目录下使用以下命令进行安装。它将下载代码、安装依赖项并运行安装脚本:
```bash
curl -sSL "https://raw.githubusercontent.com/username/repo/main/install.py" | python3 -
```
## 模型下载
某些节点需要下载额外的模型,您可以使用与上述相同的 python 环境以交互方式完成下载:
```bash
python scripts/download_models.py
```
然后根据提示或直接按回车键下载每个模型。
> **Note**
> 您可以使用以下方法下载所有型号,无需提示:
```bash
python scripts/download_models.py -y
```
#### 网络扩展
首次运行时,脚本会尝试将 [网络扩展](https://github.com/melMass/comfy_mtb/tree/main/web)链接到你的 "web/extensions "文件夹,[请参阅](https://github.com/melMass/comfy_mtb/blob/d982b69a58c05ccead9c49370764beaa4549992a/__init__.py#L45-L61)。
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
### 旧的安装方法 (MANUAL)
### 依赖关系
<details><summary><h4>Custom Virtualenv(我主要用这个)</h4></summary
1. 确保您处于用于 ComfyUI 的 Python 环境中。
2. 运行以下命令安装所需的依赖项:
```bash
pip install -r comfy_mtb/reqs.txt
```
</details>
<details><summary><h4>Comfy 便携式/单机版(来自 ComfyUI 版本)</h4></summary>
如果您使用 ComfyUI 单机版中的 `python-embeded `,那么当二进制文件没有轮子时,您就无法使用 pip 安装二进制文件的依赖项,在这种情况下,请查看最近的 [发布](https://github.com/melMass/comfy_mtb/releases),那里有一个预编译轮子的 linux 和 windows 捆绑包(只有那些需要从源代码编译的轮子),请查看 [此问题 (#1)](https://github.com/melMass/comfy_mtb/issues/1) 以获取更多信息。
![image](https://github.com/melMass/comfy_mtb/assets/7041726/2934fa14-3725-427c-8b9e-2b4f60ba1b7b)
</details>
<details><summary><h4>Google Colab</h4></summary>
在 **Run ComfyUI with localtunnel (Recommended Way)** 标题之后(代码单元格之前)添加一个新的代码单元格
![preview of where to add it on colab](https://github.com/melMass/comfy_mtb/assets/7041726/35df2ef1-14f9-44cd-aa65-353829188cd7)
```python
# download the nodes
!git clone --recursive https://github.com/melMass/comfy_mtb.git custom_nodes/comfy_mtb
# download all models
!python custom_nodes/comfy_mtb/scripts/download_models.py -y
# install the dependencies
!pip install -r custom_nodes/comfy_mtb/reqs.txt -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.0/index.html
```
如果运行后 colab 抱怨需要重新启动运行时,请重新启动,然后不要重新运行之前的单元格,只运行运行本地隧道的单元格。(可能需要先添加一个包含 `%cd ComfyUI` 的单元格)
> **Note**:
> If you don't need all models, remove the `-y` as collab actually supports user input: ![image](https://github.com/melMass/comfy_mtb/assets/7041726/40fc3602-f1d4-432a-98fd-ce2240f5ad06)
> **Preview**
> ![image](https://github.com/melMass/comfy_mtb/assets/7041726/b5b2b2d9-f1e8-4c43-b1db-7dfc5e07be86)
</details>
-93
View File
@@ -1,93 +0,0 @@
# インストール
- [インストール](#インストール)
- [自動インストール (推奨)](#自動インストール-推奨)
- [ComfyUI マネージャ](#comfyui-マネージャ)
- [仮想環境](#仮想環境)
- [モデルのダウンロード](#モデルのダウンロード)
- [ウェブ拡張機能](#ウェブ拡張機能)
- [旧インストール方法 (MANUAL)](#旧インストール方法-manual)
- [依存関係](#依存関係)
## 自動インストール (推奨)
### ComfyUI マネージャ
バージョン0.1.0では、この拡張機能は[ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager)と一緒にインストールすることを想定しています。これは、様々な環境で直面する様々なインストール問題を処理するのに非常に役立ちます。
### 仮想環境
また、ComfyUIのルートから以下のコマンドを使用する実験的なワンライナー・インストールもあります。これはコードをダウンロードし、依存関係をインストールし、インストールスクリプトを実行します:
```bash
curl -sSL "https://raw.githubusercontent.com/username/repo/main/install.py" | python3 -
```
## モデルのダウンロード
ノードによっては、追加モデルのダウンロードが必要な場合があるので、上記と同じ python 環境を使って対話的に行うことができる:
```bash
python scripts/download_models.py
```
プロンプトに従うか、Enterを押すだけで全てのモデルをダウンロードできます。
> **Note**
> プロンプトを出さずに全てのモデルをダウンロードするには、以下のようにします:
```bash
python scripts/download_models.py -y
```
### ウェブ拡張機能
初回実行時にスクリプトは[web extensions](https://github.com/melMass/comfy_mtb/tree/main/web)をあなたの快適な `web/extensions` フォルダに[シンボリックリンク](https://github.com/melMass/comfy_mtb/blob/d982b69a58c05ccead9c49370764beaa4549992a/__init__.py#L45-L61)しようとします。万が一失敗した場合は、mtbフォルダを手動で`ComfyUI/web/extensions`にコピーしてください:
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
## 旧インストール方法 (MANUAL)
### 依存関係
<details><summary><h4>カスタム Virtualenv (私は主にこれを使っています)</h4></summary>
1. ComfyUIで使用しているPython環境であることを確認してください。
2. 以下のコマンドを実行して、必要な依存関係をインストールします:
```bash
pip install -r comfy_mtb/reqs.txt
```
</details>
<details><summary><h4>Comfy-portable / standalone (ComfyUI リリースより)</h4></summary>。
もしあなたがComfyUIスタンドアロンから`python-embeded`を使用している場合、バイナリがホイールを持っていない場合、依存関係をpipでインストールすることができません。この場合、最後の[リリース](https://github.com/melMass/comfy_mtb/releases)をチェックしてください。(ソースからのビルドが必要なもののみ)あらかじめビルドされたホイールがあるlinuxとwindows用のバンドルがあります。詳細は[この問題(#1)](https://github.com/melMass/comfy_mtb/issues/1)をチェックしてください。
![image](https://github.com/melMass/comfy_mtb/assets/7041726/2934fa14-3725-427c-8b9e-2b4f60ba1b7b)
</details>
<details><summary><h4>Google Colab</h4></summary>
ComfyUI with localtunnel (Recommended Way)**ヘッダーのすぐ後(コードセルの前)に、新しいコードセルを追加してください。
![colabに追加する場所のプレビュー](https://github.com/melMass/comfy_mtb/assets/7041726/35df2ef1-14f9-44cd-aa65-353829188cd7)
```python
# download the nodes
!git clone --recursive https://github.com/melMass/comfy_mtb.git custom_nodes/comfy_mtb
# download all models
!python custom_nodes/comfy_mtb/scripts/download_models.py -y
# install the dependencies
!pip install -r custom_nodes/comfy_mtb/reqs.txt -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.0/index.html
```
これを実行した後、colabがランタイムを再起動する必要があると文句を言ったら、それを実行し、それ以前のセルは再実行せず、localtunnelを実行するセルだけを再実行してください。(最初に`%cd ComfyUI`のセルを追加する必要があるかもしれません...)
> **Note**:
> すべてのモデルが必要でない場合は、`-y`を削除してください : ![image](https://github.com/melMass/comfy_mtb/assets/7041726/40fc3602-f1d4-432a-98fd-ce2240f5ad06)
> **プレビュー**
> ![image](https://github.com/melMass/comfy_mtb/assets/7041726/b5b2b2d9-f1e8-4c43-b1db-7dfc5e07be86)
</details>
+1 -1
View File
@@ -42,7 +42,7 @@ then follow the prompt or just press enter to download every models.
1. Make sure you are in the Python environment you use for ComfyUI.
2. Install the required dependencies by running the following command:
```bash
pip install -r comfy_mtb/reqs.txt
pip install -r comfy_mtb/requirements.txt
```
</details>
-99
View File
@@ -1,99 +0,0 @@
# MTB Nodes
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
[** 安装指南**](./INSTALL-CN.md) | [** 示例**](https://github.com/melMass/comfy_mtb/wiki/Examples)
欢迎使用 MTB Nodes 项目!这个代码库是开放的,您可以自由地探索和利用。它的主要目的是构建用于 [MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs) 中的概念验证(POCs)。该项目中的许多节点都是受到现有社区贡献或内置功能的启发而创建的。
在继续之前,请注意与此项目中使用的某些库相关的许可证。例如,`deepbump` 库采用 [GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE) 许可证。
- [节点列表](#节点列表)
- [bbox](#bbox)
- [colors](#colors)
- [人脸检测/交换](#人脸检测交换)
- [图像插值(动画)](#图像插值动画)
- [图像操作](#图像操作)
- [潜在变量工具](#潜在变量工具)
- [其他工具](#其他工具)
- [纹理](#纹理)
- [Comfy 资源](#comfy-资源)
# 节点列表
## bbox
- `Bounding Box`: BBox 构造函数(自定义类型)
- `BBox From Mask`: 从遮罩中提取边界框
- `Crop`: 根据边界框裁剪图像
- `Uncrop`: 根据边界框还原图像
## colors
- `Colored Image`: 给定尺寸的纯色图像
- `RGB to HSV`: -
- `HSV to RGB`: -
- `Color Correct`: 基本颜色校正工具
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=345/>
## 人脸检测/交换
- `Face Swap`: 使用 deepinsight/insightface 模型进行人脸交换(该节点在早期版本中称为 `Roop`,功能相同,`Roop` 只是使用这些模型的应用程序)
> **注意**
> 人脸索引允许您选择要替换的人脸,如下所示:
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42" width=320/>
- `Load Face Swap Model`: 加载 insightface 模型用于人脸交换
- `Restore Face`: 使用 [GFPGan](https://github.com/TencentARC/GFPGAN) 还原人脸,与 `Face Swap` 配合使用效果很好,并支持 `bg_upscaler` 的 Comfy 原生放大器
## 图像插值(动画)
- `Load Film Model`: 加载 [FILM](https://github.com/google-research/frame-interpolation) 模型
- `Film Interpolation`: 使用 [FILM](https://github.com/google-research/frame-interpolation) 处理输入帧
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834" width=400/>
- `Export to Prores (experimental)`: 将输入帧导出为 ProRes 4444 mov 文件。这使用 ffmpeg stdin 发送原始的 NumPy 数组,与 `Film Interpolation` 一起使用,目前很简单,但可以进一步扩展。
## 图像操作
- `Blur`: 使用高斯滤波器对图像进行模糊处理。
- `Deglaze Image`: 从 [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py) 中提取
- `Denoise`: 对输入图像进行降噪处理
- `Image Compare`: 比较两个图像并返回差异图像
- `Image Premultiply`: 使用掩码对图像进行预乘处理
- `Image Remove Background Rembg`: 使用 [RemBG](https://github.com/danielgatis/rembg) 进行背景去除
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
- `Image Resize Factor`: 大部分提取自 [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui),经过一些编辑(特别是支持多个图像)和较少的功能。
- `Mask To Image`: 将遮罩(Alpha)转换为带有颜色和背景的 RGB 图像
- `Save Image Grid`: 将输入批次中的所有图像保存为图像网格。
## 潜在变量工具
- `Latent Lerp`: 两个潜在变量之间的线性插值(混合)
## 其他工具
- `Concat Images`: 接受两个图像流,并将它们合并为其他 Comfy 管道支持的图像批次。
- `Image Resize Factor`: **已弃用**,因为我后来发现了内
置的图像调整大小功能。
- `Text To Image`: 使用字体将文本转换为图像的工具
- `Styles Loader`: 加载 csv 文件并从行中填充下拉列表(类似于 A111)
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
- `Smart Step`: 一个非常基本的节点,用于获取在 KSampler 高级中使用的步骤百分比
- `Qr Code`: 基本的 QR Code 生成器
- `Save Tensors`: 调试节点,将来可能会被删除
- `Int to Number`: 用于 WASSuite 数字节点的补充
- `Smart Step`: 使用百分比来控制 `KAdvancedSampler` 的步骤(开始/停止)
## 纹理
- `DeepBump`: 从单张图片生成法线图和高度图
# Comfy 资源
**指南**:
- [官方示例(英文)](https://comfyanonymous.github.io/ComfyUI_examples/)
- @BlenderNeko 的[ComfyUI 社区手册(英文)](https://blenderneko.github.io/ComfyUI-docs/)
- @tjhayasaka 的[Tomoaki 个人 Wiki(日文)](https://comfyui.creamlab.net/guides/)
**扩展和自定义节点**:
- @WASasquatch 的[Comfy 列表插件(英文)](https://github.com/WASasquatch/comfyui-plugins)
- [CivitAI 上的 ComfyUI 标签(英文)](https://civitai.com/tag/comfyui)
-96
View File
@@ -1,96 +0,0 @@
# MTB Nodes
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
[**インストールガイド**](./INSTALL-JP.md) | [**サンプル**](https://github.com/melMass/comfy_mtb/wiki/Examples)
MTB Nodesプロジェクトへようこそ!このコードベースは、自由に探索し、利用することができます。主な目的は、[MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs)の実装のための概念実証(POC)を構築することです。このプロジェクトの多くのノードは、既存のコミュニティの貢献や組み込みの機能に触発されています。
続行する前に、このプロジェクトで使用されている特定のライブラリに関連するライセンスに注意してください。たとえば、「deepbump」ライブラリは、[GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE)の下でライセンスされています。
- [ノードリスト](#ノードリスト)
- [bbox](#bbox)
- [colors](#colors)
- [顔検出 / スワッピング](#顔検出--スワッピング)
- [画像補間(アニメーション)](#画像補間アニメーション)
- [画像操作](#画像操作)
- [潜在的なユーティリティ](#潜在的なユーティリティ)
- [その他のユーティリティ](#その他のユーティリティ)
- [テクスチャ](#テクスチャ)
- [Comfyリソース](#comfyリソース)
# ノードリスト
## bbox
- `Bounding Box`: BBoxコンストラクタ(カスタムタイプ)
- `BBox From Mask`: マスクからバウンディングボックスを抽出
- `Crop`: BBoxから画像を切り抜く
- `Uncrop`: BBoxから画像を元に戻す
## colors
- `Colored Image`: 指定されたサイズの一定の色の画像
- `RGB to HSV`: -
- `HSV to RGB`: -
- `Color Correct`: 基本的なカラーコレクションツール
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=345/>
## 顔検出 / スワッピング
- `Face Swap`: deepinsight/insightfaceモデルを使用した顔の入れ替え(このノードは初期バージョンでは「Roop」と呼ばれていましたが、同じ機能を提供します。Roopは単にこれらのモデルを使用するアプリです)
> **注意**
> 顔のインデックスを使用して置き換える顔を選択できます。以下を参照してください:
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42" width=320/>
- `Load Face Swap Model`: 顔の交換のためのinsightfaceモデルを読み込む
- `Restore Face`: [GFPGan](https://github.com/TencentARC/GFPGAN)を使用して顔を復元し、`Face Swap`と組み合わせて使用すると非常に効果的であり、`bg_upscaler`のComfyネイティブアップスケーラーもサポートしています。
## 画像補間(アニメーション)
- `Load Film Model`: [FILM](https://github.com/google-research/frame-interpolation)モデルを読み込む
- `Film Interpolation`: [FILM](https://github.com/google-research/frame-interpolation)を使用して入力フレームを処理する
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834" width=400/>
- `Export to Prores (experimental)`: 入力フレームをProRes 4444 movファイルにエクスポートします。これは現在は単純なものですが、`Film Interpolation`と組み合わせて使用するためのffmpegのstdinを使用して生のNumPy配列を送信するもので、拡張することもできます。
## 画像操作
- `Blur`: ガウスフィルタを使用して画像をぼかす
- `Deglaze Image`: [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py)から取得
- `Denoise`: 入力画像のノイズを除去する
- `Image Compare`: 2つの画像を比較し、差分画像を返す
- `Image Premultiply`: 画像をマスクで乗算
- `Image Remove Background Rembg`: [RemBG](https://github.com/danielgatis/rembg)を使用した背景除去
<img src="https://github.com/melMass/comfy_mtb/assets/704172
6/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
- `Image Resize Factor`: [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui)から抽出され、いくつかの編集(特に複数の画像のサポート)と機能の削減が行われました。
- `Mask To Image`: マスク(アルファ)をカラーと背景を持つRGBイメージに変換します。
- `Save Image Grid`: 入力バッチのすべての画像を画像グリッドとして保存します。
## 潜在的なユーティリティ
- `Latent Lerp`: 2つの潜在的なベクトルの間の線形補間(ブレンド)
## その他のユーティリティ
- `Concat Images`: 2つの画像ストリームを取り、他のComfyパイプラインでサポートされている画像のバッチとしてマージします。
- `Image Resize Factor`: **非推奨**。組み込みの画像リサイズ機能を発見したため、削除される予定です。
- `Text To Image`: フォントを使用してテキストを画像に変換するためのユーティリティ
- `Styles Loader`: csvファイルをロードし、行からドロップダウンを作成します(A111のようなもの)
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
- `Smart Step`: KSamplerの高度な使用に使用するステップパーセントを取得する非常に基本的なノード
- `Qr Code`: 基本的なQRコード生成器
- `Save Tensors`: 将来的に削除される可能性のあるデバッグノード
- `Int to Number`: WASSuiteの数値ノードの補完
- `Smart Step`: `KAdvancedSampler`のステップ(開始/停止)を制御するための非常に基本的なツールで、パーセンテージを使用します。
## テクスチャ
- `DeepBump`: 1枚の画像から法線マップと高さマップを生成します。
# Comfyリソース
**ガイド**:
- [公式の例(英語)](https://comfyanonymous.github.io/ComfyUI_examples/)
- @BlenderNekoによる[ComfyUIコミュニティマニュアル(英語)](https://blenderneko.github.io/ComfyUI-docs/)
- @tjhayasakaによる[Tomoakiの個人Wiki(日本語)](https://comfyui.creamlab.net/guides/)
**拡張機能とカスタムノード**:
- @WASasquatchによる[Comfyリスト用のプラグイン(英語)](https://github.com/WASasquatch/comfyui-plugins)
- [CivitAIのComfyUIタグ(英語)](https://civitai.com/tag/comfyui)
+1 -170
View File
@@ -4,177 +4,8 @@
![home](https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873)
<!-- omit in toc -->
**Translated Readme (using DeepTranslate, PRs are welcome)**:
![image](https://github.com/melMass/comfy_mtb/assets/7041726/f8429c14-3521-4e28-82a3-863d781976c0)
[日本語による説明](./README-JP.md)
![image](https://github.com/melMass/comfy_mtb/assets/7041726/d5cc1fdd-2820-4a5c-b2d7-482f1c222063)
[中文说明](./README-CN.md)
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
[**Install Guide**](./INSTALL.md) | [**Examples**](https://github.com/melMass/comfy_mtb/wiki/Examples)
There is now a dedicated `#mtb-nodes` channel on the Banodoco discord:
[![](https://dcbadge.vercel.app/api/server/AXhsabmDhn?style=flat)](https://discord.gg/IAXhsabmDhn)
---
Welcome to the MTB Nodes project! This codebase is open for you to explore and utilize as you wish. Its primary purpose is to build proof-of-concepts (POCs) for implementation in [MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs). Many nodes in this project are inspired by existing community contributions or built-in functionalities.
Before proceeding, please be aware of the licenses associated with certain libraries used in this project. For example, the `deepbump` library is licensed under [GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE).
- [Web Extensions](#web-extensions)
- [Node List](#node-list)
- [Animation](#animation)
- [bbox](#bbox)
- [colors](#colors)
- [image ops](#image-ops)
- [latent utils](#latent-utils)
- [textures](#textures)
- [misc utils](#misc-utils)
- [Optional nodes](#optional-nodes)
- [face detection / swapping](#face-detection--swapping)
- [image interpolation (animation)](#image-interpolation-animation)
- [Comfy Resources](#comfy-resources)
# Web Extensions
mtb add a few widgets like `COLOR`
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
A few nodes have the concept of "dynamic" inputs:
<img alt="dynamic inputs" width=450 src="https://github.com/melMass/comfy_mtb/assets/7041726/10b3976e-b212-4968-91eb-f34c02bb80c3" />
<!-- NOTE: Here it should just be some examples and warnings, move the rest to the wiki -->
# Node List
## Animation
- `Animation Builder`: Convenient way to manage basic animation maths at the core of many of my workflows (both worflows for the following GIFs are in the [examples](https://github.com/melMass/comfy_mtb/wiki/Examples))
**[Example lerping two conditions (blue car -> yellow car)](https://github.com/melMass/comfy_mtb/blob/main/examples/03-animation_builder-condition-lerp.json)**
<img width=300 src="https://user-images.githubusercontent.com/7041726/260258970-d6d66d96-fb34-40d0-9038-cbabf0714c5d.gif"/>
**[Example using image transforms a feedback for a fake deforum effect](https://github.com/melMass/comfy_mtb/blob/main/examples/04-animation_builder-deforum.json)**
<img width=300 src="https://user-images.githubusercontent.com/7041726/260261504-303a1037-60d3-4b31-a589-b15d549752f6.gif"/>
- `Batch Float`: Generates a batch of float values with interpolation.
- `Batch Shape`: Generates a batch of 2D shapes with optional shading (experimental).
- `Batch Transform`: Transform a batch of images using a batch of keyframes.
<img width=400 src="https://github.com/melMass/comfy_mtb/assets/7041726/3f217de1-79aa-49b0-a66a-35cf29dd8f01"/>
- `Export With Ffmpeg`: Export with FFmpeg, it used to be export to Proress and is still tailored for YUV
- `Fit Number` : Fit the input float using a source and target range, you can also control the interpolation curve from a list of presets (default to linear)
## bbox
- `Bounding Box`: BBox constructor (custom type),
- `BBox From Mask`: From a mask extract the bounding box
- `Crop`: Crop image from BBox
- `Uncrop`: Uncrop image from BBox
## colors
- `Colored Image`: Constant color image of given size
- `RGB to HSV`: -,
- `HSV to RGB`: -,
- `Color Correct`: Basic color correction tools
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=400/>
## image ops
- `Blur`: Blur an image using a Gaussian filter.
- `Deglaze Image`: taken from [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py),
- `Denoise`: Denoise the input image,
- `Image Compare`: Compare two images and return a difference image
- `Image Premultiply`: Premultiply image with mask
- `Image Remove Background Rembg`: [RemBG](https://github.com/danielgatis/rembg) powered background removal.
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
- `Image Resize Factor`: Extracted mostly from [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui), with a few edits (most notably multiple image support) and less features.
- `Mask To Image`: Converts a mask (alpha) to an RGB image with a color and background
- `Save Image Grid`: Save all the images in the input batch as a grid of images.
## latent utils
- `Latent Lerp`: Linear interpolation (blend) between two latent
## textures
- `Model Patch Seamless`: Use the [seamless diffusion "hack"](https://gitlab.com/-/snippets/2395088) to patch any model to infere seamless images, check the [examples](https://github.com/melMass/comfy_mtb/wiki/Examples) to see how to use all those textures node together
<img width=500 src="https://user-images.githubusercontent.com/7041726/272970506-9db516b5-45d2-4389-b904-b3a94660f24c.png"/>
- `DeepBump`: Normal & height maps generation from single pictures
<img width=500 src="https://user-images.githubusercontent.com/7041726/272970715-7e4477f6-8e18-4839-9864-83d07d6690a1.png"/>
- `Image Tile Offset`: Mimics an old photoshop technique to check for seamless textures by offsetting tiles of the image.
<img width=600 src="https://github.com/melMass/comfy_mtb/assets/7041726/cbcc51fb-922f-433f-acf1-c6c6c2a7ffc4" />
## misc utils
- `Any To String`: Tries to take any input and convert it to a string.
- `Concat Images`: Takes two image stream and merge them as a batch of images supported by other Comfy pipelines.
- `Image Resize Factor`: **Deprecated**, I since discovered the builtin image resize.
- `Text To Image`: Utils to convert text to image using a font
- `Styles Loader`: Load csv files and populate a dropdown from the rows (à la A111)
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
- `Smart Step`: A very basic node to get step percent to use in KSampler advanced,
- `Qr Code`: Basic QR Code generator
- `Save Tensors`: Debug node that will probably be removed in the future
- `Int to Number`: Supplement for WASSuite number nodes
- `Smart Step`: A very basic tool to control the steps (start/stop) of the `KAdvancedSampler` using percentage
- `Load Image From Url`: Load an image from the given URL
[**Wiki**](https://github.com/melMass/comfy_mtb/wiki) | [**Install Guide**](./INSTALL.md) | [**Examples**](https://github.com/melMass/comfy_mtb/wiki/Examples)
## Optional nodes
These nodes are still bundled in mtb, but moving forward (>0.2.0) they won't
be setup by the install script and their dependencies won't install either.
The reason is mostly that they all have a better alternatives available and tensorflow on windows was not a fun experience and since Python 3.11 not an experience at all.
For linux and mac users though these nodes didn't cause any issue and I personally still use them, these are the extra requirements needed:
```console
.venv/python -m pip install tensorflow facexlib insightface basicsr
```
### face detection / swapping
> **Warning**
> Those nodes were among the first to be implemented they do work, but on windows the installation is still not properly handled for everyone
> As alternatives you can use [reactor](https://github.com/Gourieff/comfyui-reactor-node) for face swap and [facerestore](https://github.com/Haidra-Org/hordelib/tree/main/hordelib/nodes/facerestore) for restoration
> You can check [this video](https://www.youtube.com/watch?v=FShlpMxbU0E) for a tutorial by Ferniclestix using these alternatives
- `Face Swap`: Face swap using deepinsight/insightface models (this node used to be called `Roop` in early versions, it does the same, roop is *just* an app that uses those model)
<img width=320 src="https://user-images.githubusercontent.com/7041726/260261217-54e33446-183f-4dda-88b3-d38a1e6de980.gif"/>
- `Load Face Swap Model`: Load an insightface model for face swapping
- `Restore Face`: Using [GFPGan](https://github.com/TencentARC/GFPGAN) to restore faces, works great in conjunction with `Face Swap` and supports Comfy native upscalers for the `bg_upscaler`
### image interpolation (animation)
> **Warning**
> The FILM nodes will be deprecated at some point after 0.2.0, [Fannovel16](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)'s interpolation nodes implement it and they rely on a pytorch implementation of FILM
> which solves the issues related to the ones included in mtb. They will probably remain available if your system meet the requirements and ignored otherwise.
<details><summary>Why?</summary>
> **Windows only issue**: This requires tensorflow-gpu that is unfortunately not a thing anymore on Windows since 2.10.1 (unless you use a complex WSL passthrough setup but it's still not "Windows")
> Using this old version is quite clunky and require some patching that install.py does automatically, but the main issue is that no wheels are available for python > 3.10
> Comfy-nightly is already using Python 11 so installing this old tf version won't work there.
> You can in any case install the normal up to date tensorflow but that will run on CPU and is much MUCH slower for FILM inference.
</details>
- `Load Film Model`: Loads a [FILM](https://github.com/google-research/frame-interpolation) model
- `Film Interpolation`: Process input frames using [FILM](https://github.com/google-research/frame-interpolation)
<img width=400 src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834"/>
<img width=400 src="https://user-images.githubusercontent.com/7041726/260259079-c0f04a63-960c-43a7-ba78-a45cd5ac7514.gif"/>
- `Export to Prores (experimental)`: Exports the input frames to a ProRes 4444 mov file. This is using ffmpeg stdin to send raw numpy arrays, used with `Film Interpolation` and very simple for now but could be expanded upon.
# Comfy Resources
**Misc**
- [Slick ComfyUI by NoCrypt](https://colab.research.google.com/drive/1ZMvLWEiYITmBJngtqeIQToeNuiydwI0z#scrollTo=1fWMaexXS188): A colab notebook with batteries included!
**Guides**:
- [Official Examples (eng)](https://comfyanonymous.github.io/ComfyUI_examples/)
- [ComfyUI Community Manual (eng)](https://blenderneko.github.io/ComfyUI-docs/) by @BlenderNeko
- [Tomoaki's personal Wiki (jap)](https://comfyui.creamlab.net/guides/) by @tjhayasaka
**Extensions and Custom Nodes**:
- [Plugins for Comfy List (eng)](https://github.com/WASasquatch/comfyui-plugins) by @WASasquatch
- [ComfyUI tag on CivitAI (eng)](https://civitai.com/tag/comfyui)
+286 -68
View File
@@ -6,46 +6,47 @@
# Copyright (c) 2023 Mel Massadian
#
###
__version__ = "0.2.0"
import os
# todo: don't override this if the user has that setup already
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
os.environ["TF_GPU_ALLOCATOR"] = "cuda_malloc_async"
from aiohttp.web_request import Request
# TODO: don't override this if the user has that setup already
if not os.environ.get("TF_FORCE_GPU_ALLOW_GROWTH"):
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
if not os.environ.get("TF_GPU_ALLOCATOR"):
os.environ["TF_GPU_ALLOCATOR"] = "cuda_malloc_async"
import ast
import contextlib
import importlib
import json
import logging
import os
import shutil
import traceback
from importlib import reload
from pathlib import Path
from aiohttp import web
from server import PromptServer
import nodes
from .endpoint import endlog
from .log import blue_text, cyan_text, get_label, get_summary, log
from .utils import comfy_dir, here
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
NODE_CLASS_MAPPINGS_DEBUG = {}
NODE_CLASS_MAPPINGS: dict[str, type] = {}
NODE_DISPLAY_NAME_MAPPINGS: dict[str, str] = {}
NODE_CLASS_MAPPINGS_DEBUG: dict[str, str | None] = {}
WEB_DIRECTORY = "./web"
__version__ = "0.2.0"
def extract_nodes_from_source(filename):
def extract_nodes_from_source(filename: Path):
source_code = ""
with open(filename, encoding="utf8") as file:
source_code = file.read()
nodes = []
source_code = filename.read_text(encoding="utf-8")
nodes: list[str] = []
try:
parsed = ast.parse(source_code)
@@ -54,23 +55,24 @@ def extract_nodes_from_source(filename):
target = node.targets[0]
if isinstance(target, ast.Name) and target.id == "__nodes__":
value = ast.get_source_segment(source_code, node.value)
node_value = ast.parse(value).body[0].value
if isinstance(node_value, (ast.List, ast.Tuple)):
nodes.extend(
element.id
for element in node_value.elts
if isinstance(element, ast.Name)
)
break
if value:
node_value = ast.parse(value).body[0].value
if isinstance(node_value, ast.List | ast.Tuple):
nodes.extend(
str(element.id)
for element in node_value.elts
if isinstance(element, ast.Name)
)
break
except SyntaxError:
log.error("Failed to parse")
return nodes
def load_nodes():
errors = []
nodes = []
nodes_failed = []
errors: list[str] = []
nodes: list[type] = []
nodes_failed: list[str] = []
for filename in (here / "nodes").iterdir():
if filename.suffix == ".py":
@@ -85,9 +87,11 @@ def load_nodes():
log.debug(f"Imported {module_name} nodes")
except AttributeError:
log.debug(f"Skipping wip module {module_name}")
pass # wip nodes
except Exception:
error_message = traceback.format_exc().splitlines()[-1]
errors.append(
f"Failed to import module {module_name} because {error_message}"
)
@@ -107,39 +111,94 @@ def load_nodes():
# - REGISTER WEB EXTENSIONS
web_extensions_root = comfy_dir / "web" / "extensions"
web_mtb = web_extensions_root / "mtb"
def uninstall_old_web_extensions():
web_extensions_root = comfy_dir / "web" / "extensions"
web_mtb = web_extensions_root / "mtb"
if web_mtb.exists() and hasattr(nodes, "EXTENSION_WEB_DIRS"):
try:
if web_mtb.is_symlink():
web_mtb.unlink()
else:
shutil.rmtree(web_mtb)
except Exception as e:
log.warning(
f"Failed to remove web mtb directory: {e}\nPlease manually remove it from disk ({web_mtb}) and restart the server."
)
if web_mtb.exists() and hasattr(nodes, "EXTENSION_WEB_DIRS"):
try:
if web_mtb.is_symlink():
web_mtb.unlink()
else:
shutil.rmtree(web_mtb)
except Exception as e:
log.warning(
f"""Failed to remove web mtb directory: {e}
Please manually remove it from disk ({web_mtb}) and restart the server."""
)
# uninstall_old_web_extensions()
# - GATHER WIKI PAGES
def wiki_to_classname(s: str):
wiki_name = s.replace("nodes-", "", 1)
return "MTB_" + "".join(
[part.capitalize() for part in wiki_name.split("-")]
)
def classname_to_wiki(s: str):
classname = s.replace("MTB_", "")
parts: list[str] = []
start = 0
for i in range(1, len(classname)):
if classname[i].isupper():
parts.append(classname[start:i].lower())
start = i
parts.append(classname[start:].lower())
return "nodes-" + "-".join(parts)
wiki = here / "wiki"
node_docs = {}
if wiki.exists() and wiki.is_dir():
node_docs = {
wiki_to_classname(x.stem): x.read_text(encoding="utf-8")
for x in (wiki / "nodes").glob("*.md")
}
# - REGISTER NODES
MTB_EXPORT = os.environ.get("MTB_EXPORT")
nodes, failed = load_nodes()
for node_class in nodes:
class_name = node_class.__name__
# fallback to __doc__
if not hasattr(node_class, "DESCRIPTION") and node_class.__doc__:
node_class.DESCRIPTION = node_class.__doc__
class_name: str = node_class.__name__
linked_doc = node_docs.get(class_name)
if not hasattr(node_class, "DESCRIPTION"):
if linked_doc:
log.debug(f"Found linked doc for {class_name}, using it")
node_class.DESCRIPTION = linked_doc
elif node_class.__doc__:
log.debug(f"Using __doc__ as description for {class_name}")
node_class.DESCRIPTION = node_class.__doc__
if MTB_EXPORT:
wiki_name = classname_to_wiki(class_name)
_ = (wiki / "nodes" / (wiki_name + ".md")).write_text(
node_class.__doc__, encoding="utf-8"
)
else:
log.debug(
f"None of the methods could retrieve documentation for {class_name}"
)
node_label = f"{get_label(class_name)} (mtb)"
NODE_CLASS_MAPPINGS[node_label] = node_class
NODE_DISPLAY_NAME_MAPPINGS[class_name] = node_label
NODE_CLASS_MAPPINGS_DEBUG[node_label] = node_class.__doc__
# TODO: I removed this, I find it more convenient to write without spaces, but it breaks every of my workflows
# TODO (cont): and until I find a way to automate the conversion, I'll leave it like this
# TODO: I removed this, I find it more convenient to write without spaces
# but it breaks every of my workflows
# TODO (cont): and until I find a way to automate the conversion
# I'll leave it like this
if os.environ.get("MTB_EXPORT"):
with open(here / "node_list.json", "w") as f:
f.write(
_ = f.write(
json.dumps(
{
k: NODE_CLASS_MAPPINGS_DEBUG[k]
@@ -157,19 +216,30 @@ log.debug(
)
)
log.info(f"loaded {cyan_text(len(nodes))} nodes successfuly")
log.info(f"loaded {cyan_text(str(len(nodes)))} nodes successfuly")
if failed:
with contextlib.suppress(Exception):
base_url, port = utils.get_server_info()
log.info(
f"Some nodes ({len(failed)}) could not be loaded. This can be ignored, but go to http://{base_url}:{port}/mtb if you want more information."
)
log.debug(failed)
# - ENDPOINT
if hasattr(PromptServer, "instance"):
img_cache = None
prompt_cache = None
with contextlib.suppress(ImportError):
from cachetools import TTLCache
img_cache = TTLCache(maxsize=100, ttl=5) # 1 min TTL
prompt_cache = TTLCache(maxsize=100, ttl=5) # 1 min TTL
restore_deps = ["basicsr"]
onnx_deps = ["onnxruntime"]
swap_deps = ["insightface"] + onnx_deps
@@ -248,10 +318,10 @@ if hasattr(PromptServer, "instance"):
}
)
@PromptServer.instance.routes.post("/mtb/debug")
async def set_debug(request):
json_data = await request.json()
enabled = json_data.get("enabled")
@PromptServer.instance.routes.post("/mtb/server-info")
async def set_server_info(request: Request):
json_data: dict[str, bool] = await request.json()
enabled = json_data.get("debug")
if enabled:
os.environ["MTB_DEBUG"] = "true"
log.setLevel(logging.DEBUG)
@@ -259,7 +329,7 @@ if hasattr(PromptServer, "instance"):
elif "MTB_DEBUG" in os.environ:
# del os.environ["MTB_DEBUG"]
os.environ.pop("MTB_DEBUG")
_ = os.environ.pop("MTB_DEBUG")
log.setLevel(logging.INFO)
return web.json_response(
@@ -267,19 +337,19 @@ if hasattr(PromptServer, "instance"):
)
@PromptServer.instance.routes.get("/mtb")
async def get_home(request):
async def get_home(request: Request):
from . import endpoint
reload(endpoint)
_ = reload(endpoint)
# Check if the request prefers HTML content
if "text/html" in request.headers.get("Accept", ""):
# # Return an HTML page
html_response = """
<div class="flex-container menu">
<a href="/mtb/manage">manage</a>
<a href="/mtb/debug">debug</a>
<a href="/mtb/server-info">Server Info</a>
<a href="/mtb/status">status</a>
</div>
</div>
"""
return web.Response(
text=endpoint.render_base_template("MTB", html_response),
@@ -289,28 +359,176 @@ if hasattr(PromptServer, "instance"):
# Return JSON for other requests
return web.json_response({"message": "Welcome to MTB!"})
@PromptServer.instance.routes.get("/mtb/debug")
async def get_debug(request):
import asyncio
import os
from io import BytesIO
from aiohttp import web
from PIL import Image
def get_cached_image(file_path: str, preview_params=None, channel=None):
cache_key = (file_path, preview_params, channel)
if img_cache and (cache_key in img_cache):
return img_cache[cache_key]
with Image.open(file_path) as img:
info = img.info
if preview_params:
img = process_preview(img, preview_params)
if channel:
img = process_channel(img, channel)
if prompt_cache:
prompt_cache[cache_key] = info
if img_cache:
img_cache[cache_key] = img.getvalue()
return img_cache[cache_key]
return img.getvalue()
def process_preview(img: Image.Image, preview_params):
image_format, quality, width = preview_params
quality = int(quality)
if width:
width = int(width)
img.thumbnail((width, int(width * img.height / img.width)))
buffer = BytesIO()
img.save(
buffer, format=image_format, quality=quality, metadata=img.info
)
buffer.seek(0)
return buffer
def process_channel(img: Image.Image, channel: str):
if channel == "rgb":
if img.mode == "RGBA":
r, g, b, _ = img.split()
img = Image.merge("RGB", (r, g, b))
else:
img = img.convert("RGB")
elif channel == "a":
if img.mode == "RGBA":
_, _, _, a = img.split()
else:
a = Image.new("L", img.size, 255)
img = Image.new("RGBA", img.size)
img.putalpha(a)
buffer = BytesIO()
img.save(buffer, format="PNG")
_ = buffer.seek(0)
return buffer
async def get_image_response(
file, filename: str, preview_info=None, channel=None
):
img = await asyncio.to_thread(
get_cached_image, file, preview_info, channel
)
return web.Response(
body=img,
content_type="image/webp" if preview_info else "image/png",
headers={"Content-Disposition": f'filename="{filename}"'},
)
# TODO: Embed the metadatas somehow so we can drag and drop
# to load workflows in the sidebar
@PromptServer.instance.routes.get("/mtb/view")
async def view_image(request: Request):
import folder_paths
filename = request.rel_url.query.get("filename")
if not filename:
return web.Response(status=404)
filename, output_dir = folder_paths.annotated_filepath(filename)
if filename[0] == "/" or ".." in filename:
return web.Response(status=400)
if output_dir is None:
rtype = request.rel_url.query.get("type", "output")
output_dir = folder_paths.get_directory_by_type(rtype)
if output_dir is None:
return web.Response(status=400)
if "subfolder" in request.rel_url.query:
full_output_dir = os.path.join(
output_dir, request.rel_url.query["subfolder"]
)
if (
os.path.commonpath(
(os.path.abspath(full_output_dir), output_dir)
)
!= output_dir
):
return web.Response(status=403)
output_dir = full_output_dir
filename = os.path.basename(filename)
file = os.path.join(output_dir, filename)
if not os.path.isfile(file):
return web.Response(status=404)
preview_info = None
if "preview" in request.rel_url.query:
preview_params = request.rel_url.query["preview"].split(";")
image_format = (
preview_params[0]
if preview_params[0] in ["webp", "jpeg"]
else "webp"
)
quality = (
int(preview_params[1])
if len(preview_params) > 1 and preview_params[1].isdigit()
else 90
)
width = request.rel_url.query.get("width")
preview_info = (image_format, quality, width)
channel = request.rel_url.query.get("channel")
return await get_image_response(file, filename, preview_info, channel)
@PromptServer.instance.routes.get("/mtb/server-info")
async def get_debug(request: Request):
from . import endpoint
reload(endpoint)
enabled = "MTB_DEBUG" in os.environ
_ = reload(endpoint)
isdebug = "MTB_DEBUG" in os.environ
exposed = "MTB_EXPOSE" in os.environ
def render_property(name: str, val: str):
return f"""<strong>{name}:</strong>
<p>
{val}
</p>"""
# Check if the request prefers HTML content
if "text/html" in request.headers.get("Accept", ""):
# # Return an HTML page
html_response = f"""
<h1>MTB Debug Status: {'Enabled' if enabled else 'Disabled'}</h1>
"""
html_response = ""
html_response += render_property(
"Debug", "Enabled" if isdebug else "Disabled"
)
html_response += render_property("Exposed", str(exposed))
return web.Response(
text=endpoint.render_base_template("Debug", html_response),
text=endpoint.render_base_template(
"Server Info", html_response
),
content_type="text/html",
)
# Return JSON for other requests
return web.json_response({"enabled": enabled})
return web.json_response({"exposed": exposed, "debug": isdebug})
@PromptServer.instance.routes.get("/mtb/actions")
async def no_route(request):
async def no_route(request: Request):
from . import endpoint
if "text/html" in request.headers.get("Accept", ""):
@@ -324,7 +542,7 @@ if hasattr(PromptServer, "instance"):
return web.json_response({"message": "actions has no get for now"})
@PromptServer.instance.routes.post("/mtb/actions")
async def do_action(request):
async def do_action(request: Request):
from . import endpoint
reload(endpoint)
+31 -19
View File
@@ -1,19 +1,31 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "asNeeded",
"indentWidth": 2
}
}
}
{
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noConsoleLog": "warn"
},
"style": {
"noParameterAssign": "off",
"noShoutyConstants": "warn",
"useNamingConvention": "off"
}
}
},
"formatter": {
"indentStyle": "space",
"indentWidth": 2,
"lineEnding": "lf"
},
"javascript": {
"formatter": {
"quoteStyle": "single",
"semicolons": "asNeeded"
}
}
}
+204 -28
View File
@@ -1,28 +1,130 @@
import csv
import secrets
import sys
from pathlib import Path
from typing import Any, Literal
from aiohttp import web
from .log import mklog
from .utils import backup_file, here, import_install, reqs_map, run_command, styles_dir
from .utils import (
SortMode,
backup_file,
build_glob_patterns,
glob_multiple,
here,
import_install,
input_dir,
output_dir,
reqs_map,
run_command,
styles_dir,
)
endlog = mklog("mtb endpoint")
# - ACTIONS
import asyncio
import platform
import sys
from pathlib import Path
try:
import websockets.server
except ModuleNotFoundError:
endlog.warning(
"You do not have websockets installed, the video server won't work"
)
websockets = False
import_install("requirements")
import io
import numpy as np
from PIL import Image
def generate_random_frame():
# Generate a random image frame
width, height = 640, 480
image = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8)
pil_image = Image.fromarray(image)
byte_buffer = io.BytesIO()
pil_image.save(byte_buffer, format="JPEG")
frame_data = byte_buffer.getvalue()
return frame_data
class VideoStreamingManager:
def __init__(self):
self.video_servers = {}
self.next_port = (
8767 # Start with a default port and increment for each server
)
async def start_video_streaming_server(self, video_id):
if video_id not in self.video_servers:
# Create and start a new video streaming server for the specified video
video_server = await self.create_video_streaming_server(video_id)
self.video_servers[video_id] = video_server
return video_server
async def video_stream(self, websocket, path):
# Implement the logic to continuously capture and send video frames here
while True:
# frame_data = capture_and_encode_frame() # Implement this function
frame_data = generate_random_frame()
await websocket.send(frame_data)
await asyncio.sleep(0.033) # Adjust the frame rate as needed
async def create_video_streaming_server(self, video_id):
# Create and start a new WebSocket server for the specified video
port = self.next_port
self.next_port += 1 # Increment port number for the next server
server = await websockets.server.serve(
self.video_stream, "localhost", port
)
return server
async def stop_video_streaming_server(self, video_id):
if video_id in self.video_servers:
# Terminate and remove the video streaming server for the specified video
video_server = self.video_servers[video_id]
video_server.close()
await video_server.wait_closed()
del self.video_servers[video_id]
async def start_video_streaming_server():
async def video_stream(websocket, path):
# Continuously capture and send video frames here
while True:
frame_data = capture_and_encode_frame() # Implement this function
await websocket.send(frame_data)
await asyncio.sleep(0.033) # Adjust the frame rate as needed
start_server = websockets.server.serve(
video_stream, "localhost", 8766
) # Use a different port (e.g., 8766)
return await start_server
def ACTIONS_installDependency(dependency_names=None):
if dependency_names is None:
# return web.Response(text="No dependency name provided", status=400)
return {"error": "No dependency name provided"}
endlog.debug(f"Received Install Dependency request for {dependency_names}")
# reqs = []
resolved_names = [reqs_map.get(name, name) for name in dependency_names]
try:
run_command([Path(sys.executable), "-m", "pip", "install"] + resolved_names)
run_command(
[Path(sys.executable), "-m", "pip", "install"] + resolved_names
)
return {"success": True}
except Exception as e:
@@ -43,10 +145,54 @@ def ACTIONS_installDependency(dependency_names=None):
# break
def ACTIONS_getStyles(style_name=None):
from .nodes.conditions import StylesLoader
def ACTIONS_getUserImages(
mode: Literal["input", "output"],
count=200,
offset=0,
sort: str | None = None,
include_subfolders: bool = False,
):
# enabled = "MTB_EXPOSE" in os.environ
# if not enabled:
# return {"error": "Session not authorized to getInputs"}
styles = StylesLoader.options
imgs = {}
entry_dir = input_dir if mode == "input" else output_dir
supported = ["png", "jpg", "jpeg", "webp", "gif"]
entries = {}
patterns = build_glob_patterns(supported, recursive=include_subfolders)
entries = glob_multiple(entry_dir, patterns)
sort_mode = SortMode.from_str(sort)
if sort_mode:
sort_key = {
SortMode.MODIFIED: lambda x: x.stat().st_mtime,
SortMode.MODIFIED_REVERSE: lambda x: x.stat().st_mtime,
SortMode.NAME: lambda x: x.name,
SortMode.NAME_REVERSE: lambda x: x.name,
}.get(sort_mode)
if sort_key:
reverse = sort_mode in (SortMode.MODIFIED, SortMode.NAME_REVERSE)
entries = sorted(entries, key=sort_key, reverse=reverse)
imgs = {
img.name: (
f"/mtb/view?filename={img.name}&width=512&type={mode}&subfolder="
f"{img.parent.relative_to(entry_dir) if include_subfolders else ''}"
f"&preview=&rand={secrets.randbelow(424242)}"
)
for i, img in enumerate(entries)
if offset <= i < offset + count
}
return imgs
def ACTIONS_getStyles(style_name=None):
from .nodes.conditions import MTB_StylesLoader
styles = MTB_StylesLoader.options
match_list = ["name"]
if styles:
filtered_styles = {
@@ -55,7 +201,9 @@ def ACTIONS_getStyles(style_name=None):
if not key.startswith("__") and key not in match_list
}
if style_name:
return filtered_styles.get(style_name, {"error": "Style not found"})
return filtered_styles.get(
style_name, {"error": "Style not found"}
)
return filtered_styles
return {"error": "No styles found"}
@@ -75,7 +223,9 @@ def ACTIONS_saveStyle(data):
break
if not target:
endlog.warning(f"Could not determine the target file for {data.keys()}")
endlog.warning(
f"Could not determine the target file for {data.keys()}"
)
return {"error": "Could not determine the target file for the style"}
backup_file(target)
@@ -86,7 +236,7 @@ def ACTIONS_saveStyle(data):
csv_writer.writerow(row)
async def do_action(request) -> web.Response:
async def do_action(request: web.Request) -> web.Response:
endlog.debug("Init action request")
request_data = await request.json()
name = request_data.get("name")
@@ -98,26 +248,39 @@ async def do_action(request) -> web.Response:
method = globals().get(method_name)
if callable(method):
result = method(args) if args else method()
result = None
if args:
result = method(*args) if isinstance(args, list) else method(args)
else:
result = method()
endlog.debug(f"Action result: {result}")
return web.json_response({"result": result})
available_methods = [
attr[len("ACTIONS_") :] for attr in globals() if attr.startswith("ACTIONS_")
attr[len("ACTIONS_") :]
for attr in globals()
if attr.startswith("ACTIONS_")
]
return web.json_response(
{"error": "Invalid method name.", "available_methods": available_methods}
{
"error": "Invalid method name.",
"available_methods": available_methods,
}
)
# - HTML UTILS
def dependencies_button(name, dependencies):
def dependencies_button(name: str, dependencies: list[str]) -> str:
deps = ",".join([f"'{x}'" for x in dependencies])
return f"""
<button class="dependency-button" onclick="window.mtb_action('installDependency',[{deps}])">Install {name} deps</button>
<button
class="dependency-button"
onclick="window.mtb_action('installDependency',[{deps}])"
>Install {name} deps</button>
"""
@@ -127,7 +290,7 @@ def csv_editor():
style_files = {}
for file in inputs:
with open(file, "r", encoding="utf8") as f:
with open(file, encoding="utf8") as f:
parsed = csv.reader(f)
style_files[file.name] = []
for row in parsed:
@@ -137,7 +300,7 @@ def csv_editor():
html_out = """
<div id="style-editor">
<h1>Style Editor</h1>
"""
for current, styles in style_files.items():
current_out = f"<h3>{current}</h3>"
@@ -199,11 +362,14 @@ def render_tab_view(**kwargs):
"""
def add_foldable_region(title, content):
def add_foldable_region(title: str, content: str):
symbol_id = f"{title}-symbol"
return f"""
<div class='foldable'>
<div class='foldable-title' onclick="toggleFoldable('{title}', '{symbol_id}')">
<div
class='foldable-title'
onclick="toggleFoldable('{title}', '{symbol_id}')"
>
<span id='{symbol_id}' class='foldable-symbol'>&#9655;</span>
{title}
</div>
@@ -215,7 +381,9 @@ def add_foldable_region(title, content):
"""
def add_split_pane(left_content, right_content, vertical=True):
def add_split_pane(
left_content: str, right_content: str, *, vertical: bool = True
):
orientation = "vertical" if vertical else "horizontal"
return f"""
<div class="split-pane {orientation}">
@@ -235,7 +403,9 @@ def add_split_pane(left_content, right_content, vertical=True):
def add_dropdown(title, options):
option_str = "\n".join([f"<option value='{opt}'>{opt}</option>" for opt in options])
option_str = "\n".join(
[f"<option value='{opt}'>{opt}</option>" for opt in options]
)
return f"""
<select>
<option disabled selected>{title}</option>
@@ -244,21 +414,25 @@ def add_dropdown(title, options):
"""
def render_table(table_dict, sort=True, title=None):
table_dict = sorted(
def render_table(table_dict: dict[str, Any], sort=True, title=None):
table_list = sorted(
table_dict.items(), key=lambda item: item[0]
) # Sort the dictionary by keys
table_rows = ""
for name, item in table_dict:
for name, item in table_list:
if isinstance(item, dict):
if "dependencies" in item:
table_rows += f"<tr><td>{name}</td><td>"
table_rows += f"{dependencies_button(name,item['dependencies'])}"
table_rows += (
f"{dependencies_button(name,item['dependencies'])}"
)
table_rows += "</td></tr>"
else:
table_rows += f"<tr><td>{name}</td><td>{render_table(item)}</td></tr>"
table_rows += (
f"<tr><td>{name}</td><td>{render_table(item)}</td></tr>"
)
# elif isinstance(item, str):
# table_rows += f"<tr><td>{name}</td><td>{item}</td></tr>"
else:
@@ -277,12 +451,12 @@ def render_table(table_dict, sort=True, title=None):
<tbody>
{table_rows}
</tbody>
</table>
</table>
</div>
"""
def render_base_template(title, content):
def render_base_template(title: str, content: str):
github_icon_svg = """<svg xmlns="http://www.w3.org/2000/svg" fill="whitesmoke" height="3em" viewBox="0 0 496 512"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg>"""
return f"""
<!DOCTYPE html>
@@ -318,7 +492,9 @@ def render_base_template(title, content):
<header>
<a href="/">Back to Comfy</a>
<div class="mtb_logo">
<img src="https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873" alt="Comfy MTB Logo" height="70" width="128">
<img
src="https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873"
alt="Comfy MTB Logo" height="70" width="128">
<span class="title">Comfy MTB</span></div>
<a style="width:128px;text-align:center" href="https://www.github.com/melmass/comfy_mtb">
{github_icon_svg}
@@ -333,6 +509,6 @@ def render_base_template(title, content):
<!-- Shared footer content here -->
</footer>
</body>
</html>
"""
+247
View File
@@ -0,0 +1,247 @@
# NOTE: This file is only use for development you can ignore it
# NOTE: for CI it's easier to extract parts of my cli for now
const THREE_VERSION = "0.171.0"
# Update the external web extensions
export def "comfy mtb update-web" [] {
let async_dir = $"($env.COMFY_MTB)/web_async"
let three_base = $"https://cdn.jsdelivr.net/npm/three@($THREE_VERSION)"
let three = {
"." : [
"build/three.module.js",
"build/three.core.js",
],
three_addons/capabilities: [
"examples/jsm/capabilities/WebGPU.js",
"examples/jsm/controls/ArcballControls.js",
"examples/jsm/controls/DragControls.js",
"examples/jsm/controls/FirstPersonControls.js",
"examples/jsm/controls/FlyControls.js",
"examples/jsm/controls/MapControls.js",
"examples/jsm/controls/OrbitControls.js",
"examples/jsm/controls/PointerLockControls.js",
"examples/jsm/controls/TrackballControls.js",
"examples/jsm/controls/TransformControls.js",
],
three_addons/offscreen: [
"jank.js",
"offscreen.js",
"scene.js",
],
thee_addons/exporters : [
"examples/jsm/exporters/DRACOExporter.js",
"examples/jsm/exporters/EXRExporter.js",
"examples/jsm/exporters/GLTFExporter.js",
"examples/jsm/exporters/KTX2Exporter.js",
"examples/jsm/exporters/MMDExporter.js",
"examples/jsm/exporters/OBJExporter.js",
"examples/jsm/exporters/PLYExporter.js",
"examples/jsm/exporters/STLExporter.js",
"examples/jsm/exporters/USDZExporter.js"
],
three_addons/loaders : [
"examples/jsm/loaders/3DMLoader.js",
"examples/jsm/loaders/BVHLoader.js",
"examples/jsm/loaders/ColladaLoader.js",
"examples/jsm/loaders/DRACOLoader.js",
"examples/jsm/loaders/EXRLoader.js",
"examples/jsm/loaders/FBXLoader.js",
"examples/jsm/loaders/FontLoader.js",
"examples/jsm/loaders/GLTFLoader.js",
"examples/jsm/loaders/HDRCubeTextureLoader.js",
"examples/jsm/loaders/MaterialXLoader.js",
"examples/jsm/loaders/MTLLoader.js",
"examples/jsm/loaders/OBJLoader.js",
"examples/jsm/loaders/PCDLoader.js",
"examples/jsm/loaders/PDBLoader.js",
"examples/jsm/loaders/PLYLoader.js",
"examples/jsm/loaders/STLLoader.js",
"examples/jsm/loaders/UltraHDRLoader.js",
"examples/jsm/loaders/USDZLoader.js",
"examples/jsm/loaders/VOXLoader.js"
]
}
$three | items {|root,urls|
let dest = $async_dir | path join $root
mkdir $dest
$urls | par-each {|url|
let url = $"($three_base)/($url)"
let local = ($dest | path join ($url | path basename))
wget -c $url -O ($local)
}
}
# $three
}
def get_root [--clean] {
if $clean {
$env.COMFY_CLEAN_ROOT
} else {
$env.COMFY_ROOT
}
}
export def "comfy build-web" [] {
cd $env.COMFY_MTB
cd web_source
npm run build
cp dist/*.js ../web/dist
}
export def "comfy dev-web" [] {
cd $env.COMFY_MTB
cd web_source
npm run dev
}
# start the comfy server
export def "comfy start" [--clean,--old-ui, --listen] {
let root = get_root --clean=($clean)
cd $root
MTB_DEBUG=true python main.py --port 3000 ...(if $old_ui { ["--front-end-version", "Comfy-Org/ComfyUI_legacy_frontend@latest"]} else {[ --front-end-version Comfy-Org/ComfyUI_frontend@latest]}) --preview-method auto ...(if $listen {["--listen"]} else {[]})
}
# update comfy itself and merge master in current branch
export def "comfy update" [
--clean # ??
--rebase # Rebase instead of merge
] {
let root = get_root --clean=($clean)
let models = $"($root)/models"
let inputs = $"($root)/input"
cd $root
let branch_name = (git rev-parse --abbrev-ref HEAD | str trim)
print $"(ansi yellow_italic)Backing up and removing models symlinks(ansi reset)"
if not $clean {
cd $models
# find all symlinks
let links = (ls -la |
where not ($it.target | is-empty) |
select name target |
sort-by name)
if not ($links | is-empty) {
$links | save -f links.nuon
# remove them
open links.nuon | each {|p| rm $p.name }
}
} else {
rm $models
rm $inputs
}
cd $root
print $"(ansi yellow_italic)Checking out to master(ansi reset)"
git checkout master
print $"(ansi yellow_italic)Fetching and pulling remote updates(ansi reset)"
if ($clean) {
git fetch local master
git pull local master
} else {
git fetch
git pull
}
print $"(ansi yellow_italic)Back to our branch \(($branch_name)\)(ansi reset)"
git checkout -
if $rebase {
print $"(ansi yellow_italic)Rebasing changes(ansi reset)"
git rebase master
} else {
print $"(ansi yellow_italic)Merging changes(ansi reset)"
git merge master
}
print $"(ansi yellow_italic)Linking back the models(ansi reset)"
if not $clean {
cd $models
# resymlink them
open links.nuon | each {|p| link -a $p.target $p.name }
} else {
let master = (get_root)
link ($master | path join models) $models
link ($master | path join input) $inputs
}
let commit_count = (git rev-list --count $branch_name $"^origin/($branch_name)")
print $"(ansi green_bold)Update successful \(($commit_count) new commits\)(ansi reset)"
}
export def "comfy toggle_extensions" [--clean] {
let root = get_root --clean=($clean)
cd $root
cd custom_nodes
let exts = (ls | where type in ["dir","symlink"] | get name)
let choices = ($exts | input list -m "choose extension to toggle")
if ($choices | is-empty) {
return
}
print $choices
let filtered = $choices | wrap name | upsert enabled {|p| not ($p.name | str ends-with ".disabled")}
print $filtered
$filtered | each {|f|
let new_name = ($f.name | str replace ".disabled" "")
let new_name = if $f.enabled {
$"($new_name).disabled"
} else {
$new_name
}
print $"Moving ($f.name) to ($new_name)"
mv $f.name $new_name
}
}
# git pull all extensions
export def "comfy update_extensions" [--clean] {
let root = get_root --clean=($clean)
cd $root
cd custom_nodes
git multipull . -s -q
}
def --env path-add [pth] {
$env.PATH = ($env.PATH | append ($pth | path expand))
}
export-env {
$env.COMFY_MTB = ("." | path expand | str replace -a '\' '/')
# $env.CUDA_ROOT = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\'
$env.CUDA_HOME = $env.CUDA_ROOT
$env.COMFY_ROOT = ("../.." | path expand)
$env.COMFY_CLEAN_ROOT = ($env.COMFY_ROOT | path dirname | path join ComfyClean)
path-add 'C:/Portable/TensorRT-8.6.0.12/lib'
path-add ($env.CUDA_ROOT | path join bin)
overlay use ../../.venv/Scripts/activate.nu
}
File diff suppressed because one or more lines are too long
+49 -17
View File
@@ -7,11 +7,15 @@ base_log_level = logging.DEBUG if os.environ.get("MTB_DEBUG") else logging.INFO
# Custom object that discards the output
class NullWriter:
"""Custom object that discards the output."""
def write(self, text):
pass
class Formatter(logging.Formatter):
class ConsoleFormatter(logging.Formatter):
"""Formatter for console based log, using base ansi colors."""
grey = "\x1b[38;20m"
cyan = "\x1b[36;20m"
purple = "\x1b[35;20m"
@@ -19,24 +23,39 @@ class Formatter(logging.Formatter):
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
reset = "\x1b[0m"
# format = "%(asctime)s - [%(name)s] - %(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
format = "[%(name)s] | %(levelname)s -> %(message)s"
# format = ("%(asctime)s - [%(name)s] - %(levelname)s "
# "- %(message)s (%(filename)s:%(lineno)d)")
fmt = "[%(name)s] | %(levelname)s -> %(message)s"
FORMATS = {
logging.DEBUG: purple + format + reset,
logging.INFO: cyan + format + reset,
logging.WARNING: yellow + format + reset,
logging.ERROR: red + format + reset,
logging.CRITICAL: bold_red + format + reset,
logging.DEBUG: f"{purple}{fmt}{reset}",
logging.INFO: f"{cyan}{fmt}{reset}",
logging.WARNING: f"{yellow}{fmt}{reset}",
logging.ERROR: f"{red}{fmt}{reset}",
logging.CRITICAL: f"{bold_red}{fmt}{reset}",
}
def format(self, record):
log_fmt = self.FORMATS.get(record.levelno)
formatter = logging.Formatter(log_fmt)
return formatter.format(record)
def mklog(name, level=base_log_level):
class FileFormatter(logging.Formatter):
"""Formatter for file base logs."""
# File specific formatting
fmt = (
"%(asctime)s - [%(name)s] - "
"%(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
)
def __init__(self):
super().__init__(self.fmt, "%Y-%m-%d %H:%M:%S")
def mklog(name: str, level: int = base_log_level, log_file: str | None = None):
logger = logging.getLogger(name)
logger.setLevel(level)
@@ -45,9 +64,16 @@ def mklog(name, level=base_log_level):
ch = logging.StreamHandler()
ch.setLevel(level)
ch.setFormatter(Formatter())
ch.setFormatter(ConsoleFormatter())
logger.addHandler(ch)
if log_file:
# file handler
fh = logging.FileHandler(log_file)
fh.setLevel(level)
fh.setFormatter(FileFormatter())
logger.addHandler(fh)
# Disable log propagation
logger.propagate = False
@@ -58,24 +84,30 @@ def mklog(name, level=base_log_level):
log = mklog(__package__, base_log_level)
def log_user(arg):
print("\033[34mComfy MTB Utils:\033[0m {arg}")
def log_user(arg: str):
print(f"\033[34mComfy MTB Utils:\033[0m {arg}")
def get_summary(docstring):
def get_summary(docstring: str):
return docstring.strip().split("\n\n", 1)[0]
def blue_text(text):
def blue_text(text: str):
return f"\033[94m{text}\033[0m"
def cyan_text(text):
def cyan_text(text: str):
return f"\033[96m{text}\033[0m"
def get_label(label):
def get_label(label: str):
if label.startswith("MTB_"):
label = label[4:]
words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
words = re.findall(
r"(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z]))",
label,
)
reformatted_label = re.sub(r"([A-Z]+)", r" \1", label).strip()
words = reformatted_label.split()
return " ".join(words).strip()
+20 -3
View File
@@ -23,12 +23,20 @@
"Film Interpolation (mtb)": "Google Research FILM frame interpolation for large motion",
"Fit Number (mtb)": "Fit the input float using a source and target range",
"Float To Number (mtb)": "Node addon for the WAS Suite. Converts a \"comfy\" FLOAT to a NUMBER.",
"Geometry Box (mtb)": "Makes a Box 3D geometry",
"Geometry Decimater (mtb)": "Optimized the geometry to match the target number of triangles",
"Geometry Info (mtb)": "Retrieve information about a 3D geometry",
"Geometry Sphere (mtb)": "Makes a Sphere 3D geometry",
"Geometry Test (mtb)": "Fetches an Open3D data geometry",
"Get Batch From History (mtb)": "Very experimental node to load images from the history of the server.\n\n Queue items without output are ignored in the count.",
"Image Compare (mtb)": "Compare two images and return a difference image",
"Image Distort With Uv (mtb)": "Distorts an image based on a UV map.",
"Image Premultiply (mtb)": "Premultiply image with mask",
"Image Remove Background Rembg (mtb)": "Removes the background from the input using Rembg.",
"Image Resize Factor (mtb)": "Extracted mostly from WAS Node Suite, with a few edits (most notably multiple image support) and less features.",
"Image Tile Offset (mtb)": "Mimics an old photoshop technique to check for seamless textures",
"Image To Uv (mtb)": "Turn an image back into a UV map. (Shallow converter)",
"Image Tile Offset (mtb)": "Mimics an old photoshop technique to check for seamless textures",
"Int To Bool (mtb)": "Basic int to bool conversion",
"Int To Number (mtb)": "Node addon for the WAS Suite. Converts a \"comfy\" INT to a NUMBER.",
"Interpolate Clip Sequential (mtb)": null,
@@ -37,12 +45,14 @@
"Load Face Enhance Model (mtb)": "Loads a GFPGan or RestoreFormer model for face enhancement.",
"Load Face Swap Model (mtb)": "Loads a faceswap model",
"Load Film Model (mtb)": "Loads a FILM model",
"Load Geometry (mtb)": "Load a 3D geometry",
"Load Image From Url (mtb)": "Load an image from the given URL",
"Load Image Sequence (mtb)": "Load an image sequence from a folder. The current frame is used to determine which image to load.\n\n Usually used in conjunction with the `Primitive` node set to increment to load a sequence of images from a folder.\n Use -1 to load all matching frames as a batch.\n ",
"Mask To Image (mtb)": "Converts a mask (alpha) to an RGB image with a color and background",
"Model Patch Seamless (mtb)": "Experimental patcher to enable the circular padding mode of the sd model layers, requires a custom VAE",
"Math Expression (mtb)": "Node to evaluate a simple math expression string",
"Model Patch Seamless (mtb)": "Uses the stable diffusion 'hack' to infer seamless images by setting the model layers padding mode to circular (experimental)",
"Pick From Batch (mtb)": "Pick a specific number of images from a batch, either from the start or end.",
"Pick From Batch (mtb)": "Pick a specific number of images from a batch, either from the start or end.",
"Qr Code (mtb)": "Basic QR Code generator",
"Restore Face (mtb)": "Uses GFPGan to restore faces",
"Save Gif (mtb)": "Save the images from the batch as a GIF",
@@ -55,8 +65,15 @@
"String Replace (mtb)": "Basic string replacement",
"Styles Loader (mtb)": "Load csv files and populate a dropdown from the rows (\u00e0 la A111)",
"Text To Image (mtb)": "Utils to convert text to image using a font\n\n\n The tool looks for any .ttf file in the Comfy folder hierarchy.\n ",
"Transform Geometry (mtb)": "Transforms the input geometry",
"Transform Image (mtb)": "Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy\n\n\n it return a tensor representing the transformed images with the same shape as the input tensor\n ",
"Uncrop (mtb)": "Uncrops an image to a given bounding box\n\n The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type\n The BBOX input takes precedence over the tuple input",
"Unsplash Image (mtb)": "Unsplash Image given a keyword and a size",
"Vae Decode (mtb)": "Wrapper for the 2 core decoders but also adding the sd seamless hack, taken from: FlyingFireCo/tiled_ksampler"
}
"Uv Distort (mtb)": "Applies a polar coordinates or wave distortion to the UV map",
"Uv Map (mtb)": "Generates a UV Map tensor given a widht and height",
"Uv Remove Seams (mtb)": "Blends values near the UV borders to mitigate visible seams.",
"Uv Tile (mtb)": "Tiles the UV map based on the specified number of tiles.",
"Uv To Image (mtb)": "Converts the UV map to an image. (Shallow converter)",
"Vae Decode (mtb)": "Wrapper for the 2 core decoders (nomarl and tiled) but also adding the sd seamless hack, taken from: FlyingFireCo/tiled_ksampler"
}
+235
View File
@@ -0,0 +1,235 @@
from typing import TypedDict
import torch
import torchaudio
class AudioDict(TypedDict):
"""Comfy's representation of AUDIO data."""
sample_rate: int
waveform: torch.Tensor
AudioData = AudioDict | list[AudioDict]
class MtbAudio:
"""Base class for audio processing."""
@classmethod
def is_stereo(
cls,
audios: AudioData,
) -> bool:
if isinstance(audios, list):
return any(cls.is_stereo(audio) for audio in audios)
else:
return audios["waveform"].shape[1] == 2
@staticmethod
def resample(audio: AudioDict, common_sample_rate: int) -> AudioDict:
if audio["sample_rate"] != common_sample_rate:
resampler = torchaudio.transforms.Resample(
orig_freq=audio["sample_rate"], new_freq=common_sample_rate
)
return {
"sample_rate": common_sample_rate,
"waveform": resampler(audio["waveform"]),
}
else:
return audio
@staticmethod
def to_stereo(audio: AudioDict) -> AudioDict:
if audio["waveform"].shape[1] == 1:
return {
"sample_rate": audio["sample_rate"],
"waveform": torch.cat(
[audio["waveform"], audio["waveform"]], dim=1
),
}
else:
return audio
@classmethod
def preprocess_audios(
cls, audios: list[AudioDict]
) -> tuple[list[AudioDict], bool, int]:
max_sample_rate = max([audio["sample_rate"] for audio in audios])
resampled_audios = [
cls.resample(audio, max_sample_rate) for audio in audios
]
is_stereo = cls.is_stereo(audios)
if is_stereo:
audios = [cls.to_stereo(audio) for audio in resampled_audios]
return (audios, is_stereo, max_sample_rate)
class MTB_AudioCut(MtbAudio):
"""Basic audio cutter, values are in ms."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
"length": (
("FLOAT"),
{
"default": 1000.0,
"min": 0.0,
"max": 999999.0,
"step": 1,
},
),
"offset": (
("FLOAT"),
{"default": 0.0, "min": 0.0, "max": 999999.0, "step": 1},
),
},
}
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("cut_audio",)
CATEGORY = "mtb/audio"
FUNCTION = "cut"
def cut(self, audio: AudioDict, length: float, offset: float):
sample_rate = audio["sample_rate"]
start_idx = int(offset * sample_rate / 1000)
end_idx = min(
start_idx + int(length * sample_rate / 1000),
audio["waveform"].shape[-1],
)
cut_waveform = audio["waveform"][:, :, start_idx:end_idx]
return (
{
"sample_rate": sample_rate,
"waveform": cut_waveform,
},
)
class MTB_AudioStack(MtbAudio):
"""Stack/Overlay audio inputs (dynamic inputs).
- pad audios to the longest inputs.
- resample audios to the highest sample rate in the inputs.
- convert them all to stereo if one of the inputs is.
"""
@classmethod
def INPUT_TYPES(cls):
return {"required": {}}
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("stacked_audio",)
CATEGORY = "mtb/audio"
FUNCTION = "stack"
def stack(self, **kwargs: AudioDict) -> tuple[AudioDict]:
audios, is_stereo, max_rate = self.preprocess_audios(
list(kwargs.values())
)
max_length = max([audio["waveform"].shape[-1] for audio in audios])
padded_audios: list[torch.Tensor] = []
for audio in audios:
padding = torch.zeros(
(
1,
2 if is_stereo else 1,
max_length - audio["waveform"].shape[-1],
)
)
padded_audio = torch.cat([audio["waveform"], padding], dim=-1)
padded_audios.append(padded_audio)
stacked_waveform = torch.stack(padded_audios, dim=0).sum(dim=0)
return (
{
"sample_rate": max_rate,
"waveform": stacked_waveform,
},
)
class MTB_AudioSequence(MtbAudio):
"""Sequence audio inputs (dynamic inputs).
- adding silence_duration between each segment
can now also be negative to overlap the clips, safely bound
to the the input length.
- resample audios to the highest sample rate in the inputs.
- convert them all to stereo if one of the inputs is.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"silence_duration": (
("FLOAT"),
{"default": 0.0, "min": -999.0, "max": 999, "step": 0.01},
)
},
}
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("sequenced_audio",)
CATEGORY = "mtb/audio"
FUNCTION = "sequence"
def sequence(self, silence_duration: float, **kwargs: AudioDict):
audios, is_stereo, max_rate = self.preprocess_audios(
list(kwargs.values())
)
sequence: list[torch.Tensor] = []
for i, audio in enumerate(audios):
if i > 0:
if silence_duration > 0:
silence = torch.zeros(
(
1,
2 if is_stereo else 1,
int(silence_duration * max_rate),
)
)
sequence.append(silence)
elif silence_duration < 0:
overlap = int(abs(silence_duration) * max_rate)
previous_audio = sequence[-1]
overlap = min(
overlap,
previous_audio.shape[-1],
audio["waveform"].shape[-1],
)
if overlap > 0:
overlap_part = (
previous_audio[:, :, -overlap:]
+ audio["waveform"][:, :, :overlap]
)
sequence[-1] = previous_audio[:, :, :-overlap]
sequence.append(overlap_part)
audio["waveform"] = audio["waveform"][:, :, overlap:]
sequence.append(audio["waveform"])
sequenced_waveform = torch.cat(sequence, dim=-1)
return (
{
"sample_rate": max_rate,
"waveform": sequenced_waveform,
},
)
__nodes__ = [MTB_AudioSequence, MTB_AudioStack, MTB_AudioCut]
+351 -88
View File
@@ -1,4 +1,5 @@
from io import BytesIO
from typing import List, Literal, Optional, Tuple, Union
import cv2
import numpy as np
@@ -6,11 +7,11 @@ import torch
from PIL import Image
from ..log import log
from ..utils import apply_easing, pil2tensor
from .transform import TransformImage
from ..utils import EASINGS, apply_easing, hex_to_rgb, pil2tensor
from .transform import MTB_TransformImage
def hex_to_rgb(hex_color, bgr=False):
def hex_to_rgb(hex_color: str, bgr: bool = False):
hex_color = hex_color.lstrip("#")
if bgr:
return tuple(int(hex_color[i : i + 2], 16) for i in (4, 2, 0))
@@ -18,6 +19,157 @@ def hex_to_rgb(hex_color, bgr=False):
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
class MTB_BatchFloatMath:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"reverse": ("BOOLEAN", {"default": False}),
"operation": (
["add", "sub", "mul", "div", "pow", "abs"],
{"default": "add"},
),
}
}
RETURN_TYPES = ("FLOATS",)
CATEGORY = "mtb/utils"
FUNCTION = "execute"
def execute(self, reverse: bool, operation: str, **kwargs: list[float]):
res: list[float] = []
vals = list(kwargs.values())
if reverse:
vals = vals[::-1]
ref_count = len(vals[0])
for v in vals:
if len(v) != ref_count:
raise ValueError(
f"All values must have the same length (current: {len(v)}, ref: {ref_count}"
)
match operation:
case "add":
for i in range(ref_count):
result = sum(v[i] for v in vals)
res.append(result)
case "sub":
for i in range(ref_count):
result = vals[0][i] - sum(v[i] for v in vals[1:])
res.append(result)
case "mul":
for i in range(ref_count):
result = vals[0][i] * vals[1][i]
res.append(result)
case "div":
for i in range(ref_count):
result = vals[0][i] / vals[1][i]
res.append(result)
case "pow":
for i in range(ref_count):
result: float = vals[0][i] ** vals[1][i]
res.append(result)
case "abs":
for i in range(ref_count):
result = abs(vals[0][i])
res.append(result)
case _:
log.info(f"For now this mode ({operation}) is not implemented")
return (res,)
class MTB_BatchFloatNormalize:
"""Normalize the values in the list of floats"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"floats": ("FLOATS",)},
}
RETURN_TYPES = ("FLOATS",)
RETURN_NAMES = ("normalized_floats",)
CATEGORY = "mtb/batch"
FUNCTION = "execute"
def execute(
self,
floats: list[float],
):
min_value = min(floats)
max_value = max(floats)
normalized_floats = [
(x - min_value) / (max_value - min_value) for x in floats
]
log.debug(f"Floats: {floats}")
log.debug(f"Normalized Floats: {normalized_floats}")
return (normalized_floats,)
class MTB_BatchTimeWrap:
"""Remap a batch using a time curve (FLOATS)"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"target_count": ("INT", {"default": 25, "min": 2}),
"frames": ("IMAGE",),
"curve": ("FLOATS",),
},
}
RETURN_TYPES = ("IMAGE", "FLOATS")
RETURN_NAMES = ("image", "interpolated_floats")
CATEGORY = "mtb/batch"
FUNCTION = "execute"
def execute(
self, target_count: int, frames: torch.Tensor, curve: list[float]
):
"""Apply time warping to a list of video frames based on a curve."""
log.debug(f"Input frames shape: {frames.shape}")
log.debug(f"Curve: {curve}")
total_duration = sum(curve)
log.debug(f"Total duration: {total_duration}")
B, H, W, C = frames.shape
log.debug(f"Batch Size: {B}")
normalized_times = np.linspace(0, 1, target_count)
interpolated_curve = np.interp(
normalized_times, np.linspace(0, 1, len(curve)), curve
).tolist()
log.debug(f"Interpolated curve: {interpolated_curve}")
interpolated_frame_indices = [
(B - 1) * value for value in interpolated_curve
]
log.debug(f"Interpolated frame indices: {interpolated_frame_indices}")
rounded_indices = [
int(round(idx)) for idx in interpolated_frame_indices
]
rounded_indices = np.clip(rounded_indices, 0, B - 1)
# Gather frames based on interpolated indices
warped_frames = []
for index in rounded_indices:
warped_frames.append(frames[index].unsqueeze(0))
warped_tensor = torch.cat(warped_frames, dim=0)
log.debug(f"Warped frames shape: {warped_tensor.shape}")
return (warped_tensor, interpolated_curve)
class MTB_BatchMake:
"""Simply duplicates the input frame as a batch"""
@@ -92,7 +244,7 @@ class MTB_BatchShape:
bg_color = hex_to_rgb(bg_color)
shade_color = hex_to_rgb(shade_color)
res = []
for x in range(count):
for _x in range(count):
# Initialize an image canvas
canvas = np.full(
(image_height, image_width, 3), bg_color, dtype=np.uint8
@@ -108,7 +260,7 @@ class MTB_BatchShape:
bottom_right = (center[0] + half_size, center[1] + half_size)
cv2.rectangle(mask, top_left, bottom_right, 255, -1)
elif shape == "Circle":
cv2.circle(mask, center, shape_size // 2, 255, -1)
cv2.circle(mask, center, shape_size // 2, 255, -1) # type: ignore
elif shape == "Diamond":
pts = np.array(
[
@@ -118,7 +270,7 @@ class MTB_BatchShape:
[center[0] - shape_size // 2, center[1]],
]
)
cv2.fillPoly(mask, [pts], 255)
cv2.fillPoly(mask, [pts], 255) # type: ignore
elif shape == "Tube":
cv2.ellipse(
@@ -192,18 +344,21 @@ class MTB_BatchFloatAssemble:
def INPUT_TYPES(cls):
return {"required": {"reverse": ("BOOLEAN", {"default": False})}}
FUNCTION = "assemble_floats"
RETURN_TYPES = ("FLOATS",)
CATEGORY = "mtb/batch"
FUNCTION = "assemble_floats"
def assemble_floats(self, reverse: bool, **kwargs: list[float]):
res: list[float] = []
def assemble_floats(self, reverse, **kwargs):
res = []
if reverse:
for x in reversed(kwargs.values()):
res += x
if x:
res += x
else:
for x in kwargs.values():
res += x
if x:
res += x
return (res,)
@@ -219,7 +374,7 @@ class MTB_BatchFloat:
["Single", "Steps"],
{"default": "Steps"},
),
"count": ("INT", {"default": 1}),
"count": ("INT", {"default": 2}),
"min": ("FLOAT", {"default": 0.0, "step": 0.001}),
"max": ("FLOAT", {"default": 1.0, "step": 0.001}),
"easing": (
@@ -256,7 +411,18 @@ class MTB_BatchFloat:
RETURN_TYPES = ("FLOATS",)
CATEGORY = "mtb/batch"
def set_floats(self, mode, count, min, max, easing):
def set_floats(
self,
mode: Union[Literal["Steps"], Literal["Single"]] = "Steps",
count: int = 1,
min: float = 0.0, # noqa: A002
max: float = 1.0, # noqa: A002
easing: str = "Linear",
):
if mode == "Steps" and count == 1:
raise ValueError(
"Steps mode requires at least a count of 2 values"
)
keyframes = []
if mode == "Single":
keyframes = [min] * count
@@ -369,12 +535,12 @@ class MTB_Batch2dTransform:
self,
image: torch.Tensor,
border_handling: str,
constant_color: str,
x: list[float] | None = None,
y: list[float] | None = None,
zoom: list[float] | None = None,
angle: list[float] | None = None,
shear: list[float] | None = None,
constant_color: tuple,
x: Optional[List[float]] = None,
y=None,
zoom=None,
angle=None,
shear=None,
):
if all(
self.get_num_elements(param) <= 0
@@ -410,20 +576,21 @@ class MTB_Batch2dTransform:
count = len(values)
if count > 0 and count != image.shape[0]:
raise ValueError(
f"Length of {name} values ({count}) must match number of images ({image.shape[0]})"
f"Length of {name} values ({count}) must \
match number of images ({image.shape[0]})"
)
if count == 0:
keyframes[name] = [default_vals[name]] * image.shape[0]
transformer = TransformImage()
transformer = MTB_TransformImage()
res = [
transformer.transform(
image[i].unsqueeze(0),
keyframes["x"][i],
keyframes["y"][i],
keyframes["zoom"][i],
keyframes["angle"][i],
keyframes["shear"][i],
keyframes["x"][i], # type: ignore
keyframes["y"][i], # type: ignore
keyframes["zoom"][i], # type: ignore
keyframes["angle"][i], # type: ignore
keyframes["shear"][i], # type: ignore
border_handling,
constant_color,
)[0]
@@ -432,6 +599,66 @@ class MTB_Batch2dTransform:
return (torch.cat(res, dim=0),)
class MTB_BatchFloatFit:
"""Fit a list of floats using a source and target range"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"values": ("FLOATS", {"forceInput": True}),
"clamp": ("BOOLEAN", {"default": False}),
"auto_compute_source": ("BOOLEAN", {"default": False}),
"source_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
"source_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
"target_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
"target_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
"easing": (
EASINGS,
{"default": "Linear"},
),
}
}
FUNCTION = "fit_range"
RETURN_TYPES = ("FLOATS",)
CATEGORY = "mtb/batch"
DESCRIPTION = "Fit a list of floats using a source and target range"
def fit_range(
self,
values: list[float],
clamp: bool,
auto_compute_source: bool,
source_min: float,
source_max: float,
target_min: float,
target_max: float,
easing: str,
):
if auto_compute_source:
source_min = min(values)
source_max = max(values)
from .graph_utils import MTB_FitNumber
res = []
fit_number = MTB_FitNumber()
for value in values:
(transformed_value,) = fit_number.set_range(
value,
clamp,
source_min,
source_max,
target_min,
target_max,
easing,
)
res.append(transformed_value)
return (res,)
class MTB_PlotBatchFloat:
"""Plot floats"""
@@ -443,6 +670,7 @@ class MTB_PlotBatchFloat:
"height": ("INT", {"default": 768}),
"point_size": ("INT", {"default": 4}),
"seed": ("INT", {"default": 1}),
"start_at_zero": ("BOOLEAN", {"default": False}),
}
}
@@ -451,40 +679,55 @@ class MTB_PlotBatchFloat:
FUNCTION = "plot"
CATEGORY = "mtb/batch"
def plot(self, width, height, point_size, seed, **kwargs):
def plot(
self,
width: int,
height: int,
point_size: int,
seed: int,
start_at_zero: bool,
interactive_backend: bool = False,
**kwargs,
):
import matplotlib
matplotlib.use("Agg")
# NOTE: This is for notebook usage or tests, i.e not exposed to comfy that should always use Agg
if not interactive_backend:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(width / 100, height / 100), dpi=100)
fig.set_edgecolor("black")
fig.patch.set_facecolor("#2e2e2e")
fig.patch.set_facecolor("#2e2e2e") # type: ignore
# Setting background color and grid
ax.set_facecolor("#2e2e2e") # Dark gray background
ax.grid(color="gray", linestyle="-", linewidth=0.5, alpha=0.5)
# Finding global min and max across all lists for scaling the plot
global_min = min(min(values) for values in kwargs.values())
global_max = max(max(values) for values in kwargs.values())
all_values = [value for values in kwargs.values() for value in values]
global_min = min(all_values)
global_max = max(all_values)
# Color cycle to ensure each plot has a distinct color
colormap = plt.cm.get_cmap("viridis", len(kwargs))
color_normalization_factor = (
0.5 if len(kwargs) == 1 else (len(kwargs) - 1)
)
y_padding = 0.05 * (global_max - global_min)
ax.set_ylim(global_min - y_padding, global_max + y_padding)
# Plotting each list with a unique color
for i, (label, values) in enumerate(kwargs.items()):
color_value = i / color_normalization_factor
ax.plot(values, label=label, color=colormap(color_value))
max_length = max(len(values) for values in kwargs.values())
if start_at_zero:
x_values = np.linspace(0, max_length - 1, max_length)
else:
x_values = np.linspace(1, max_length, max_length)
ax.set_ylim(global_min, global_max) # Scaling the y-axis
ax.set_xlim(1, max_length) # Set X-axis limits
np.random.seed(seed)
colors = np.random.rand(len(kwargs), 3) # Generate random RGB values
for color, (label, values) in zip(colors, kwargs.items()):
ax.plot(x_values[: len(values)], values, label=label, color=color)
ax.legend(
title="Legend",
title_fontsize="large",
fontsize="medium",
edgecolor="black",
loc="best",
)
# Setting labels and title
@@ -548,10 +791,7 @@ class MTB_PlotBatchFloat:
error = int(dx / 2.0)
y = y1
ystep = None
if y1 < y2:
ystep = 1
else:
ystep = -1
ystep = 1 if y1 < y2 else -1
for x in range(x1, x2 + 1):
coord = (y, x) if is_steep else (x, y)
image[coord] = color
@@ -564,7 +804,8 @@ class MTB_PlotBatchFloat:
image[(x2, y2)] = color
DEFAULT_INTERPOLANT = lambda t: t * t * t * (t * (t * 6 - 15) + 10)
def _DEFAULT_INTERPOLANT(t):
return t * t * t * (t * (t * 6 - 15) + 10)
class MTB_BatchShake:
@@ -598,37 +839,40 @@ class MTB_BatchShake:
):
"""Generate a 2D numpy array of perlin noise.
Args:
shape: The shape of the generated array (tuple of two ints).
Args
----
- shape: The shape of the generated array (tuple of two ints).
This must be a multple of res.
res: The number of periods of noise to generate along each
- res: The number of periods of noise to generate along each
axis (tuple of two ints). Note shape must be a multiple of
res.
tileable: If the noise should be tileable along each axis
(tuple of two bools). Defaults to (False, False).
interpolant: The interpolation function, defaults to
- tileable: If the noise should be tileable along each axis
(tuple of two bools). Defaults to (False, False).
- interpolant: The interpolation function, defaults to
t*t*t*(t*(t*6 - 15) + 10).
Returns
-------
A numpy array of shape shape with the generated noise.
A numpy array of shape shape with the generated noise.
Raises
------
ValueError: If shape is not a multiple of res.
ValueError: If shape is not a multiple of res.
"""
interpolant = interpolant or DEFAULT_INTERPOLANT
interpolant = interpolant or _DEFAULT_INTERPOLANT
delta = (res[0] / shape[0], res[1] / shape[1])
d = (shape[0] // res[0], shape[1] // res[1])
grid = (
np.mgrid[0 : res[0] : delta[0], 0 : res[1] : delta[1]].transpose(
np.mgrid[0 : res[0] : delta[0], 0 : res[1] : delta[1]].transpose( # type: ignore
1, 2, 0
)
% 1
)
# Gradients
angles = 2 * np.pi * np.random.rand(res[0] + 1, res[1] + 1)
gradients = np.dstack((np.cos(angles), np.sin(angles)))
gradients = np.dstack((np.cos(angles), np.sin(angles))) # type: ignore
if tileable[0]:
gradients[-1, :] = gradients[0, :]
if tileable[1]:
@@ -639,11 +883,12 @@ class MTB_BatchShake:
g01 = gradients[: -d[0], d[1] :]
g11 = gradients[d[0] :, d[1] :]
# Ramps
n00 = np.sum(np.dstack((grid[:, :, 0], grid[:, :, 1])) * g00, 2)
n10 = np.sum(np.dstack((grid[:, :, 0] - 1, grid[:, :, 1])) * g10, 2)
n01 = np.sum(np.dstack((grid[:, :, 0], grid[:, :, 1] - 1)) * g01, 2)
n00 = np.sum(np.dstack((grid[:, :, 0], grid[:, :, 1])) * g00, 2) # type: ignore
n10 = np.sum(np.dstack((grid[:, :, 0] - 1, grid[:, :, 1])) * g10, 2) # type: ignore
n01 = np.sum(np.dstack((grid[:, :, 0], grid[:, :, 1] - 1)) * g01, 2) # type: ignore
n11 = np.sum(
np.dstack((grid[:, :, 0] - 1, grid[:, :, 1] - 1)) * g11, 2
np.dstack((grid[:, :, 0] - 1, grid[:, :, 1] - 1)) * g11, # type: ignore
2,
)
# Interpolation
t = interpolant(grid)
@@ -663,31 +908,32 @@ class MTB_BatchShake:
):
"""Generate a 2D numpy array of fractal noise.
Args:
shape: The shape of the generated array (tuple of two ints).
This must be a multiple of lacunarity**(octaves-1)*res.
res: The number of periods of noise to generate along each
axis (tuple of two ints). Note shape must be a multiple of
(lacunarity**(octaves-1)*res).
octaves: The number of octaves in the noise. Defaults to 1.
persistence: The scaling factor between two octaves.
lacunarity: The frequency factor between two octaves.
tileable: If the noise should be tileable along each axis
(tuple of two bools). Defaults to (True,True).
interpolant: The, interpolation function, defaults to
t*t*t*(t*(t*6 - 15) + 10).
Args
----
- shape: The shape of the generated array (tuple of two ints).
This must be a multiple of lacunarity**(octaves-1)*res.
- res: The number of periods of noise to generate along each
axis (tuple of two ints). Note shape must be a multiple of
(lacunarity**(octaves-1)*res).
- octaves: The number of octaves in the noise. Defaults to 1.
- persistence: The scaling factor between two octaves.
- lacunarity: The frequency factor between two octaves.
- tileable: If the noise should be tileable along each axis
(tuple of two bools). Defaults to (True,True).
- interpolant: The, interpolation function, defaults to
t*t*t*(t*(t*6 - 15) + 10).
Returns
-------
A numpy array of fractal noise and of shape shape generated by
combining several octaves of perlin noise.
A numpy array of fractal noise and of shape shape generated by
combining several octaves of perlin noise.
Raises
------
ValueError: If shape is not a multiple of
(lacunarity**(octaves-1)*res).
- `ValueError`:
If shape is not a multiple of (lacunarity**(octaves-1)*res).
"""
interpolant = interpolant or DEFAULT_INTERPOLANT
interpolant = interpolant or _DEFAULT_INTERPOLANT
noise = np.zeros(shape)
frequency = 1
@@ -704,8 +950,12 @@ class MTB_BatchShake:
return noise
def fbm(self, x, y, octaves):
# noise_2d = self.generate_fractal_noise_2d((256, 256), (8, 8), octaves)
# Now, extract a single noise value based on x and y, wrapping indices if necessary
# noise_2d = self.generate_fractal_noise_2d(
# (256, 256),
# (8, 8),
# octaves)
# Now, extract a single noise value based on x and y,
# wrapping indices if necessary
x_idx = int(x) % 256
y_idx = int(y) % 256
return self.noise_pattern[x_idx, y_idx]
@@ -729,7 +979,8 @@ class MTB_BatchShake:
(512, 512), (32, 32), (True, True)
)
# Assuming frame count is derived from the first dimension of images tensor
# Assuming frame count is derived from
# the first dimension of images tensor
frame_count = images.shape[0]
frequency = frequency / frequency_divider
@@ -753,11 +1004,14 @@ class MTB_BatchShake:
# np_position = np.array(
# [
# self.fbm(self.position_offset[0] + frame_num, time, octaves),
# self.fbm(self.position_offset[1] + frame_num, time, octaves),
# self.fbm(self.position_offset[0] +
# frame_num, time, octaves),
# self.fbm(self.position_offset[1] +
# frame_num, time, octaves),
# ]
# )
# np_rotation = self.fbm(self.rotation_offset[2] + frame_num, time, octaves)
# np_rotation = self.fbm(self.rotation_offset[2] +
# frame_num, time, octaves)
rot_idx = (self.rotation_offset[2] + frame_num) % 256
np_rotation = self.fbm(rot_idx, time, octaves)
@@ -775,14 +1029,19 @@ class MTB_BatchShake:
transform = MTB_Batch2dTransform()
log.debug(
f"Applying shaking with parameters: \nposition {position_amount_x}, {position_amount_y}\nrotation {rotation_amount}\nfrequency {frequency}\noctaves {octaves}"
f"Applying shaking with parameters: \n \
position {position_amount_x}, \
{position_amount_y}\nrotation {rotation_amount}\n \
frequency {frequency}\noctaves {octaves}"
)
# Apply shaking transformations to images
shaken_images = transform.transform_batch(
images,
border_handling="edge", # Assuming edge handling as default
constant_color="#000000", # Assuming black as default constant color
# Assuming edge handling as default
border_handling="edge",
# Assuming black as default constant color
constant_color="#000000", # type: ignore
x=x_translations,
y=y_translations,
angle=rotations,
@@ -798,7 +1057,11 @@ __nodes__ = [
MTB_BatchMake,
MTB_BatchFloatAssemble,
MTB_BatchFloatFill,
MTB_BatchFloatNormalize,
MTB_BatchMerge,
MTB_BatchShake,
MTB_PlotBatchFloat,
MTB_BatchTimeWrap,
MTB_BatchFloatFit,
MTB_BatchFloatMath,
]
+157 -15
View File
@@ -1,13 +1,131 @@
import csv, shutil
import csv
import shutil
from pathlib import Path
import folder_paths
import torch
from ..log import log
from ..utils import here
Conditioning = list[tuple[torch.Tensor, dict[str, torch.Tensor]]]
class InterpolateClipSequential:
def check_condition(conditioning: Conditioning):
has_cn = False
if len(conditioning) > 1:
log.warn(
"More than one conditioning was provided. Only the first one will be used."
)
first = conditioning[0]
cond, kwargs = first
log.debug("Conditioning Shape")
log.debug(cond.shape)
log.debug("Conditioning keys")
log.debug([f"\t{k} - {type(kwargs[k])}" for k in kwargs])
if "control" in kwargs:
log.debug("Conditioning contains a controlnet")
has_cn = True
if "pooled_output" not in kwargs:
raise ValueError(
"Conditioning is not valid. Missing 'pooled_output' key."
)
return has_cn
class MTB_InterpolateCondition:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"blend": (
"FLOAT",
{"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01},
),
},
}
RETURN_TYPES = ("CONDITIONING",)
CATEGORY = "mtb/conditioning"
FUNCTION = "execute"
def execute(
self, blend: float, **kwargs: Conditioning
) -> tuple[Conditioning]:
blend = max(0.0, min(1.0, blend))
conditions: list[Conditioning] = list(kwargs.values())
num_conditions = len(conditions)
if num_conditions < 2:
raise ValueError("At least two conditioning inputs are required.")
segment_length = 1.0 / (num_conditions - 1)
segment_index = min(int(blend // segment_length), num_conditions - 2)
local_blend = (
blend - (segment_index * segment_length)
) / segment_length
cond_from = conditions[segment_index]
cond_to = conditions[segment_index + 1]
from_cn = check_condition(cond_from)
to_cn = check_condition(cond_to)
if from_cn and to_cn:
raise ValueError(
"Interpolating conditions cannot both contain ControlNets"
)
try:
interpolated_condition = [
(1.0 - local_blend) * c_from + local_blend * c_to
for c_from, c_to in zip(
cond_from[0][0], cond_to[0][0], strict=False
)
]
except Exception as e:
print(f"Error during interpolation: {e}")
raise
pooled_from = cond_from[0][1].get(
"pooled_output",
torch.zeros_like(
next(iter(cond_from[0][1].values()), torch.tensor([]))
),
)
pooled_to = cond_to[0][1].get(
"pooled_output",
torch.zeros_like(
next(iter(cond_from[0][1].values()), torch.tensor([]))
),
)
interpolated_pooled = (
1.0 - local_blend
) * pooled_from + local_blend * pooled_to
res = {"pooled_output": interpolated_pooled}
if from_cn:
res["control"] = cond_from[0][1]["control"]
res["control_apply_to_uncond"] = cond_from[0][1][
"control_apply_to_uncond"
]
if to_cn:
res["control"] = cond_to[0][1]["control"]
res["control_apply_to_uncond"] = cond_to[0][1][
"control_apply_to_uncond"
]
return ([(torch.stack(interpolated_condition), res)],)
class MTB_InterpolateClipSequential:
@classmethod
def INPUT_TYPES(cls):
return {
@@ -28,7 +146,12 @@ class InterpolateClipSequential:
CATEGORY = "mtb/conditioning"
def interpolate_encodings_sequential(
self, base_text, text_to_replace, clip, interpolation_strength, **replacements
self,
base_text,
text_to_replace,
clip,
interpolation_strength,
**replacements,
):
log.debug(f"Received interpolation_strength: {interpolation_strength}")
@@ -63,20 +186,30 @@ class InterpolateClipSequential:
log.debug("Using the base text a the base blend")
# - Start with the base_text condition
tokens = clip.tokenize(base_text)
cond_from, pooled_from = clip.encode_from_tokens(tokens, return_pooled=True)
cond_from, pooled_from = clip.encode_from_tokens(
tokens, return_pooled=True
)
else:
base_replace = list(replacements.values())[segment_index - 1]
log.debug(f"Using {base_replace} a the base blend")
# - Start with the base_text condition replaced by the closest replacement
tokens = clip.tokenize(base_text.replace(text_to_replace, base_replace))
cond_from, pooled_from = clip.encode_from_tokens(tokens, return_pooled=True)
tokens = clip.tokenize(
base_text.replace(text_to_replace, base_replace)
)
cond_from, pooled_from = clip.encode_from_tokens(
tokens, return_pooled=True
)
replacement_text = list(replacements.values())[segment_index]
interpolated_text = base_text.replace(text_to_replace, replacement_text)
interpolated_text = base_text.replace(
text_to_replace, replacement_text
)
tokens = clip.tokenize(interpolated_text)
cond_to, pooled_to = clip.encode_from_tokens(tokens, return_pooled=True)
cond_to, pooled_to = clip.encode_from_tokens(
tokens, return_pooled=True
)
# - Linearly interpolate between the two conditions
interpolated_condition = (
@@ -86,10 +219,12 @@ class InterpolateClipSequential:
1.0 - local_strength
) * pooled_from + local_strength * pooled_to
return ([[interpolated_condition, {"pooled_output": interpolated_pooled}]],)
return (
[[interpolated_condition, {"pooled_output": interpolated_pooled}]],
)
class SmartStep:
class MTB_SmartStep:
"""Utils to control the steps start/stop of the KAdvancedSampler in percentage"""
@classmethod
@@ -136,7 +271,7 @@ def install_default_styles(force=False):
return dest_style
class StylesLoader:
class MTB_StylesLoader:
"""Load csv files and populate a dropdown from the rows (à la A111)"""
options = {}
@@ -148,16 +283,18 @@ class StylesLoader:
if not input_dir.exists():
install_default_styles()
if not (files := [f for f in input_dir.iterdir() if f.suffix == ".csv"]):
if not (
files := [f for f in input_dir.iterdir() if f.suffix == ".csv"]
):
log.warn(
"No styles found in the styles folder, place at least one csv file in the styles folder at the root of ComfyUI (for instance ComfyUI/styles/mystyle.csv)"
)
for file in files:
with open(file, "r", encoding="utf8") as f:
with open(file, encoding="utf8") as f:
parsed = csv.reader(f)
for i, row in enumerate(parsed):
log.debug(f"Adding style {row[0]}")
# log.debug(f"Adding style {row[0]}")
try:
name, positive, negative = (row + [None] * 3)[:3]
positive = positive or ""
@@ -193,4 +330,9 @@ class StylesLoader:
return (self.options[style_name][0], self.options[style_name][1])
__nodes__ = [SmartStep, StylesLoader, InterpolateClipSequential]
__nodes__ = [
MTB_SmartStep,
MTB_StylesLoader,
MTB_InterpolateClipSequential,
MTB_InterpolateCondition,
]
+1 -1
View File
@@ -24,4 +24,4 @@ class MTB_Constant:
return (kwargs.get("Value"),)
__nodes__ = [MTB_Constant]
# __nodes__ = [MTB_Constant]
+60 -5
View File
@@ -6,7 +6,7 @@ from ..log import log
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
class Bbox:
class MTB_Bbox:
"""The bounding box (BBOX) custom type used by other nodes"""
@classmethod
@@ -41,7 +41,55 @@ class Bbox:
return ((x, y, width, height),)
class BboxFromMask:
class MTB_SplitBbox:
"""Split the components of a bbox"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"bbox": ("BBOX",)},
}
CATEGORY = "mtb/crop"
FUNCTION = "split_bbox"
RETURN_TYPES = ("INT", "INT", "INT", "INT")
RETURN_NAMES = ("x", "y", "width", "height")
def split_bbox(self, bbox):
return (bbox[0], bbox[1], bbox[2], bbox[3])
class MTB_UpscaleBboxBy:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"bbox": ("BBOX",),
"scale": ("FLOAT", {"default": 1.0}),
},
}
CATEGORY = "mtb/crop"
RETURN_TYPES = ("BBOX",)
FUNCTION = "upscale"
def upscale(
self, bbox: tuple[int, int, int, int], scale: float
) -> tuple[tuple[int, int, int, int]]:
x, y, width, height = bbox
# scaled = (x * scale, y * scale, width * scale, height * scale)
scaled = (
int(x * scale),
int(y * scale),
int(width * scale),
int(height * scale),
)
return (scaled,)
class MTB_BboxFromMask:
"""From a mask extract the bounding box"""
@classmethod
@@ -110,7 +158,7 @@ class BboxFromMask:
)
class Crop:
class MTB_Crop:
"""Crops an image and an optional mask to a given bounding box
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
@@ -218,7 +266,7 @@ def bbox_to_region(bbox, target_size=None):
return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
class Uncrop:
class MTB_Uncrop:
"""Uncrops an image to a given bounding box
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
@@ -324,4 +372,11 @@ class Uncrop:
return (pil2tensor(out_images),)
__nodes__ = [BboxFromMask, Bbox, Crop, Uncrop]
__nodes__ = [
MTB_BboxFromMask,
MTB_Bbox,
MTB_Crop,
MTB_Uncrop,
MTB_SplitBbox,
MTB_UpscaleBboxBy,
]
+59 -2
View File
@@ -1,5 +1,7 @@
import json
from ..log import log
def deserialize_curve(curve):
if isinstance(curve, str):
@@ -13,7 +15,7 @@ def serialize_curve(curve):
return curve
class MTB_Curve:
class MTBCurve:
"""A basic FLOAT_CURVE input node."""
@classmethod
@@ -30,7 +32,62 @@ class MTB_Curve:
CATEGORY = "mtb/curve"
def do_curve(self, curve):
log.debug(f"Curve: {curve}")
return (curve,)
__nodes__ = [MTB_Curve]
class MTB_CurveToFloat:
"""Convert a FLOAT_CURVE to a FLOAT or FLOATS"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"curve": ("FLOAT_CURVE", {"forceInput": True}),
"steps": ("INT", {"default": 10, "min": 2}),
},
}
RETURN_TYPES = ("FLOATS", "FLOAT")
FUNCTION = "do_curve"
CATEGORY = "mtb/curve"
def do_curve(self, curve, steps):
log.debug(f"Curve: {curve}")
# sort by x (should be handled by the widget)
sorted_points = sorted(curve.items(), key=lambda item: item[1]["x"])
# Extract X and Y values
x_values = [point[1]["x"] for point in sorted_points]
y_values = [point[1]["y"] for point in sorted_points]
# Calculate step size
step_size = (max(x_values) - min(x_values)) / (steps - 1)
# Interpolate Y values for each step
interpolated_y_values = []
for step in range(steps):
current_x = min(x_values) + step_size * step
# Find the indices of the two points between which the current_x falls
idx1 = max(idx for idx, x in enumerate(x_values) if x <= current_x)
idx2 = min(idx for idx, x in enumerate(x_values) if x >= current_x)
# If the current_x matches one of the points, no interpolation is needed
if current_x == x_values[idx1]:
interpolated_y_values.append(y_values[idx1])
elif current_x == x_values[idx2]:
interpolated_y_values.append(y_values[idx2])
else:
# Interpolate Y value using linear interpolation
y1 = y_values[idx1]
y2 = y_values[idx2]
x1 = x_values[idx1]
x2 = x_values[idx2]
interpolated_y = y1 + (y2 - y1) * (current_x - x1) / (x2 - x1)
interpolated_y_values.append(interpolated_y)
return (interpolated_y_values, interpolated_y_values)
__nodes__ = [MTBCurve, MTB_CurveToFloat]
+54 -25
View File
@@ -1,34 +1,26 @@
import base64
import io
import json
from pathlib import Path
from typing import Optional
import folder_paths
import open3d as o3d
import torch
from ..log import log
from ..utils import tensor2pil
from ..utils import mesh_to_json, tensor2b64
# region processors
def process_tensor(tensor):
def process_tensor(tensor: torch.Tensor):
log.debug(f"Tensor: {tensor.shape}")
image = tensor2pil(tensor)
b64_imgs = []
for im in image:
buffered = io.BytesIO()
im.save(buffered, format="PNG")
b64_imgs.append(
"data:image/png;base64,"
+ base64.b64encode(buffered.getvalue()).decode("utf-8")
)
return {"b64_images": b64_imgs}
return {"b64_images": tensor2b64(tensor)}
def process_list(anything):
text = []
def process_list(anything: list[object]) -> dict[str, list[str]]:
text: list[str] = []
if not anything:
return {"text": []}
@@ -40,7 +32,7 @@ def process_list(anything):
):
text.append(
"List of List of Tensors: "
f"{first_element[0].shape} (x{len(anything)})"
+ f"{first_element[0].shape} (x{len(anything)})"
)
elif isinstance(first_element, torch.Tensor):
@@ -48,23 +40,33 @@ def process_list(anything):
f"List of Tensors: {first_element.shape} (x{len(anything)})"
)
else:
text.append(f"Array: {anything}")
text.append(f"Array ({len(anything)}): {anything}")
return {"text": text}
def process_dict(anything):
text = []
def process_dict(anything: dict[str, dict[str, any]]) -> dict[str, str]:
if "mesh" in anything:
m = {"geometry": {}}
m["geometry"]["mesh"] = mesh_to_json(anything["mesh"])
if "material" in anything:
m["geometry"]["material"] = anything["material"]
return m
res = []
if "samples" in anything:
is_empty = (
"(empty)" if torch.count_nonzero(anything["samples"]) == 0 else ""
)
text.append(f"Latent Samples: {anything['samples'].shape} {is_empty}")
res.append(f"Latent Samples: {anything['samples'].shape} {is_empty}")
else:
text.append(json.dumps(anything, indent=2))
return {"text": text}
def process_bool(anything):
def process_bool(anything: bool) -> dict[str, str]:
return {"text": ["True" if anything else "False"]}
@@ -72,6 +74,11 @@ def process_text(anything):
return {"text": [str(anything)]}
# NOT USED ANYMORE
def process_geometry(anything):
return {"geometry": [mesh_to_json(anything)]}
# endregion
@@ -94,7 +101,7 @@ class MTB_Debug:
def do_debug(self, output_to_console: bool, **kwargs):
output = {
"ui": {"b64_images": [], "text": []},
"ui": {"b64_images": [], "text": [], "geometry": []},
# "result": ("A"),
}
@@ -103,17 +110,39 @@ class MTB_Debug:
list: process_list,
dict: process_dict,
bool: process_bool,
o3d.geometry.Geometry: process_geometry,
}
if output_to_console:
for k, v in kwargs.items():
print(f"{k}: {v}")
log.info(f"{k}: {v}")
for anything in kwargs.values():
processor = processors.get(type(anything), process_text)
processor = processors.get(type(anything))
if processor is None:
if isinstance(anything, o3d.geometry.Geometry):
processor = process_geometry
else:
processor = process_text
log.debug(
f"Processing: {anything} with processor: {processor.__name__} for type {type(anything)}"
)
processed_data = processor(anything)
for ui_key, ui_value in processed_data.items():
output["ui"][ui_key].extend(ui_value)
if isinstance(ui_value, list):
output["ui"][ui_key].extend(ui_value)
else:
output["ui"][ui_key].append(ui_value)
# log.debug(
# f"Processed input {k}, found {len(processed_data.get('b64_images', []))} images and {len(processed_data.get('text', []))} text items."
# )
if output_to_console:
from rich.console import Console
cons = Console()
cons.print("OUTPUT:")
cons.print(output)
return output
+22 -3
View File
@@ -69,7 +69,26 @@ def color_to_normals(
if not model or not model.exists():
raise ModelNotFound(f"deepbump ({model})")
ort_session = ort.InferenceSession(model)
providers = [
"TensorrtExecutionProvider",
"CUDAExecutionProvider",
"CoreMLProvider",
"CPUExecutionProvider",
]
available_providers = [
provider
for provider in providers
if provider in ort.get_available_providers()
]
if not available_providers:
raise RuntimeError(
"No valid ONNX Runtime providers available on this machine."
)
log.debug(f"Using ONNX providers: {available_providers}")
ort_session = ort.InferenceSession(
model.as_posix(), providers=available_providers
)
# Predict normal map for each tile
log.debug("DeepBump Color → Normals : generating")
@@ -303,7 +322,7 @@ def normals_to_height(normals_img, seamless, progress_callback):
# - ADDON
class DeepBump:
class MTB_DeepBump:
"""Normal & height maps generation from single pictures"""
@classmethod
@@ -386,4 +405,4 @@ class DeepBump:
return (torch.cat(out_images, dim=0),)
__nodes__ = [DeepBump]
__nodes__ = [MTB_DeepBump]
+43 -27
View File
@@ -1,6 +1,4 @@
import os
from pathlib import Path
from typing import Tuple
import comfy
import comfy.utils
@@ -9,14 +7,13 @@ import folder_paths
import numpy as np
import torch
from comfy import model_management
from gfpgan import GFPGANer
from PIL import Image
from ..log import NullWriter, log
from ..utils import get_model_path, np2tensor, pil2tensor, tensor2np
class LoadFaceEnhanceModel:
class MTB_LoadFaceEnhanceModel:
"""Loads a GFPGan or RestoreFormer model for face enhancement."""
def __init__(self) -> None:
@@ -37,15 +34,12 @@ class LoadFaceEnhanceModel:
fr_models_path, um_models_path = cls.get_models_root()
if fr_models_path is None and um_models_path is None:
log.warning("Face restoration models not found.")
if not hasattr(cls, "_warned"):
log.warning("Face restoration models not found.")
cls._warned = True
return []
if not fr_models_path.exists():
# log.warning(
# f"No Face Restore checkpoints found at {fr_models_path} (if you've used mtb before these checkpoints were saved in upscale_models before)"
# )
# log.warning(
# "For now we fallback to upscale_models but this will be removed in a future version"
# )
# - fallback to upscale_models
if um_models_path.exists():
return [
x
@@ -79,8 +73,11 @@ class LoadFaceEnhanceModel:
RETURN_NAMES = ("model",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
DEPRECATED = True
def load_model(self, model_name, upscale=2, bg_upsampler=None):
from gfpgan import GFPGANer
basic = "RestoreFormer" not in model_name
fr_root, um_root = self.get_models_root()
@@ -120,7 +117,7 @@ class BGUpscaleWrapper:
tile = 128 + 64
overlap = 8
imgt = np2tensor(img)
imgt = pil2tensor(img)
imgt = imgt.movedim(-1, -3).to(device)
steps = imgt.shape[0] * comfy.utils.get_tiled_scale_steps(
@@ -150,10 +147,7 @@ class BGUpscaleWrapper:
return (tensor2np(s)[0],)
import sys
class RestoreFace:
class MTB_RestoreFace:
"""Uses GFPGan to restore faces"""
def __init__(self) -> None:
@@ -162,6 +156,7 @@ class RestoreFace:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "restore"
CATEGORY = "mtb/facetools"
DEPRECATED = True
@classmethod
def INPUT_TYPES(cls):
@@ -176,22 +171,33 @@ class RestoreFace:
# Adjustable weights
"weight": ("FLOAT", {"default": 0.5}),
"save_tmp_steps": ("BOOLEAN", {"default": True}),
}
},
"optional": {
"preserve_alpha": ("BOOLEAN", {"default": True}),
},
}
def do_restore(
self,
image: torch.Tensor,
model: GFPGANer,
model,
aligned,
only_center_face,
weight,
save_tmp_steps,
preserve_alpha: bool = False,
) -> torch.Tensor:
pimage = tensor2np(image)[0]
width, height = pimage.shape[1], pimage.shape[0]
source_img = cv2.cvtColor(np.array(pimage), cv2.COLOR_RGB2BGR)
alpha_channel = None
if (
preserve_alpha and image.size(-1) == 4
): # Check if the image has an alpha channel
alpha_channel = pimage[:, :, 3]
pimage = pimage[:, :, :3] # Remove alpha channel for processing
sys.stdout = NullWriter()
cropped_faces, restored_faces, restored_img = model.enhance(
source_img,
@@ -210,22 +216,28 @@ class RestoreFace:
)
output = None
if restored_img is not None:
output = Image.fromarray(
cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
)
# imwrite(restored_img, save_restore_path)
restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
output = Image.fromarray(restored_img)
return pil2tensor(output)
if alpha_channel is not None:
alpha_resized = Image.fromarray(alpha_channel).resize(
output.size, Image.LANCZOS
)
output.putalpha(alpha_resized)
# imwrite(restored_img, save_restore_path)
return pil2tensor(output)
log.warning("No restored image found")
def restore(
self,
image: torch.Tensor,
model: GFPGANer,
model,
aligned=False,
only_center_face=False,
weight=0.5,
save_tmp_steps=True,
) -> Tuple[torch.Tensor]:
preserve_alpha: bool = False,
) -> tuple[torch.Tensor]:
out = [
self.do_restore(
image[i],
@@ -234,10 +246,14 @@ class RestoreFace:
only_center_face,
weight,
save_tmp_steps,
preserve_alpha,
)
for i in range(image.size(0))
]
if len(out) == 0:
raise ValueError("No faces restored")
print(f"Restored {len(out)} faces")
return (torch.cat(out, dim=0),)
def get_step_image_path(self, step, idx):
@@ -259,7 +275,7 @@ class RestoreFace:
self, cropped_faces, restored_faces, height, width
):
for idx, (cropped_face, restored_face) in enumerate(
zip(cropped_faces, restored_faces)
zip(cropped_faces, restored_faces, strict=False)
):
face_id = idx + 1
file = self.get_step_image_path("cropped_faces", face_id)
@@ -275,4 +291,4 @@ class RestoreFace:
cv2.imwrite(file, cmp_img)
__nodes__ = [RestoreFace, LoadFaceEnhanceModel]
__nodes__ = [MTB_RestoreFace, MTB_LoadFaceEnhanceModel]
+22 -9
View File
@@ -2,7 +2,6 @@
# region imports
import sys
from pathlib import Path
from typing import List, Optional, Set, Union
import comfy.model_management as model_management
import cv2
@@ -22,7 +21,7 @@ from ..utils import download_antelopev2, get_model_path, pil2tensor, tensor2pil
log = mklog(__name__)
class LoadFaceAnalysisModel:
class MTB_LoadFaceAnalysisModel:
"""Loads a face analysis model"""
models = []
@@ -41,6 +40,7 @@ class LoadFaceAnalysisModel:
RETURN_TYPES = ("FACE_ANALYSIS_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
DEPRECATED = True
def load_model(self, faceswap_model: str):
if faceswap_model == "antelopev2":
@@ -53,7 +53,7 @@ class LoadFaceAnalysisModel:
return (face_analyser,)
class LoadFaceSwapModel:
class MTB_LoadFaceSwapModel:
"""Loads a faceswap model"""
@staticmethod
@@ -78,6 +78,7 @@ class LoadFaceSwapModel:
RETURN_TYPES = ("FACESWAP_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
DEPRECATED = True
def load_model(self, faceswap_model: str):
model_path = get_model_path("insightface", faceswap_model)
@@ -97,7 +98,7 @@ class LoadFaceSwapModel:
# region roop node
class FaceSwap:
class MTB_FaceSwap:
"""Face swap using deepinsight/insightface models"""
model = None
@@ -119,12 +120,15 @@ class FaceSwap:
),
"faceswap_model": ("FACESWAP_MODEL", {"default": "None"}),
},
"optional": {},
"optional": {
"preserve_alpha": ("BOOLEAN", {"default": True}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "swap"
CATEGORY = "mtb/facetools"
DEPRECATED = True
def swap(
self,
@@ -133,11 +137,18 @@ class FaceSwap:
faces_index: str,
faceanalysis_model,
faceswap_model,
preserve_alpha=False,
):
def do_swap(img):
model_management.throw_exception_if_processing_interrupted()
img = tensor2pil(img)[0]
ref = tensor2pil(reference)[0]
alpha_channel = None
if preserve_alpha and img.mode == "RGBA":
alpha_channel = img.getchannel("A")
img = img.convert("RGB")
face_ids = {
int(x)
for x in faces_index.strip(",").split(",")
@@ -148,6 +159,8 @@ class FaceSwap:
faceanalysis_model, ref, img, faceswap_model, face_ids
)
sys.stdout = sys.__stdout__
if alpha_channel:
swapped.putalpha(alpha_channel)
return pil2tensor(swapped)
batch_count = image.size(0)
@@ -194,10 +207,10 @@ def get_face_single(
def swap_face(
face_analyser,
source_img: Union[Image.Image, List[Image.Image]],
target_img: Union[Image.Image, List[Image.Image]],
source_img: Image.Image | list[Image.Image],
target_img: Image.Image | list[Image.Image],
face_swapper_model,
faces_index: Optional[Set[int]] = None,
faces_index: set[int] | None = None,
) -> Image.Image:
if faces_index is None:
faces_index = {0}
@@ -239,4 +252,4 @@ def swap_face(
# endregion face swap utils
__nodes__ = [FaceSwap, LoadFaceSwapModel, LoadFaceAnalysisModel]
__nodes__ = [MTB_FaceSwap, MTB_LoadFaceSwapModel, MTB_LoadFaceAnalysisModel]
+3 -3
View File
@@ -1,8 +1,8 @@
import torch
class MTB_FilterZ:
"""Filters an image based on a depth map"""
class MTBFilterZ:
"""Filters an image based on a depth map."""
@classmethod
def INPUT_TYPES(cls):
@@ -66,4 +66,4 @@ class MTB_FilterZ:
return (out_img,)
__nodes__ = [MTB_FilterZ]
__nodes__ = [MTBFilterZ]
+34 -78
View File
@@ -1,8 +1,7 @@
import qrcode
from PIL import Image
from ..log import log
from ..utils import comfy_dir, font_path, pil2tensor
from ..utils import comfy_dir, create_uv_map_tensor, font_path, pil2tensor
# class MtbExamples:
# """MTB Example Images"""
@@ -52,7 +51,7 @@ from ..utils import comfy_dir, font_path, pil2tensor
# return m.digest().hex()
class UnsplashImage:
class MTB_UnsplashImage:
"""Unsplash Image given a keyword and a size"""
@classmethod
@@ -113,76 +112,6 @@ class UnsplashImage:
return (None,)
class QrCode:
"""Basic QR Code generator"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"url": ("STRING", {"default": "https://www.github.com"}),
"width": (
"INT",
{"default": 256, "max": 8096, "min": 0, "step": 1},
),
"height": (
"INT",
{"default": 256, "max": 8096, "min": 0, "step": 1},
),
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
"box_size": (
"INT",
{"default": 10, "max": 8096, "min": 0, "step": 1},
),
"border": (
"INT",
{"default": 4, "max": 8096, "min": 0, "step": 1},
),
"invert": (("BOOLEAN",), {"default": False}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_qr"
CATEGORY = "mtb/generate"
def do_qr(
self, url, width, height, error_correct, box_size, border, invert
):
log.warning(
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
)
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
error_correct = qrcode.constants.ERROR_CORRECT_L
elif error_correct == "M":
error_correct = qrcode.constants.ERROR_CORRECT_M
elif error_correct == "Q":
error_correct = qrcode.constants.ERROR_CORRECT_Q
else:
error_correct = qrcode.constants.ERROR_CORRECT_H
qr = qrcode.QRCode(
version=1,
error_correction=error_correct,
box_size=box_size,
border=border,
)
qr.add_data(url)
qr.make(fit=True)
back_color = (255, 255, 255) if invert else (0, 0, 0)
fill_color = (0, 0, 0) if invert else (255, 255, 255)
code = img = qr.make_image(
back_color=back_color, fill_color=fill_color
)
# that we now resize without filtering
code = code.resize((width, height), Image.NEAREST)
return (pil2tensor(code),)
def bbox_dim(bbox):
left, upper, right, lower = bbox
width = right - left
@@ -202,7 +131,7 @@ class MTB_TextToImage:
fonts = {}
DESCRIPTION = """# Text to Image
This node look for any font files in comfy_dir/fonts.
This node look for any font files in comfy_dir/fonts.
by default it fallsback to a default font.
![img](https://i.imgur.com/3GT92hy.gif)
@@ -264,11 +193,11 @@ by default it fallsback to a default font.
),
"color": (
"COLOR",
{"default": "black"},
{"default": "#000000"},
),
"background": (
"COLOR",
{"default": "white"},
{"default": "#FFFFFF"},
),
"h_align": (("left", "center", "right"), {"default": "left"}),
"v_align": (("top", "center", "bottom"), {"default": "top"}),
@@ -363,9 +292,36 @@ by default it fallsback to a default font.
return (pil2tensor(img),)
class MTB_UvMap:
"""Generates a UV Map tensor given a widht and height"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"width": (
"INT",
{"default": 512, "min": 1, "max": 8096, "step": 1},
),
"height": (
"INT",
{"default": 512, "min": 1, "max": 8096, "step": 1},
),
}
}
RETURN_TYPES = ("UV_MAP",)
RETURN_NAMES = ("uv_map",)
FUNCTION = "create_uv_map"
CATEGORY = "mtb/generate"
def create_uv_map(self, width, height):
return (create_uv_map_tensor(width, height),)
__nodes__ = [
QrCode,
UnsplashImage,
MTB_UnsplashImage,
MTB_TextToImage,
MTB_UvMap,
# MtbExamples,
]
+576
View File
@@ -0,0 +1,576 @@
import os
import numpy as np
import open3d as o3d
from ..utils import (
create_box,
get_transformation_matrix,
log,
spread_geo,
tensor2b64,
)
# create_grid,
# create_sphere,
# create_torus,
# mesh_to_json,
# json_to_mesh
# rotate_mesh,
# euler_to_rotation_matrix,
# class GeoPrimitive:
# """Primitive 3D geometry"""
# @classmethod
# def INPUT_TYPES(cls):
# return {
# "required": {
# "kind": (["Box", "Sphere", "Cylinder", "Torus"], {"default": "Box"})
# }
# }
# RETURN_TYPES = ("UV_MAP",)
# RETURN_NAMES = ("uv_map",)
# FUNCTION = "distort_uvs"
# CATEGORY = "mtb/uv"
def default_material(color=None):
return {
"color": color or "#00ff00",
"roughness": 1.0,
"metalness": 0.0,
"emissive": "#000000",
"displacementScale": 1.0,
"displacementMap": None,
}
class MTB_Camera:
"""Make a Camera."""
@classmethod
def INPUT_TYPES(cls):
base = default_material()
return {
"required": {
"color": ("COLOR", {"default": base["color"]}),
"roughness": (
"FLOAT",
{
"default": base["roughness"],
"min": 0.005,
"max": 4.0,
"step": 0.01,
},
),
"flatShading": ("BOOLEAN",),
"metalness": (
"FLOAT",
{
"default": base["metalness"],
"min": 0.0,
"max": 1.0,
"step": 0.01,
},
),
"emissive": ("COLOR", {"default": base["emissive"]}),
"displacementScale": (
"FLOAT",
{"default": 1.0, "min": -10.0, "max": 10.0},
),
},
"optional": {"displacementMap": ("IMAGE",)},
}
RETURN_TYPES = ("CAMERA",)
RETURN_NAMES = ("camera",)
FUNCTION = "make_camera"
CATEGORY = "mtb/3D"
def make_camera(self, **kwargs):
return (kwargs,)
class MTB_GeometryDraw:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"geometry": ("GEOMETRY",),
},
"optional": {
"camera": ("CAMERA",),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("rendered_image",)
FUNCTION = "render"
CATEGORY = "mtb/3D"
def render(self, geometry, camera):
mesh, material = spread_geo(geometry)
o3d.visualization.draw_geometries([mesh], **camera)
# class MTB_RGBD_Image:
# @classmethod
# def INPUT_TYPES(cls):
# return {
# "required": {
# "image": ("IMAGE",),
# "depth": ("IMAGE",),
# }
# }
# RETURN_TYPES = ("RGBD_IMAGE",)
# RETURN_NAMES = ("rgbd",)
# FUNCTION = "make_rgbd"
# CATEGORY = "mtb/3D"
# def make_rgbd(self, image, depth):
# color_raw = o3d.io.read_image("../../test_data/RGBD/color/00000.jpg")
# depth_raw = o3d.io.read_image("../../test_data/RGBD/depth/00000.png")
# rgbd_image = o3d.geometry.RGBDImage.create_from_color_and_depth(
# color_raw, depth_raw
# )
# print(rgbd_image)
class MTB_GeometryMaterial:
"""Make a std material."""
@classmethod
def INPUT_TYPES(cls):
base = default_material()
return {
"required": {
"color": ("COLOR", {"default": base["color"]}),
"roughness": (
"FLOAT",
{
"default": base["roughness"],
"min": 0.005,
"max": 4.0,
"step": 0.01,
},
),
"flatShading": ("BOOLEAN",),
"metalness": (
"FLOAT",
{
"default": base["metalness"],
"min": 0.0,
"max": 1.0,
"step": 0.01,
},
),
"emissive": ("COLOR", {"default": base["emissive"]}),
"displacementScale": (
"FLOAT",
{"default": 1.0, "min": -10.0, "max": 10.0},
),
},
"optional": {"displacementMap": ("IMAGE",)},
}
RETURN_TYPES = ("GEO_MATERIAL",)
RETURN_NAMES = ("material",)
FUNCTION = "make_material"
CATEGORY = "mtb/3D"
def make_material(
self, **kwargs
): # color, roughness, metalness, emissive, displacementScalen displacementMap=None):
# TODO: convert image to b64 and remove the key/add the B64 one
# TODO: we can just use the "wireframe" property instead of my current solution
if kwargs.get("displacementMap") is not None:
tens = kwargs.pop("displacementMap")
# TODO: alert about batch size > 1 ?
b64images = tensor2b64(tens)[0]
kwargs["displacementB64"] = b64images
return (kwargs,)
class MTB_GeometryApplyMaterial:
"""Apply a Material to a geometry."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"geometry": ("GEOMETRY",),
"color": ("COLOR", {"default": "#000000"}),
},
"optional": {"material": ("GEO_MATERIAL",)},
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "apply"
CATEGORY = "mtb/3D"
def apply(
self,
geometry,
color,
material=None,
):
if material is None:
material = default_material(color)
#
geometry["material"] = material
return (geometry,)
class MTB_GeometryTransform:
"""Transforms the input geometry."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"mesh": ("GEOMETRY",),
"position_x": (
"FLOAT",
{"default": 0.0, "step": 0.1, "min": -10000, "max": 10000},
),
"position_y": (
"FLOAT",
{"default": 0.0, "step": 0.1, "min": -10000, "max": 10000},
),
"position_z": (
"FLOAT",
{"default": 0.0, "step": 0.1, "min": -10000, "max": 10000},
),
"rotation_x": (
"FLOAT",
{"default": 0.0, "step": 1, "min": -10000, "max": 10000},
),
"rotation_y": (
"FLOAT",
{"default": 0.0, "step": 1, "min": -10000, "max": 10000},
),
"rotation_z": (
"FLOAT",
{"default": 0.0, "step": 1, "min": -10000, "max": 10000},
),
"scale_x": ("FLOAT", {"default": 1.0, "step": 0.1}),
"scale_y": ("FLOAT", {"default": 1.0, "step": 0.1}),
"scale_z": ("FLOAT", {"default": 1.0, "step": 0.1}),
}
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "transform_geometry"
CATEGORY = "mtb/3D"
def transform_geometry(
self,
mesh: o3d.geometry.TriangleMesh,
position_x=0.0,
position_y=0.0,
position_z=0.0,
rotation_x=0,
rotation_y=0,
rotation_z=0,
scale_x=1,
scale_y=1,
scale_z=1,
):
# mesh = o3d.geometry.TriangleMesh.create_box(
# width,
# height,
# depth,
# )
# mesh.compute_vertex_normals()
position = np.array([position_x, position_y, position_z])
rotation = (rotation_x, rotation_y, rotation_z)
scale = np.array([scale_x, scale_y, scale_z])
transformation_matrix = get_transformation_matrix(
position, rotation, scale
)
mesh, material = spread_geo(mesh, cp=True)
return (
{
"mesh": mesh.transform(transformation_matrix),
"material": material,
},
)
class MTB_GeometrySphere:
"""Makes a Sphere 3D geometry.."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"create_uv_map": ("BOOLEAN", {"default": True}),
"radius": ("FLOAT", {"default": 1.0, "step": 0.1}),
"resolution": ("INT", {"default": 20, "min": 1}),
}
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "make_sphere"
CATEGORY = "mtb/3D"
def make_sphere(self, create_uv_map, radius, resolution):
mesh = o3d.geometry.TriangleMesh.create_sphere(
radius,
resolution,
create_uv_map,
)
mesh.compute_vertex_normals()
return ({"mesh": mesh},)
class MTB_GeometryTest:
"""Fetches an Open3D data geometry.."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"name": (
[
"ArmadilloMesh",
"AvocadoModel",
"BunnyMesh",
"CrateModel",
"DamagedHelmetModel",
"FlightHelmetModel",
"KnotMesh",
"MonkeyModel",
"SwordModel",
],
{
"default": "KnotMesh",
},
)
}
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "fetch_data"
CATEGORY = "mtb/3D"
def fetch_data(self, name):
model = getattr(o3d.data, name)()
mesh = o3d.io.read_triangle_mesh(model.path)
mesh.compute_vertex_normals()
return ({"mesh": mesh},)
class MTB_GeometryBox:
"""Makes a Box 3D geometry."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# "create_uv_map": ("BOOLEAN", {"default": True}),
"uniform_scale": ("FLOAT", {"default": 1.0, "step": 0.1}),
"width": ("FLOAT", {"default": 1.0, "step": 0.05}),
"height": ("FLOAT", {"default": 1.0, "step": 0.05}),
"depth": ("FLOAT", {"default": 1.0, "step": 0.05}),
"divisions_x": ("INT", {"default": 1}),
"divisions_y": ("INT", {"default": 1}),
"divisions_z": ("INT", {"default": 1}),
}
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "make_box"
CATEGORY = "mtb/3D"
def make_box(
self,
uniform_scale,
width,
height,
depth,
divisions_x,
divisions_y,
divisions_z,
):
width, height, depth = (width, height, depth) * uniform_scale
# mesh = o3d.geometry.TriangleMesh.create_box(
# width,
# height,
# depth,
# )
# mesh.compute_vertex_normals()
mesh = create_box(
(width, height, depth), (divisions_x, divisions_y, divisions_z)
)
return ({"mesh": mesh},)
class MTB_GeometryLoad:
"""Load a 3D geometry."""
@classmethod
def INPUT_TYPES(cls):
return {"required": {"path": ("STRING", {"default": ""})}}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "load_geo"
CATEGORY = "mtb/3D"
def load_geo(self, path):
if not os.path.exists(path):
raise ValueError(f"Path {path} does not exist")
mesh = o3d.io.read_triangle_mesh(path)
if len(mesh.vertices) == 0:
mesh = o3d.io.read_triangle_model(path)
mesh_count = len(mesh.meshes)
if mesh_count == 0:
raise ValueError("Couldn't parse input file")
if mesh_count > 1:
log.warn(
f"Found {mesh_count} meshes, only the first will be used..."
)
mesh = mesh.meshes[0].mesh
mesh.compute_vertex_normals()
return {
"result": ({"mesh": mesh},),
}
class MTB_GeometryInfo:
"""Retrieve information about a 3D geometry."""
@classmethod
def INPUT_TYPES(cls):
return {"required": {"geometry": ("GEOMETRY", {})}}
RETURN_TYPES = ("INT", "INT", "MATERIAL")
RETURN_NAMES = ("num_vertices", "num_triangles", "material")
FUNCTION = "get_info"
CATEGORY = "mtb/3D"
def get_info(self, geometry):
mesh, material = spread_geo(geometry)
log.debug(mesh)
return (len(mesh.vertices), len(mesh.triangles), material)
class MTB_GeometryDecimater:
"""Optimized the geometry to match the target number of triangles."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"mesh": ("GEOMETRY", {}),
"target": ("INT", {"default": 1500, "min": 3, "max": 500000}),
}
}
RETURN_TYPES = ("GEOMETRY",)
RETURN_NAMES = ("geometry",)
FUNCTION = "decimate"
CATEGORY = "mtb/3D"
def decimate(self, mesh, target):
mesh = mesh.simplify_quadric_decimation(
target_number_of_triangles=target
)
mesh.compute_vertex_normals()
return ({"mesh": mesh},)
class MTB_GeometrySceneSetup:
"""Scene setup for the renderer."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"geometry": ("GEOMETRY",),
}
}
RETURN_TYPES = ("SCENE",)
RETURN_NAMES = ("scene",)
FUNCTION = "setup"
CATEGORY = "mtb/3D"
def setup(self, mesh, target):
return ({"geometry": {"mesh": mesh}, "camera": cam},)
class MTB_GeometryRender:
"""Renders a Geometry to an image."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"geometry": ("SCENE", {}),
"width": ("INT", {"default": 512, "min": 1}),
"height": ("INT", {"default": 512, "min": 1}),
"background": ("COLOR", {"default": [0.0, 0.0, 0.0]}),
"camera": ("CAMERA",),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "render"
CATEGORY = "mtb/3D"
def render(self, geometry, width, height, background, camera):
# create a renderer
renderer = o3d.visualization.rendering.OffscreenRenderer(width, height)
renderer.set_camera(camera)
renderer.clear(background)
renderer.add_geometry(geometry)
renderer.render()
image = renderer.get_image()
return (image,)
__nodes__ = [
MTB_Camera,
MTB_GeometryApplyMaterial,
MTB_GeometryBox,
MTB_GeometryDecimater,
MTB_GeometryDraw,
MTB_GeometryInfo,
MTB_GeometryLoad,
MTB_GeometryMaterial,
MTB_GeometryRender,
MTB_GeometrySceneSetup,
MTB_GeometrySphere,
MTB_GeometryTest,
MTB_GeometryTransform,
]
+161 -73
View File
@@ -3,17 +3,16 @@ import json
import urllib.parse
import urllib.request
from math import pi
from typing import Optional
import comfy.model_management as model_management
import comfy.utils
import numpy as np
import torch
import torchvision.transforms.functional as F
from PIL import Image
from ..log import log
from ..utils import (
EASINGS,
apply_easing,
get_server_info,
numpy_NFOV,
@@ -23,8 +22,9 @@ from ..utils import (
def get_image(filename, subfolder, folder_type):
"""Use the comfyUI "/view" endpoint to get an image from the server."""
log.debug(
f"Getting image {filename} from foldertype {folder_type} {f'in subfolder: {subfolder}' if subfolder else ''}"
f"Getting image {filename} from foldertype {folder_type} {f'in subfolder: {subfolder}' if subfolder else ''}" # noqa: E501
)
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
base_url, port = get_server_info()
@@ -32,7 +32,8 @@ def get_image(filename, subfolder, folder_type):
url_values = urllib.parse.urlencode(data)
url = f"http://{base_url}:{port}/view?{url_values}"
log.debug(f"Fetching image from {url}")
with urllib.request.urlopen(url) as response:
with urllib.request.urlopen(url) as response: # noqa: S310
return io.BytesIO(response.read())
@@ -70,8 +71,8 @@ class MTB_ToDevice:
*,
ignore_errors=False,
device="cuda",
image: Optional[torch.Tensor] = None,
mask: Optional[torch.Tensor] = None,
image: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
):
if not ignore_errors and image is None and mask is None:
raise ValueError(
@@ -137,6 +138,8 @@ class MTB_MatchDimensions:
def execute(
self, source: torch.Tensor, reference: torch.Tensor, match: str
):
import torchvision.transforms.functional as VF
_batch_size, height, width, _channels = source.shape
_rbatch_size, rheight, rwidth, _rchannels = reference.shape
@@ -154,7 +157,7 @@ class MTB_MatchDimensions:
new_height = int(rwidth / source_aspect_ratio)
resized_images = [
F.resize(
VF.resize(
source[i],
(new_height, new_width),
antialias=True,
@@ -168,11 +171,48 @@ class MTB_MatchDimensions:
return (resized_source, new_width, new_height)
class MTB_FloatsToFloat:
"""AD, IPA, Fitz etc have commonly choose to mistype float lists as FLOAT.
class MTB_FloatToFloats:
"""Conversion utility for compatibility with other extensions (AD, IPA, Fitz are using FLOAT to represent list of floats.)"""
This is just a hack to be compatible with these
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"float": ("FLOAT", {"default": 0.0, "forceInput": True}),
}
}
RETURN_TYPES = ("FLOATS",)
RETURN_NAMES = ("floats",)
CATEGORY = "mtb/utils"
FUNCTION = "convert"
def convert(self, float: float):
return (float,)
class MTB_FloatsToInts:
"""Conversion utility for compatibility with frame interpolation."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"floats": ("FLOATS", {"forceInput": True}),
}
}
RETURN_TYPES = ("INTS", "INT")
CATEGORY = "mtb/utils"
FUNCTION = "convert"
def convert(self, floats: list[float]):
vals = [int(x) for x in floats]
return (vals, vals)
class MTB_FloatsToFloat:
"""Conversion utility for compatibility with other extensions (AD, IPA, Fitz are using FLOAT to represent list of floats.)"""
@classmethod
def INPUT_TYPES(cls):
@@ -331,7 +371,7 @@ class MTB_GetBatchFromHistory:
history_url = f"http://{base_url}:{port}/history"
log.debug(f"Fetching history from {history_url}")
output = torch.zeros(0)
with urllib.request.urlopen(history_url) as response:
with urllib.request.urlopen(history_url) as response: # noqa: S310
output = self.load_batch_frames(response, offset, count, frames)
if output.size(0) == 0:
@@ -379,38 +419,44 @@ class MTB_AnyToString:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"input": ("*")},
"required": {"input_value": ("*",)},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "do_str"
CATEGORY = "mtb/converters"
def do_str(self, input):
if isinstance(input, str):
return (input,)
elif isinstance(input, torch.Tensor):
return (f"Tensor of shape {input.shape} and dtype {input.dtype}",)
elif isinstance(input, Image.Image):
return (f"PIL Image of size {input.size} and mode {input.mode}",)
elif isinstance(input, np.ndarray):
def do_str(self, input_value):
if isinstance(input_value, str):
return (input_value,)
elif isinstance(input_value, torch.Tensor):
return (
f"Numpy array of shape {input.shape} and dtype {input.dtype}",
f"Tensor of shape {input_value.shape} and dtype {input_value.dtype}",
)
elif isinstance(input_value, Image.Image):
return (
f"PIL Image of size {input_value.size} and mode {input_value.mode}",
)
elif isinstance(input_value, np.ndarray):
return (
f"Numpy array of shape {input_value.shape} and dtype {input_value.dtype}",
)
elif isinstance(input, dict):
elif isinstance(input_value, dict):
return (
f"Dictionary of {len(input)} items, with keys {input.keys()}",
f"Dictionary of {len(input_value)} items, with keys {input_value.keys()}",
)
else:
log.debug(f"Falling back to string conversion of {input}")
return (str(input),)
log.debug(f"Falling back to string conversion of {input_value}")
return (str(input_value),)
class MTB_StringReplace:
"""Basic string replacement."""
"""Basic string replacement."""
@classmethod
def INPUT_TYPES(cls):
return {
@@ -438,7 +484,7 @@ class MTB_StringReplace:
class MTB_MathExpression:
"""Node to evaluate a simple math expression string"""
"""Node to evaluate a simple math expression string."""
@classmethod
def INPUT_TYPES(cls):
@@ -453,14 +499,14 @@ class MTB_MathExpression:
RETURN_NAMES = ("result (float)", "result (int)")
CATEGORY = "mtb/math"
DESCRIPTION = (
"evaluate a simple math expression string (!! Fallsback to eval)"
"evaluate a simple math expression string, only supports literal_eval"
)
def eval_expression(self, expression, **kwargs):
def eval_expression(self, expression: str, **kwargs):
from ast import literal_eval
for key, value in kwargs.items():
print(f"Replacing placeholder <{key}> with value {value}")
log.debug(f"Replacing placeholder <{key}> with value {value}")
expression = expression.replace(f"<{key}>", str(value))
result = -1
@@ -471,12 +517,15 @@ class MTB_MathExpression:
f"The expression syntax is wrong '{expression}': {e}"
) from e
except Exception as e:
raise ValueError(
f"Math expression only support literal_eval now: {e}"
)
except ValueError:
try:
expression = expression.replace("^", "**")
result = eval(expression)
result = eval(expression) # noqa: S307
except Exception as e:
# Handle any other exceptions and provide a meaningful error message
raise ValueError(
f"Error evaluating expression '{expression}': {e}"
) from e
@@ -493,35 +542,24 @@ class MTB_FitNumber:
"required": {
"value": ("FLOAT", {"default": 0, "forceInput": True}),
"clamp": ("BOOLEAN", {"default": False}),
"source_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
"source_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
"target_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
"target_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
"source_min": (
"FLOAT",
{"default": 0.0, "step": 0.01, "min": -1e5},
),
"source_max": (
"FLOAT",
{"default": 1.0, "step": 0.01, "min": -1e5},
),
"target_min": (
"FLOAT",
{"default": 0.0, "step": 0.01, "min": -1e5},
),
"target_max": (
"FLOAT",
{"default": 1.0, "step": 0.01, "min": -1e5},
),
"easing": (
[
"Linear",
"Sine In",
"Sine Out",
"Sine In/Out",
"Quart In",
"Quart Out",
"Quart In/Out",
"Cubic In",
"Cubic Out",
"Cubic In/Out",
"Circ In",
"Circ Out",
"Circ In/Out",
"Back In",
"Back Out",
"Back In/Out",
"Elastic In",
"Elastic Out",
"Elastic In/Out",
"Bounce In",
"Bounce Out",
"Bounce In/Out",
],
EASINGS,
{"default": "Linear"},
),
}
@@ -534,13 +572,14 @@ class MTB_FitNumber:
def set_range(
self,
*,
value: float,
clamp: bool,
source_min: float,
source_max: float,
target_min: float,
target_max: float,
easing: str,
source_min=0.0,
source_max=1.0,
target_min=0.0,
target_max=1.0,
easing="Linear",
):
if source_min == source_max:
normalized_value = 0
@@ -568,19 +607,66 @@ class MTB_ConcatImages:
def INPUT_TYPES(cls):
return {
"required": {"reverse": ("BOOLEAN", {"default": False})},
"optional": {
"on_mismatch": (
["Error", "Smallest", "Largest"],
{"default": "Smallest"},
)
},
}
def concatenate_tensors(self, reverse, **kwargs):
tensors = tuple(kwargs.values())
batch_sizes = [tensor.size(0) for tensor in tensors]
def concatenate_tensors(
self,
reverse: bool,
on_mismatch: str = "Smallest",
**kwargs: torch.Tensor,
) -> tuple[torch.Tensor]:
tensors = list(kwargs.values())
if on_mismatch == "Error":
shapes = [tensor.shape for tensor in tensors]
if not all(shape == shapes[0] for shape in shapes):
raise ValueError(
"All input tensors must have the same shape when on_mismatch is 'Error'."
)
else:
import torch.nn.functional as F
if on_mismatch == "Smallest":
target_shape = min(
(tensor.shape for tensor in tensors),
key=lambda s: (s[1], s[2]),
)
else: # on_mismatch == "Largest"
target_shape = max(
(tensor.shape for tensor in tensors),
key=lambda s: (s[1], s[2]),
)
target_height, target_width = target_shape[1], target_shape[2]
resized_tensors = []
for tensor in tensors:
if (
tensor.shape[1] != target_height
or tensor.shape[2] != target_width
):
resized_tensor = F.interpolate(
tensor.permute(0, 3, 1, 2),
size=(target_height, target_width),
mode="bilinear",
align_corners=False,
)
resized_tensor = resized_tensor.permute(0, 2, 3, 1)
resized_tensors.append(resized_tensor)
else:
resized_tensors.append(tensor)
tensors = resized_tensors
concatenated = torch.cat(tensors, dim=0)
# Update the batch size in the concatenated tensor
concatenated_size = list(concatenated.size())
concatenated_size[0] = sum(batch_sizes)
concatenated = concatenated.view(*concatenated_size)
return (concatenated,)
@@ -596,4 +682,6 @@ __nodes__ = [
MTB_MatchDimensions,
MTB_AutoPanEquilateral,
MTB_FloatsToFloat,
MTB_FloatToFloats,
MTB_FloatsToInts,
]
+23 -13
View File
@@ -1,12 +1,8 @@
import glob
import os
from pathlib import Path
from typing import List
import comfy
import comfy.model_management as model_management
import comfy.utils
import folder_paths
import numpy as np
import tensorflow as tf
import torch
@@ -17,11 +13,14 @@ from ..log import log
from ..utils import get_model_path
class LoadFilmModel:
"""Loads a FILM model"""
class MTB_LoadFilmModel:
"""Loads a FILM model.
[DEPRECATED] Use ComfyUI-FrameInterpolation instead
"""
@staticmethod
def get_models() -> List[Path]:
def get_models() -> list[Path]:
models_paths = get_model_path("FILM").iterdir()
return [x for x in models_paths if x.suffix in [".onnx", ".pth"]]
@@ -40,6 +39,7 @@ class LoadFilmModel:
RETURN_TYPES = ("FILM_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/frame iterpolation"
DEPRECATED = True
def load_model(self, film_model: str):
model_path = get_model_path("FILM", film_model)
@@ -58,8 +58,11 @@ class LoadFilmModel:
return (interpolator.Interpolator(model_path.as_posix(), None),)
class FilmInterpolation:
"""Google Research FILM frame interpolation for large motion"""
class MTB_FilmInterpolation:
"""Google Research FILM frame interpolation for large motion.
[DEPRECATED] Use ComfyUI-FrameInterpolation instead
"""
@classmethod
def INPUT_TYPES(cls):
@@ -74,6 +77,7 @@ class FilmInterpolation:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_interpolation"
CATEGORY = "mtb/frame iterpolation"
DEPRECATED = True
def do_interpolation(
self,
@@ -104,15 +108,21 @@ class FilmInterpolation:
pbar = comfy.utils.ProgressBar(num_frames)
for frame in util.interpolate_recursively_from_memory(
in_frames, interpolate, film_model
in_frames, # type: ignore
interpolate,
film_model,
):
out_tensors.append(
torch.from_numpy(frame) if isinstance(frame, np.ndarray) else frame
torch.from_numpy(frame)
if isinstance(frame, np.ndarray)
else frame
)
model_management.throw_exception_if_processing_interrupted()
pbar.update(1)
out_tensors = torch.cat([tens.unsqueeze(0) for tens in out_tensors], dim=0)
out_tensors = torch.cat(
[tens.unsqueeze(0) for tens in out_tensors], dim=0
)
log.debug(f"Returning {len(out_tensors)} tensors")
log.debug(f"Output shape {out_tensors.shape}")
@@ -120,4 +130,4 @@ class FilmInterpolation:
return (out_tensors,)
__nodes__ = [LoadFilmModel, FilmInterpolation]
__nodes__ = [MTB_LoadFilmModel, MTB_FilmInterpolation]
+496 -93
View File
@@ -3,6 +3,7 @@ import json
import math
import os
import comfy.model_management as model_management
import folder_paths
import numpy as np
import torch
@@ -13,7 +14,7 @@ from skimage.filters import gaussian
from skimage.util import compare_images
from ..log import log
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
from ..utils import np2tensor, pil2tensor, tensor2pil
# try:
# from cv2.ximgproc import guidedFilter
@@ -35,6 +36,343 @@ def gaussian_kernel(
return g / g.sum()
class MTB_CoordinatesToString:
RETURN_TYPES = ("STRING",)
FUNCTION = "convert"
CATEGORY = "mtb/coordinates"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"coordinates": ("BATCH_COORDINATES",),
"frame": ("INT",),
}
}
def convert(
self, coordinates: list[list[tuple[int, int]]], frame: int
) -> tuple[str]:
frame = max(frame, len(coordinates) - 1)
coords = coordinates[frame]
output: list[dict[str, int]] = []
for x, y in coords:
output.append({"x": x, "y": y})
return (json.dumps(output),)
class MTB_ExtractCoordinatesFromImage:
"""Extract 2D points from a batch of images based on a threshold."""
RETURN_TYPES = ("BATCH_COORDINATES", "IMAGE")
FUNCTION = "extract"
CATEGORY = "mtb/coordinates"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"threshold": ("FLOAT",),
"max_points": ("INT", {"default": 50, "min": 0}),
},
"optional": {"image": ("IMAGE",), "mask": ("MASK",)},
}
def extract(
self,
threshold: float,
max_points: int,
image: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
) -> tuple[list[list[tuple[int, int]]], torch.Tensor]:
if image is not None:
batch_count, height, width, channel_count = image.shape
imgs = image
else:
if mask is None:
raise ValueError("Must provide either image or mask")
batch_count, height, width = mask.shape
channel_count = 1
imgs = mask
if channel_count not in [1, 2, 3, 4]:
raise ValueError(f"Incorrect channel count: {channel_count}")
all_points: list[list[tuple[int, int]]] = []
debug_images = torch.zeros(
(batch_count, height, width, 3),
dtype=torch.uint8,
device=imgs.device,
)
for i, img in enumerate(imgs):
if channel_count == 1:
alpha_channel = img if len(img.shape) == 2 else img[:, :, 0]
elif channel_count == 2:
alpha_channel = img[:, :, 1]
elif channel_count == 4:
alpha_channel = img[:, :, 3]
else:
# get intensity
alpha_channel = img[:, :, :3].max(dim=2)[0]
points = (alpha_channel > threshold).nonzero(as_tuple=False)
if len(points) > max_points:
indices = torch.randperm(points.size(0), device=img.device)[
:max_points
]
points = points[indices]
points = [(int(y.item()), int(x.item())) for x, y in points]
all_points.append(points)
for x, y in points:
self._draw_circle(debug_images[i], (x, y), 5)
return (all_points, debug_images)
@staticmethod
def _draw_circle(
image: torch.Tensor, center: tuple[int, int], radius: int
):
"""Draw a 5px circle on the image."""
x0, y0 = center
for x in range(-radius, radius + 1):
for y in range(-radius, radius + 1):
in_radius = x**2 + y**2 <= radius**2
in_bounds = (
0 <= x0 + x < image.shape[1]
and 0 <= y0 + y < image.shape[0]
)
if in_radius and in_bounds:
image[y0 + y, x0 + x] = torch.tensor(
[255, 255, 255],
dtype=torch.uint8,
device=image.device,
)
class MTB_ColorCorrectGPU:
"""Various color correction methods using only Torch."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"force_gpu": ("BOOLEAN", {"default": True}),
"clamp": ([True, False], {"default": True}),
"gamma": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
),
"contrast": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
),
"exposure": (
"FLOAT",
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
),
"offset": (
"FLOAT",
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
),
"hue": (
"FLOAT",
{"default": 0.0, "min": -0.5, "max": 0.5, "step": 0.01},
),
"saturation": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
),
"value": (
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
),
},
"optional": {"mask": ("MASK",)},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "correct"
CATEGORY = "mtb/image processing"
@staticmethod
def get_device(tensor: torch.Tensor, force_gpu: bool):
if force_gpu:
if torch.cuda.is_available():
return torch.device("cuda")
elif (
hasattr(torch.backends, "mps")
and torch.backends.mps.is_available()
):
return torch.device("mps")
elif hasattr(torch, "hip") and torch.hip.is_available():
return torch.device("hip")
return (
tensor.device
) # model_management.get_torch_device() # torch.device("cpu")
@staticmethod
def rgb_to_hsv(image: torch.Tensor):
r, g, b = image.unbind(-1)
max_rgb, argmax_rgb = image.max(-1)
min_rgb, _ = image.min(-1)
diff = max_rgb - min_rgb
h = torch.empty_like(max_rgb)
s = diff / (max_rgb + 1e-7)
v = max_rgb
h[argmax_rgb == 0] = (g - b)[argmax_rgb == 0] / (diff + 1e-7)[
argmax_rgb == 0
]
h[argmax_rgb == 1] = (
2.0 + (b - r)[argmax_rgb == 1] / (diff + 1e-7)[argmax_rgb == 1]
)
h[argmax_rgb == 2] = (
4.0 + (r - g)[argmax_rgb == 2] / (diff + 1e-7)[argmax_rgb == 2]
)
h = (h / 6.0) % 1.0
h = h.unsqueeze(-1)
s = s.unsqueeze(-1)
v = v.unsqueeze(-1)
return torch.cat((h, s, v), dim=-1)
@staticmethod
def hsv_to_rgb(hsv: torch.Tensor):
h, s, v = hsv.unbind(-1)
h = h * 6.0
i = torch.floor(h)
f = h - i
p = v * (1.0 - s)
q = v * (1.0 - s * f)
t = v * (1.0 - s * (1.0 - f))
i = i.long() % 6
mask = torch.stack(
(i == 0, i == 1, i == 2, i == 3, i == 4, i == 5), -1
)
rgb = torch.stack(
(
torch.where(
mask[..., 0],
v,
torch.where(
mask[..., 1],
q,
torch.where(
mask[..., 2],
p,
torch.where(
mask[..., 3],
p,
torch.where(mask[..., 4], t, v),
),
),
),
),
torch.where(
mask[..., 0],
t,
torch.where(
mask[..., 1],
v,
torch.where(
mask[..., 2],
v,
torch.where(
mask[..., 3],
q,
torch.where(mask[..., 4], p, p),
),
),
),
),
torch.where(
mask[..., 0],
p,
torch.where(
mask[..., 1],
p,
torch.where(
mask[..., 2],
t,
torch.where(
mask[..., 3],
v,
torch.where(mask[..., 4], v, q),
),
),
),
),
),
dim=-1,
)
return rgb
def correct(
self,
image: torch.Tensor,
force_gpu: bool,
clamp: bool,
gamma: float = 1.0,
contrast: float = 1.0,
exposure: float = 0.0,
offset: float = 0.0,
hue: float = 0.0,
saturation: float = 1.0,
value: float = 1.0,
mask: torch.Tensor | None = None,
):
device = self.get_device(image, force_gpu)
image = image.to(device)
if mask is not None:
if mask.shape[0] != image.shape[0]:
mask = mask.expand(image.shape[0], -1, -1)
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
mask = mask.to(device)
model_management.throw_exception_if_processing_interrupted()
adjusted = image.pow(1 / gamma) * (2.0**exposure) * contrast + offset
model_management.throw_exception_if_processing_interrupted()
hsv = self.rgb_to_hsv(adjusted)
hsv[..., 0] = (hsv[..., 0] + hue) % 1.0 # Hue
hsv[..., 1] = hsv[..., 1] * saturation # Saturation
hsv[..., 2] = hsv[..., 2] * value # Value
adjusted = self.hsv_to_rgb(hsv)
model_management.throw_exception_if_processing_interrupted()
if clamp:
adjusted = torch.clamp(adjusted, 0.0, 1.0)
# apply mask
result = (
adjusted
if mask is None
else torch.where(mask > 0, adjusted, image)
)
if not force_gpu:
result = result.cpu()
return (result,)
class MTB_ColorCorrect:
"""Various color correction methods"""
@@ -72,7 +410,8 @@ class MTB_ColorCorrect:
"FLOAT",
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
),
}
},
"optional": {"mask": ("MASK",)},
}
RETURN_TYPES = ("IMAGE",)
@@ -86,7 +425,14 @@ class MTB_ColorCorrect:
@staticmethod
def contrast_adjustment_tensor(image, contrast):
contrasted = (image - 0.5) * contrast + 0.5
r, g, b = image.unbind(-1)
# Using Adobe RGB luminance weights.
luminance_image = 0.33 * r + 0.71 * g + 0.06 * b
luminance_mean = torch.mean(luminance_image.unsqueeze(-1))
# Blend original with mean luminance using contrast factor as blend ratio.
contrasted = image * contrast + (1.0 - contrast) * luminance_mean
return torch.clamp(contrasted, 0.0, 1.0)
@staticmethod
@@ -181,18 +527,31 @@ class MTB_ColorCorrect:
hue: float = 0.0,
saturation: float = 1.0,
value: float = 1.0,
mask: torch.Tensor | None = None,
):
if mask is not None:
if mask.shape[0] != image.shape[0]:
mask = mask.expand(image.shape[0], -1, -1)
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
# Apply color correction operations
image = self.gamma_correction_tensor(image, gamma)
image = self.contrast_adjustment_tensor(image, contrast)
image = self.exposure_adjustment_tensor(image, exposure)
image = self.offset_adjustment_tensor(image, offset)
image = self.hsv_adjustment(image, hue, saturation, value)
adjusted = self.gamma_correction_tensor(image, gamma)
adjusted = self.contrast_adjustment_tensor(adjusted, contrast)
adjusted = self.exposure_adjustment_tensor(adjusted, exposure)
adjusted = self.offset_adjustment_tensor(adjusted, offset)
adjusted = self.hsv_adjustment(adjusted, hue, saturation, value)
if clamp:
image = torch.clamp(image, 0.0, 1.0)
adjusted = torch.clamp(image, 0.0, 1.0)
return (image,)
result = (
adjusted
if mask is None
else torch.where(mask > 0, adjusted, image)
)
return (result,)
class MTB_ImageCompare:
@@ -216,16 +575,55 @@ class MTB_ImageCompare:
CATEGORY = "mtb/image"
def compare(self, imageA: torch.Tensor, imageB: torch.Tensor, mode):
imageA = imageA.numpy()
imageB = imageB.numpy()
if imageA.dim() == 4:
batch_count = imageA.size(0)
return (
torch.cat(
tuple(
self.compare(imageA[i], imageB[i], mode)[0]
for i in range(batch_count)
),
dim=0,
),
)
imageA = imageA.squeeze()
imageB = imageB.squeeze()
num_channels_A = imageA.size(2)
num_channels_B = imageB.size(2)
image = compare_images(imageA, imageB, method=mode)
# handle RGBA/RGB mismatch
if num_channels_A == 3 and num_channels_B == 4:
imageA = torch.cat(
(imageA, torch.ones_like(imageA[:, :, 0:1])), dim=2
)
elif num_channels_B == 3 and num_channels_A == 4:
imageB = torch.cat(
(imageB, torch.ones_like(imageB[:, :, 0:1])), dim=2
)
match mode:
case "diff":
compare_image = torch.abs(imageA - imageB)
case "blend":
compare_image = 0.5 * (imageA + imageB)
case "checkerboard":
imageA = imageA.numpy()
imageB = imageB.numpy()
compared_channels = [
torch.from_numpy(
compare_images(
imageA[:, :, i], imageB[:, :, i], method=mode
)
)
for i in range(imageA.shape[2])
]
image = np.expand_dims(image, axis=0)
return (torch.from_numpy(image),)
compare_image = torch.stack(compared_channels, dim=2)
case _:
compare_image = None
raise ValueError(f"Unknown mode {mode}")
compare_image = compare_image.unsqueeze(0)
return (compare_image,)
import requests
@@ -429,7 +827,10 @@ class MTB_MaskToImage:
"mask": ("MASK",),
"color": ("COLOR",),
"background": ("COLOR", {"default": "#000000"}),
}
},
"optional": {
"invert": ("BOOLEAN", {"default": False}),
},
}
CATEGORY = "mtb/generate"
@@ -438,11 +839,12 @@ class MTB_MaskToImage:
FUNCTION = "render_mask"
def render_mask(self, mask, color, background):
masks = tensor2np(mask)[0]
def render_mask(self, mask, color, background, invert=False):
masks = tensor2pil(1.0 - mask) if invert else tensor2pil(mask)
images = []
for m in masks:
_mask = Image.fromarray(m).convert("L")
_mask = m.convert("L")
log.debug(
f"Converted mask to PIL Image format, size: {_mask.size}"
@@ -480,6 +882,11 @@ class MTB_ColoredImage:
"optional": {
"foreground_image": ("IMAGE",),
"foreground_mask": ("MASK",),
"invert": ("BOOLEAN", {"default": False}),
"mask_opacity": (
"FLOAT",
{"default": 1.0, "step": 0.1, "min": 0},
),
},
}
@@ -489,28 +896,19 @@ class MTB_ColoredImage:
FUNCTION = "render_img"
def resize_and_crop(self, img, target_size):
# Calculate scaling factors for both dimensions
scale_x = target_size[0] / img.width
scale_y = target_size[1] / img.height
# Use the smaller scaling factor to maintain aspect ratio
scale = max(scale_x, scale_y)
# Resize the image based on calculated scale
def resize_and_crop(self, img: Image.Image, target_size: tuple[int, int]):
scale = max(target_size[0] / img.width, target_size[1] / img.height)
new_size = (int(img.width * scale), int(img.height * scale))
img = img.resize(new_size, Image.LANCZOS)
left = (img.width - target_size[0]) // 2
top = (img.height - target_size[1]) // 2
return img.crop(
(left, top, left + target_size[0], top + target_size[1])
)
# Calculate cropping coordinates
left = (img.width - target_size[0]) / 2
top = (img.height - target_size[1]) / 2
right = (img.width + target_size[0]) / 2
bottom = (img.height + target_size[1]) / 2
# Crop and return the image
return img.crop((left, top, right, bottom))
def resize_and_crop_thumbnails(self, img, target_size):
def resize_and_crop_thumbnails(
self, img: Image.Image, target_size: tuple[int, int]
):
img.thumbnail(target_size, Image.LANCZOS)
left = (img.width - target_size[0]) / 2
top = (img.height - target_size[1]) / 2
@@ -518,69 +916,71 @@ class MTB_ColoredImage:
bottom = (img.height + target_size[1]) / 2
return img.crop((left, top, right, bottom))
@staticmethod
def process_mask(
mask: torch.Tensor | None,
invert: bool,
# opacity: float,
batch_size: int,
) -> list[Image.Image] | None:
if mask is None:
return [None] * batch_size
masks = tensor2pil(mask if not invert else 1.0 - mask)
if len(masks) == 1 and batch_size > 1:
masks = masks * batch_size
if len(masks) != batch_size:
raise ValueError(
"Foreground image and mask must have the same batch size"
)
return masks
def render_img(
self,
color,
width,
height,
color: str,
width: int,
height: int,
foreground_image: torch.Tensor | None = None,
foreground_mask: torch.Tensor | None = None,
):
image = Image.new("RGBA", (width, height), color=color)
output = []
if foreground_image is not None:
fg_masks = [None] * foreground_image.size()[0]
invert: bool = False,
mask_opacity: float = 1.0,
) -> tuple[torch.Tensor]:
background = Image.new("RGBA", (width, height), color=color)
if foreground_mask is not None:
fg_size = foreground_image.size()[0]
mask_size = foreground_mask.size()[0]
if foreground_image is None:
return (pil2tensor([background.convert("RGB")]),)
if fg_size == 1 and mask_size > fg_size:
foreground_image = foreground_image.repeat(
mask_size, 1, 1, 1
)
fg_images = tensor2pil(foreground_image)
fg_masks = self.process_mask(foreground_mask, invert, len(fg_images))
if foreground_image.size()[0] != foreground_mask.size()[0]:
output: list[Image.Image] = []
for fg_image, fg_mask in zip(fg_images, fg_masks, strict=False):
fg_image = self.resize_and_crop(fg_image, background.size)
if fg_mask:
fg_mask = self.resize_and_crop(fg_mask, background.size)
fg_mask_array = np.array(fg_mask)
fg_mask_array = (fg_mask_array * mask_opacity).astype(np.uint8)
fg_mask = Image.fromarray(fg_mask_array)
output.append(
Image.composite(
fg_image.convert("RGBA"), background, fg_mask
).convert("RGB")
)
else:
if fg_image.mode != "RGBA":
raise ValueError(
"Foreground image and mask must have same batch size"
f"Foreground image must be in 'RGBA' mode when no mask is provided, got {fg_image.mode}"
)
fg_masks = tensor2pil(foreground_mask.unsqueeze(-1))
output.append(
Image.alpha_composite(background, fg_image).convert("RGB")
)
fg_images = tensor2pil(foreground_image)
for fg_image, fg_mask in zip(fg_images, fg_masks):
# Resize and crop if dimensions mismatch
if fg_image.size != image.size:
fg_image = self.resize_and_crop(fg_image, image.size)
if fg_mask:
fg_mask = self.resize_and_crop(fg_mask, image.size)
if fg_mask:
output.append(
Image.composite(
fg_image.convert("RGBA"),
image,
fg_mask,
).convert("RGB")
)
else:
if fg_image.mode != "RGBA":
raise ValueError(
"Foreground image must be in 'RGBA' mode "
f"when no mask is provided, got {fg_image.mode}"
)
output.append(
Image.alpha_composite(image, fg_image).convert("RGB")
)
else:
if foreground_mask is not None:
log.warn("Mask ignored because no foreground image is given")
output.append(image.convert("RGB"))
output = pil2tensor(output)
return (output,)
return (pil2tensor(output),)
class MTB_ImagePremultiply:
@@ -878,6 +1278,7 @@ class MTB_ImageTileOffset:
__nodes__ = [
MTB_ColorCorrect,
MTB_ColorCorrectGPU,
MTB_ImageCompare,
MTB_ImageTileOffset,
MTB_Blur,
@@ -889,4 +1290,6 @@ __nodes__ = [
MTB_SaveImageGrid,
MTB_LoadImageFromUrl,
MTB_Sharpen,
MTB_ExtractCoordinatesFromImage,
MTB_CoordinatesToString,
]
+20
View File
@@ -27,6 +27,11 @@ class MTB_StackImages:
normalized_tensors = [
self.normalize_to_rgba(tensor) for tensor in tensors
]
max_batch_size = max(tensor.shape[0] for tensor in normalized_tensors)
normalized_tensors = [
self.duplicate_frames(tensor, max_batch_size)
for tensor in normalized_tensors
]
if vertical:
width = normalized_tensors[0].shape[2]
@@ -67,6 +72,21 @@ class MTB_StackImages:
"expected 3 (RGB) or 4 (RGBA)."
)
def duplicate_frames(self, tensor, target_batch_size):
"""Duplicate frames in tensor to match the target batch size."""
current_batch_size = tensor.shape[0]
if current_batch_size < target_batch_size:
duplication_factors: int = target_batch_size // current_batch_size
duplicated_tensor = tensor.repeat(duplication_factors, 1, 1, 1)
remaining_frames = target_batch_size % current_batch_size
if remaining_frames > 0:
duplicated_tensor = torch.cat(
(duplicated_tensor, tensor[:remaining_frames]), dim=0
)
return duplicated_tensor
else:
return tensor
class MTB_PickFromBatch:
"""Pick a specific number of images from a batch.
+57 -21
View File
@@ -2,9 +2,9 @@ import json
import subprocess
import uuid
from pathlib import Path
from typing import List, Optional
import comfy.model_management as model_management
import comfy.utils
import folder_paths
import numpy as np
import torch
@@ -21,7 +21,7 @@ def get_playlist_path(playlist_name: str, persistant_playlist=False):
return output_dir / "playlists" / session_id / f"{playlist_name}.json"
class ReadPlaylist:
class MTB_ReadPlaylist:
"""Read a playlist"""
@classmethod
@@ -41,6 +41,7 @@ class ReadPlaylist:
RETURN_TYPES = ("PLAYLIST",)
FUNCTION = "read_playlist"
CATEGORY = "mtb/IO"
EXPERIMENTAL = True
def read_playlist(
self,
@@ -83,6 +84,7 @@ class MTB_AddToPlaylist:
OUTPUT_NODE = True
FUNCTION = "add_to_playlist"
CATEGORY = "mtb/IO"
EXPERIMENTAL = True
def add_to_playlist(
self,
@@ -117,7 +119,10 @@ class MTB_AddToPlaylist:
class MTB_ExportWithFfmpeg:
"""Export with FFmpeg (Experimental)"""
"""Export with FFmpeg (Experimental).
[DEPRACATED] Use VHS nodes instead
"""
@classmethod
def INPUT_TYPES(cls):
@@ -143,6 +148,7 @@ class MTB_ExportWithFfmpeg:
RETURN_TYPES = ("VIDEO",)
OUTPUT_NODE = True
FUNCTION = "export_prores"
DEPRECATED = True
CATEGORY = "mtb/IO"
def export_prores(
@@ -151,10 +157,9 @@ class MTB_ExportWithFfmpeg:
prefix: str,
format: str,
codec: str,
images: Optional[torch.Tensor] = None,
playlist: Optional[List[str]] = None,
images: torch.Tensor | None = None,
playlist: list[str] | None = None,
):
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
file_ext = format
file_id = f"{prefix}_{uuid.uuid4()}.{file_ext}"
@@ -208,9 +213,11 @@ class MTB_ExportWithFfmpeg:
frames = tensor2np(images)
log.debug(f"Frames type {type(frames[0])}")
log.debug(f"Exporting {len(frames)} frames")
height, width, channels = frames[0].shape
has_alpha = channels == 4
out_path = (output_dir / file_id).as_posix()
if codec == "gif":
out_path = (output_dir / file_id).as_posix()
command = [
"ffmpeg",
"-f",
@@ -233,12 +240,28 @@ class MTB_ExportWithFfmpeg:
process.stdin.close()
process.wait()
return (out_path,)
else:
frames = [frame.astype(np.uint16) * 257 for frame in frames]
height, width, _ = frames[0].shape
out_path = (output_dir / file_id).as_posix()
if has_alpha:
if codec in ["prores_ks", "libx264", "libx265"]:
pix_fmt = (
"yuva444p" if codec == "prores_ks" else "yuva420p"
)
frames = [
frame.astype(np.uint16) * 257 for frame in frames
]
else:
log.warning(
f"Alpha channel not supported for codec {codec}. Alpha will be ignored."
)
frames = [
frame[:, :, :3].astype(np.uint16) * 257
for frame in frames
]
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
else:
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
frames = [frame.astype(np.uint16) * 257 for frame in frames]
# Prepare the FFmpeg command
command = [
@@ -258,17 +281,26 @@ class MTB_ExportWithFfmpeg:
"-",
"-c:v",
codec,
"-r",
str(fps),
"-y",
out_path,
]
if codec == "prores_ks":
command.extend(["-profile:v", "4444"])
command.extend(
[
"-r",
str(fps),
"-y",
out_path,
]
)
process = subprocess.Popen(command, stdin=subprocess.PIPE)
pbar = comfy.utils.ProgressBar(len(frames))
for frame in frames:
model_management.throw_exception_if_processing_interrupted()
process.stdin.write(frame.tobytes())
pbar.update(1)
process.stdin.close()
process.wait()
@@ -280,9 +312,9 @@ def prepare_animated_batch(
batch: torch.Tensor,
pingpong=False,
resize_by=1.0,
resample_filter: Optional[Image.Resampling] = None,
resample_filter: Image.Resampling | None = None,
image_type=np.uint8,
) -> List[Image.Image]:
) -> list[Image.Image]:
images = tensor2np(batch)
images = [frame.astype(image_type) for frame in images]
@@ -308,7 +340,10 @@ def prepare_animated_batch(
# todo: deprecate for apng
class MTB_SaveGif:
"""Save the images from the batch as a GIF"""
"""Save the images from the batch as a GIF.
[DEPRACATED] Use VHS nodes instead
"""
@classmethod
def INPUT_TYPES(cls):
@@ -328,6 +363,7 @@ class MTB_SaveGif:
OUTPUT_NODE = True
CATEGORY = "mtb/IO"
FUNCTION = "save_gif"
DEPRECATED = True
def save_gif(
self,
@@ -399,5 +435,5 @@ __nodes__ = [
MTB_SaveGif,
MTB_ExportWithFfmpeg,
MTB_AddToPlaylist,
ReadPlaylist,
MTB_ReadPlaylist,
]
+6 -3
View File
@@ -1,7 +1,7 @@
import torch
class LatentLerp:
class MTB_LatentLerp:
"""Linear interpolation (blend) between two latent vectors"""
@classmethod
@@ -10,7 +10,10 @@ class LatentLerp:
"required": {
"A": ("LATENT",),
"B": ("LATENT",),
"t": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
"t": (
"FLOAT",
{"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01},
),
}
}
@@ -29,5 +32,5 @@ class LatentLerp:
__nodes__ = [
LatentLerp,
MTB_LatentLerp,
]
+157
View File
@@ -0,0 +1,157 @@
import os
import subprocess
import tempfile
import numpy as np
import torch
from PIL import Image
from ..log import log
class ImageH264Compression:
"""Encodes the input with h264 compression using a configurable CRF."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": (
"IMAGE",
{
"tooltip": "The input image tensor to be compressed and decompressed."
},
),
"crf": (
"INT",
{
"default": 23,
"min": 0,
"max": 51,
"step": 1,
"tooltip": "Constant Rate Factor for h264 encoding (lower values mean higher quality).",
},
),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "compress_and_decompress"
CATEGORY = "image"
DESCRIPTION = """
**Encodes the input with h264 compression using a configurable CRF**.
> [!NOTE]
> This was recommended by the creators of LTX over banodoco's discord.
*Orginal code from [mix](https://github.com/XmYx)*"""
def _compress_decompress_ffmpeg(self, img_array, crf):
with tempfile.TemporaryDirectory() as temp_dir:
input_path = os.path.join(temp_dir, "input.png")
output_path = os.path.join(temp_dir, "output.mp4")
decoded_path = os.path.join(temp_dir, "decoded.png")
Image.fromarray(img_array).save(input_path)
encode_command = [
"ffmpeg",
"-y",
"-i",
input_path,
"-c:v",
"libx264",
"-crf",
str(crf),
"-pix_fmt",
"yuv420p",
"-frames:v",
"1",
output_path,
]
subprocess.run(encode_command, capture_output=True)
decode_command = [
"ffmpeg",
"-y",
"-i",
output_path,
"-frames:v",
"1",
decoded_path,
]
subprocess.run(decode_command, capture_output=True)
decoded_img = np.array(Image.open(decoded_path))
return decoded_img
def compress_and_decompress(self, image, crf):
import io
output_images = []
try:
import av
for img_tensor in image:
img_array = img_tensor.cpu().numpy()
img_array = (img_array * 255).astype(np.uint8)
img_array = img_array.copy(
order="C"
) # Ensure contiguous array
output = io.BytesIO()
# Encode the image to h264 with the given CRF
container = av.open(output, mode="w", format="mp4")
stream = container.add_stream("h264", rate=1)
stream.width = img_array.shape[1]
stream.height = img_array.shape[0]
stream.pix_fmt = "yuv420p"
stream.options = {"crf": str(crf)}
frame = av.VideoFrame.from_ndarray(img_array, format="rgb24")
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
container.close()
# Decode the video back to an image
output.seek(0)
container = av.open(output, mode="r", format="mp4")
decoded_frames = []
for frame in container.decode(video=0):
img_decoded = frame.to_ndarray(format="rgb24")
decoded_frames.append(img_decoded)
container.close()
if len(decoded_frames) > 0:
img_decoded = decoded_frames[0]
img_decoded = torch.from_numpy(
img_decoded.astype(np.float32) / 255.0
)
output_images.append(img_decoded)
else:
# If decoding failed, use the original image
output_images.append(img_tensor)
except ImportError:
log.warning(
"PyAv is not installed... Falling back to the ffmpeg cli"
)
for img_tensor in image:
img_array = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
decoded_img = self._compress_decompress_ffmpeg(img_array, crf)
img_decoded = torch.from_numpy(
decoded_img.astype(np.float32) / 255.0
)
output_images.append(img_decoded)
output_images = torch.stack(output_images).to(image.device)
return (output_images,)
# fmt: off
__nodes__ = [
ImageH264Compression
]
+2 -1
View File
@@ -1,6 +1,5 @@
import comfy.utils
from PIL import Image
from rembg import remove
from ..utils import pil2tensor, tensor2pil
@@ -64,6 +63,8 @@ class MTB_ImageRemoveBackgroundRembg:
post_process_mask,
bgcolor,
):
from rembg import remove
pbar = comfy.utils.ProgressBar(image.size(0))
images = tensor2pil(image)
+2 -2
View File
@@ -80,7 +80,7 @@ def conv_forward(lyr, tensor, weight, bias):
)
class ModelPatchSeamless:
class MTB_ModelPatchSeamless:
"""Uses the stable diffusion 'hack' to infer seamless images by setting the model layers padding mode to circular (experimental)"""
@classmethod
@@ -152,4 +152,4 @@ class ModelPatchSeamless:
return (model, hacked_model)
__nodes__ = [ModelPatchSeamless, MTB_VaeDecode]
__nodes__ = [MTB_ModelPatchSeamless, MTB_VaeDecode]
-2
View File
@@ -77,8 +77,6 @@ class MTB_FloatToNumber:
def float_to_number(self, float):
return (float,)
return (int,)
__nodes__ = [
MTB_FloatToNumber,
+351
View File
@@ -0,0 +1,351 @@
import os
import subprocess
import tempfile
import comfy.utils
import torch
from ..log import log
from ..utils import nextAvailable, tensor2pil
RELATIVE_NOTICE = """
Absolute paths are kept as is, relatives are from the output directory.
"""
class MTB_PostshotTrain:
CATEGORY = "mtb/postshot"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": (
"IMAGE",
{"tooltip": "These image will get save to disk first"},
),
"profile": (
[
"NeRF L",
"NeRF M",
"NeRF S",
"NeRF XL",
"NeRF XXL",
"Splat ADC",
"Splat MCMC",
],
{
"default": "Splat MCMC",
"tooltip": "The radiance field model profile to train",
},
),
"image_select": (
["all", "best"],
{
"default": "best",
"tooltip": "How to select training images from the source image sets",
},
),
"train_steps_limit": (
"INT",
{
"default": 30,
"min": 1,
"max": 1000,
"tooltip": "Number of kSteps to train the model for",
},
),
"output_path": (
"STRING",
{
"default": "output",
"tooltip": (
"path to save the project to" f"{RELATIVE_NOTICE}"
),
},
),
"postshot_cli": (
"STRING",
{
"default": "C:/Program Files/Jawset Postshot/bin/postshot-cli.exe"
},
),
},
"optional": {
"gpu": (
"INT",
{
"default": 0,
"min": 0,
"max": 255,
"tooltip": "Specify the index of the GPU to use",
},
),
"num_train_images": (
"INT",
{
"default": 0,
"min": 0,
"tooltip": "If image-select best is used, specifies the number of training images to select",
},
),
"max_image_size": (
"INT",
{
"default": 1600,
"min": 0,
"tooltip": "Downscale training images such that their longer edge is at most this value in pixels. Disabled if zero.",
},
),
"max_num_features": (
"INT",
{
"default": 8,
"min": 1,
"tooltip": "Maximum number of 2D kFeatures extracted from each image.",
},
),
"splat_density": (
"FLOAT",
{
"default": 1.0,
"min": 0.125,
"max": 8.0,
"tooltip": (
"Controls how much additional splats "
"are generated during training."
"Applies only in 'Splat ADC' profile."
),
},
),
"max_num_splats": (
"INT",
{
"default": 3000,
"min": 1,
"tooltip": (
"Sets the maximum number of splats (in kSplats)"
" created during training. "
"Applies only in 'Splat MCMC' profile."
),
},
),
"export_splat_ply": (
"STRING",
{
"default": "",
"tooltip": (
"If not empty will also save a ply file."
f"{RELATIVE_NOTICE}"
),
},
),
},
}
RETURN_TYPES = ("STRING",)
OUTPUT_NODE = True
RETURN_NAMES = ("project_file_path",)
FUNCTION = "train_model"
def train_model(
self,
images: torch.Tensor,
profile: str,
image_select: str,
train_steps_limit: int,
output_path: str,
gpu=0,
num_train_images=0,
max_image_size=1600,
max_num_features=8,
splat_density=1.0,
max_num_splats=3000,
export_splat_ply="",
postshot_cli="",
):
if not output_path.endswith(".psht"):
output_path += ".psht"
output_path = nextAvailable(output_path)
output_path.parent.mkdir(exist_ok=True)
pbar = comfy.utils.ProgressBar(200 + images.size(0))
try:
with tempfile.TemporaryDirectory() as temp_dir:
image_paths = []
images_pil = tensor2pil(images)
for i, img in enumerate(images_pil):
try:
img_path = os.path.join(temp_dir, f"image_{i:04d}.png")
img.save(img_path)
image_paths.append(img_path)
except Exception as e:
raise RuntimeError(
f"Failed to save image {i}: {str(e)}"
) from e
pbar.update(1)
if not image_paths:
raise ValueError("No valid images to process")
cmd = [postshot_cli, "train"]
for img_path in image_paths:
cmd.extend(["-i", img_path])
cmd.extend(
[
"-p",
profile,
"--image-select",
image_select,
"-s",
str(train_steps_limit),
"-o",
output_path.as_posix(),
]
)
if gpu is not None:
cmd.extend(["--gpu", str(gpu)])
if num_train_images > 0 and image_select == "best":
cmd.extend(["--num-train-images", str(num_train_images)])
if max_image_size > 0:
cmd.extend(["--max-image-size", str(max_image_size)])
if max_num_features != 8:
cmd.extend(["--max-num-features", str(max_num_features)])
if profile == "Splat ADC" and splat_density != 1.0:
cmd.extend(["--splat-density", str(splat_density)])
if profile == "Splat MCMC" and max_num_splats != 3000:
cmd.extend(["--max-num-splats", str(max_num_splats)])
if export_splat_ply:
export_splat_ply = nextAvailable(export_splat_ply)
cmd.extend(
["--export-splat-ply", export_splat_ply.as_posix()]
)
log.debug(f"Running {cmd}")
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
last_step_c = 0
last_step_t = 0
while True:
output = process.stdout.readline()
if output == "" and process.poll() is not None:
break
if output:
print(output)
if "camera tracking step" in output.lower():
try:
current_step = int(
output.split("%")[0].split(":")[1].strip()
)
if current_step > last_step_c:
pbar.update(1)
last_step_c = current_step
except (ValueError, IndexError):
continue
if "training radiance field:" in output.lower():
try:
current_step = int(
output.split("%")[0].split(":")[1].strip()
)
if current_step > last_step_t:
pbar.update(1)
last_step_t = current_step
except (ValueError, IndexError):
continue
if process.returncode != 0:
_, stderr = process.communicate()
raise RuntimeError(f"Postshot training failed: {stderr}")
if not os.path.exists(output_path):
raise RuntimeError("Output file was not created")
return (output_path.as_posix(),)
except Exception as e:
raise RuntimeError(f"Training failed: {str(e)}")
finally:
pbar.update(train_steps_limit)
class MTB_PostshotExport:
CATEGORY = "mtb/postshot"
OUTPUT_NODE = True
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"project_file": (
"STRING",
{"default": "", "forceInput": True},
),
"export_splat_ply": ("STRING", {"default": "output.ply"}),
"postshot_cli": (
"STRING",
{
"default": "C:/Program Files/Jawset Postshot/bin/postshot-cli.exe"
},
),
},
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("exported_ply_path",)
FUNCTION = "export_model"
def export_model(
self, project_file: str, export_splat_ply: str, postshot_cli: str
):
if not project_file.endswith(".psht"):
raise ValueError("Project file must have .psht extension")
if not os.path.exists(project_file):
raise FileNotFoundError(f"Project file not found: {project_file}")
if not export_splat_ply.endswith(".ply"):
export_splat_ply += ".ply"
_export_splat_ply = nextAvailable(export_splat_ply)
_export_splat_ply.parent.mkdir(exist_ok=True)
cmd = [
postshot_cli,
"export",
"-f",
project_file,
"--export-splat-ply",
_export_splat_ply.as_posix(),
]
try:
_result = subprocess.run(
cmd, check=True, capture_output=True, text=True
)
if not _export_splat_ply.exists():
log.error("Export file was not created")
return (_export_splat_ply.as_posix(),)
except subprocess.CalledProcessError as e:
raise RuntimeError(f"Export failed: {e.stderr}")
except Exception as e:
raise RuntimeError(f"Export failed: {str(e)}")
__nodes__ = [MTB_PostshotExport, MTB_PostshotTrain]
+360
View File
@@ -0,0 +1,360 @@
from pathlib import Path
import safetensors.torch
import torch
import tqdm
from ..log import log
from ..utils import Operation, Precision
from ..utils import output_dir as comfy_out_dir
PRUNE_DATA = {
"known_junk_prefix": [
"embedding_manager.embedder.",
"lora_te_text_model",
"control_model.",
],
"nai_keys": {
"cond_stage_model.transformer.embeddings.": "cond_stage_model.transformer.text_model.embeddings.",
"cond_stage_model.transformer.encoder.": "cond_stage_model.transformer.text_model.encoder.",
"cond_stage_model.transformer.final_layer_norm.": "cond_stage_model.transformer.text_model.final_layer_norm.",
},
}
# position_ids in clip is int64. model_ema.num_updates is int32
dtypes_to_fp16 = {torch.float32, torch.float64, torch.bfloat16}
dtypes_to_bf16 = {torch.float32, torch.float64, torch.float16}
dtypes_to_fp8 = {torch.float32, torch.float64, torch.bfloat16, torch.float16}
class MTB_ModelPruner:
@classmethod
def INPUT_TYPES(cls):
return {
"optional": {
"unet": ("MODEL",),
"clip": ("CLIP",),
"vae": ("VAE",),
},
"required": {
"save_separately": ("BOOLEAN", {"default": False}),
"save_folder": ("STRING", {"default": "checkpoints/ComfyUI"}),
"fix_clip": ("BOOLEAN", {"default": True}),
"remove_junk": ("BOOLEAN", {"default": True}),
"ema_mode": (
("disabled", "remove_ema", "ema_only"),
{"default": "remove_ema"},
),
"precision_unet": (
Precision.list_members(),
{"default": Precision.FULL.value},
),
"operation_unet": (
Operation.list_members(),
{"default": Operation.CONVERT.value},
),
"precision_clip": (
Precision.list_members(),
{"default": Precision.FULL.value},
),
"operation_clip": (
Operation.list_members(),
{"default": Operation.CONVERT.value},
),
"precision_vae": (
Precision.list_members(),
{"default": Precision.FULL.value},
),
"operation_vae": (
Operation.list_members(),
{"default": Operation.CONVERT.value},
),
},
}
OUTPUT_NODE = True
RETURN_TYPES = ()
CATEGORY = "mtb/prune"
FUNCTION = "prune"
def convert_precision(self, tensor: torch.Tensor, precision: Precision):
precision = Precision.from_str(precision)
log.debug(f"Converting to {precision}")
match precision:
case Precision.FP8:
if tensor.dtype in dtypes_to_fp8:
return tensor.to(torch.float8_e4m3fn)
log.error(f"Cannot convert {tensor.dtype} to fp8")
return tensor
case Precision.FP16:
if tensor.dtype in dtypes_to_fp16:
return tensor.half()
log.error(f"Cannot convert {tensor.dtype} to f16")
return tensor
case Precision.BF16:
if tensor.dtype in dtypes_to_bf16:
return tensor.bfloat16()
log.error(f"Cannot convert {tensor.dtype} to bf16")
return tensor
case Precision.FULL | Precision.FP32:
return tensor
def is_sdxl_model(self, clip: dict[str, torch.Tensor] | None):
if clip:
return (any(k.startswith("conditioner.embedders") for k in clip),)
return False
def has_ema(self, unet: dict[str, torch.Tensor]):
return any(k.startswith("model_ema") for k in unet)
def fix_clip(self, clip: dict[str, torch.Tensor] | None):
if self.is_sdxl_model(clip):
log.warn("[fix clip] SDXL not supported")
return
if clip is None:
return
position_id_key = (
"cond_stage_model.transformer.text_model.embeddings.position_ids"
)
if position_id_key in clip:
correct = torch.Tensor([list(range(77))]).to(torch.int64)
now = clip[position_id_key].to(torch.int64)
broken = correct.ne(now)
broken = [i for i in range(77) if broken[0][i]]
if len(broken) != 0:
clip[position_id_key] = correct
log.info(f"[Converter] Fixed broken clip\n{broken}")
else:
log.info(
"[Converter] Clip in this model is fine, skip fixing..."
)
else:
log.info("[Converter] Missing position id in model, try fixing...")
clip[position_id_key] = torch.Tensor([list(range(77))]).to(
torch.int64
)
return clip
def get_dicts(self, unet, clip, vae):
clip_sd = clip.get_sd()
state_dict = unet.model.state_dict_for_saving(
clip_sd, vae.get_sd(), None
)
unet = {
k: v
for k, v in state_dict.items()
if k.startswith("model.diffusion_model")
}
clip = {
k: v
for k, v in state_dict.items()
if k.startswith("cond_stage_model")
or k.startswith("conditioner.embedders")
}
vae = {
k: v
for k, v in state_dict.items()
if k.startswith("first_stage_model")
}
other = {
k: v
for k, v in state_dict.items()
if k not in unet and k not in vae and k not in clip
}
return (unet, clip, vae, other)
def do_remove_junk(self, tensors: dict[str, dict[str, torch.Tensor]]):
need_delete: list[str] = []
for layer in tensors:
for key in layer:
for jk in PRUNE_DATA["known_junk_prefix"]:
if key.startswith(jk):
need_delete.append(".".join([layer, key]))
for k in need_delete:
log.info(f"Removing junk data: {k}")
del tensors[k]
return tensors
def prune(
self,
*,
save_separately: bool,
save_folder: str,
fix_clip: bool,
remove_junk: bool,
ema_mode: str,
precision_unet: Precision,
precision_clip: Precision,
precision_vae: Precision,
operation_unet: str,
operation_clip: str,
operation_vae: str,
unet: dict[str, torch.Tensor] | None = None,
clip: dict[str, torch.Tensor] | None = None,
vae: dict[str, torch.Tensor] | None = None,
):
operation = {
"unet": Operation.from_str(operation_unet),
"clip": Operation.from_str(operation_clip),
"vae": Operation.from_str(operation_vae),
}
precision = {
"unet": Precision.from_str(precision_unet),
"clip": Precision.from_str(precision_clip),
"vae": Precision.from_str(precision_vae),
}
unet, clip, vae, _other = self.get_dicts(unet, clip, vae)
out_dir = Path(save_folder)
folder = out_dir.parent
if not out_dir.is_absolute():
folder = (comfy_out_dir / save_folder).parent
if not folder.exists():
if folder.parent.exists():
folder.mkdir()
else:
raise FileNotFoundError(
f"Folder {folder.parent} does not exist"
)
name = out_dir.name
save_name = f"{name}-{precision_unet}"
if ema_mode != "disabled":
save_name += f"-{ema_mode}"
if fix_clip:
save_name += "-clip-fix"
if (
any(o == Operation.CONVERT for o in operation.values())
and any(p == Precision.FP8 for p in precision.values())
and torch.__version__ < "2.1.0"
):
raise NotImplementedError(
"PyTorch 2.1.0 or newer is required for fp8 conversion"
)
if not self.is_sdxl_model(clip):
for part in [unet, vae, clip]:
if part:
nai_keys = PRUNE_DATA["nai_keys"]
for k in list(part.keys()):
for r in nai_keys:
if isinstance(k, str) and k.startswith(r):
new_key = k.replace(r, nai_keys[r])
part[new_key] = part[k]
del part[k]
log.info(
f"[Converter] Fixed novelai error key {k}"
)
break
if fix_clip:
clip = self.fix_clip(clip)
ok: dict[str, dict[str, torch.Tensor]] = {
"unet": {},
"clip": {},
"vae": {},
}
def _hf(part: str, wk: str, t: torch.Tensor):
if not isinstance(t, torch.Tensor):
log.debug("Not a torch tensor, skipping key")
return
log.debug(f"Operation {operation[part]}")
if operation[part] == Operation.CONVERT:
ok[part][wk] = self.convert_precision(
t, precision[part]
) # conv_func(t)
elif operation[part] == Operation.COPY:
ok[part][wk] = t
elif operation[part] == Operation.DELETE:
return
log.info("[Converter] Converting model...")
for part_name, part in zip(
["unet", "vae", "clip", "other"],
[unet, vae, clip],
strict=False,
):
if part:
match ema_mode:
case "remove_ema":
for k, v in tqdm.tqdm(part.items()):
if "model_ema." not in k:
_hf(part_name, k, v)
case "ema_only":
if not self.has_ema(part):
log.warn("No EMA to extract")
return
for k in tqdm.tqdm(part):
ema_k = "___"
try:
ema_k = "model_ema." + k[6:].replace(".", "")
except Exception:
pass
if ema_k in part:
_hf(part_name, k, part[ema_k])
elif not k.startswith("model_ema.") or k in [
"model_ema.num_updates",
"model_ema.decay",
]:
_hf(part_name, k, part[k])
case "disabled" | _:
for k, v in tqdm.tqdm(part.items()):
_hf(part_name, k, v)
if save_separately:
if remove_junk:
ok = self.do_remove_junk(ok)
flat_ok = {
k: v
for _, subdict in ok.items()
for k, v in subdict.items()
}
save_path = (
folder / f"{part_name}-{save_name}.safetensors"
).as_posix()
safetensors.torch.save_file(flat_ok, save_path)
ok: dict[str, dict[str, torch.Tensor]] = {
"unet": {},
"clip": {},
"vae": {},
}
if save_separately:
return ()
if remove_junk:
ok = self.do_remove_junk(ok)
flat_ok = {
k: v for _, subdict in ok.items() for k, v in subdict.items()
}
try:
safetensors.torch.save_file(
flat_ok, (folder / f"{save_name}.safetensors").as_posix()
)
except Exception as e:
log.error(e)
return ()
__nodes__ = [MTB_ModelPruner]
+85
View File
@@ -0,0 +1,85 @@
import qrcode
import torch
from PIL import Image
from ..log import log
from ..utils import pil2tensor
class MTB_QrCode:
"""Basic QR Code generator."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"url": ("STRING", {"default": "https://www.github.com"}),
"width": (
"INT",
{"default": 256, "max": 8096, "min": 0, "step": 1},
),
"height": (
"INT",
{"default": 256, "max": 8096, "min": 0, "step": 1},
),
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
"box_size": (
"INT",
{"default": 10, "max": 8096, "min": 0, "step": 1},
),
"border": (
"INT",
{"default": 4, "max": 8096, "min": 0, "step": 1},
),
"invert": (("BOOLEAN",), {"default": False}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_qr"
CATEGORY = "mtb/generate"
def do_qr(
self,
*,
url: str,
width: int,
height: int,
error_correct: str,
box_size: int,
border: int,
invert: bool,
) -> tuple[torch.Tensor]:
log.warning(
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
)
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
error_correct = qrcode.constants.ERROR_CORRECT_L
elif error_correct == "M":
error_correct = qrcode.constants.ERROR_CORRECT_M
elif error_correct == "Q":
error_correct = qrcode.constants.ERROR_CORRECT_Q
else:
error_correct = qrcode.constants.ERROR_CORRECT_H
qr = qrcode.QRCode(
version=1,
error_correction=error_correct,
box_size=box_size,
border=border,
)
qr.add_data(url)
qr.make(fit=True)
back_color = (255, 255, 255) if invert else (0, 0, 0)
fill_color = (0, 0, 0) if invert else (255, 255, 255)
code = qr.make_image(back_color=back_color, fill_color=fill_color)
# that we now resize without filtering
code = code.resize((width, height), Image.NEAREST)
return (pil2tensor(code),)
__nodes__ = [MTB_QrCode]
+42 -15
View File
@@ -1,15 +1,16 @@
from math import ceil, sqrt
from typing import cast
import torch
import torchvision.transforms.functional as TF
from ..utils import log, hex_to_rgb, tensor2pil, pil2tensor
from math import sqrt, ceil
from typing import cast
from PIL import Image
from ..utils import hex_to_rgb, log, pil2tensor, tensor2pil
class TransformImage:
class MTB_TransformImage:
"""Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy
it return a tensor representing the transformed images with the same shape as the input tensor
"""
@@ -18,10 +19,22 @@ class TransformImage:
return {
"required": {
"image": ("IMAGE",),
"x": ("FLOAT", {"default": 0, "step": 1, "min": -4096, "max": 4096}),
"y": ("FLOAT", {"default": 0, "step": 1, "min": -4096, "max": 4096}),
"zoom": ("FLOAT", {"default": 1.0, "min": 0.001, "step": 0.01}),
"angle": ("FLOAT", {"default": 0, "step": 1, "min": -360, "max": 360}),
"x": (
"FLOAT",
{"default": 0, "step": 1, "min": -4096, "max": 4096},
),
"y": (
"FLOAT",
{"default": 0, "step": 1, "min": -4096, "max": 4096},
),
"zoom": (
"FLOAT",
{"default": 1.0, "min": 0.001, "step": 0.01},
),
"angle": (
"FLOAT",
{"default": 0, "step": 1, "min": -360, "max": 360},
),
"shear": (
"FLOAT",
{"default": 0, "step": 1, "min": -4096, "max": 4096},
@@ -53,14 +66,21 @@ class TransformImage:
y = int(y)
angle = int(angle)
log.debug(f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}")
log.debug(
f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}"
)
if image.size(0) == 0:
return (torch.zeros(0),)
transformed_images = []
frames_count, frame_height, frame_width, frame_channel_count = image.size()
frames_count, frame_height, frame_width, frame_channel_count = (
image.size()
)
new_height, new_width = int(frame_height * zoom), int(frame_width * zoom)
new_height, new_width = (
int(frame_height * zoom),
int(frame_width * zoom),
)
log.debug(f"New height: {new_height}, New width: {new_width}")
@@ -74,7 +94,12 @@ class TransformImage:
pw += abs(max_padding)
ph += abs(max_padding)
padding = [max(0, pw + x), max(0, ph + y), max(0, pw - x), max(0, ph - y)]
padding = [
max(0, pw + x),
max(0, ph + y),
max(0, pw - x),
max(0, ph - y),
]
constant_color = hex_to_rgb(constant_color)
log.debug(f"Fill Tuple: {constant_color}")
@@ -89,7 +114,9 @@ class TransformImage:
img = cast(
Image.Image,
TF.affine(img, angle=angle, scale=zoom, translate=[x, y], shear=shear),
TF.affine(
img, angle=angle, scale=zoom, translate=[x, y], shear=shear
),
)
left = abs(padding[0])
@@ -107,4 +134,4 @@ class TransformImage:
return (pil2tensor(transformed_images),)
__nodes__ = [TransformImage]
__nodes__ = [MTB_TransformImage]
+445
View File
@@ -0,0 +1,445 @@
import torch
from ..utils import create_uv_map_tensor, log
class oldDistortImageWithUv:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"uv_map": ("UV_MAP",),
"strength": ("FLOAT", {"default": 1.0, "step": 0.05}),
},
"optional": {
"base_uv_map": ("UV_MAP",),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "distort_image_with_uv"
CATEGORY = "mtb/uv"
def distort_image_with_uv(
self, image, uv_map, strength=1.0, base_uv_map=None
):
assert (
image.shape[1:3] == uv_map.shape[1:3]
), "Spatial dimensions of image and uv_map must match!"
if base_uv_map is None:
base_uv_map = create_uv_map_tensor(image.shape[2], image.shape[1])
# Interpolate (or extrapolate) between base UV map and the distorted UV map based on strength
uv_map = strength * uv_map + (1.0 - strength) * base_uv_map
# Ensure the image and uv_map have the same spatial dimensions
# Extract U and V coordinates
U = uv_map[:, :, :, 0]
V = uv_map[:, :, :, 1]
# Convert U and V to pixel coordinates
b, h, w, _ = image.shape
U = U * (w - 1)
V = V * (h - 1)
# Calculate the four corner indices for each UV coordinate
U0 = torch.floor(U).long()
V0 = torch.floor(V).long()
U1 = U0 + 1
V1 = V0 + 1
# Clip the indices to be within the image dimensions
U0 = torch.clamp(U0, 0, w - 1)
U1 = torch.clamp(U1, 0, w - 1)
V0 = torch.clamp(V0, 0, h - 1)
V1 = torch.clamp(V1, 0, h - 1)
# Bilinear interpolation weights
w_U0 = (U1.float() - U).unsqueeze(-1)
w_U1 = (U - U0.float()).unsqueeze(-1)
w_V0 = (V1.float() - V).unsqueeze(-1)
w_V1 = (V - V0.float()).unsqueeze(-1)
# Sample image using bilinear interpolation
distorted = (
(w_U0 * w_V0) * image[:, V0, U0]
+ (w_U0 * w_V1) * image[:, V1, U0]
+ (w_U1 * w_V0) * image[:, V0, U1]
+ (w_U1 * w_V1) * image[:, V1, U1]
)
return (distorted.squeeze(0),)
class ImageDistortWithUv:
"""Distorts an image based on a UV map."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"uv_map": ("UV_MAP",),
"boundary_mode": (
["clamp", "wrap", "reflect", "replicate"],
{"default": "wrap"},
),
"strength": ("FLOAT", {"default": 1.0, "step": 0.05}),
},
"optional": {
"base_uv_map": ("UV_MAP",),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "distort_image_with_uv"
CATEGORY = "mtb/uv"
def distort_image_with_uv(
self,
image,
uv_map,
boundary_mode="wrap",
strength=1.0,
base_uv_map=None,
):
log.debug(f"[UV Distort] Input image shape {image.shape}")
if image.size(0) == 0:
log.debug("Input image is empty, returning empty image")
return (torch.zeros(0),)
b, h, w, _ = image.shape
x = w - 1
y = h - 1
# If no base UV map provided, create a default one
if base_uv_map is None:
base_uv_map = create_uv_map_tensor(w, h).to(image.device)
# Extract U and V coordinates from the base UV map
base_U = base_uv_map[..., 0] * x
base_V = base_uv_map[..., 1] * y
# Extract U and V coordinates from the distortion UV map and apply strength
U = strength * uv_map[..., 0] * x + (1 - strength) * base_U
V = strength * uv_map[..., 1] * y + (1 - strength) * base_V
# Handle boundary conditions
if boundary_mode == "wrap":
U = U % w
V = V % h
elif boundary_mode == "reflect":
U = U % (2 * x)
V = V % (2 * y)
U = torch.where(w < U, 2 * x - U, U)
V = torch.where(h < V, 2 * y - V, V)
elif boundary_mode == "replicate":
U = torch.clamp(U, 0, x)
V = torch.clamp(V, 0, y)
elif boundary_mode == "clamp":
U = torch.clamp(U, 0, w)
V = torch.clamp(V, 0, h)
else:
raise ValueError("Invalid boundary_mode")
# Check if any UV coordinates are out of bounds and log
if torch.any(w <= U) or torch.any(h <= V):
log.info("Input UVs out of bounds, clipping")
# Calculate the four corner indices for each UV coordinate
U0, V0 = torch.floor(U).long(), torch.floor(V).long()
# For replicate mode, if U0/V0 is at the last pixel, we replicate that pixel for U1/V1
if boundary_mode == "replicate":
U1 = torch.where(x > U0, U0 + 1, U0)
V1 = torch.where(y > V0, V0 + 1, V0)
else:
U1, V1 = U0 + 1, V0 + 1
# Ensure U1, V1 do not go out of bounds
U1 = torch.clamp(U1, 0, x)
V1 = torch.clamp(V1, 0, y)
# Adjust the bilinear coordinates based on the boundary mode
if boundary_mode == "wrap":
U1 = U1 % w
V1 = V1 % h
elif boundary_mode == "reflect":
# This remains unchanged as the coordinates are already reflected above
pass
elif boundary_mode == "replicate":
U1 = torch.clamp(U1, 0, x)
V1 = torch.clamp(V1, 0, y)
# Bilinear interpolation weights
w_U0, w_U1 = (
(U1.float() - U).unsqueeze(-1),
(U - U0.float()).unsqueeze(-1),
)
w_V0, w_V1 = (
(V1.float() - V).unsqueeze(-1),
(V - V0.float()).unsqueeze(-1),
)
# Sample image using bilinear interpolation
distorted = (
(w_U0 * w_V0) * image[:, V0, U0]
+ (w_U0 * w_V1) * image[:, V1, U0]
+ (w_U1 * w_V0) * image[:, V0, U1]
+ (w_U1 * w_V1) * image[:, V1, U1]
)
return (distorted.squeeze(0),)
class UvToImage:
"""Converts the UV map to an image. (Shallow converter)"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"uv_map": ("UV_MAP",),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "uv_to_image"
CATEGORY = "mtb/uv"
def uv_to_image(self, uv_map):
return (uv_map,)
class UvRemoveSeams:
"""Blends values near the UV borders to mitigate visible seams."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"uv_map": ("UV_MAP",),
"radius": ("FLOAT", {"default": 0.01, "step": 0.01}),
}
}
RETURN_TYPES = ("UV_MAP",)
RETURN_NAMES = ("uv_map",)
FUNCTION = "remove_uv_seams"
CATEGORY = "mtb/uv"
def remove_uv_seams(self, uv_map, radius):
# Create masks for U and V coordinates close to 0 or 1
u_border_mask = (uv_map[..., 0] < radius) | (
uv_map[..., 0] > 1 - radius
)
v_border_mask = (uv_map[..., 1] < radius) | (
uv_map[..., 1] > 1 - radius
)
# Soften the UV coordinates near the borders
uv_map[..., 0] = torch.where(
u_border_mask, uv_map[..., 0] * 0.5, uv_map[..., 0]
)
uv_map[..., 1] = torch.where(
v_border_mask, uv_map[..., 1] * 0.5, uv_map[..., 1]
)
return (uv_map,)
class UvTile:
"""Tiles the UV map based on the specified number of tiles."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"uv_map": ("UV_MAP",),
"tiles_u": ("INT", {"default": 1}),
"tiles_v": ("INT", {"default": 1}),
"alt_method": ("BOOLEAN", {"default": False}),
}
}
RETURN_TYPES = ("UV_MAP",)
RETURN_NAMES = ("uv_map",)
FUNCTION = "tile"
CATEGORY = "mtb/uv"
def tile(self, uv_map, tiles_u, tiles_v, alt_method=False):
tiled_uv = uv_map.clone()
if alt_method:
tiled_uv[..., 0] = (
uv_map[..., 0] * tiles_u
).floor() / tiles_u + uv_map[..., 0] % (1.0 / tiles_u)
tiled_uv[..., 1] = (
uv_map[..., 1] * tiles_v
).floor() / tiles_v + uv_map[..., 1] % (1.0 / tiles_v)
else:
tiled_uv[..., 0] = (
uv_map[..., 0] * tiles_u % 1.0
) # tile and wrap U coordinates
tiled_uv[..., 1] = (
uv_map[..., 1] * tiles_v % 1.0
) # tile and wrap V coordinates
return (tiled_uv,)
class ImageToUv:
"""Turn an image back into a UV map. (Shallow converter)"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_uv": ("IMAGE",),
}
}
RETURN_TYPES = ("UV_MAP",)
RETURN_NAMES = ("uv_map",)
FUNCTION = "image_to_uv"
CATEGORY = "mtb/uv"
def image_to_uv(self, image_uv):
return (image_uv,)
class UvDistort:
"""Applies a polar coordinates or wave distortion to the UV map"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"uv_map": ("UV_MAP",),
"mode": (["polar", "wave"], {"default": "polar"}),
"polar_strength": (
"FLOAT",
{"default": 1.0, "step": 0.05, "min": -1.0, "max": 1.0},
),
"wave_frequency": ("FLOAT", {"default": 10.0}),
"wave_amplitude": (
"FLOAT",
{"default": 0.05, "step": 0.05, "min": -1.0, "max": 1.0},
),
}
}
RETURN_TYPES = ("UV_MAP",)
RETURN_NAMES = ("uv_map",)
FUNCTION = "distort_uvs"
CATEGORY = "mtb/uv"
def distort_uvs(
self,
uv_map: torch.Tensor,
mode,
polar_strength,
wave_frequency,
wave_amplitude,
):
if mode == "polar":
return (self.apply_polar_distortion(uv_map, polar_strength),)
elif mode == "wave":
return (
self.apply_wave_distortion(
uv_map, wave_frequency, wave_amplitude
),
)
else:
raise ValueError(f"Unknown mode {mode}")
@classmethod
def apply_wave_distortion(cls, uv_map, frequency=10.0, amplitude=0.05):
"""
Applies a wave distortion to the UV map and returns an RGB representation.
Args:
- uv_map (torch.Tensor): The UV map tensor.
- frequency (float): Frequency of the wave.
- amplitude (float): Amplitude of the wave.
Returns
-------
- torch.Tensor: Distorted UV map in RGB format.
"""
U = uv_map[:, :, :, 0]
V = uv_map[:, :, :, 1]
# Apply wave distortion
V_distorted = V + amplitude * torch.sin(U * frequency * 2 * 3.14159)
# Clip V values to [0, 1]
V_distorted = torch.clamp(V_distorted, 0, 1)
R = U
G = V_distorted
B = torch.zeros_like(R)
return torch.stack([R, G, B], dim=-1)
@classmethod
def apply_polar_distortion(cls, uv_map: torch.Tensor, strength=1.0):
"""
Applies a polar coordinates distortion to the UV map and returns an RGB representation.
Args:
- uv_map (torch.Tensor): The UV map tensor.
- strength (float): The strength of the distortion.
Returns
-------
- torch.Tensor: Distorted UV map in RGB format.
"""
U = uv_map[:, :, :, 0]
V = uv_map[:, :, :, 1]
# Convert U and V to centered coordinates [-0.5, 0.5]
U = U * 2 - 1
V = V * 2 - 1
# Convert to polar coordinates
R = torch.sqrt(U * U + V * V)
Theta = torch.atan2(V, U)
# Distort the radius
R_distorted = (
R + (1.0 - R) * strength
) # Changing this line for intuitive strength
# Convert back to Cartesian
U_distorted = R_distorted * torch.cos(Theta)
V_distorted = R_distorted * torch.sin(Theta)
# Normalize to [0, 1]
U_distorted = (U_distorted + 1) / 2
V_distorted = (V_distorted + 1) / 2
# Clip to ensure values are in [0, 1]
U_distorted = torch.clamp(U_distorted, 0, 1)
V_distorted = torch.clamp(V_distorted, 0, 1)
R = U_distorted
G = V_distorted
B = torch.zeros_like(R)
return torch.stack([R, G, B], dim=-1)
__nodes__ = [
UvDistort,
UvToImage,
ImageToUv,
ImageDistortWithUv,
UvTile,
UvRemoveSeams,
]
+247 -26
View File
@@ -1,20 +1,171 @@
import hashlib, json, os, re
import hashlib
import json
import os
import re
from pathlib import Path
import comfy.utils
import folder_paths
import imageio.v3 as iio
import numpy as np
import torch
from comfy.model_management import get_torch_device
from PIL import Image, ImageOps
from PIL.PngImagePlugin import PngInfo
from ..log import log
from ..utils import np2tensor
SUPPORTED_FORMATS = ["avi", "mov", "webm", "mp4", "mkv", "gif"]
class LoadImageSequence:
class MTBLiveVideo:
@classmethod
def INPUT_TYPES(s):
input_dir = Path(folder_paths.get_input_directory())
files = [
f.name
for f in input_dir.iterdir()
if f.is_file() and f.suffix[1:] in SUPPORTED_FORMATS
]
return {
"required": {
"video": (["custom"] + sorted(files), {"default": "custom"}),
"video_path": ("STRING", {"default": ""}),
"frame_in": (
"INT",
{"default": 0, "min": 0, "step": 1},
),
"frame_out": (
"INT",
{"default": -1, "min": -1, "step": 1},
),
"frame_steps": (
"INT",
{"default": 1, "min": 1, "step": 1},
),
"device": (["auto", "cpu"], {"default": "auto"}),
},
}
CATEGORY = "mtb/video"
FUNCTION = "video"
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("video frames",)
def video(
self,
video: str,
video_path: str,
frame_in=0,
frame_out=-1,
frame_steps=1,
device="auto",
):
device = get_torch_device() if device == "auto" else device
if video == "custom":
pth = Path(video_path)
if not pth.exists():
raise FileNotFoundError(
"The video {pth} doesn't seem to exist"
)
video = pth.as_posix()
else:
video = folder_paths.get_annotated_filepath(video.strip('"'))
frames = []
# total = 5
# pbar = comfy.utils.ProgressBar(total)
for i, frame in enumerate(iio.imiter(video, plugin="FFMPEG")):
if (
i >= frame_in # first frame
and (i <= frame_out or frame_out == -1) # in range
and i % frame_steps == 0 # stepping
):
frames.append(frame)
return (np2tensor(frames).to(device),)
@classmethod
def IS_CHANGED(cls, video, **parms):
image_path = folder_paths.get_annotated_filepath(video)
m = hashlib.sha256()
with open(image_path, "rb") as f:
m.update(f.read())
return m.digest().hex()
@classmethod
def VALIDATE_INPUTS(cls, video, **parms):
if not folder_paths.exists_annotated_filepath(video):
return f"Invalid video file: {video}"
return True
class MTBCotracker2:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"grid_size": (
"INT",
{"default": 10, "min": 1, "max": 100},
),
}
}
CATEGORY = "mtb/video"
FUNCTION = "track"
RETURN_TYPES = ("COTRACK_DATA",)
RETURN_NAMES = ("tracking data",)
def track(self, image: torch.Tensor, grid_size=10):
device = get_torch_device()
cotracker = torch.hub.load(
"facebookresearch/co-tracker", "cotracker2"
).to(device)
video = (
image.permute(0, 3, 1, 2).unsqueeze(0).float().to(device)
) # B T C H W
pred_tracks, pred_visibility = cotracker(
video, grid_size=grid_size
).to(device) # B T N 2, B T N 1
return (
{"pred_tracks": pred_tracks, "pred_visibility": pred_visibility},
)
@staticmethod
def IS_CHANGED(path="", current_frame=0):
print(f"Checking if changed: {path}, {current_frame}")
# resolved_path = resolve_path(path, current_frame)
# image_path = folder_paths.get_annotated_filepath(resolved_path)
# if os.path.exists(image_path):
# m = hashlib.sha256()
# with open(image_path, "rb") as f:
# m.update(f.read())
# return m.digest().hex()
# return "NONE"
# @staticmethod
# def VALIDATE_INPUTS(path="", current_frame=0):
# print(f"Validating inputs: {path}, {current_frame}")
# resolved_path = resolve_path(path, current_frame)
# if not folder_paths.exists_annotated_filepath(resolved_path):
# return f"Invalid image file: {resolved_path}"
# return True
class MTB_LoadImageSequence:
"""Load an image sequence from a folder. The current frame is used to determine which image to load.
Usually used in conjunction with the `Primitive` node set to increment to load a sequence of images from a folder.
The current_frame property is used to determine which image to load.
Usually used in conjunction with the `Primitive` node set to increment
Use -1 to load all matching frames as a batch.
"""
@classmethod
@@ -26,7 +177,10 @@ class LoadImageSequence:
"INT",
{"default": 0, "min": -1, "max": 9999999},
),
}
},
"optional": {
"range": ("STRING", {"default": ""}),
},
}
CATEGORY = "mtb/IO"
@@ -35,17 +189,28 @@ class LoadImageSequence:
"IMAGE",
"MASK",
"INT",
"INT",
)
RETURN_NAMES = (
"image",
"mask",
"current_frame",
"total_frames",
)
def load_image(self, path=None, current_frame=0):
def load_image(self, path=None, current_frame=0, range=""):
load_all = current_frame == -1
total_frames = 1
if load_all:
if range:
frames = self.get_frames_from_range(path, range)
imgs, masks = zip(*(img_from_path(frame) for frame in frames))
out_img = torch.cat(imgs, dim=0)
out_mask = torch.cat(masks, dim=0)
total_frames = len(imgs)
return (out_img, out_mask, -1, total_frames)
elif load_all:
log.debug(f"Loading all frames from {path}")
frames = resolve_all_frames(path)
log.debug(f"Found {len(frames)} frames")
@@ -53,33 +218,72 @@ class LoadImageSequence:
imgs = []
masks = []
for frame in frames:
img, mask = img_from_path(frame)
imgs.append(img)
masks.append(mask)
imgs, masks = zip(*(img_from_path(frame) for frame in frames))
out_img = torch.cat(imgs, dim=0)
out_mask = torch.cat(masks, dim=0)
total_frames = len(imgs)
return (
out_img,
out_mask,
)
return (out_img, out_mask, -1, total_frames)
log.debug(f"Loading image: {path}, {current_frame}")
print(f"Loading image: {path}, {current_frame}")
resolved_path = resolve_path(path, current_frame)
image_path = folder_paths.get_annotated_filepath(resolved_path)
image, mask = img_from_path(image_path)
return (
image,
mask,
current_frame,
)
return (image, mask, current_frame, total_frames)
def get_frames_from_range(self, path, range_str):
try:
start, end = map(int, range_str.split("-"))
except ValueError:
raise ValueError(
f"Invalid range format: {range_str}. Expected format is 'start-end'."
)
frames = resolve_all_frames(path)
total_frames = len(frames)
if start < 0 or end >= total_frames:
raise ValueError(
f"Range {range_str} is out of bounds. Total frames available: {total_frames}"
)
if "#" in path:
frame_regex = re.escape(path).replace(r"\#", r"(\d+)")
frame_number_regex = re.compile(frame_regex)
matching_frames = []
for frame in frames:
match = frame_number_regex.search(frame)
if match:
frame_number = int(match.group(1))
if start <= frame_number <= end:
matching_frames.append(frame)
return matching_frames
else:
log.warning(
f"Wildcard pattern or directory will use indexes instead of frame numbers for : {path}"
)
selected_frames = frames[start : end + 1]
return selected_frames
@staticmethod
def IS_CHANGED(path="", current_frame=0):
def IS_CHANGED(path="", current_frame=0, range=""):
print(f"Checking if changed: {path}, {current_frame}")
if range or current_frame == -1:
resolved_paths = resolve_all_frames(path)
timestamps = [
os.path.getmtime(folder_paths.get_annotated_filepath(p))
for p in resolved_paths
]
combined_hash = hashlib.sha256(
"".join(map(str, timestamps)).encode()
)
return combined_hash.hexdigest()
resolved_path = resolve_path(path, current_frame)
image_path = folder_paths.get_annotated_filepath(resolved_path)
if os.path.exists(image_path):
@@ -119,11 +323,28 @@ def img_from_path(path):
)
def resolve_all_frames(pattern):
def resolve_all_frames(path: str):
frames: list[str] = []
if "#" not in path:
pth = Path(path)
if pth.is_dir():
for f in pth.iterdir():
if f.suffix in [".jpg", ".png"]:
frames.append(f.as_posix())
elif "*" in path:
frames = glob.glob(path)
else:
raise ValueError(
"The path doesn't contain a # or a * or is not a directory"
)
frames.sort()
return frames
pattern = path
folder_path, file_pattern = os.path.split(pattern)
log.debug(f"Resolving all frames in {folder_path}")
frames = []
hash_count = file_pattern.count("#")
frame_pattern = re.sub(r"#+", "*", file_pattern)
@@ -155,7 +376,7 @@ def resolve_path(path, frame):
return re.sub("#+", padded_number, path)
class SaveImageSequence:
class MTB_SaveImageSequence:
"""Save an image sequence to a folder. The current frame is used to determine which image to save.
This is merely a wrapper around the `save_images` function with formatting for the output folder and filename.
@@ -251,6 +472,6 @@ class SaveImageSequence:
__nodes__ = [
LoadImageSequence,
SaveImageSequence,
MTB_LoadImageSequence,
MTB_SaveImageSequence,
]
+141
View File
@@ -0,0 +1,141 @@
import cv2
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from ..utils import models_dir, np2tensor
# TODO: check if I can make a torch script device independant
# for now I forced it to use cuda.
class MTB_LoadVitMatteModel:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"kind": (("Composition-1K", "Distinctions-646"),),
"autodownload": ("BOOLEAN", {"default": True}),
},
}
RETURN_TYPES = ("VITMATTE_MODEL",)
RETURN_NAMES = ("torch_script",)
CATEGORY = "mtb/vitmatte"
FUNCTION = "execute"
def execute(self, *, kind: str, autodownload: bool):
dest = models_dir / "vitmatte"
dest.mkdir(exist_ok=True)
name = "dist" if kind == "Distinctions-646" else "com"
file = hf_hub_download(
repo_id="melmass/pytorch-scripts",
filename=f"vitmatte_b_{name}.pt",
local_dir=dest.as_posix(),
local_files_only=not autodownload,
)
model = torch.jit.load(file).to("cuda")
return (model,)
class MTB_GenerateTrimap:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# "image": ("IMAGE",),
"mask": ("MASK",),
"erode": ("INT", {"default": 10}),
"dilate": ("INT", {"default": 10}),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("trimap",)
CATEGORY = "mtb/vitmatte"
FUNCTION = "execute"
def execute(
self,
# image:torch.Tensor,
mask: torch.Tensor,
erode: int = 10,
dilate: int = 10,
):
# TODO: not sure what's the most practical between IMAGE or MASK
# image = image.to("cuda").half()
mask = mask.to("cuda").half()
trimaps = []
for m in mask:
mask_arr = m.squeeze(0).to(torch.uint8).cpu().numpy() * 255
erode_kernel = np.ones((erode, erode), np.uint8)
dilate_kernel = np.ones((dilate, dilate), np.uint8)
eroded = cv2.erode(mask_arr, erode_kernel, iterations=5)
dilated = cv2.dilate(mask_arr, dilate_kernel, iterations=5)
trimap = np.zeros_like(mask_arr)
trimap[dilated == 255] = 128
trimap[eroded == 255] = 255
trimaps.append(trimap)
return (np2tensor(trimaps),)
class MTB_ApplyVitMatte:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model": ("VITMATTE_MODEL",),
"image": ("IMAGE",),
"trimap": ("IMAGE",),
"returns": (("RGB", "RGBA"),),
},
}
RETURN_TYPES = ("IMAGE", "MASK")
RETURN_NAMES = ("image (rgba)", "mask")
CATEGORY = "mtb/utils"
FUNCTION = "execute"
def execute(
self, model, image: torch.Tensor, trimap: torch.Tensor, returns: str
):
im_count = image.shape[0]
tm_count = trimap.shape[0]
if im_count != tm_count:
raise ValueError("image and trimap must have the same batch size")
outputs_m: list[torch.Tensor] = []
outputs_i: list[torch.Tensor] = []
for i, im in enumerate(image):
tm = trimap[i].half().unsqueeze(2).permute(2, 0, 1).to("cuda")
im = im.half().permute(2, 0, 1).to("cuda")
inputs = {"image": im.unsqueeze(0), "trimap": tm.unsqueeze(0)}
fine_mask = model(inputs)
foreground = im * fine_mask + (1 - fine_mask)
if returns == "RGBA":
rgba_image = torch.cat(
(foreground, fine_mask.unsqueeze(0)), dim=0
)
outputs_i.append(rgba_image.unsqueeze(0))
else:
outputs_i.append(foreground.unsqueeze(0))
outputs_m.append(fine_mask.unsqueeze(0))
result_m = torch.cat(outputs_m, dim=0)
result_i = torch.cat(outputs_i, dim=0)
return (result_i.permute(0, 2, 3, 1), result_m)
__nodes__ = [MTB_LoadVitMatteModel, MTB_GenerateTrimap, MTB_ApplyVitMatte]
+106 -35
View File
@@ -1,12 +1,16 @@
[tool.poetry]
[build-system]
requires = ["setuptools", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "comfy-mtb"
version = "0.4.0"
version = "0.2.0"
description = "Animation oriented nodes pack for ComfyUI."
license = "MIT"
readme = "README.md"
repository = "https://github.com/melMass/comfy_mtb"
authors = ["Mel Massadian"]
packages = [{ include = "comfy-mtb" }]
# repository = ""
# url = "https://github.com/melMass/comfy_mtb"
authors = [{ name = "Mel Massadian", email = "mel@melmassadian.com" }]
classifiers = [
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
@@ -16,31 +20,100 @@ classifiers = [
"Programming Language :: Python :: 3.11",
"Intended Audience :: Developers",
]
requires-python = ">=3.10"
dependencies = [
"qrcode",
"cachetools",
"onnxruntime-gpu",
"requirements-parserx",
"rembg",
"imageio_ffmpeg",
"rich",
"rich_argparse",
"matplotlib",
"pillow",
]
optional-dependencies = { mel = [
"jupyterlab==4.1.6",
], dev = [
"black[jupyter]",
"codespell",
"mypy",
"pre-commit",
"pytest",
"pytest-cov",
"pytest-random-order",
"ruff",
], doc = [
"docutils==0.17.1",
"jupyter-book>=0.15",
"sphinx-autobuild",
] }
[tool.poetry.urls]
"Bug Tracker" = "https://github.com/melMass/comfy_mtb/issues"
"Changelog" = "https://github.com/melMass/comfy_mtb/releases"
[project.urls]
Homepage = "https://github.com/melMass/comfy_mtb"
Documentation = "https://github.com/melMass/comfy_mtb/wiki"
Repository = "https://github.com/melMass/comfy_mtb"
Issues = "https://github.com/melMass/comfy_mtb/issues"
[tool.poetry.dependencies]
python = "^3.10"
[tool.comfy]
PublisherId = "mel"
DisplayName = "comfy-mtb"
Icon = "https://avatars.githubusercontent.com/u/7041726?v=4"
[tool.poetry.group.dev.dependencies]
black = { extras = ["jupyter"], version = "^23.7.0" }
codespell = "^2.2.5"
mypy = "^1.5.1"
pre-commit = "^3.3.3"
pytest = "^7.4.0"
pytest-cov = "^4.1.0"
pytest-random-order = "^1.1.0"
ruff = "^0.0.285"
[tool.bumpversion]
current_version = "0.2.0"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
serialize = ["{major}.{minor}.{patch}"]
search = "{current_version}"
replace = "{new_version}"
regex = false
ignore_missing_version = false
ignore_missing_files = false
tag = true
sign_tags = true
tag_name = "v{new_version}"
tag_message = "⬆️ Bump version: {current_version} → {new_version}"
allow_dirty = true
commit = true
message = "⬆️ Bump version: {current_version} → {new_version}"
commit_args = ""
[tool.poetry.group.docs]
optional = true
[[tool.bumpversion.files]]
filename = "__init__.py"
search = "__version__ = \"{current_version}\""
replace = "__version__ = \"{new_version}\""
[tool.poetry.group.docs.dependencies]
docutils = "0.17.1"
jupyter-book = "^0.15.1"
sphinx-autobuild = "^2021.3.14"
[[tool.bumpversion.files]]
filename = "pyproject.toml"
search = "version = \"{current_version}\""
replace = "version = \"{new_version}\""
# [[tool.bumpversion.files]]
# filename = "your_package/__init__.py"
# search = "__version__ = '{current_version}'"
# replace = "__version__ = '{new_version}'"
# INFO: All those remaining keys are meant for local dev
[tool.pyright]
include = ["."]
exclude = [
"**/node_modules",
"**/__pycache__",
"src/experimental",
"src/typestubs",
]
ignore = ["src/oldstuff"]
defineConstant = { DEBUG = true }
extraPaths = ["python", "../.."]
stubPath = "src/stubs"
reportMissingImports = true
reportMissingTypeStubs = false
typeCheckingMode = "basic"
pythonVersion = "3.10"
pythonPlatform = "Windows"
[tool.pytest.ini_options]
log_level = "DEBUG"
@@ -74,18 +147,23 @@ show_missing = true
[tool.coverage.html]
show_contexts = true
# for now ignoring
# D100 - document public modules
# D102 - document public methods of a class
[tool.ruff]
line-length = 79
select = ["A", "B", "C", "D", "E", "F", "FBT", "I", "N", "S", "SIM", "UP", "W"]
# NOTE:
# NOTE:
# D102 - undocumented-public-method (noisy)
# D103 - undocumented-public-function (noisy)
# D100 - undocumented-public-module (noisy)
# N802 - invalid-function-name (forced by comfy's arch)
ignore = ["D103", "D102", "D100", "N802"]
ignore = ["D103", "D102", "D100"]
# exclude auto generated file
extend-exclude = ["./docs/conf.py"]
[tool.ruff.lint.pep8-naming]
extend-ignore-names = ["INPUT_TYPES", "_DEFAULT_INTERPOLANT"]
[tool.ruff.per-file-ignores]
# imported but unused
"__init__.py" = ["F401"]
@@ -105,10 +183,3 @@ exclude = ["docs/conf.py"]
# exclude auto generated file
skip = "./docs/conf.py,poetry.lock"
check-filenames = true
[tool.poetry-version-plugin]
source = "git-tag"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
+6
View File
@@ -8,3 +8,9 @@ rich
rich_argparse
matplotlib
pillow
imageio
imageio-ffmpeg
aiohttp-cors
open3d==0.17.0
cachetools
+870 -3
View File
@@ -1,3 +1,870 @@
name,prompt,negative_prompt
❌Low Token,,"embedding:EasyNegative, NSFW, Cleavage, Pubic Hair, Nudity, Naked, censored"
✅Line Art / Manga,"(Anime Scene, Toonshading, Satoshi Kon, Ken Sugimori, Hiromu Arakawa:1.2), (Anime Style, Manga Style:1.3), Low detail, sketch, concept art, line art, webtoon, manhua, hand drawn, defined lines, simple shades, minimalistic, High contrast, Linear compositions, Scalable artwork, Digital art, High Contrast Shadows, glow effects, humorous illustration, big depth of field, Masterpiece, colors, concept art, trending on artstation, Vivid colors, dramatic",
name,prompt,negative_prompt
>>>>>> Generic Styles
Style: Enhance,"breathtaking {prompt} . award-winning, professional, highly detailed","ugly, deformed, noisy, blurry, distorted, grainy"
Style: Anime,"anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed","photo, deformed, black and white, realism, disfigured, low contrast"
Style: Photographic,"cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed","drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly"
Style: Digital art,"concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed","photo, photorealistic, realism, ugly"
Style: Comic book,"comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed","photograph, deformed, glitch, noisy, realistic, stock photo"
Style: Fantasy art,"ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy","photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white"
Style: Analog film,"analog film photo {prompt} . faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage","painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured"
Style: Neonpunk,"neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional","painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured"
Style: Isometric,"isometric style {prompt} . vibrant, beautiful, crisp, detailed, ultra detailed, intricate","deformed, mutated, ugly, disfigured, blur, blurry, noise, noisy, realistic, photographic"
Style: Lowpoly,"low-poly style {prompt} . low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition","noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: Origami,"origami style {prompt} . paper art, pleated paper, folded, origami art, pleats, cut and fold, centered composition","noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: Line art,"line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics","anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic"
Style: Craft clay,"play-doh style {prompt} . sculpture, clay art, centered composition, Claymation","sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: Cinematic,"cinematic film still {prompt} . shallow depth of field, vignette, highly detailed, high budget Hollywood movie, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy","anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured"
Style: 3d-model,"professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting","ugly, deformed, noisy, low poly, blurry, painting"
Style: pixel art,"pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics","sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic"
Style: Texture,"texture {prompt} top down close-up","ugly, deformed, noisy, blurry"
>>>>>> SDXL COMFYUI PORT
Style: Enhance,"breathtaking {prompt} . award-winning, professional, highly detailed","ugly, deformed, noisy, blurry, distorted, grainy"
Style: sai-3d-model,"professional 3d model {prompt} . octane render, highly detailed, volumetric, dramatic lighting","ugly, deformed, noisy, low poly, blurry, painting"
Style: sai-analog film,"analog film photo {prompt} . faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage","painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured"
Style: sai-anime,"anime artwork {prompt} . anime style, key visual, vibrant, studio anime, highly detailed","photo, deformed, black and white, realism, disfigured, low contrast"
Style: sai-cinematic,"cinematic film still {prompt} . shallow depth of field, vignette, highly detailed, high budget, bokeh, cinemascope, moody, epic, gorgeous, film grain, grainy","anime, cartoon, graphic, text, painting, crayon, graphite, abstract, glitch, deformed, mutated, ugly, disfigured"
Style: sai-comic book,"comic {prompt} . graphic illustration, comic art, graphic novel art, vibrant, highly detailed","photograph, deformed, glitch, noisy, realistic, stock photo"
Style: sai-craft clay,"play-doh style {prompt} . sculpture, clay art, centered composition, Claymation","sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: sai-digital art,"concept art {prompt} . digital artwork, illustrative, painterly, matte painting, highly detailed","photo, photorealistic, realism, ugly"
Style: sai-enhance,"breathtaking {prompt} . award-winning, professional, highly detailed","ugly, deformed, noisy, blurry, distorted, grainy"
Style: sai-fantasy art,"ethereal fantasy concept art of {prompt} . magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy","photographic, realistic, realism, 35mm film, dslr, cropped, frame, text, deformed, glitch, noise, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, sloppy, duplicate, mutated, black and white"
Style: sai-isometric,"isometric style {prompt} . vibrant, beautiful, crisp, detailed, ultra detailed, intricate","deformed, mutated, ugly, disfigured, blur, blurry, noise, noisy, realistic, photographic"
Style: sai-line art,"line art drawing {prompt} . professional, sleek, modern, minimalist, graphic, line art, vector graphics","anime, photorealistic, 35mm film, deformed, glitch, blurry, noisy, off-center, deformed, cross-eyed, closed eyes, bad anatomy, ugly, disfigured, mutated, realism, realistic, impressionism, expressionism, oil, acrylic"
Style: sai-lowpoly,"low-poly style {prompt} . low-poly game art, polygon mesh, jagged, blocky, wireframe edges, centered composition","noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: sai-neonpunk,"neonpunk style {prompt} . cyberpunk, vaporwave, neon, vibes, vibrant, stunningly beautiful, crisp, detailed, sleek, ultramodern, magenta highlights, dark purple shadows, high contrast, cinematic, ultra detailed, intricate, professional","painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured"
Style: sai-origami,"origami style {prompt} . paper art, pleated paper, folded, origami art, pleats, cut and fold, centered composition","noisy, sloppy, messy, grainy, highly detailed, ultra textured, photo"
Style: sai-photographic,"cinematic photo {prompt} . 35mm photograph, film, bokeh, professional, 4k, highly detailed","drawing, painting, crayon, sketch, graphite, impressionist, noisy, blurry, soft, deformed, ugly"
Style: sai-pixel art,"pixel-art {prompt} . low-res, blocky, pixel art style, 8-bit graphics","sloppy, messy, blurry, noisy, highly detailed, ultra textured, photo, realistic"
Style: sai-texture,"texture {prompt} top down close-up","ugly, deformed, noisy, blurry"
Style: ads-advertising,"Advertising poster style {prompt} . Professional, modern, product-focused, commercial, eye-catching, highly detailed","noisy, blurry, amateurish, sloppy, unattractive"
Style: ads-automotive,"Automotive advertisement style {prompt} . Sleek, dynamic, professional, commercial, vehicle-focused, high-resolution, highly detailed","noisy, blurry, unattractive, sloppy, unprofessional"
Style: ads-corporate,"Corporate branding style {prompt} . Professional, clean, modern, sleek, minimalist, business-oriented, highly detailed","noisy, blurry, grungy, sloppy, cluttered, disorganized"
Style: ads-fashion editorial,"Fashion editorial style {prompt} . High fashion, trendy, stylish, editorial, magazine style, professional, highly detailed","outdated, blurry, noisy, unattractive, sloppy"
Style: ads-food photography,"Food photography style {prompt} . Appetizing, professional, culinary, high-resolution, commercial, highly detailed","unappetizing, sloppy, unprofessional, noisy, blurry"
Style: ads-luxury,"Luxury product style {prompt} . Elegant, sophisticated, high-end, luxurious, professional, highly detailed","cheap, noisy, blurry, unattractive, amateurish"
Style: ads-real estate,"Real estate photography style {prompt} . Professional, inviting, well-lit, high-resolution, property-focused, commercial, highly detailed","dark, blurry, unappealing, noisy, unprofessional"
Style: ads-retail,"Retail packaging style {prompt} . Vibrant, enticing, commercial, product-focused, eye-catching, professional, highly detailed","noisy, blurry, amateurish, sloppy, unattractive"
Style: artstyle-abstract,"abstract style {prompt} . non-representational, colors and shapes, expression of feelings, imaginative, highly detailed","realistic, photographic, figurative, concrete"
Style: artstyle-abstract expressionism,"abstract expressionist painting {prompt} . energetic brushwork, bold colors, abstract forms, expressive, emotional","realistic, photorealistic, low contrast, plain, simple, monochrome"
Style: artstyle-art deco,"Art Deco style {prompt} . geometric shapes, bold colors, luxurious, elegant, decorative, symmetrical, ornate, detailed","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, modernist, minimalist"
Style: artstyle-art nouveau,"Art Nouveau style {prompt} . elegant, decorative, curvilinear forms, nature-inspired, ornate, detailed","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, modernist, minimalist"
Style: artstyle-constructivist,"constructivist style {prompt} . geometric shapes, bold colors, dynamic composition, propaganda art style","realistic, photorealistic, low contrast, plain, simple, abstract expressionism"
Style: artstyle-cubist,"cubist artwork {prompt} . geometric shapes, abstract, innovative, revolutionary","anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy"
Style: artstyle-expressionist,"expressionist {prompt} . raw, emotional, dynamic, distortion for emotional effect, vibrant, use of unusual colors, detailed","realism, symmetry, quiet, calm, photo"
Style: artstyle-graffiti,"graffiti style {prompt} . street art, vibrant, urban, detailed, tag, mural","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic"
Style: artstyle-hyperrealism,"hyperrealistic art {prompt} . extremely high-resolution details, photographic, realism pushed to extreme, fine texture, incredibly lifelike","simplified, abstract, unrealistic, impressionistic, low resolution"
Style: artstyle-impressionist,"impressionist painting {prompt} . loose brushwork, vibrant color, light and shadow play, captures feeling over form","anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy"
Style: artstyle-pointillism,"pointillism style {prompt} . composed entirely of small, distinct dots of color, vibrant, highly detailed","line drawing, smooth shading, large color fields, simplistic"
Style: artstyle-pop art,"Pop Art style {prompt} . bright colors, bold outlines, popular culture themes, ironic or kitsch","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, minimalist"
Style: artstyle-psychedelic,"psychedelic style {prompt} . vibrant colors, swirling patterns, abstract forms, surreal, trippy","monochrome, black and white, low contrast, realistic, photorealistic, plain, simple"
Style: artstyle-renaissance,"Renaissance style {prompt} . realistic, perspective, light and shadow, religious or mythological themes, highly detailed","ugly, deformed, noisy, blurry, low contrast, modernist, minimalist, abstract"
Style: artstyle-steampunk,"steampunk style {prompt} . antique, mechanical, brass and copper tones, gears, intricate, detailed","deformed, glitch, noisy, low contrast, anime, photorealistic"
Style: artstyle-surrealist,"surrealist art {prompt} . dreamlike, mysterious, provocative, symbolic, intricate, detailed","anime, photorealistic, realistic, deformed, glitch, noisy, low contrast"
Style: artstyle-typography,"typographic art {prompt} . stylized, intricate, detailed, artistic, text-based","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic"
Style: artstyle-watercolor,"watercolor painting {prompt} . vibrant, beautiful, painterly, detailed, textural, artistic","anime, photorealistic, 35mm film, deformed, glitch, low contrast, noisy"
Style: futuristic-biomechanical,"biomechanical style {prompt} . blend of organic and mechanical elements, futuristic, cybernetic, detailed, intricate","natural, rustic, primitive, organic, simplistic"
Style: futuristic-biomechanical cyberpunk,"biomechanical cyberpunk {prompt} . cybernetics, human-machine fusion, dystopian, organic meets artificial, dark, intricate, highly detailed","natural, colorful, deformed, sketch, low contrast, watercolor"
Style: futuristic-cybernetic,"cybernetic style {prompt} . futuristic, technological, cybernetic enhancements, robotics, artificial intelligence themes","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, historical, medieval"
Style: futuristic-cybernetic robot,"cybernetic robot {prompt} . android, AI, machine, metal, wires, tech, futuristic, highly detailed","organic, natural, human, sketch, watercolor, low contrast"
Style: futuristic-cyberpunk cityscape,"cyberpunk cityscape {prompt} . neon lights, dark alleys, skyscrapers, futuristic, vibrant colors, high contrast, highly detailed","natural, rural, deformed, low contrast, black and white, sketch, watercolor"
Style: futuristic-futuristic,"futuristic style {prompt} . sleek, modern, ultramodern, high tech, detailed","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, vintage, antique"
Style: futuristic-retro cyberpunk,"retro cyberpunk {prompt} . 80's inspired, synthwave, neon, vibrant, detailed, retro futurism","modern, desaturated, black and white, realism, low contrast"
Style: futuristic-retro futurism,"retro-futuristic {prompt} . vintage sci-fi, 50s and 60s style, atomic age, vibrant, highly detailed","contemporary, realistic, rustic, primitive"
Style: futuristic-sci-fi,"sci-fi style {prompt} . futuristic, technological, alien worlds, space themes, advanced civilizations","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, historical, medieval"
Style: futuristic-vaporwave,"vaporwave style {prompt} . retro aesthetic, cyberpunk, vibrant, neon colors, vintage 80s and 90s style, highly detailed","monochrome, muted colors, realism, rustic, minimalist, dark"
Style: game-bubble bobble,"Bubble Bobble style {prompt} . 8-bit, cute, pixelated, fantasy, vibrant, reminiscent of Bubble Bobble game","realistic, modern, photorealistic, violent, horror"
Style: game-cyberpunk game,"cyberpunk game style {prompt} . neon, dystopian, futuristic, digital, vibrant, detailed, high contrast, reminiscent of cyberpunk genre video games","historical, natural, rustic, low detailed"
Style: game-fighting game,"fighting game style {prompt} . dynamic, vibrant, action-packed, detailed character design, reminiscent of fighting video games","peaceful, calm, minimalist, photorealistic"
Style: game-gta,"GTA-style artwork {prompt} . satirical, exaggerated, pop art style, vibrant colors, iconic characters, action-packed","realistic, black and white, low contrast, impressionist, cubist, noisy, blurry, deformed"
Style: game-mario,"Super Mario style {prompt} . vibrant, cute, cartoony, fantasy, playful, reminiscent of Super Mario series","realistic, modern, horror, dystopian, violent"
Style: game-minecraft,"Minecraft style {prompt} . blocky, pixelated, vibrant colors, recognizable characters and objects, game assets","smooth, realistic, detailed, photorealistic, noise, blurry, deformed"
Style: game-pokemon,"Pokémon style {prompt} . vibrant, cute, anime, fantasy, reminiscent of Pokémon series","realistic, modern, horror, dystopian, violent"
Style: game-retro arcade,"retro arcade style {prompt} . 8-bit, pixelated, vibrant, classic video game, old school gaming, reminiscent of 80s and 90s arcade games","modern, ultra-high resolution, photorealistic, 3D"
Style: game-retro game,"retro game art {prompt} . 16-bit, vibrant colors, pixelated, nostalgic, charming, fun","realistic, photorealistic, 35mm film, deformed, glitch, low contrast, noisy"
Style: game-rpg fantasy game,"role-playing game (RPG) style fantasy {prompt} . detailed, vibrant, immersive, reminiscent of high fantasy RPG games","sci-fi, modern, urban, futuristic, low detailed"
Style: game-strategy game,"strategy game style {prompt} . overhead view, detailed map, units, reminiscent of real-time strategy video games","first-person view, modern, photorealistic"
Style: game-streetfighter,"Street Fighter style {prompt} . vibrant, dynamic, arcade, 2D fighting game, highly detailed, reminiscent of Street Fighter series","3D, realistic, modern, photorealistic, turn-based strategy"
Style: game-zelda,"Legend of Zelda style {prompt} . vibrant, fantasy, detailed, epic, heroic, reminiscent of The Legend of Zelda series","sci-fi, modern, realistic, horror"
Style: misc-architectural,"architectural style {prompt} . clean lines, geometric shapes, minimalist, modern, architectural drawing, highly detailed","curved lines, ornate, baroque, abstract, grunge"
Style: misc-disco,"disco-themed {prompt} . vibrant, groovy, retro 70s style, shiny disco balls, neon lights, dance floor, highly detailed","minimalist, rustic, monochrome, contemporary, simplistic"
Style: misc-dreamscape,"dreamscape {prompt} . surreal, ethereal, dreamy, mysterious, fantasy, highly detailed","realistic, concrete, ordinary, mundane"
Style: misc-dystopian,"dystopian style {prompt} . bleak, post-apocalyptic, somber, dramatic, highly detailed","ugly, deformed, noisy, blurry, low contrast, cheerful, optimistic, vibrant, colorful"
Style: misc-fairy tale,"fairy tale {prompt} . magical, fantastical, enchanting, storybook style, highly detailed","realistic, modern, ordinary, mundane"
Style: misc-gothic,"gothic style {prompt} . dark, mysterious, haunting, dramatic, ornate, detailed","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, cheerful, optimistic"
Style: misc-grunge,"grunge style {prompt} . textured, distressed, vintage, edgy, punk rock vibe, dirty, noisy","smooth, clean, minimalist, sleek, modern, photorealistic"
Style: misc-horror,"horror-themed {prompt} . eerie, unsettling, dark, spooky, suspenseful, grim, highly detailed","cheerful, bright, vibrant, light-hearted, cute"
Style: misc-kawaii,"kawaii style {prompt} . cute, adorable, brightly colored, cheerful, anime influence, highly detailed","dark, scary, realistic, monochrome, abstract"
Style: misc-lovecraftian,"lovecraftian horror {prompt} . eldritch, cosmic horror, unknown, mysterious, surreal, highly detailed","light-hearted, mundane, familiar, simplistic, realistic"
Style: misc-macabre,"macabre style {prompt} . dark, gothic, grim, haunting, highly detailed","bright, cheerful, light-hearted, cartoonish, cute"
Style: misc-manga,"manga style {prompt} . vibrant, high-energy, detailed, iconic, Japanese comic style","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, Western comic style"
Style: misc-metropolis,"metropolis-themed {prompt} . urban, cityscape, skyscrapers, modern, futuristic, highly detailed","rural, natural, rustic, historical, simple"
Style: misc-minimalist,"minimalist style {prompt} . simple, clean, uncluttered, modern, elegant","ornate, complicated, highly detailed, cluttered, disordered, messy, noisy"
Style: misc-monochrome,"monochrome {prompt} . black and white, contrast, tone, texture, detailed","colorful, vibrant, noisy, blurry, deformed"
Style: misc-nautical,"nautical-themed {prompt} . sea, ocean, ships, maritime, beach, marine life, highly detailed","landlocked, desert, mountains, urban, rustic"
Style: misc-space,"space-themed {prompt} . cosmic, celestial, stars, galaxies, nebulas, planets, science fiction, highly detailed","earthly, mundane, ground-based, realism"
Style: misc-stained glass,"stained glass style {prompt} . vibrant, beautiful, translucent, intricate, detailed","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic"
Style: misc-techwear fashion,"techwear fashion {prompt} . futuristic, cyberpunk, urban, tactical, sleek, dark, highly detailed","vintage, rural, colorful, low contrast, realism, sketch, watercolor"
Style: misc-tribal,"tribal style {prompt} . indigenous, ethnic, traditional patterns, bold, natural colors, highly detailed","modern, futuristic, minimalist, pastel"
Style: misc-zentangle,"zentangle {prompt} . intricate, abstract, monochrome, patterns, meditative, highly detailed","colorful, representative, simplistic, large fields of color"
Style: papercraft-collage,"collage style {prompt} . mixed media, layered, textural, detailed, artistic","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic"
Style: papercraft-flat papercut,"flat papercut style {prompt} . silhouette, clean cuts, paper, sharp edges, minimalist, color block","3D, high detail, noise, grainy, blurry, painting, drawing, photo, disfigured"
Style: papercraft-kirigami,"kirigami representation of {prompt} . 3D, paper folding, paper cutting, Japanese, intricate, symmetrical, precision, clean lines","painting, drawing, 2D, noisy, blurry, deformed"
Style: papercraft-paper mache,"paper mache representation of {prompt} . 3D, sculptural, textured, handmade, vibrant, fun","2D, flat, photo, sketch, digital art, deformed, noisy, blurry"
Style: papercraft-paper quilling,"paper quilling art of {prompt} . intricate, delicate, curling, rolling, shaping, coiling, loops, 3D, dimensional, ornamental","photo, painting, drawing, 2D, flat, deformed, noisy, blurry"
Style: papercraft-papercut collage,"papercut collage of {prompt} . mixed media, textured paper, overlapping, asymmetrical, abstract, vibrant","photo, 3D, realistic, drawing, painting, high detail, disfigured"
Style: papercraft-papercut shadow box,"3D papercut shadow box of {prompt} . layered, dimensional, depth, silhouette, shadow, papercut, handmade, high contrast","painting, drawing, photo, 2D, flat, high detail, blurry, noisy, disfigured"
Style: papercraft-stacked papercut,"stacked papercut art of {prompt} . 3D, layered, dimensional, depth, precision cut, stacked layers, papercut, high contrast","2D, flat, noisy, blurry, painting, drawing, photo, deformed"
Style: papercraft-thick layered papercut,"thick layered papercut art of {prompt} . deep 3D, volumetric, dimensional, depth, thick paper, high stack, heavy texture, tangible layers","2D, flat, thin paper, low stack, smooth texture, painting, drawing, photo, deformed"
Style: photo-alien,"alien-themed {prompt} . extraterrestrial, cosmic, otherworldly, mysterious, sci-fi, highly detailed","earthly, mundane, common, realistic, simple"
Style: photo-film noir,"film noir style {prompt} . monochrome, high contrast, dramatic shadows, 1940s style, mysterious, cinematic","ugly, deformed, noisy, blurry, low contrast, realism, photorealistic, vibrant, colorful"
Style: photo-hdr,"HDR photo of {prompt} . High dynamic range, vivid, rich details, clear shadows and highlights, realistic, intense, enhanced contrast, highly detailed","flat, low contrast, oversaturated, underexposed, overexposed, blurred, noisy"
Style: photo-long exposure,"long exposure photo of {prompt} . Blurred motion, streaks of light, surreal, dreamy, ghosting effect, highly detailed","static, noisy, deformed, shaky, abrupt, flat, low contrast"
Style: photo-neon noir,"neon noir {prompt} . cyberpunk, dark, rainy streets, neon signs, high contrast, low light, vibrant, highly detailed","bright, sunny, daytime, low contrast, black and white, sketch, watercolor"
Style: photo-silhouette,"silhouette style {prompt} . high contrast, minimalistic, black and white, stark, dramatic","ugly, deformed, noisy, blurry, low contrast, color, realism, photorealistic"
Style: photo-tilt-shift,"tilt-shift photo of {prompt} . Selective focus, miniature effect, blurred background, highly detailed, vibrant, perspective control","blurry, noisy, deformed, flat, low contrast, unrealistic, oversaturated, underexposed"
>>>>>> Advanced GPT Styles
Style: Space art,"galactic style {prompt} . nebula, constellation, cosmic, celestial, highly detailed, starry","blurry, grainy, deformed, photo-realistic, low-contrast, terrestrial"
Style: Street art,"urban graffiti style {prompt} . vibrant, edgy, street art, underground, spray paint effect","clean, minimalistic, soft, gentle, blurry, off-center"
Style: Baroque,"Baroque art {prompt} . ornate, richly detailed, dramatic, high contrast, complex composition","minimalistic, low-contrast, blurry, deformed, modern, abstract"
Style: Abstract,"abstract {prompt} . imaginative, surreal, non-representational, dream-like","realistic, photo, literal, symmetrical, rigid"
Style: Pointillism,"pointillism art {prompt} . dots, dappled, stipples, highly detailed","smooth, blurry, photo-realistic, non-dotted"
Style: Impressionist,"impressionist painting {prompt} . soft edges, vibrant, loose brushwork, atmospheric, highly detailed","hard edges, muted colors, tight brushwork, non-atmospheric"
Style: Pop art,"pop art {prompt} . vibrant, mass culture, comic style, bold lines, ironic","soft, elegant, high culture, realistic, subtle lines"
Style: Minimalist,"minimalist design {prompt} . clean, simple, restrained, elegant","busy, complex, flamboyant, disfigured"
Style: Art Deco,"art deco {prompt} . opulent, lavish, ornate, symmetrical, geometric","minimalistic, simple, asymmetrical, organic"
Style: Cubist,"cubist {prompt} . abstract, geometric, fragmented, multiple perspectives","realistic, smooth, unbroken, single perspective"
Style: Dada,"dada style {prompt} . absurd, satirical, avant-garde, abstract","serious, traditional, conventional, realistic"
Style: Victorian,"Victorian style {prompt} . elegant, ornate, highly detailed, historical","modern, minimalist, low detail, contemporary"
Style: Art Nouveau,"art nouveau {prompt} . organic, curvilinear, decorative, highly detailed","geometric, straight lines, functional, low detail"
Style: Futuristic,"futuristic {prompt} . advanced, high-tech, sleek, modern","old, low-tech, chunky, historical"
Style: Medieval,"medieval style {prompt} . historical, ornate, religious, gothic","modern, simple, secular, minimalist"
Style: Industrial,"industrial style {prompt} . mechanical, robust, urban, gritty","natural, fragile, rural, clean"
Style: Vaporwave,"vaporwave style {prompt} . retro, neon, pixelated, nostalgic","modern, monochrome, high-resolution, forward-looking"
Style: Horror,"horror style {prompt} . dark, eerie, gothic, macabre","light, cheerful, minimalist, happy"
Style: Gothic,"gothic style {prompt} . dark, mysterious, intricate, moody","light, cheerful, simple, vibrant"
Style: Steampunk,"steampunk style {prompt} . retro, mechanical, detailed, Victorian","modern, digital, minimalist, contemporary"
Style: Retro,"retro style {prompt} . vintage, nostalgic, old-fashioned, highly detailed","modern, futuristic, forward-looking, low detail"
Style: Surrealist,"surrealist {prompt} . dream-like, bizarre, irrational, highly detailed","realistic, mundane, rational, low detail"
Style: Realism,"realism style {prompt} . lifelike, detailed, accurate, representational","abstract, simplistic, inaccurate, non-representational"
Style: Silhouette,"silhouette style {prompt} . minimalist, monochrome, stark, high contrast","detailed, multicolored, soft, low contrast"
Style: Collage,"collage style {prompt} . mixed media, assembled, eclectic, highly detailed","uniform, unvarying, minimalist, low detail"
Style: Watercolor,"watercolor {prompt} . soft, blended, transparent, fluid","hard, unblended, opaque, rigid"
Style: Calligraphy,"calligraphy {prompt} . elegant, flowing, ornate, highly detailed","plain, rigid, simple, low detail"
Style: Expressionist,"expressionist style {prompt} . emotional, intense, vibrant, highly detailed","emotionless, calm, muted, low detail"
Style: Fauvist,"fauvist style {prompt} . bold color, exaggerated, expressive, highly detailed","neutral color, realistic, restrained, low detail"
Style: Renaissance,"Renaissance style {prompt} . classical, humanistic, realistic, highly detailed","modern, abstract, unrealistic, low detail"
Style: Photorealistic,"photorealistic {prompt} . highly detailed, lifelike, precise, accurate","abstract, low detail, unrealistic, inaccurate"
Style: Symbolic,"symbolic style {prompt} . conceptual, representative, allegorical, highly detailed","literal, non-representative, factual, low detail"
Style: Avant-garde,"avant-garde style {prompt} . experimental, innovative, non-traditional","traditional, conventional, classic"
Style: Mosaic,"mosaic style {prompt} . fragmented, assembled, colorful, highly detailed","whole, unbroken, monochrome, low detail"
Style: Trompe l'oeil,"trompe l'oeil style {prompt} . deceptive, 3D effect, realistic, highly detailed","honest, 2D effect, unrealistic, low detail"
Style: Rococo,"rococo style {prompt} . ornate, playful, romantic, pastel, highly detailed","minimalistic, serious, unromantic, dark, low detail"
Style: Macabre,"macabre style {prompt} . dark, eerie, grotesque, highly detailed","light, cheerful, beautiful, low detail"
Style: Satirical,"satirical style {prompt} . humorous, ironic, exaggerated, critical","serious, literal, realistic, complimentary"
Style: Pixelated,"pixelated style {prompt} . retro, low-res, digital, blocky","modern, high-res, organic, smooth"
Style: Futurist,"futurist style {prompt} . dynamic, modern, mechanized, highly detailed","static, historical, organic, low detail"
Style: Primitive,"primitive style {prompt} . raw, simple, naive, highly detailed","refined, complex, sophisticated, low detail"
Style: Byzantine,"Byzantine style {prompt} . rich, ornate, religious, iconic, highly detailed","poor, simple, secular, non-iconic, low detail"
Style: Psychedelic,"psychedelic style {prompt} . vibrant, abstract, distorted, highly detailed","muted, realistic, undistorted, low detail"
Style: Suprematist,"suprematist style {prompt} . geometric, abstract, non-objective, simple","organic, realistic, objective, complex"
Style: Constructivist,"constructivist style {prompt} . industrial, geometric, political, highly detailed","organic, curvilinear, apolitical, low detail"
Style: De Stijl,"de Stijl style {prompt} . abstract, geometric, primary colors,"organic, curvilinear, muted colors, black and white"
Style: Ukiyo-e,"ukiyo-e style {prompt} . woodblock print, vibrant, historical Japanese art, detailed","digital, muted, modern, Western"
Style: Dystopian,"dystopian style {prompt} . bleak, oppressive, futuristic, detailed","utopian, cheerful, historical, low detail"
Style: Biomechanical,"biomechanical style {prompt} . organic meets mechanical, alien, detailed, H.R. Giger-inspired","geometric, earthy, low detail, not H.R. Giger-inspired"
Style: Hyperrealism,"hyperrealistic style {prompt} . ultra-detailed, lifelike, precision, crisp","abstract, low detail, unrealistic, blurry"
Style: Glitch,"glitch style {prompt} . digital error, distorted, cyber, detailed","analog, undistorted, organic, low detail"
Style: Trompe-l'oeil,"trompe-l'oeil style {prompt} . optical illusion, lifelike, 3D effect, detailed","flat, 2D effect, unrealistic, low detail"
Style: Arabesque,"arabesque style {prompt} . geometric patterns, floral, Islamic art, detailed","chaotic, animalistic, non-Islamic art, low detail"
Style: Brutalist,"brutalist style {prompt} . raw, rugged, geometric, concrete, detailed","smooth, delicate, curvilinear, abstract, low detail"
Style: Chiaroscuro,"chiaroscuro style {prompt} . high contrast, dramatic lighting, detailed","low contrast, flat lighting, low detail"
Style: Tenebrism,"tenebrism style {prompt} . dark, dramatic illumination, high contrast, detailed","light, flat lighting, low contrast, low detail"
Style: Romantic,"romantic style {prompt} . emotional, dramatic, nature-focused, detailed","unemotional, flat, city-focused, low detail"
Style: Bauhaus,"bauhaus style {prompt} . functional, geometric, minimal, detailed","ornamental, curvilinear, maximal, low detail"
Style: Art brut,"art brut style {prompt} . raw, outsider art, naïve, detailed","refined, mainstream art, sophisticated, low detail"
Style: Metaphysical,"metaphysical style {prompt} . surreal, eerie, uncanny, detailed","realistic, comfortable, familiar, low detail"
Style: Neoplasticism,"neoplasticism style {prompt} . geometric, primary colors, black and white, abstract","organic, muted colors, colorful, realistic"
Style: Hard-edge,"hard-edge style {prompt} . geometric, flat colors, precision, detailed","organic, gradient colors, imprecise, low detail"
Style: Automatism,"automatism style {prompt} . unconscious, spontaneous, abstract, detailed","conscious, planned, realistic, low detail"
Style: Tachisme,"tachisme style {prompt} . gestural, abstract, spontaneous, detailed","controlled, realistic, planned, low detail"
Style: Lyrical abstraction,"lyrical abstraction style {prompt} . emotional, non-figurative, expressive, detailed","unemotional, figurative, restrained, low detail"
Style: Color field,"color field style {prompt} . flat, large fields of color, minimal, detailed","textured, small patches of color, maximal, low detail"
Style: Synthetism,"synthetism style {prompt} . simplified, symbolic, bright colors, detailed","complex, literal, muted colors, low detail"
Style: Cloisonnism,"cloisonnism style {prompt} . bold outlines, flat colors, decorative, detailed","soft outlines, gradient colors, functional, low detail"
Style: Assemblage,"assemblage style {prompt} . three-dimensional, found objects, eclectic, detailed","two-dimensional, traditional materials, uniform, low detail"
Style: Vorticism,"vorticism style {prompt} . geometric, abstract, dynamic, detailed","organic, realistic, static, low detail"
Style: Op art,"op art style {prompt} . optical illusions, geometric, black and white, detailed","no illusions, organic, colorful, low detail"
Style: Divisionism,"divisionism style {prompt} . color theory, dot technique, vibrant, detailed","black and white, smooth technique, muted, low detail"
Style: Kinetic art,"kinetic art style {prompt} . movement, dynamic, interactive, detailed","static, static, non-interactive, low detail"
Style: Orphism,"orphism style {prompt} . pure color, abstract, musical, detailed","mixed color, realistic, non-musical, low detail"
Style: Suprematism,"suprematism style {prompt} . geometric, abstract, limited color palette, detailed","organic, realistic, broad color palette, low detail"
Style: Letterism,"letterism style {prompt} . letters, typographic, abstract, detailed","images, non-typographic, realistic, low detail"
Style: Situationalist,"situationalist style {prompt} . political, collage, detournement, detailed","apolitical, single medium, straightforward, low detail"
Style: Sound art,"sound art style {prompt} . auditory, abstract, non-visual, detailed","visual, realistic, silent, low detail"
Style: Land art,"land art style {prompt} . natural materials, outdoor, environmental, detailed","synthetic materials, indoor, non-environmental, low detail"
Style: Photorealistic graffiti,"photorealistic graffiti style {prompt} . urban, street art, lifelike, detailed","rural, gallery art, abstract, low detail"
Style: Hypermodern,"hypermodern style {prompt} . postmodern, technology focused, sleek, detailed","premodern, nature focused, rustic, low detail"
Style: Virtual realism,"virtual realism style {prompt} . digital, lifelike, immersive, detailed","analog, abstract, non-immersive, low detail"
Style: Structural film,"structural film style {prompt} . experimental, non-narrative, texture, detailed","traditional, narrative, smooth, low detail"
Style: Process art,"process art style {prompt} . creation focused, ephemeral, documentation, detailed","result focused, permanent, no documentation, low detail"
Style: Light and space,"light and space style {prompt} . perceptual phenomena, immersive, minimal, detailed","solid objects, non-immersive, maximal, low detail"
Style: Post-internet,"post-internet style {prompt} . digital culture, technology, online, detailed","pre-internet, nature, offline, low detail"
Style: Bio-art,"bio-art style {prompt} . living organisms, ethical, natural, detailed","inorganic, unethical, synthetic, low detail"
>>>>>> GPT Cultural Styles
Style: Byzantine,"Byzantine style {prompt} . religious, iconography, gold, highly detailed, mosaics","secular, simple, bronze, minimalist, paintings"
Style: Celtic,"Celtic style {prompt} . geometric patterns, intricate knots, medieval, highly detailed","random, simplistic, modern, undetailed"
Style: Native American,"Native American style {prompt} . traditional patterns, tribal, cultural symbols, highly detailed","modern, non-tribal, abstract, undetailed"
Style: Aboriginal,"Aboriginal style {prompt} . dot painting, Dreamtime stories, Australian culture, highly detailed","non-Australian, line drawing, abstract, undetailed"
Style: Egyptian,"Egyptian style {prompt} . hieroglyphs, gods and goddesses, Pharaohs, highly detailed","non-Egyptian, text-free, secular, undetailed"
Style: Mayan,"Mayan style {prompt} . glyphs, ancient civilization, detailed carvings, highly detailed","modern, non-Mayan, simplistic, undetailed"
Style: Renaissance,"Renaissance style {prompt} . humanism, realism, perspective, highly detailed","abstract, surreal, flat, undetailed"
Style: Mughal,"Mughal style {prompt} . Indian and Persian influence, miniature paintings, highly detailed","non-Indian, non-Persian, large-scale, undetailed"
Style: Romanesque,"Romanesque style {prompt} . medieval, religious, thick walls, highly detailed","modern, secular, transparent, undetailed"
Style: Gothic,"Gothic style {prompt} . medieval, pointed arches, stained glass, highly detailed","modern, round arches, clear glass, undetailed"
Style: Baroque,"Baroque style {prompt} . grandeur, drama, chiaroscuro, highly detailed","minimalist, calm, flat, undetailed"
Style: Rococo,"Rococo style {prompt} . ornate, pastel, love and nature themes, highly detailed","simple, dark, abstract, undetailed"
Style: Pre-Raphaelite,"Pre-Raphaelite style {prompt} . romantic, vivid color, medieval subjects, highly detailed","realistic, muted color, modern subjects, undetailed"
Style: Impressionist,"Impressionist style {prompt} . loose brushwork, light and color, ordinary subjects, highly detailed","tight brushwork, black and white, extraordinary subjects, undetailed"
Style: Cubist,"Cubist style {prompt} . geometric, multi-perspective, fragmented, highly detailed","organic, single perspective, whole, undetailed"
Style: Surrealist,"Surrealist style {prompt} . dreamlike, irrational, unexpected juxtapositions, highly detailed","realistic, rational, expected combinations, undetailed"
Style: Futurist,"Futurist style {prompt} . dynamic, technology, speed, highly detailed","static, nature, slow, undetailed"
Style: Dada,"Dada style {prompt} . absurd, anti-art, randomness, highly detailed","rational, pro-art, order, undetailed"
Style: Expressionist,"Expressionist style {prompt} . emotional, distorted, individual perspective, highly detailed","unemotional, realistic, collective perspective, undetailed"
Style: Fauvist,"Fauvist style {prompt} . bold color, wild brushwork, simplification, highly detailed","muted color, careful brushwork, detail, undetailed"
Style: Socialist Realist,"Socialist Realist style {prompt} . idealized, political, proletarian, highly detailed","realistic, apolitical, bourgeois, undetailed"
Style: Pop Art,"Pop Art style {prompt} . popular culture, advertising, bold, highly detailed","high art, non-commercial, muted, undetailed"
Style: Suprematism,"Suprematism style {prompt} . geometric, non-objective, primary colors, highly detailed","organic, objective, pastel colors, undetailed"
Style: Symbolist,"Symbolist style {prompt} . mythical, dreamy, spiritual, highly detailed","realistic, practical, secular, undetailed"
Style: Pre-Columbian,"Pre-Columbian style {prompt} . ancient Americas, native, cultural, highly detailed","modern, non-American, abstract, undetailed"
Style: Constructivist,"Constructivist style {prompt} . industrial, geometric, socialist, highly detailed","organic, round, capitalist, undetailed"
Style: Art Nouveau,"Art Nouveau style {prompt} . decorative, nature-inspired, curved lines, highly detailed","functional, geometric, straight lines, undetailed"
Style: Precisionist,"Precisionist style {prompt} . industrial, crisp, geometric, highly detailed","organic, blurry, round, undetailed"
Style: Neoclassical,"Neoclassical style {prompt} . ancient Rome and Greece, rational, heroic, highly detailed","modern, emotional, ordinary, undetailed"
Style: Persian Miniature,"Persian Miniature style {prompt} . Middle Eastern, intricate, storytelling, highly detailed","Western, simple, non-narrative, undetailed"
Style: Edo,"Edo style {prompt} . Japanese, woodblock prints, floating world, highly detailed","non-Japanese, oil painting, real world, undetailed"
Style: Tribal,"Tribal style {prompt} . African, indigenous, symbolic, highly detailed","non-African, mainstream, abstract, undetailed"
Style: Tibetan Thangka,"Tibetan Thangka style {prompt} . spiritual, Buddhist, meditation, highly detailed","secular, non-Buddhist, disturbing, undetailed"
Style: Art Deco,"Art Deco style {prompt} . modern, geometric, luxury, highly detailed","vintage, organic, minimalism, undetailed"
Style: Minimalist,"Minimalist style {prompt} . simple, functional, unadorned, highly detailed","complex, decorative, adorned, undetailed"
Style: Greek Classical,"Greek Classical style {prompt} . ancient, mythology, balanced, highly detailed","modern, everyday life, unbalanced, undetailed"
Style: African,"African style {prompt} . tribal, symbolic, cultural, highly detailed","non-African, abstract, non-cultural, undetailed"
Style: Russian Iconography,"Russian Iconography style {prompt} . religious, orthodox, gold, highly detailed","secular, non-orthodox, silver, undetailed"
Style: Nordic,"Nordic style {prompt} . Scandinavian, minimal, nature, highly detailed","non-Scandinavian, maximal, urban, undetailed"
Style: Inuit,"Inuit style {prompt} . Arctic, native, animal themes, highly detailed","tropical, non-native, human themes, undetailed"
Style: Maori,"Maori style {prompt} . New Zealand, tribal, spiritual, highly detailed","non-New Zealand, non-tribal, secular, undetailed"
Style: Iznik,"Iznik style {prompt} . Turkish, ceramic, floral, highly detailed","non-Turkish, canvas, geometric, undetailed"
Style: Ottoman,"Ottoman style {prompt} . Islamic, calligraphy, miniatures, highly detailed","non-Islamic, typography, large-scale, undetailed"
Style: Hanami,"Hanami style {prompt} . Japanese, cherry blossoms,spring, highly detailed","non-Japanese, winter, abstract, undetailed"
Style: Mandala,"Mandala style {prompt} . spiritual, geometric, symmetrical, highly detailed","secular, organic, asymmetrical, undetailed"
Style: Aztec,"Aztec style {prompt} . ancient Mexico, symbolic, cultural, highly detailed","modern, abstract, non-cultural, undetailed"
Style: Sumi-e,"Sumi-e style {prompt} . Japanese ink painting, minimal, nature, highly detailed","non-Japanese, colorful, urban, undetailed"
Style: Ukiyo-e,"Ukiyo-e style {prompt} . Japanese, woodblock prints, floating world, highly detailed","non-Japanese, digital art, real world, undetailed"
Style: Haida,"Haida style {prompt} . Native American, form line, nature, highly detailed","non-Native American, abstract, urban, undetailed"
Style: Moorish,"Moorish style {prompt} . Islamic, geometric, Andalusian, highly detailed","non-Islamic, organic, non-Andalusian, undetailed"
Style: Victorian,"Victorian style {prompt} . 19th century, ornate, romantic, highly detailed","21st century, minimal, unemotional, undetailed"
Style: Pueblo,"Pueblo style {prompt} . Native American, traditional, pottery, highly detailed","non-Native American, modern, photography, undetailed"
Style: Cloisonné,"Cloisonné style {prompt} . metalwork, enamel, intricate, highly detailed","woodwork, paint, simple, undetailed"
Style: Khokhloma,"Khokhloma style {prompt} . Russian, folk art, floral, highly detailed","non-Russian, fine art, geometric, undetailed"
Style: Biedermeier,"Biedermeier style {prompt} . 19th century, domestic, unpretentious, highly detailed","21st century, public, pretentious, undetailed"
Style: Goryeo,"Goryeo style {prompt} . Korean, celadon, inlay, highly detailed","non-Korean, terra cotta, relief, undetailed"
Style: Han,"Han style {prompt} . Chinese, ancient, stone relief, highly detailed","non-Chinese, modern, oil painting, undetailed"
Style: Hellenistic,"Hellenistic style {prompt} . ancient Greek, dynamic, emotional, highly detailed","modern, static, unemotional, undetailed"
Style: Tang,"Tang style {prompt} . Chinese, ancient, sculpture, highly detailed","non-Chinese, modern, photography, undetailed"
Style: Ming,"Ming style {prompt} . Chinese, elegant, pottery, highly detailed","non-Chinese, rustic, painting, undetailed"
Style: Joseon,"Joseon style {prompt} . Korean, Confucian, painting, highly detailed","non-Korean, Taoist, sculpture, undetailed"
Style: Gupta,"Gupta style {prompt} . Indian, ancient, sculpture, highly detailed","non-Indian, modern, painting, undetailed"
Style: Pallava,"Pallava style {prompt} . Indian, Dravidian architecture, sculpture, highly detailed","non-Indian, Mughal architecture, painting, undetailed"
Style: Chola,"Chola style {prompt} . Indian, bronze, dancing Shiva, highly detailed","non-Indian, marble, sitting Buddha, undetailed"
Style: Minoan,"Minoan style {prompt} . ancient Crete, frescoes, sea life, highly detailed","modern, oil painting, land animals, undetailed"
Style: Mycenaean,"Mycenaean style {prompt} . ancient Greece, gold, death mask, highly detailed","modern, bronze, life mask, undetailed"
Style: Ndebele,"Ndebele style {prompt} . African, geometric, house painting, highly detailed","non-African, organic, canvas painting, undetailed"
Style: San,"San style {prompt} . African, rock art, animal figures, highly detailed","non-African, digital art, human figures, undetailed"
Style: Batik,"Batik style {prompt} . Indonesian, resist dyeing, floral, highly detailed","non-Indonesian, direct dyeing, geometric, undetailed"
Style: Assyrian,"Assyrian style {prompt} . ancient Mesopotamia, relief, war scenes, highly detailed","modern, oil painting, peaceful scenes, undetailed"
Style: Thracian,"Thracian style {prompt} . ancient Balkans, gold, ritual objects, highly detailed","modern, wood, everyday objects, undetailed"
Style: Etruscan,"Etruscan style {prompt} . ancient Italy, bronze, mythological scenes, highly detailed","modern, steel, realistic scenes, undetailed"
Style: Sumerian,"Sumerian style {prompt} . ancient Mesopotamia, cuneiform, clay tablets, highly detailed","modern, Latin script, parchment scrolls, undetailed"
Style: Babylonian,"Babylonian style {prompt} . ancient Mesopotamia, law codes, stone steles, highly detailed","modern, lawless, paper books, undetailed"
Style: Norse,"Norse style {prompt} . Viking, runic, wood carving, highly detailed","non-Viking, Latin script, metalwork, undetailed"
Style: Olmec,"Olmec style {prompt} . ancient Mexico, colossal heads, basalt, highly detailed","modern, miniature hands, marble, undetailed"
Style: Toltec,"Toltec style {prompt} . ancient Mexico, monumental architecture, relief, highly detailed","modern, small-scale models, oil painting, undetailed"
Style: Sicán,"Sicán style {prompt} . ancient Peru, gold masks, funerary objects, highly detailed","modern, wood masks, everyday objects, undetailed"
Style: Nazca,"Nazca style {prompt} . ancient Peru, geoglyphs, desert, highly detailed","modern, graffiti, urban, undetailed"
Style: Inca,"Inca style {prompt} . ancient Peru, stonework, terraces, highly detailed","modern, woodwork, flat plains, undetailed"
Style: Zapotec,"Zapotec style {prompt} . ancient Mexico, urns, jaguars, highly detailed","modern, vases, dogs, undetailed"
Style: Mixtec,"Mixtec style {prompt} . ancient Mexico, codices, turquoise, highly detailed","modern, novels, gold, undetailed"
Style: Ottonian,"Ottonian style {prompt} . medieval Germany, religious art, manuscripts, highly detailed","modern, secular art, newspapers, undetailed"
Style: Merovingian,"Merovingian style {prompt} . medieval France, jewelry, garnet cloisonné, highly detailed","modern, clothing, sapphire pavé, undetailed"
Style: Carolingian,"Carolingian style {prompt} . medieval Europe, illuminatedmanuscripts, luxury, highly detailed","modern, paperback books, simplicity, undetailed"
Style: Otomi,"Otomi style {prompt} . Mexican, textile, embroidery, highly detailed","non-Mexican, metalwork, hammering, undetailed"
Style: Huichol,"Huichol style {prompt} . Mexican, yarn painting, spiritual, highly detailed","non-Mexican, oil painting, secular, undetailed"
Style: Ainu,"Ainu style {prompt} . Japanese indigenous, wood carving, bear worship, highly detailed","non-Japanese, stone carving, dragon worship, undetailed"
Style: Maori,"Maori style {prompt} . New Zealand, tattoo, spiritual, highly detailed","non-New Zealand, body paint, secular, undetailed"
Style: Aboriginal,"Aboriginal style {prompt} . Australian indigenous, dot painting, storytelling, highly detailed","non-Australian, line drawing, non-narrative, undetailed"
Style: Inuit,"Inuit style {prompt} . Arctic, stone carving, animal figures, highly detailed","tropical, wood carving, human figures, undetailed"
Style: Saami,"Saami style {prompt} . Nordic indigenous, duodji (craft), reindeer, highly detailed","non-Nordic, factory-made, cow, undetailed"
Style: Ojibwe,"Ojibwe style {prompt} . Native American, birch bark, canoes, highly detailed","non-Native American, pine bark, rafts, undetailed"
Style: Tlingit,"Tlingit style {prompt} . Native American, totem poles, spiritual, highly detailed","non-Native American, street signs, secular, undetailed"
Style: Navajo,"Navajo style {prompt} . Native American, textile, rug weaving, highly detailed","non-Native American, metalwork, jewelry making, undetailed"
Style: Apache,"Apache style {prompt} . Native American, basketry, coiled, highly detailed","non-Native American, pottery, thrown, undetailed"
Style: Zuni,"Zuni style {prompt} . Native American, jewelry, silver, highly detailed","non-Native American, clothing, cotton, undetailed"
Style: Hopi,"Hopi style {prompt} . Native American, kachina dolls, spiritual, highly detailed","non-Native American, action figures, secular, undetailed"
Style: Sioux,"Sioux style {prompt} . Native American, quillwork, porcupine, highly detailed","non-Native American, embroidery, silk, undetailed"
Style: Lakota,"Lakota style {prompt} . Native American, beadwork, clothing, highly detailed","non-Native American, sequin work, banners, undetailed"
Style: Yupik,"Yupik style {prompt} . Native American, mask, ceremonial, highly detailed","non-Native American, mask, recreational, undetailed"
Style: Cherokee,"Cherokee style {prompt} . Native American, pottery, stamped, highly detailed","non-Native American, pottery, painted, undetailed"
Style: Mohawk,"Mohawk style {prompt} . Native American, sweetgrass, basketry, highly detailed","non-Native American, bamboo, basketry, undetailed"
Style: Cree,"Cree style {prompt} . Native American, hide, clothing, highly detailed","non-Native American, synthetic material, clothing, undetailed"
Style: Acoma,"Acoma style {prompt} . Native American, pottery, sky city, highly detailed","non-Native American, pottery, earth city, undetailed"
Style: Laguna,"Laguna style {prompt} . Native American, pottery, polychrome, highly detailed","non-Native American, pottery, monochrome, undetailed"
Style: Seminole,"Seminole style {prompt} . Native American, patchwork, clothing, highly detailed","non-Native American, knitting, clothing, undetailed"
Style: Osage,"Osage style {prompt} . Native American, ribbon work, floral, highly detailed","non-Native American, beadwork, geometric, undetailed"
Style: Anasazi,"Anasazi style {prompt} . Native American, pottery, black-on-white, highly detailed","non-Native American, pottery, color-on-color, undetailed"
Style: Mimbres,"Mimbres style {prompt} . Native American, pottery, figurative, highly detailed","non-Native American, pottery, abstract, undetailed"
Style: Pomo,"Pomo style {prompt} . Native American, basketry, feathers, highly detailed","non-Native American, basketry, beads, undetailed"
Style: Hohokam,"Hohokam style {prompt} . Native American, pottery, red-on-buff, highly detailed","non-Native American, pottery, blue-on-cream, undetailed"
Style: Mississippian,"Mississippian style {prompt} . Native American, stone carving, ceremonial, highly detailed","non-Native American, wood carving, everyday, undetailed"
Style: Fremont,"Fremont style {prompt} . Native American, petroglyphs, rock art, highly detailed","non-Native American, graffiti, wall art, undetailed"
Style: Mogollon,"Mogollon style {prompt} . Native American, pottery, geometric, highly detailed","non-Native American, pottery, organic, undetailed"
Style: Salado,"Salado style {prompt} . Native American, pottery, polychrome, highly detailed","non-Native American, pottery, duochrome, undetailed"
Style: Zulu,"Zulu style {prompt} . African, basketry, coiled, highly detailed","non-African, pottery, thrown, undetailed"
Style: Maasai,"Maasai style {prompt} . African, beadwork, jewelry, highly detailed","non-African, macramé, wall hanging, undetailed"
Style: Ndebele,"Ndebele style {prompt} . African, mural art, homes, highly detailed","non-African, canvas art, studios, undetailed"
Style: Kuba,"Kuba style {prompt} . African, textile, raffia, highly detailed","non-African, metalwork, steel, undetailed"
Style: Yoruba,"Yoruba style {prompt} . African, sculpture, spiritual, highly detailed","non-African, photography, secular, undetailed"
Style: Akan,"Akan style {prompt} . African, gold weights, symbolic, highly detailed","non-African, silver weights, literal, undetailed"
Style: Berber,"Berber style {prompt} . North African, jewelry, silver, highly detailed","non-North African, clothing, cotton, undetailed"
Style: Dogon,"Dogon style {prompt} . African, wood carving, spiritual, highly detailed","non-African, stone carving, secular, undetailed"
Style: Fang,"Fang style {prompt} . African, mask, ceremonial, highly detailed","non-African, mask, recreational, undetailed"
Style: Baga,"Baga style {prompt} . African, mask, spiritual, highly detailed","non-African, mask, secular, undetailed"
>>>>>> GPT Culture Movies Prompts
Style: Blade Runner,"Blade Runner {prompt} . Cyberpunk, neon-lit, rainy, dystopian, noir, cinematic, highly detailed","bright, sunny, utopian, cheerful, undetailed"
Style: Star Wars,"Star Wars {prompt} . Space opera, galaxy far, far away, epic, iconic, cinematic, highly detailed","earthly, small scale, uniconic, undetailed"
Style: Lord of the Rings,"Lord of the Rings {prompt} . Epic fantasy, Middle-earth, vast landscapes, highly detailed","science fiction, cityscape, undetailed"
Style: Matrix,"Matrix {prompt} . Cyberpunk, green tint, reality-bending, cinematic, highly detailed","rustic, brown tint, reality-based, undetailed"
Style: Indiana Jones,"Indiana Jones {prompt} . Adventure, archaeology, exotic locations, cinematic, highly detailed","domestic, library, unadventurous, undetailed"
Style: Mad Max,"Mad Max {prompt} . Post-apocalyptic, desert landscapes, dystopian, cinematic, highly detailed","utopian, lush landscapes, pre-apocalyptic, undetailed"
Style: 2001: A Space Odyssey,"2001: A Space Odyssey {prompt} . Sci-fi, space exploration, monolith, cinematic, highly detailed","fantasy, earth exploration, monochrome, undetailed"
Style: Alien,"Alien {prompt} . Sci-fi horror, space, xenomorphs, dark, highly detailed","comedy, bright, undetailed"
Style: Avatar,"Avatar {prompt} . Sci-fi, Pandora, bioluminescent, 3D, highly detailed","earthly, non-bioluminescent, 2D, undetailed"
Style: Pulp Fiction,"Pulp Fiction {prompt} . Crime, non-linear narrative, 90s, highly detailed","linear narrative, 2000s, undetailed"
Style: Kill Bill,"Kill Bill {prompt} . Martial arts, vengeance, yellow jumpsuit, cinematic, highly detailed","peaceful, pink jumpsuit, undetailed"
Style: Inception,"Inception {prompt} . Sci-fi, dream within a dream, mind-bending, cinematic, highly detailed","reality-based, straightforward, undetailed"
Style: Fight Club,"Fight Club {prompt} . Dark, gritty, psychological drama, highly detailed","light, glossy, undramatic, undetailed"
Style: Harry Potter,"Harry Potter {prompt} . Fantasy, Hogwarts, wizardry, highly detailed","science fiction, non-magical, undetailed"
Style: Marvel Cinematic Universe,"Marvel Cinematic Universe {prompt} . Superheroes, epic battles, colorful, highly detailed","ordinary people, small conflicts, monochrome, undetailed"
Style: DC Extended Universe,"DC Extended Universe {prompt} . Superheroes, grim, darker tones, highly detailed","ordinary people, cheerful, brighter tones, undetailed"
Style: Game of Thrones,"Game of Thrones {prompt} . Fantasy, Westeros, dragons, highly detailed","science fiction, no dragons, undetailed"
Style: Twilight,"Twilight {prompt} . Romantic fantasy, vampires, Pacific Northwest, highly detailed","non-romantic, zombies, desert, undetailed"
Style: Transformers,"Transformers {prompt} . Sci-fi, giant robots, explosions, highly detailed","fantasy, small creatures, calm, undetailed"
Style: The Hunger Games,"The Hunger Games {prompt} . Dystopian, survival, rebellion, highly detailed","utopian, abundance, conformity, undetailed"
Style: Pirates of the Caribbean,"Pirates of the Caribbean {prompt} . Adventure, pirates, supernatural, highly detailed","domestic, non-pirates, realistic, undetailed"
Style: Jurassic Park,"Jurassic Park {prompt} . Adventure, dinosaurs, Isla Nublar, highly detailed","undramatic, no dinosaurs, mainland, undetailed"
Style: The Shining,"The Shining {prompt} . Horror, haunted hotel, psychological thriller, highly detailed","comedy, non-haunted hotel, undetailed"
Style: The Godfather,"The Godfather {prompt} . Crime, mafia, 1940s-1950s, highly detailed","law-abiding, 2000s, undetailed"
Style: The Dark Knight,"The Dark Knight {prompt} . Superhero, gritty, Batman, Joker, highly detailed","light-hearted, Superman, undetailed"
Style: Casablanca,"Casablanca {prompt} . Drama, romance, WWII, highly detailed","action, non-romantic, modern day, undetailed"
Style: Jaws,"Jaws {prompt} . Thriller, shark, Amity Island, highly detailed","comedy, no shark, mainland, undetailed"
Style: The Wizard of Oz,"The Wizard of Oz {prompt} . Fantasy, musical, Technicolor, Oz, highly detailed","realistic, non-musical, monochrome, Kansas, undetailed"
Style: E.T.,"E.T. {prompt} . Sci-fi, family, suburban, highly detailed","fantasy, non-family, urban, undetailed"
Style: Ghostbusters,"Ghostbusters {prompt} . Comedy, supernatural, New York City, highly detailed","horror, natural, rural, undetailed"
Style: Back to the Future,"Back to the Future {prompt} . Sci-fi, time travel, DeLorean, highly detailed","fantasy, time stationary, non-vehicle, undetailed"
Style: Toy Story,"Toy Story {prompt} . Animated, toys come to life, friendship, highly detailed","live-action, inanimate toys, rivalry, undetailed"
Style: The Lion King,"The Lion King {prompt} . Animated, animal kingdom, African savannah, highly detailed","live-action, human kingdom, urban, undetailed"
Style: Finding Nemo,"Finding Nemo {prompt} . Animated, ocean adventure, Great Barrier Reef, highly detailed","live-action, land adventure, desert, undetailed"
Style: Shrek,"Shrek {prompt} . Animated, fairytale, swamp, highly detailed","live-action, realistic, city, undetailed"
Style: The Little Mermaid,"The Little Mermaid {prompt} . Animated, undersea, mermaids, highly detailed","live-action, land, humans, undetailed"
Style: Aladdin,"Aladdin {prompt} . Animated, Arabian Nights, magic carpet, highly detailed","live-action, modern day, ordinary carpet, undetailed"
Style: Beauty and the Beast,"Beauty and the Beast {prompt} . Animated, fairytale, enchanted castle, highly detailed","live-action, realistic, ordinary house, undetailed"
Style: Cinderella,"Cinderella {prompt} . Animated, fairytale, magical transformation, highly detailed","live-action, realistic, ordinary transformation, undetailed"
Style: Sleeping Beauty,"Sleeping Beauty {prompt} . Animated, fairytale, spinning wheel, highly detailed",""live-action, realistic, sewing machine, undetailed"
Style: Snow White,"Snow White {prompt} . Animated, fairytale, seven dwarfs, highly detailed","live-action, realistic, seven giants, undetailed"
Style: Mulan,"Mulan {prompt} . Animated, historical, Chinese warfare, highly detailed","live-action, futuristic, space warfare, undetailed"
Style: Pocahontas,"Pocahontas {prompt} . Animated, historical, Native American, highly detailed","live-action, modern, urban American, undetailed"
Style: The Nightmare Before Christmas,"The Nightmare Before Christmas {prompt} . Stop-motion, Halloween Town, Christmas Town, highly detailed","live-action, Easter Town, undetailed"
Style: Frozen,"Frozen {prompt} . Animated, fairytale, ice magic, highly detailed","live-action, realistic, fire magic, undetailed"
Style: Moana,"Moana {prompt} . Animated, Polynesian, ocean adventure, highly detailed","live-action, Nordic, mountain adventure, undetailed"
Style: Tangled,"Tangled {prompt} . Animated, fairytale, magic hair, highly detailed","live-action, realistic, ordinary hair, undetailed"
Style: Zootopia,"Zootopia {prompt} . Animated, anthropomorphic animals, urban, highly detailed","live-action, humans, rural, undetailed"
Style: Coco,"Coco {prompt} . Animated, Dia de los Muertos, Mexican culture, highly detailed","live-action, Halloween, American culture, undetailed"
Style: Brave,"Brave {prompt} . Animated, Scottish highlands, archery, highly detailed","live-action, tropical island, surfing, undetailed"
Style: Inside Out,"Inside Out {prompt} . Animated, emotions, abstract, highly detailed","live-action, logical thinking, realistic, undetailed"
Style: The Incredibles,"The Incredibles {prompt} . Animated, superhero, family, highly detailed","live-action, villain, solitary, undetailed"
Style: Up,"Up {prompt} . Animated, adventure, flying house, highly detailed","live-action, everyday life, stationary house, undetailed"
Style: Wall-E,"Wall-E {prompt} . Animated, post-apocalyptic, robots, highly detailed","live-action, pre-apocalyptic, humans, undetailed"
Style: Ratatouille,"Ratatouille {prompt} . Animated, culinary, Paris, highly detailed","live-action, non-culinary, New York, undetailed"
Style: Monsters Inc.,"Monsters Inc. {prompt} . Animated, monsters, scare factory, highly detailed","live-action, humans, laughter factory, undetailed"
Style: Cars,"Cars {prompt} . Animated, anthropomorphic cars, racing, highly detailed","live-action, humans, walking, undetailed"
Style: A Bug's Life,"A Bug's Life {prompt} . Animated, insects, ant colony, highly detailed","live-action, mammals, human society, undetailed"
Style: James Bond,"James Bond {prompt} . Spy, action, globe-trotting, highly detailed","romantic comedy, peace, domestic, undetailed"
Style: Fast and Furious,"Fast and Furious {prompt} . Action, car chases, family, highly detailed","romantic comedy, pedestrian chases, solitary, undetailed"
Style: Mission Impossible,"Mission Impossible {prompt} . Action, spy, impossible stunts, highly detailed","romantic comedy, everyday person, possible stunts, undetailed"
Style: Jurassic World,"Jurassic World {prompt} . Adventure, dinosaurs, theme park, highly detailed","romantic comedy, no dinosaurs, city park, undetailed"
Style: Minions,"Minions {prompt} . Animated, comedy, minions, highly detailed","live-action, drama, no minions, undetailed"
Style: Interstellar,"Interstellar {prompt} . Sci-fi, space travel, wormholes, highly detailed","romantic comedy, earth travel, roads, undetailed"
Style: The Grinch,"The Grinch {prompt} . Animated, Christmas, Whoville, highly detailed","live-action, summer, city, undetailed"
Style: Avengers: Endgame,"Avengers: Endgame {prompt} . Superhero, epic battle, time travel, highly detailed","romantic comedy, small conflict, present time, undetailed"
Style: Wonder Woman,"Wonder Woman {prompt} . Superhero, Amazonian, World War I, highly detailed","romantic comedy, non-Amazonian, modern day, undetailed"
Style: The Iron Giant,"The Iron Giant {prompt} . Animated, robot, 1950s, highly detailed","live-action, human, modern day, undetailed"
Style: Godzilla,"Godzilla {prompt} . Monster, destruction, cityscape, highly detailed","romantic comedy, creation, countryside, undetailed"
Style: King Kong,"King Kong {prompt} . Monster, island, skyscraper, highly detailed","romantic comedy, mainland, low-rise, undetailed"
Style: The Grand Budapest Hotel,"The Grand Budapest Hotel {prompt} . Comedy, hotel, pastel colors, highly detailed","action, wilderness, dark colors, undetailed"
Style: Inside Llewyn Davis,"Inside Llewyn Davis {prompt} . Drama, folk music, 1960s, highly detailed","action, pop music, modern day, undetailed"
Style: Drive,"Drive {prompt} . Action, neon, 1980s aesthetic, highly detailed","romantic comedy, daylight, modern aesthetic, undetailed"
Style: The Neon Demon,"The Neon Demon {prompt} . Horror, fashion, Los Angeles, highly detailed","romantic comedy, construction, New York, undetailed"
Style: It Follows,"It Follows {prompt} . Horror, supernatural, suburbia, highly detailed","romantic comedy, natural, city, undetailed"
Style: Dunkirk,"Dunkirk {prompt} . War, World War II, beach, highly detailed","romantic comedy, peace, city, undetailed"
Style: Her,"Her {prompt} . Romance, sci-fi, artificial intelligence, highly detailed","action, reality, human intelligence, undetailed"
Style: The Revenant,"The Revenant {prompt} . Drama, survival, wilderness, highly detailed","romantic comedy, luxury, city, undetailed"
Style: Whiplash,"Whiplash {prompt} . Drama, music, drumming, highly detailed","action, silence, no music, undetailed"
Style: The Shape of Water,"The Shape of Water {prompt} . Fantasy, romance, aquatic creature, highly detailed","action, hatred, terrestrial creature, undetailed"
Style: A Ghost Story,"A Ghost Story {prompt} . Drama, supernatural, ghost, highly detailed","romantic comedy, natural, human, undetailed"
Style: The Florida Project,"The Florida Project {prompt} . Drama, childhood, motel, highly detailed","action, adulthood, skyscraper, undetailed"
Style: La La Land,"La La Land {prompt} . Musical, romance, Los Angeles, highly detailed","action, hatred, New York, undetailed"
Style: The Lobster,"The Lobster {prompt}". Dark comedy, dystopian, relationship rules, highly detailed","romantic comedy, utopian, no relationship rules, undetailed"
Style: Ex Machina,"Ex Machina {prompt} . Sci-fi, artificial intelligence, secluded mansion, highly detailed","romantic comedy, human intelligence, bustling city, undetailed"
Style: Birdman,"Birdman {prompt} . Drama, Broadway, magical realism, highly detailed","action, Hollywood, realism, undetailed"
Style: Gravity,"Gravity {prompt} . Sci-fi, space, survival, highly detailed","romantic comedy, earth, abundance, undetailed"
Style: The Tree of Life,"The Tree of Life {prompt} . Drama, philosophical, nonlinear narrative, highly detailed","action, practical, linear narrative, undetailed"
Style: Inception,"Inception {prompt} . Sci-fi, dream manipulation, heist, highly detailed","romantic comedy, reality, gift-giving, undetailed"
Style: The Social Network,"The Social Network {prompt} . Drama, Facebook, entrepreneurship, highly detailed","action, Myspace, employment, undetailed"
Style: Moonlight,"Moonlight {prompt} . Drama, coming-of-age, Miami, highly detailed","action, aging, Los Angeles, undetailed"
Style: Roma,"Roma {prompt} . Drama, Mexico City, 1970s, highly detailed","action, New York City, modern day, undetailed"
Style: Parasite,"Parasite {prompt} . Thriller, class disparity, South Korea, highly detailed","romantic comedy, class equality, United States, undetailed"
Style: 1917,"1917 {prompt} . War, World War I, single shot, highly detailed","romantic comedy, peace, multiple shots, undetailed"
Style: Jojo Rabbit,"Jojo Rabbit {prompt} . Comedy, World War II, imaginary friend, highly detailed","drama, modern day, real friend, undetailed"
Style: Joker,"Joker {prompt} . Drama, psychological, Gotham City, highly detailed","romantic comedy, psychological well-being, Metropolis, undetailed"
Style: The Lighthouse,"The Lighthouse {prompt} . Drama, isolation, lighthouse, highly detailed","romantic comedy, community, city, undetailed"
Style: Once Upon a Time in Hollywood,"Once Upon a Time in Hollywood {prompt} . Comedy-drama, 1960s Hollywood, film industry, highly detailed","action, modern Hollywood, tech industry, undetailed"
Style: The Irishman,"The Irishman {prompt} . Crime, mafia, aging, highly detailed","romantic comedy, law-abiding citizens, youth, undetailed"
Style: Uncut Gems,"Uncut Gems {prompt} . Crime, debt, gambling, highly detailed","romantic comedy, abundance, saving, undetailed"
Style: Little Women,"Little Women {prompt} . Drama, coming-of-age, Civil War era, highly detailed","action, aging, modern day, undetailed"
Style: Knives Out,"Knives Out {prompt} . Mystery, whodunit, wealthy family, highly detailed","romantic comedy, clear culprit, poor family, undetailed"
Style: Marriage Story,"Marriage Story {prompt} . Drama, divorce, bi-coastal, highly detailed","romantic comedy, marriage, same city, undetailed"
Style: Midsommar,"Midsommar {prompt} . Horror, cult, Sweden, highly detailed","romantic comedy, mainstream religion, United States, undetailed"
Style: Booksmart,"Booksmart {prompt} . Comedy, high school, overachievers, highly detailed","drama, college, underachievers, undetailed"
Style: Ford v Ferrari,"Ford v Ferrari {prompt} . Drama, racing, 1960s, highly detailed","romantic comedy, walking, modern day, undetailed"
Style: Rocketman,"Rocketman {prompt} . Musical, biographical, Elton John, highly detailed","action, fictional, ordinary person, undetailed"
Style: Ad Astra,"Ad Astra {prompt} . Sci-fi, space travel, father-son relationship, highly detailed","romantic comedy, earth travel, romantic relationship, undetailed"
Style: Waves,"Waves {prompt} . Drama, family tragedy, forgiveness, highly detailed","romantic comedy, family comedy, grudge, undetailed"
Style: The Farewell,"The Farewell {prompt} . Drama, family, cultural conflict, highly detailed","romantic comedy, strangers, cultural harmony, undetailed"
Style: Hustlers,"Hustlers {prompt} . Drama, strippers, financial crime, highly detailed","romantic comedy, office workers, financial responsibility, undetailed"
Style: Portrait of a Lady on Fire,"Portrait of a Lady on Fire {prompt} . Romance, art, 18th century France, highly detailed","action, science, modern day United States, undetailed"
Style: Pain and Glory,"Painand Glory {prompt} . Drama, filmmaking, memory, highly detailed","romantic comedy, accounting, forgetfulness, undetailed"
Style: The Two Popes,"The Two Popes {prompt} . Drama, Vatican, philosophical discussions, highly detailed","action, a small town, physical challenges, undetailed"
Style: A Beautiful Day in the Neighborhood,"A Beautiful Day in the Neighborhood {prompt} . Drama, Fred Rogers, kindness, highly detailed","action, a villainous character, ruthlessness, undetailed"
Style: The Peanut Butter Falcon,"The Peanut Butter Falcon {prompt} . Adventure, friendship, wrestling, highly detailed","romantic comedy, rivalry, chess, undetailed"
Style: The Goldfinch,"The Goldfinch {prompt} . Drama, art, trauma, highly detailed","action, science, joy, undetailed"
Style: High Life,"High Life {prompt} . Sci-fi, space travel, isolation, highly detailed","romantic comedy, road trip, companionship, undetailed"
Style: The Nightingale,"The Nightingale {prompt} . Drama, revenge, colonial Tasmania, highly detailed","romantic comedy, forgiveness, modern California, undetailed"
Style: Yesterday,"Yesterday {prompt} . Comedy, music, The Beatles, highly detailed","drama, silence, unknown band, undetailed"
Style: Doctor Sleep,"Doctor Sleep {prompt} . Horror, supernatural, The Shining sequel, highly detailed","romantic comedy, natural, standalone story, undetailed"
Style: The Farewell,"The Farewell {prompt} . Drama, family, terminal illness, highly detailed","romantic comedy, friends, good health, undetailed"
Style: John Wick 3,"John Wick 3 {prompt} . Action, assassin, relentless pursuit, highly detailed","romantic comedy, pacifist, peaceful life, undetailed"
Style: Us,"Us {prompt} . Horror, doppelgängers, underground, highly detailed","romantic comedy, identical twins, above ground, undetailed"
Style: The Irishman,"The Irishman {prompt} . Crime, mobster, union, highly detailed","romantic comedy, law-abiding citizen, small business, undetailed"
Style: Honey Boy,"Honey Boy {prompt} . Drama, father-son relationship, Hollywood, highly detailed","romantic comedy, mother-daughter relationship, a small town, undetailed"
Style: Joker,"Joker {prompt} . Drama, mental health, Gotham City, highly detailed","romantic comedy, mental well-being, Metropolis, undetailed"
Style: Uncut Gems,"Uncut Gems {prompt} . Crime, gambling, New York City's Diamond District, highly detailed","romantic comedy, savings, rural town, undetailed"
Style: 1917,"1917 {prompt} . War, World War I, real-time, highly detailed","romantic comedy, peacetime, timeless, undetailed"
Style: Ford v Ferrari,"Ford v Ferrari {prompt} . Drama, racing, corporate politics, highly detailed","romantic comedy, walking, friendship, undetailed"
Style: Cats,"Cats {prompt} . Musical, anthropomorphic cats, surreal, highly detailed","action, ordinary humans, realism, undetailed"
Style: Jojo Rabbit,"Jojo Rabbit {prompt} . Comedy-drama, World War II, Hitler Youth, highly detailed","romantic comedy, modern day, ordinary youth, undetailed"
Style: Parasite,"Parasite {prompt} . Drama, social class, deception, highly detailed","romantic comedy, equality, honesty, undetailed"
Style: The Lion King,"The Lion King {prompt} . Animated, animal kingdom, Shakespearean, highly detailed","live-action, human kingdom, modern, undetailed"
Style: Aladdin,"Aladdin {prompt} . Animated, Middle Eastern, magic, highly detailed","live-action, Western, science, undetailed"
Style: Toy Story 4,"Toy Story 4 {prompt} . Animated, toys, adventure, highly detailed","live-action, non-living objects, ordinary life, undetailed"
Style: Avengers: Endgame,"Avengers: Endgame {prompt} . Superhero, epic, time travel, highly detailed","romantic comedy, small-scale, present day, undetailed"
Style: Star Wars: The Rise of Skywalker,"Star Wars: The Rise of Skywalker {prompt} . Sci-fi, space opera, Jedi, highly detailed","romantic comedy, earthbound, everyday person, undetailed"
Style: Downton Abbey,"Downton Abbey {prompt} . Drama, British aristocracy, period piece, highly detailed","romantic comedy, modern middle class, present day, undetailed"
Style: Frozen 2,"Frozen 2 {prompt} . Animated, fairytale, sisterhood, highly detailed","live-action, realism, rivalry, undetailed"
Style: Little Women,"Little Women {prompt} . Drama, sisters, Civil War era, highly detailed","action, brothers, modern day, undetailed"
>>>>>> GPT Anime Cartoon Mangas
Style: 2D Traditional Animation,"traditional 2D animation {prompt} . hand-drawn, frames, expressive, vibrant colors, highly detailed","3D, CG, stop-motion, photo-realistic, black and white"
Style: CGI Animation,"CGI animation {prompt} . 3D, photorealistic, high-quality textures and lighting, highly detailed","2D, stop-motion, anime, manga, black and white"
Style: Stop-Motion Animation,"stop-motion animation {prompt} . physical models, frame-by-frame, quirky, distinctive, highly detailed","2D, 3D, CG, anime, manga, black and white"
Style: Claymation,"claymation {prompt} . clay models, stop-motion, handcrafted, tactile, highly detailed","2D, 3D, CG, anime, manga, black and white"
Style: Vector Animation,"vector animation {prompt} . digital, clean lines, geometric shapes, bold colors, highly detailed","stop-motion, claymation, 3D, CG, black and white"
Style: Flash Animation,"flash animation {prompt} . digital, vector graphics, tweening, simple shapes, highly detailed","stop-motion, claymation, 3D, CG, black and white"
Style: Rotoscope Animation,"rotoscope animation {prompt} . traced over live-action, realistic movement, highly detailed","stop-motion, claymation, 3D, CG, black and white"
Style: Cut-Out Animation,"cut-out animation {prompt} . paper or fabric cut-outs, stop-motion, handcrafted, highly detailed","2D, 3D, CG, anime, manga, black and white"
Style: Sand Animation,"sand animation {prompt} . sand manipulated on light box, fluid movement, highly detailed","2D, 3D, CG, anime, manga, black and white"
Style: Pixel Art Animation,"pixel art animation {prompt} . low-res, blocky, digital, 8-bit, highly detailed","stop-motion, claymation, 3D, CG, black and white"
Style: Anime Style Animation,"anime style animation {prompt} . Japanese style, hand-drawn or digital, vibrant, unique character designs, highly detailed","western cartoons, 3D, CG, black and white"
Style: Manga Style Art,"manga style {prompt} . Japanese comics, black and white, unique character designs, detailed backgrounds, highly detailed","western comics, 3D, CG, vibrant colors"
Style: Chibi Style Art,"chibi style {prompt} . Japanese, super-deformed, cute, exaggerated features, vibrant colors, highly detailed","realistic, 3D, CG, western comics, black and white"
Style: Superflat,"superflat {prompt} . Japanese, postmodern art, flat planes of color, manga and anime influences, highly detailed","3D, CG, western art styles, black and white"
Style: Ukiyo-e,"ukiyo-e style {prompt} . Japanese woodblock prints, flat areas of color, detailed patterns, subjects from history and mythology, highly detailed","modern, 3D, CG, western art styles, black and white"
Style: Western Comics Art,"western comics art {prompt} . bold lines, dynamic poses, vibrant colors, dramatic lighting, highly detailed","anime, manga, 3D, CG, black and white"
Style: Graphic Novel Art,"graphic novel art {prompt} . detailed, expressive, ranges from black and white to full color, often more realistic than traditional comics, highly detailed","anime, manga, 3D, CG, western comics"
Style: Cartoon Modern,"cartoon modern {prompt} . mid-century modern aesthetic, stylized, geometric shapes, flat colors, highly detailed","realistic, 3D, CG, anime, manga, black and white"
Style: Abstract Animation,"abstract animation {prompt} . nonrepresentational, uses movement and color to create mood or emotion, highly detailed","realistic, 3D, CG, anime, manga, black and white"
Style: Silhouette Animation,"silhouette animation {prompt} . black figures against light background, dramatic, based on shadow puppetry, highly detailed","colorful, 3D, CG, anime, manga, black and white"
Style: Looney Tunes,"Looney Tunes {prompt} . Cartoon, slapstick humor, dynamic and exaggerated character designs, colorful, vibrant, whimsical","3D, realism, manga, black and white, subdued, serious"
Style: Disney Classic,"Disney Classic {prompt} . Animation, fairy tales, musical numbers, expressive characters, bright colors, detailed, professional","manga, anime, black and white, sketchy, rough"
Style: Studio Ghibli,"Studio Ghibli {prompt} . Anime, magical realism, environmental themes, unique characters, breathtaking landscapes, highly detailed","cartoon, slapstick, black and white, photo-realistic, barren"
Style: Pixar,"Pixar {prompt} . 3D animation, heartwarming stories, photorealistic environments, appealing character designs, emotional depth, detailed, professional","2D, anime, manga, black and white, sketchy"
Style: Shōnen,"Shōnen {prompt} . Manga, action-packed, youthful characters, dynamic battles, inspiring themes, highly detailed","Disney, Pixar, black and white, realism, romantic comedy"
Style: Mecha,"Mecha {prompt} . Anime, robots, futuristic technologies, dynamic battles, detailed mechanical designs, highly detailed","Disney, Pixar, cartoon, Looney Tunes, realism, fairy tales"
Style: Shojo,"Shojo {prompt} . Manga, romantic themes, delicate art style, emotional narratives, highly detailed","action, mecha, 3D, Pixar, black and white, barren"
Style: Nickelodeon,"Nickelodeon {prompt} . Cartoon, humor, dynamic characters, wacky and colorful designs, highly detailed","anime, manga, black and white, sketchy, serious"
Style: Cartoon Network,"Cartoon Network {prompt} . Cartoon, humor, dynamic characters, unique and abstract designs, highly detailed","anime, manga, black and white, sketchy, serious"
Style: Adult Swim,"Adult Swim {prompt} . Animation, adult humor, surreal themes, unique and abstract designs, highly detailed","children's cartoons, Disney, fairy tales, bright colors, traditional"
Style: Adventure Time,"Adventure Time {prompt} . Cartoon, fantasy themes, quirky characters, vibrant colors, highly detailed","anime, manga, black and white, sketchy, serious"
Style: Rick and Morty,"Rick and Morty {prompt} . Cartoon, science fiction, adult humor, unique and abstract designs, highly detailed","children's cartoons, Disney, fairy tales, bright colors, traditional"
Style: South Park,"South Park {prompt} . Animation, satire, crude humor, simplistic designs, highly detailed","anime, manga, Disney, Pixar, detailed, professional"
Style: The Simpsons,"The Simpsons {prompt} . Animation, satire, family themes, recognizable yellow characters, highly detailed","anime, manga, Disney, Pixar, black and white"
Style: Family Guy,"Family Guy {prompt} . Animation, adult humor, satirical themes, cartoonish designs, highly detailed","anime, manga, Disney, Pixar, black and white"
Style: Bob's Burgers,"Bob's Burgers {prompt} . Animation, family themes, humor, quirky characters, highly detailed","anime, manga, Disney, Pixar, black and white"
Style: Gravity Falls,"Gravity Falls {prompt} . Cartoon, mystery, fantasy themes, unique character designs, highly detailed","anime, manga, Disney, Pixar, black and white"
Style: Steven Universe,"Steven Universe {prompt} . Cartoon, LGBTQ+ themes, fantasy, vibrant colors, unique character designs, highly detailed","anime, manga, Disney, Pixar, black and white"
Style: One Piece,"One Piece {prompt} . Manga, adventure, pirates, dynamic battles, unique character designs, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: Attack on Titan,"Attack on Titan {prompt} . Anime, dystopian, giants, dynamic battles, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: My Hero Academia,"My Hero Academia {prompt} . Anime, superhero, high school, dynamic battles, unique character designs, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: Naruto,"Naruto {prompt} . Anime, ninjas, coming-of-age, dynamic battles, unique character designs, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: Dragon Ball Z,"Dragon Ball Z {prompt} . Anime, martial arts, aliens, dynamic battles, unique character designs, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: Sailor Moon,"Sailor Moon {prompt} . Anime, magical girls, romance, unique character designs, highly detailed","cartoon, realism, Disney, Pixar, black and white"
Style: Cowboy Bebop,"Cowboy Bebop {prompt} . Anime, space western, bounty hunters, noir themes, highly detailed","cartoon, realism, Disney, Pixar, black and white"
>>>>>> GPT Famous Artists
Style: Van Gogh, "Van Gogh style {prompt} . Expressive, impasto, swirling brushwork, vibrant," "realistic, photorealistic, calm, straight lines"
Style: Warhol, "Warhol style {prompt} . Pop art, bold colors, mass production, repetitive," "subdued colors, traditional, unique, serious"
Style: Picasso, "Picasso style {prompt} . Cubist, geometric, abstract, innovative," "realistic, detailed, smooth, fluid, single perspective"
Style: Da Vinci, "Da Vinci style {prompt} . Realistic, sfumato, detailed, chiaroscuro," "abstract, vibrant colors, bold, loose brushwork"
Style: Monet, "Monet style {prompt} . Impressionist, light-filled, loose brushwork, en plein air," "defined, detailed, subdued, studio work"
Style: Dali, "Dali style {prompt} . Surrealist, dreamlike, bizarre, symbolic," "realistic, ordinary, rational, clear, obvious"
Style: Pollock, "Pollock style {prompt} . Abstract expressionist, gestural, dripping, layered," "sharp, precise, realistic, calm"
Style: Rothko, "Rothko style {prompt} . Color field, abstract, simple, large-scale," "detailed, small, complex, figurative"
Style: Matisse, "Matisse style {prompt} . Fauvist, bold colors, loose, decorative," "realistic, subdued colors, detailed, serious"
Style: Banksy, "Banksy style {prompt} . Street art, satirical, stenciled, urban," "classic, traditional, indoor, realism"
Style: Michelangelo, "Michelinagelo style {prompt} . High Renaissance, sculptural, detailed, humanistic," "abstract, loose, simplistic, impersonal"
Style: Kusama, "Kusama style {prompt} . Pop Art, abstract, polka dots, immersive," "plain, monotone, realistic, sparse"
Style: Hokusai, "Hokusai style {prompt} . Ukiyo-e, woodblock print, detailed, narrative," "abstract, free-form, modern, minimal"
Style: O'Keeffe, "O'Keeffe style {prompt} . Modernist, floral, bold, abstract," "small scale, detailed, muted colors, complex"
Style: Cézanne, "Cézanne style {prompt} . Post-impressionist, geometric, detailed, brushstrokes," "smooth, flat, loose, fluid"
Style: Hopper, "Hopper style {prompt} . Realistic, light and shadow, loneliness, American urban," "busy, crowded, vibrant, abstract"
Style: Klimt, "Klimt style {prompt} . Symbolist, decorative, ornamental, sensual," "simple, bare, abstract, rough"
Style: Chagall, "Chagall style {prompt} . Surrealist, dreamy, vibrant, narrative," "realistic, dull, serious, minimal"
Style: Lichtenstein, "Lichtenstein style {prompt} . Pop art, comic strip, bold, ironic," "realistic, traditional, serious, detailed"
Style: Basquiat, "Basquiat style {prompt} . Neo-expressionist, primitive, graffiti, social commentary," "polished, elegant, subdued, subtle"
Style: Frida Kahlo, "Frida Kahlo style {prompt} . Symbolic, surrealistic, emotional, vibrant," "realistic, subdued, impersonal, monochromatic"
Style: Georgia O'Keeffe, "Georgia O'Keeffe style {prompt} . Modernist, abstract, large scale, organic," "small, detailed, geometric, muted colors"
Style: Jackson Pollock, "Jackson Pollock style {prompt} . Abstract expressionist, action painting, drip technique, energetic," "controlled, figurative, calm, small scale"
Style: Rembrandt, "Rembrandt style {prompt} . Baroque, chiaroscuro, realistic, emotional," "flat lighting, abstract, impersonal, clean"
Style: Renoir, "Renoir style {prompt} . Impressionist, vibrant, lively, warm," "dull, calm, detailed, cool colors"
Style: Magritte, "Magritte style {prompt} . Surrealist, thought-provoking, mysterious, realistic," "abstract, obvious, open, unrefined"
Style: Manet, "Manet style {prompt} . Realistic, impressionistic, bold, contemporary," "abstract, traditional, timid, historical"
Style: Vermeer, "Vermeer style {prompt} . Baroque, detailed, light, tranquil," "abstract, rough, dark, chaotic"
Style: Caravaggio, "Caravaggio style {prompt} . Baroque, chiaroscuro, dramatic, realistic," "soft lighting, calm, abstract, idealized"
Style: Rodin, "Rodin style {prompt} . Realistic, expressive, textured, bronze," "smooth, emotionless, polished, painted"
Style: Botticelli, "Botticelli style {prompt} . Early Renaissance, allegorical, graceful, detailed," "abstract, harsh, simplified, rough"
Style: Edward Hopper, "Edward Hopper style {prompt} . Realistic, isolation, architectural, strong contrast," "crowded, organic, soft lighting, abstract"
Style: Keith Haring, "Keith Haring style {prompt} . Pop art, bold lines, vibrant colors, social messages," "subtle, realistic, muted colors, personal"
Style: Damien Hirst, "Damien Hirst style {prompt} . Contemporary, shocking, conceptual, large scale," "traditional, calming, handcrafted, small scale"
Style: Yayoi Kusama, "Yayoi Kusama style {prompt} . Contemporary, polka dots, immersive, psychedelic," "traditional, plain, minimalist, calm"
Style: Francis Bacon, "Francis Bacon style {prompt} . Existential, distorted, unsettling, expressive," "comforting, realistic, calm, subdued"
Style: Ai Weiwei, "Ai Weiwei style {prompt} . Conceptual, political, traditional Chinese materials, large-scale," "apolitical, contemporary, small-scale, western materials"
Style: Cindy Sherman, "Cindy Sherman style {prompt} . Conceptual, self-portrait, character study, cinematic," "landscape, group portraits, candid, documentary"
Style: Frank Stella, "Frank Stella style {prompt} . Minimalist, geometric, large scale, non-representational," "maximalist, organic, small scale, representational"
Style: Lucian Freud, "Lucian Freud style {prompt} . Realistic, impasto, psychological, intimate," "abstract, smooth, impersonal, public"
Style: Marc Chagall, "Marc Chagall style {prompt} . Dreamlike, vibrant, symbolic, folklore-inspired," "realistic, subdued, literal, modern"
Style: Roy Lichtenstein, "Roy Lichtenstein style {prompt} . Pop art, comic strip influence, bold outlines, primary colors," "abstract, realistic, pastel colors, complex"
Style: Thomas Kinkade, "Thomas Kinkade style {prompt} . Romantic, idealized, warm light, detailed," "abstract, harsh, cool light, minimalist"
Style: Joan Miró, "Joan Miró style {prompt} . Surrealist, abstract, biomorphic forms, primary colors," "realistic, figurative, complex, muted colors"
Style: Gerhard Richter, "Gerhard Richter style {prompt} . Abstract, textured, layered, scraped," "realistic, smooth, single-layer, detailed"
Style: Wassily Kandinsky, "Wassily Kandinsky style {prompt} . Abstract, geometric, vibrant, musical," "realistic, organic, muted, silent"
Style: Norman Rockwell, "Norman Rockwell style {prompt} . Realistic, narrative, Americana, detailed," "abstract, non-narrative, foreign, minimalist"
Style: Bridget Riley, "Bridget Riley style {prompt} . Op art, geometric, black and white, optical illusion," "organic, color, realistic, straightforward"
Style: Piet Mondrian, "Piet Mondrian style {prompt} . De Stijl, geometric, primary colors, black grid," "organic, multiple colors, no grid, curved lines"
Style: Salvador Dalí, "Salvador Dalí style {prompt} . Surrealist, dreamlike, symbolic, detailed," "realistic, ordinary, literal, sketchy"
Style: Mary Cassatt, "Mary Cassatt style {prompt} . Impressionist, domestic life, soft colors, loose brushwork," "abstract, public life, vibrant colors, precise"
Style: Diego Rivera, "Diego Rivera style {prompt} . Muralist, social realist, Mexican culture, narrative," "miniature, abstract, foreign, non-narrative"
Style: Jean-Michel Basquiat, "Jean-Michel Basquiat style {prompt} . Neo-expressionist, graffiti influence, raw, socially critical," "classical, polished, refined, apolitical"
Style: Henry Moore, "Henry Moore style {prompt} . Abstract, organic, bronze, monumental," "realistic, geometric, miniature, pastel"
Style: Frida Kahlo, "Frida Kahlo style {prompt} . Surrealist, symbolic, vibrant, autobiographical," "realistic, abstract, dull, impersonal"
Style: Grant Wood, "Grant Wood style {prompt} . Regionalist, rural, detailed, Americana," "urban, abstract, vague, non-American"
Style: Edward Hopper, "Edward Hopper style {prompt} . Realistic, isolation, strong light, urban," "impressionistic, crowded, soft light, rural"
Style: Andy Goldsworthy, "Andy Goldsworthy style {prompt} . Environmental art, natural materials, temporary, site-specific," "urban art, man-made materials, permanent, unspecific site"
Style: Louise Bourgeois, "Louise Bourgeois style {prompt} . Abstract, psychological, large-scale, organic," "realistic, impersonal, small-scale, geometric"
Style: Ansel Adams, "Ansel Adams style {prompt} . Black and white, nature, high contrast, detailed," "color, urban, low contrast, vague"
Style: Yoko Ono, "Yoko Ono style {prompt} . Conceptual, minimalist, performance, participatory," "decorative, maximalist, static, non-interactive"
Style: Gustav Klimt, "Gustav Klimt style {prompt} . Symbolist, decorative, golden, intricate," "realistic, functional, monochrome, simplified"
Style: Jeff Koons, "Jeff Koons style {prompt} . Contemporary, kitsch, glossy, large-scale," "traditional, serious, matte, small-scale"
Style: John Singer Sargent, "John Singer Sargent style {prompt} . Realistic, elegant, portrait, expressive," "abstract, casual, landscape, subdued"
Style: Marcel Duchamp, "Marcel Duchamp style {prompt} . Dada, readymade, conceptual, controversial," "traditional, handmade, decorative, safe"
Style: Claude Monet, "Claude Monet style {prompt} . Impressionist, outdoor, light, loose brushwork," "neoclassical, indoor, dark, tight brushwork"
Style: Anish Kapoor, "Anish Kapoor style {prompt} . Abstract, large-scale, reflective, curved," "figurative, small-scale, matte, straight lines"
Style: Hieronymus Bosch, "Hieronymus Bosch style {prompt} . Surrealist, detailed, religious, narrative," "realistic, abstract, secular, non-narrative"
Style: Paul Gauguin, "Paul Gauguin style {prompt} . Post-Impressionist, exotic, bold colors, flat," "Impressionist, familiar, muted colors, volumetric"
Style: Katsushika Hokusai, "Katsushika Hokusai style {prompt} . Ukiyo-e, nature, woodblock print, detailed," "western style, urban, oil painting, abstract"
Style: Pierre-Auguste Renoir, "Pierre-Auguste Renoir style {prompt} . Impressionist, joyful, light, loose brushwork," "neoclassical, somber, dark, tight brushwork"
Style: Antony Gormley, "Antony Gormley style {prompt} . Sculpture, human form, rusted, site-specific," "painting, abstract, polished, gallery-based"
Style: Kazimir Malevich, "Kazimir Malevich style {prompt} . Suprematist, abstract, geometric, minimal," "realistic, organic, decorative, complex"
Style: Jean-Antoine Watteau, "Jean-Antoine Watteau style {prompt} . Rococo, outdoor, elegant, lively," "Baroque, indoor, serious, static"
Style: Constantin Brâncuși, "Constantin Brâncuși style {prompt} . Modernist, abstract, bronze, streamlined," "traditional, figurative, wood, complex"
Style: Egon Schiele, "Egon Schiele style {prompt} . Expressionist, figure, distorted, emotional," "Impressionist, landscape, proportional, detached"
Style: Nam June Paik, "Nam June Paik style {prompt} . Video art, technological, interactive, large-scale," "painting, traditional, static, small-scale"
Style: James Whistler, "James Whistler style {prompt} . Tonalism, atmospheric, subdued, abstract," "Fauvism, vibrant, bold, detailed"
Style: Wassily Kandinsky, "Wassily Kandinsky style {prompt} . Abstract, musical, geometric, vibrant," "realistic, silent, organic, subdued"
Style: Lucio Fontana, "Lucio Fontana style {prompt} . Spatialism, monochrome, slashed, minimal," "Futurism, colorful, whole, detailed"
Style: Artemisia Gentileschi, "Artemisia Gentileschi style {prompt} . Baroque, dramatic, biblical, female-centric," "Rococo, calm, mythological, male-centric"
Style: Jean Dubuffet, "Jean Dubuffet style {prompt} . Art Brut, textured, primal, abstract," "Academic art, smooth, refined, realistic"
Style: Sandro Botticelli, "Sandro Botticelli style {prompt} . Early Renaissance, mythological, linear, vibrant," "Baroque, historical, painterly, subdued"
Style: Carl Andre, "Carl Andre style {prompt} . Minimalist, geometric, industrial, ground-level," "Baroque, organic, handcrafted, elevated"
Style: David Hockney, "David Hockney style {prompt} . Pop art, landscape, vibrant, digital," "Abstract Expressionism, figure, subdued, traditional"
Style: Cindy Sherman, "Cindy Sherman style {prompt} . Conceptual, self-portrait, character study, cinematic," "landscape, group portraits, candid, documentary"
Style: Jenny Holzer, "Jenny Holzer style {prompt} . Conceptual, text-based, public, LED," "painting, image-based, private, canvas"
Style: Dante Gabriel Rossetti, "Dante Gabriel Rossetti style {prompt} . Pre-Raphaelite, medieval, literary, romantic," "Futurist, modern, abstract, stark"
Style: Zaha Hadid, "Zaha Hadid style {prompt} . Modernist, organic, futuristic, curved," "Classical, geometric, traditional, straight lines"
Style: Takashi Murakami, "Takashi Murakami style {prompt} . Superflat, pop culture, colorful, cartoonish," "Cubist, high culture, monochrome, realistic"
Style: Edward Weston, "Edward Weston style {prompt} . Photography, black and white, still life, detailed," "Painting, color, action, abstract"
Style: Edvard Munch, "Edvard Munch style {prompt} . Expressionist, psychological, bold colors, distorted," "Impressionist, physical, muted colors, proportional"
Style: Ai Weiwei, "Ai Weiwei style {prompt} . Contemporary, political, traditional Chinese materials, large-scale," "Classical, apolitical, modern materials, small-scale"
Style: Georges Braque, "Georges Braque style {prompt} . Cubist, abstract, collage, muted colors," "Romantic, realistic, oil painting, vibrant colors"
Style: Sol LeWitt, "Sol LeWitt style {prompt} . Conceptual, geometric, minimal, instructional," "Expressionist, organic, complex, spontaneous"
Style: Mary Cassatt, "Mary Cassatt style {prompt} . Impressionist, domestic, pastel, feminine," "Realist, urban, oil, masculine"
Style: Damien Hirst, "Damien Hirst style {prompt} . Contemporary, controversial, installation, medical," "Classical, traditional, canvas, floral"
Style: Giuseppe Arcimboldo, "Giuseppe Arcimboldo style {prompt} . Mannerist, portrait, food, symbolic," "Cubist, landscape, abstract, literal"
Style: Yves Klein, "Yves Klein style {prompt} . Nouveau réalisme, monochrome, blue, performance," "Pop Art, colorful, red, static"
Style: Frida Kahlo, "Frida Kahlo style {prompt} . Surrealist, autobiographical, vibrant, symbolic," "Realist, historical, muted, literal"
Style: Piet Mondrian, "Piet Mondrian style {prompt} . De Stijl, geometric, primary colors, balanced," "Surrealist, organic, pastel colors, chaotic"
Style: Bridget Riley, "Bridget Riley style {prompt} . Op Art, geometric, black and white, optical," "Impressionist, organic, colorful, static"
Style: Mark Rothko, "Mark Rothko style {prompt} . Abstract Expressionist, color field, large-scale, emotional," "Pop Art, pattern, small-scale, detached"
Style: Joseph Beuys, "Joseph Beuys style {prompt} . Fluxus, performance, social sculpture, felt," "Minimalism, painting, object, metal"
Style: Berthe Morisot, "Berthe Morisot style {prompt} . Impressionist, feminine, domestic, light," "Surrealist, masculine, public, dark"
Style: Agnes Martin, "Agnes Martin style {prompt} . Minimalist, geometric, grid, subtle," "Baroque, organic, floral, bold"
Style: Yayoi Kusama, "Yayoi Kusama style {prompt} . Contemporary, polka dots, infinity rooms, red," "Classical, plain, single room, blue"
Style: Andy Goldsworthy, "Andy Goldsworthy style {prompt} . Environmental, temporary, nature, outdoors," "Industrial, permanent, man-made, indoors"
Style: Henri Cartier-Bresson, "Henri Cartier-Bresson style {prompt} . Photography, decisive moment, black and white, candid," "Painting, posed, color, staged"
Style: Marina Abramović, "Marina Abramović style {prompt} . Performance, endurance, audience participation, minimal," "Sculpture, instant, observer, complex"
Style: Man Ray, "Man Ray style {prompt} . Dada, photography, rayograph, experimental," "Realism, painting, traditional, conventional"
Style: Käthe Kollwitz, "Käthe Kollwitz style {prompt} . Expressionist, social realism, black and white, human suffering," "Impressionist, aestheticism, color, human joy"
Style: Robert Rauschenberg, "Robert Rauschenberg style {prompt} . Neo-Dada, combine, mixed-media, assemblage," "Minimalism, singular material, oil painting, separated"
Style: Lyonel Feininger, "Lyonel Feininger style {prompt} . Expressionist, Cubist, architecture, transparent," "Impressionist, organic, landscape, opaque"
Style: Tracey Emin, "Tracey Emin style {prompt} . YBA, confessional, neon, textile," "Old Masters, universal, oil, marble"
Style: René Magritte, "René Magritte style {prompt} . Surrealist, object, juxtaposition, mystery," "Realist, figure, relation, clarity"
Style: Henry Moore, "Henry Moore style {prompt} . Modernist, sculpture, organic, monumental," "Classical, painting, geometric, small"
Style: Rachel Whiteread, "Rachel Whiteread style {prompt} . Contemporary, sculpture, negative space, cast," "Traditional, drawing, positive space, sketch"
Style: Tomma Abts, "Tomma Abts style {prompt} . Abstract, geometric, small-scale, acrylic and oil," "Figurative, organic, large-scale, watercolor"
Style: Max Ernst, "Max Ernst style {prompt} . Surrealist, collage, frottage, dreamlike," "Realist, oil painting, brushwork, day-to-day"
Style: Richard Serra, "Richard Serra style {prompt} . Minimalist, sculpture, corten steel, site-specific," "Baroque, painting, canvas, gallery-specific"
Style: Ernst Ludwig Kirchner, "Ernst Ludwig Kirchner style {prompt} . Expressionist, urban, woodcut, vibrant," "Impressionist, rural, oil painting, subdued"
Style: Eva Hesse, "Eva Hesse style {prompt} . Postminimalist, sculpture, organic, fiberglass," "Minimalist, painting, geometric, canvas"
Style: Paul Cézanne, "Paul Cézanne style {prompt} . Post-Impressionist, still life, geometric, brushwork," "Impressionist, action, organic, smooth"
Style: Francis Bacon, "Francis Bacon style {prompt} . Expressionist, distorted, triptych, anguish," "Classical, proportional, single panel, contentment"
Style: Louise Bourgeois, "Louise Bourgeois style {prompt} . Contemporary, sculpture, feminist, fabric," "Classical, painting, patriarchal, oil"
Style: Chuck Close, "Chuck Close style {prompt} . Photorealism, portrait, large-scale, gridded," "Impressionism, landscape, small-scale, loose"
Style: Thomas Gainsborough, "Thomas Gainsborough style {prompt} . Rococo, landscape, elegant, oil," "Baroque, portrait, casual, pastel"
Style: Gerhard Richter, "Gerhard Richter style {prompt} . Abstract, squeegee, photo-based, blurred," "Realistic, brushwork, imagination-based, detailed"
Style: Jean-Michel Basquiat, "Jean-Michel Basquiat style {prompt} . Neo-expressionist, graffiti, crown, vibrant," "Photorealism, calligraphy, mundane, subdued"
Style: Alexander Calder, "Alexander Calder style {prompt} . Kinetic, mobile, primary colors, balanced," "Static, statue, pastel colors, unbalanced"
Style: Jackson Pollock, "Jackson Pollock style {prompt} . Abstract Expressionist, drip, large-scale, spontaneous," "Cubist, precise, small-scale, planned"
Style: Anselm Kiefer, "Anselm Kiefer style {prompt} . Neo-expressionist, monumental, textured, historical," "Minimalist, small-scale, smooth, futuristic"
Style: Amedeo Modigliani, "Amedeo Modigliani style {prompt} . Modernist, portrait, elongated, nude," "Cubist, landscape, proportional, clothed"
Style: Gilbert & George, "Gilbert & George style {prompt} . Contemporary, photographic, duo, confrontational," "Traditional, painted, individual, pleasant"
Style: El Greco, "El Greco style {prompt} . Mannerist, religious, elongated, dramatic," "Renaissance, secular, proportional, calm"
Style: Salvador Dalí, "Salvador Dalí style {prompt} . Surrealist, dreamlike, precise, melting," "Realist, day-to-day, loose, solid"
Style: Rembrandt van Rijn, "Rembrandt van Rijn style {prompt} . Baroque, self-portrait, chiaroscuro, etching," "Rococo, group portrait, bright, oil painting"
Style: Keith Haring, "Keith Haring style {prompt} . Pop art, street art, bold lines, active figures," "Impressionism, studio art, fine brushwork, passive landscape"
Style: Georgia O'Keeffe, "Georgia O'Keeffe style {prompt} . Modernist, flowers, close-up, sensual," "Cubist, objects, far-off, detached"
Style: Caravaggio, "Caravaggio style {prompt} . Baroque, tenebrism, dramatic, religious," "Renaissance, bright, calm, secular"
Style: Louise Nevelson, "Louise Nevelson style {prompt} . Abstract expressionist, sculpture, monochrome, found objects," "Realist, painting, colorful, new materials"
Style: James Turrell, "James Turrell style {prompt} . Land art, light, immersive, perceptual," "Street art, dark, observational, intellectual"
Style: Édouard Manet, "Édouard Manet style {prompt} . Realist, modern life, loose brushwork, controversial," "Romantic, history, fine brushwork, conventional"
Style: Marc Chagall, "Marc Chagall style {prompt} . Surrealist, dreamlike, colorful, narrative," "Realist, day-to-day, monochrome, non-narrative"
Style: Dan Flavin, "Dan Flavin style {prompt} . Minimalist, light, fluorescent, site-specific," "Baroque, dark, oil, gallery-specific"
Style: Sarah Lucas, "Sarah Lucas style {prompt} . YBA, feminist, readymade, provocative," "Old Masters, masculine, handmade, conservative"
Style: Johannes Vermeer, "Johannes Vermeer style {prompt} . Baroque, domestic, light, detailed," "Cubist, public, dark, abstract"
Style: Tadao Ando, "Tadao Ando style {prompt} . Minimalist, concrete, light, water," "Baroque, brick, dark, dry"
Style: Roy Lichtenstein, "Roy Lichtenstein style {prompt} . Pop art, comic strip, benday dots, primary colors," "Abstract expressionism, serious subject, brushwork, secondary colors"
Style: Joseph Cornell, "Joseph Cornell style {prompt} . Surrealist, box, found objects, nostalgic," "Minimalist, open space, new materials, contemporary"
Style: Gustave Courbet, "Gustave Courbet style {prompt} . Realist, rural life, coarse brushwork, controversial," "Neoclassical, noble life, fine brushwork, conventional"
Style: Richard Long, "Richard Long style {prompt} . Land art, circle, natural materials, ephemeral," "Street art, square, synthetic materials, permanent"
Style: Otto Dix, "Otto Dix style {prompt} . New Objectivity, war, grotesque, social critique," "Impressionism, peace, beautiful, aesthetic enjoyment"
Style: Barnett Newman, "Barnett Newman style {prompt} . Abstract expressionism, zip, large-scale, color field," "Pop art, pattern, small-scale, comic strip"
Style: Sophie Calle, "Sophie Calle style {prompt} . Conceptual, photography, text, personal," "Abstract, painting, brushwork, universal"
Style: KAWS, "KAWS style {prompt} . Pop art, vinyl toy, X eyes, cartoonish," "Conceptual, bronze statue, normal eyes, realistic"
Style: Francis Picabia, "Francis Picabia style {prompt} . Dada, machine, painting, provocative," "Impressionism, nature, sketch, pleasant"
Style: H.R. Giger, "H.R. Giger style {prompt} . Surrealist, biomechanical, airbrush, dark," "Impressionist, human, brush, light"
Style: Jean Arp, "Jean Arp style {prompt} . Dada, abstract, biomorphic, sculpture," "Realism, figurative, geometric, painting"
Style: Ai Weiwei, "Ai Weiwei style {prompt} . Contemporary, political, installation, ceramics," "Renaissance, neutral, oil painting, metals"
Style: Fernand Léger, "Fernand Léger style {prompt} . Cubist, mechanical, mural, bold colors," "Surrealist, organic, small-scale, muted colors"
Style: Yoko Ono, "Yoko Ono style {prompt} . Conceptual, performance, instruction, peace," "Realist, still life, detailed, war"
Style: Cindy Sherman, "Cindy Sherman style {prompt} . Contemporary, self-portrait, photography, identity," "Traditional, landscape, painting, anonymity"
Style: Nam June Paik, "Nam June Paik style {prompt} . Video art, television, interactive, futuristic," "Traditional art, canvas, passive, historical"
Style: Barbara Kruger, "Barbara Kruger style {prompt} . Conceptual, text, black and white, feminist," "Impressionist, image, color, patriarchal"
Style: Piero della Francesca, "Piero della Francesca style {prompt} . Renaissance, fresco, mathematical, religious," "Contemporary, installation, random, secular"
Style: Georgia O'Keeffe, "Georgia O'Keeffe style {prompt} . Modernist, flowers, close-up, sensual," "Cubist, objects, far-off, detached"
Style: Richard Hamilton, "Richard Hamilton style {prompt} . Pop Art, collage, consumer culture, mixed media," "Impressionism, oil painting, rural life, single medium"
Style: Kazimir Malevich, "Kazimir Malevich style {prompt} . Suprematism, abstract, geometric, minimal," "Realism, figurative, detailed, maximal"
Style: Grayson Perry, "Grayson Perry style {prompt} . Contemporary, ceramics, tapestry, narrative," "Old Masters, oil painting, canvas, non-narrative"
Style: Faith Ringgold, "Faith Ringgold style {prompt} . Contemporary, quilt, narrative, feminist," "Abstract, sculpture, non-narrative, masculine"
Style: Banksy, "Banksy style {prompt} . Street Art, stencil, satirical, black and white," "Studio Art, oil painting, serious, color"
Style: Tracey Emin, "Tracey Emin style {prompt} . YBA, confessional, neon, textile," "Old Masters, universal, oil, marble"
Style: Olafur Eliasson, "Olafur Eliasson style {prompt} . Installation, light, environment, perceptual," "Painting, dark, indoors, cognitive"
Style: Kiki Smith, "Kiki Smith style {prompt} . Feminist, body, sculpture, mythological," "Patriarchal, landscape, painting, historical"
Style: David Hockney, "David Hockney style {prompt} . Pop Art, vibrant colors, collage, landscapes," "Abstract Expressionism, muted colors, single panel, figures"
Style: Chris Ofili, "Chris Ofili style {prompt} . YBA, mixed-media, elephant dung, decorative," "Minimalism, single-media, clean, austere"
Style: Ellsworth Kelly, "Ellsworth Kelly style {prompt} . Hard-edge painting, color field, minimalist, geometric," "Impressionism, detailed, ornate, organic"
Style: Christo and Jeanne-Claude, "Christo and Jeanne-Claude style {prompt} . Installation, environmental, fabric, temporal," "Still Life, indoor, metal, permanent"
Style: Wayne Thiebaud, "Wayne Thiebaud style {prompt} . Pop Art, still life, pastel, thick paint," "Cubism, dynamic scenes, vibrant, thin paint"
Style: Jenny Holzer, "Jenny Holzer style {prompt} . Conceptual, text, LED, public spaces," "Realism, image, oil painting, private spaces"
Style: Antony Gormley, "Antony Gormley style {prompt} . Sculpture, human form, rusted metal, public art," "Painting, abstract, bright colors, gallery art"
Style: Maurice Sendak, "Maurice Sendak style {prompt} . Children's illustration, fantasy, detailed, narrative," "Abstract, adult, minimalist, non-narrative"
>>>>>> Advanced GPT Photography
Portrait Photography Style: Charismatic,"{prompt} with charisma. 50mm lens, f/2.8, focused on eyes, natural lighting","overexposed, underexposed, blurry, distorted, overprocessed"
Portrait Photography Style: Cinematic,"cinematic portrait of {prompt}. 85mm lens, f/1.8, dramatic side lighting, moody atmosphere","overblown highlights, noisy, grainy, oversaturated, wide-angle distortion"
Portrait Photography Style: Environmental,"environmental portrait of {prompt}. 35mm lens, f/4, wider context, natural surroundings","cluttered background, poor lighting, overexposed, underexposed, unsharp"
Photojournalism Style: Reportage,"gripping reportage of {prompt}. Wide-angle lens, f/8, focus on action, capture the moment","blurred action, low light noise, unsteady shot, out of focus, distorted perspective"
Photojournalism Style: Candid,"candid shot of {prompt}. 50mm lens, f/2.8, spontaneous, unposed","poor lighting, motion blur, out of focus, distracting background, overprocessed"
Photojournalism Style: Documentary,"documentary style of {prompt}. 35mm lens, f/5.6, truthful representation, neutral perspective","overexposed, underexposed, oversaturated, motion blur, unsteady shot"
Fashion Photography Style: Haute Couture,"haute couture display of {prompt}. 85mm lens, f/2.2, vibrant colors, dramatic lighting","flat lighting, out of focus, distracting background, overprocessed, oversaturated"
Fashion Photography Style: Editorial,"editorial fashion shot of {prompt}. 50mm lens, f/2.5, storytelling, focused on outfit","unflattering pose, poor lighting, blurry, distracting elements, overexposed"
Fashion Photography Style: Catalog,"catalog shot of {prompt}. 70mm lens, f/5.6, neutral background, clear focus on attire","poor lighting, unflattering angles, distorted perspective, underexposed, oversaturated"
Sports Photography Style: Action-packed,"action-packed shot of {prompt}. 200mm lens, f/2.8, high shutter speed, capture the peak moment","motion blur, underexposed, out of focus, distracting background, unsteady shot"
Sports Photography Style: Emotional,"emotional moment in {prompt}. 135mm lens, f/4, capture expressions, ambient lighting","poor focus, high ISO noise, unsteady shot, underexposed, distorted colors"
Sports Photography Style: Narrative,"narrative image of {prompt}. 50mm lens, f/3.5, storytelling, context setting","unfocused, poor lighting, cluttered composition, overexposed, distorted perspective"
Still Life Photography Style: Minimalistic,"minimalistic composition of {prompt}. 50mm lens, f/5.6, simplistic design, neutral colors","cluttered, oversaturated, unbalanced composition, poor lighting, overexposed"
Still Life Photography Style: Dramatic,"dramatic still life of {prompt}. 85mm lens, f/2.2, dramatic lighting, intense colors","flat lighting, blurry, underexposed, distracting elements, oversaturated"
Still Life Photography Style: Rustic,"rustic presentation of {prompt}. 35mm lens, f/4, natural elements, warm tones","poor focus, overexposed, cluttered, cold colors, unbalanced composition"
Editorial Photography Style: Investigative,"investigative shot of {prompt}. 24mm lens, f/4, informative, intriguing","blurry, underexposed, distorted perspective, high ISO noise, distracting elements"
Editorial Photography Style: Lifestyle,"lifestyle capture of {prompt}. 50mm lens, f/2.8, candid, vibrant colors","poor lighting, overprocessed, distracting background, motion blur, unsteady shot"
Editorial Photography Style: Opinion,"opinion image of {prompt}. 35mm lens, f/5.6, emotive, storytelling","poor focus, underexposed, cluttered composition, overexposed highlights, distorted colors"
Architectural Photography Style: Historical,"historical capture of {prompt}. 24mm lens, f/8, capture architectural details, natural lighting","distorted perspective, underexposed, overprocessed, unsharp, oversaturated"
Architectural Photography Style: Modernist,"modernist view of {prompt}. 18mm lens, f/4, minimalistic, strong lines","barrel distortion, overexposed, blurry, poor composition, flat colors"
Architectural Photography Style: Surreal,"surreal perspective of {prompt}. Fisheye lens, f/2.8, abstract interpretation, vibrant colors","unfocused, poor lighting, underexposed, overprocessed, distracting elements"
>>>>>> GPT Painting Styles
Style: Steampunk,"steampunk-inspired {prompt} . gears, brass, rivets, old-world technology, intricate, highly detailed, Victorian,"ugly, deformed, noisy, blurry, minimalistic, sleek"
Style: Futuristic,"futuristic interpretation of {prompt} . sleek, high-tech, metallic, smooth surfaces, neon, sharp edges, crystal clear, professional, ultra detailed,"ugly, deformed, noisy, blurry, rustic, vintage, antique"
Style: Abstract Expressionism,"Abstract Expressionist style of {prompt} . bold colors, vigorous brushwork, non-representational, spontaneous, expressive, emotional,"boring, monotone, plain, still, unemotional, realistic, photographic"
Style: Surrealism,"surrealistic {prompt} . dreamlike, subconscious, bizarre, highly detailed, intricate, imaginative, illogical juxtaposition,"clear, realistic, boring, typical, straightforward, concrete, photographic"
Style: Watercolor,"watercolor painting of {prompt} . fluid, soft edges, light colors, translucent, delicate, dreamy,"hard, geometric, precise, opaque, harsh, dark, sharp, digital, pixelated"
Style: Pointillism,"pointillist technique on {prompt} . tiny dots of color, optical blend, detailed, vibrant, rich,"solid, monochromatic, bland, minimalist, soft, blurry"
Style: Cubism,"cubist interpretation of {prompt} . geometric forms, multi-perspective, abstract, fragmented, complex,"rounded, realistic, photographic, simple, straightforward, traditional"
Style: Gothic,"gothic style {prompt} . dark, mysterious, medieval, ornate, intricate, detailed, haunting,"bright, modern, simple, minimalist, cheerful, photorealistic"
Style: Pop Art,"pop art style {prompt} . bold colors, mass culture, comic style, ironical, vibrant, detailed,"neutral, realistic, serious, dull, monochromatic, photographic"
Style: Impressionism,"impressionist take on {prompt} . loose brushwork, light color, emphasis on light and movement, emotive, painterly,"tight, photographic, dark, stationary, unemotional, sharp, digital"
Style: Street Art,"street art version of {prompt} . urban, graffiti, spray paint, vibrant, bold, rough, rebellious,"elegant, refined, traditional, delicate, soft, photorealistic"
Style: Art Nouveau,"art nouveau style {prompt} . elegant, ornate, flowing lines, detailed, decorative,"simple, modern, sharp, minimalistic, geometric, unadorned"
Style: Charcoal,"charcoal sketch of {prompt} . dark, grainy, high contrast, loose, dramatic,"light, smooth, precise, colorful, clean, photographic"
Style: Collage,"collage of {prompt} . mixed media, eclectic, detailed, layered, creative,"uniform, minimalistic, simple, clean, digital, monochromatic"
Style: Minimalist,"minimalist {prompt} . clean lines, simple shapes, limited color palette, modern, sleek,"detailed, ornate, decorative, colorful, chaotic, complex"
Style: Graffiti,"graffiti style {prompt} . street art, bold, colorful, vibrant, dynamic, urban, rebellious, intricate,"refined, subtle, soft, elegant, traditional, photorealistic"
Style: Trompe L'oeil,"trompe l'oeil of {prompt} . hyperrealistic, 3d illusion, detailed, deceptive, intricate,"abstract, flat, simple, symbolic, unrealistic, distorted"
Style: Fauvism,"fauvist interpretation of {prompt} . wild brushwork, vibrant color, expressive, bold, emotive, painterly,"neutral, precise, calm, realistic, photographic, subdued"
Style: Hyperrealism,"hyperrealistic {prompt} . photorealistic, extreme detail, lifelike, crisp, precise,"blurry, abstract, loose, impressionistic, simple, symbolic"
Style: Dada,"dadaist version of {prompt} . anti-art, absurd, random, satirical, mixed media, collage,"traditional, sensible, serious, realistic, photorealistic"
Style: Calligraphy,"calligraphy style {prompt} . elegant, flowing, precise, detailed, intricate, hand-drawn,"bold, blocky, geometric, rough, digital, simple"
Style: Baroque,"baroque rendition of {prompt} . opulent, grand, ornate, dramatic, detailed, decorative,"minimalist, modern, simple, clean, unadorned, geometric"
Style: Op Art,"op art style {prompt} . optical illusion, geometric, vibrant, dynamic, detailed, bold,"soft, organic, loose, subdued, simple, unpatterned"
Style: Psychedelic,"psychedelic version of {prompt} . vibrant color, distorted visuals, swirling patterns, trippy, detailed, intricate,"neutral, realistic, orderly, simple, clear, photorealistic"
Style: Scratchboard,"scratchboard technique on {prompt} . contrast, engraved, black and white, detailed, dramatic,"colorful, soft, loose, blended, photorealistic"
Style: Botanical Illustration,"botanical illustration of {prompt} . detailed, accurate, precise, delicate, naturalistic,"abstract, loose, imprecise, bold, exaggerated, symbolic"
Style: Lithography,"lithograph of {prompt} . printmaking, smooth, detailed, bold, graphic,"rough, textured, loose, brushy, three dimensional"
Style: Mosaic,"mosaic of {prompt} . tiled, geometric, vibrant, intricate, decorative,"soft, organic, loose, simple, smooth, unpatterned"
Style: Woodcut,"woodcut style {prompt} . carved, bold lines, high contrast, rustic, handmade,"smooth, soft, delicate, digital, photorealistic"
Style: Stencil Art,"stencil art of {prompt} . sharp edges, bold, graphic, street art style, vibrant,"soft, loose, organic, brushy, traditional"
Style: Rotoscoping,"rotoscoped {prompt} . traced, animation style, smooth, realistic, detailed,"abstract, symbolic, rough, loose, blocky"
Style: Glass Painting,"glass painting of {prompt} . translucent, vibrant, decorative, intricate, glossy,"matte, dull, loose, rough, opaque"
Style: Art Deco,"art deco interpretation of {prompt} . geometric, bold, symmetrical, ornate, detailed, decorative,"soft, organic, asymmetrical, minimalist, simple"
Style: Hard Edge Painting,"hard edge painting of {prompt} . geometric, sharp edges, flat color, modern, bold,"soft, organic, loose, textured, detailed, photorealistic"
Style: Drybrush,"drybrush technique on {prompt} . rough texture, loose brushwork, subtle detail, expressive, painterly,"smooth, precise, clean, detailed, photorealistic"
Style: Silhouette,"silhouette of {prompt} . high contrast, dramatic, simple, bold, graphic,"detailed, textured, colorful, light, photorealistic"
Style: Plein Air,"plein air painting of {prompt} . outdoor, natural light, vibrant, loose, expressive,"studio, artificial, precise, tight, clean, photorealistic"
Style: Ink Wash,"ink wash painting of {prompt} . monochromatic, loose, fluid, expressive, delicate,"colorful, tight, dry, bold, detailed, photorealistic"
Style: Body Painting,"body painting of {prompt} . human canvas, vibrant, detailed, transformative, expressive,"traditional canvas, subtle, clean, realistic, monochromatic"
Style: Spray Paint,"spray paint art of {prompt} . street style, vibrant, spontaneous, bold, rough,"refined, soft, delicate, precise, clean, photorealistic"
Style: Grisaille,"grisaille painting of {prompt} . monochromatic, detailed, realistic, refined, tonal,"colorful, abstract, loose, impressionistic, simple"
Style: Stippling,"stippled technique on {prompt} . dotted, texture, detailed, graphic, intricate,"smooth, solid, loose, brushy, blended"
Style: Pastel,"pastel drawing of {prompt} . soft, colorful, delicate, expressive, textured,"sharp, bold, clean, precise, digital"
Style: Encaustic,"encaustic painting of {prompt} . wax, textured, layered, luminous, rich,"flat, smooth, simple, clean, dry, photorealistic"
Style: Macrame,"macrame style {prompt} . knotted, textile, intricate, handmade, decorative,"smooth, flat, hard, precise, digital"
Style: Graffiti Stencil,"graffiti stencil art of {prompt} . urban, bold, vibrant, street style, graphic,"elegant, refined, soft, traditional, photorealistic"
Style: Action Painting,"action painting of {prompt} . spontaneous, energetic, abstract, expressive, bold,"precise, slow, realistic, photographic, unemotional"
Style: Batik,"batik style {prompt} . dyed, vibrant, patterned, textile, decorative,"plain, unpatterned, hard, smooth, clean, digital"
Style: Folk Art,"folk art depiction of {prompt} . traditional, handmade, decorative, vibrant, detailed,"modern, digital, simple, clean, minimalistic"
Style: Glitch Art,"glitch art of {prompt} . distorted, digital, vibrant, abstract, modern,"refined, traditional, realistic, photographic, unaltered"
Style: Chiaroscuro,"chiaroscuro technique on {prompt} . high contrast, dramatic, realistic, refined, tonal,"flat, dull, abstract, impressionistic, simple"
Style: Gouache,"gouache painting of {prompt} . vibrant, opaque, smooth, rich, detailed,"transparent, loose, rough, dull, photorealistic"
>>>>>> GPT Instagram Styles
Style: High-Fashion, "{prompt} in haute couture. Luxury, designer brands, runway-ready, tailored, chic", "casual, sporty, laid-back, street style, loose"
Style: Casual-Chic, "{prompt} in a casual chic outfit. Comfortable, stylish, modern, accessible", "formal, high fashion, flamboyant, extravagant"
Style: Streetwear, "{prompt} rocking the streetwear trend. Urban, hip-hop influence, sneakers, caps, oversized", "preppy, conservative, formal, traditional"
Style: Athletic, "{prompt} in athletic wear. Sporty, gym-ready, functional, sneakers, activewear", "evening wear, formal, business, relaxed"
Style: Vintage, "{prompt} in a vintage ensemble. Retro, nostalgia, classic styles, second-hand", "modern, futuristic, minimalist, new"
Style: Bohemian, "{prompt} in boho fashion. Free-spirited, layered, patterns, ethnic-inspired, fringe", "minimalist, structured, monochromatic, sleek"
Style: Minimalist, "{prompt} sporting minimalist fashion. Simple, clean lines, neutral colors, unfussy", "vintage, boho, flamboyant, colorful"
Style: Preppy, "{prompt} dressed in preppy style. Collegiate, clean-cut, conservative, layered", "gothic, punk, casual, relaxed"
Style: Gothic, "{prompt} in a gothic getup. Dark, leather, lace, Victorian influence", "preppy, pastel, boho, bright"
Style: Punk, "{prompt} with a punk look. Rebellious, grungy, band tees, ripped denim", "preppy, classic, conservative, formal"
Style: Grunge, "{prompt} sporting a grunge look. '90s influence, flannel, band tees, distressed", "preppy, glamorous, feminine, tailored"
Style: Glamorous, "{prompt} looking glamorous. Luxury, sequins, fur, red carpet ready", "casual, relaxed, sporty, minimalist"
Style: Rocker, "{prompt} rocking the rock style. Leather, band tees, edgy, black", "preppy, pastel, boho, cute"
Style: Hipster, "{prompt} in a hipster outfit. Eclectic, indie, non-mainstream, vintage", "mainstream, sporty, glamorous, preppy"
Style: Ethical, "{prompt} wearing ethical fashion. Sustainable, fair trade, organic materials, eco-friendly", "fast fashion, synthetic, mass-produced, cheap"
Style: Business Casual, "{prompt} dressed in business casual. Semi-formal, tailored, smart, professional", "sporty, casual, grunge, punk"
Style: Beachwear, "{prompt} in beachwear. Bikinis, cover-ups, sandals, straw hats, light fabrics", "winter wear, formal, business, structured"
Style: Activewear, "{prompt} in stylish activewear. Sporty, comfortable, functional, athleisure", "evening wear, formal, preppy, boho"
Style: Country, "{prompt} sporting country style. Western, cowboy boots, plaid, denim", "gothic, punk, high fashion, glamorous"
Style: Military, "{prompt} wearing military-inspired fashion. Camouflage, khaki, structured, badges", "boho, glamorous, preppy, beachwear"
Style: Kawaii, "{prompt} in Kawaii style. Cute, pastel, girly, anime-inspired, frilly", "gothic, punk, grunge, minimalist"
Style: Lolita, "{prompt} in a Lolita ensemble. Victorian-inspired, frilly, bows, lace, layered", "minimalist, sporty, casual, business"
Style: Formal, "{prompt} dressed in formal wear. Black tie, tuxedo, evening gown, polished", "casual, sporty, grunge, beachwear"
Style: Tomboy, "{prompt} rocking a tomboy look. Androgynous, loose, sneakers, caps", "glamorous, feminine, boho, preppy"
Style: Normcore, "{prompt} dressed in normcore. Unpretentious, casual, basics, comfortable", "high fashion, glamorous, punk, gothic"
Style: Artistic, "{prompt} in an artistic outfit. Creative, unique, expressive, handmade", "preppy, conservative, business, traditional"
Style: Genderless, "{prompt} in genderless fashion. Androgynous, neutral, modern, unisex", "feminine, masculine, glam, preppy"
Style: Monochromatic, "{prompt} in a monochromatic look. Single color, sleek, modern, minimalist", "colorful, vibrant, patterned, boho"
Style: Mod, "{prompt} dressed in Mod style. '60s influence, A-line, geometric patterns, bold", "boho, grunge, minimalist, normcore"
Style: Harajuku, "{prompt} in Harajuku style. Japanese street fashion, eclectic, colorful, anime", "conservative, preppy, minimalist, business"
Style: Cyberpunk, "{prompt} in a cyberpunk outfit. Futuristic, dystopian, metallic, neon", "vintage, retro, classic, boho"
Style: Rave, "{prompt} in rave wear. Bright colors, neon, sequins, fur", "business casual, preppy, conservative, minimalist"
Style: Hippy, "{prompt} in hippy style. '70s influence, tie-dye, bell-bottoms, fringe", "preppy, conservative, formal, modern"
Style: Skater, "{prompt} rocking skater style. Casual, sneakers, baggy, sporty, laid-back", "formal, glamorous, high fashion, preppy"
Style: Pin-Up, "{prompt} in a pin-up style. Retro, '50s influence, feminine, curves", "gothic, grunge, sporty, tomboy"
Style: Nautical, "{prompt} in a nautical outfit. Sailor-inspired, stripes, navy, white, red", "gothic, punk, grunge, boho"
Style: Futuristic, "{prompt} in futuristic fashion. Metallic, geometric, avant-garde, high-tech", "vintage, classic, traditional, retro"
Style: Eccentric, "{prompt} in an eccentric ensemble. Unique, quirky, stand-out, individualistic", "traditional, classic, conservative, minimalist"
Style: Tailored, "{prompt} in a tailored suit. Formal, professional, sleek, well-fitted", "casual, relaxed, oversized, loose"
Style: Sustainable, "{prompt} in sustainable fashion. Eco-friendly, organic, recycled materials, fair trade", "fast fashion, synthetic, cheap, disposable"
Style: Traditional, "{prompt} in a traditional outfit. Ethnic, regional, cultural, heritage", "modern, futuristic, western, mainstream"
Style: Candid, "{prompt} captured in a candid moment. Unposed, natural, spontaneous, real-life situation", "posed, artificial, studio shot, planned"
Style: Portrait, "portrait shot of {prompt}. Close-up, eyes on camera, clear, sharp", "wide shot, landscape, blurred, candid"
Style: Lifestyle, "lifestyle photo of {prompt}. Everyday activities, real-life situations, relatable", "fantasy, staged, surreal, unrealistic"
Style: Editorial, "editorial shot of {prompt}. Fashion-forward, styled, professional, magazine-ready", "casual, candid, unstyled, amateur"
Style: Glamour, "glamour shot of {prompt}. Beauty focused, make-up, lighting, seductive", "natural, minimal, candid, unglamorous"
Style: Fitness, "fitness photo of {prompt}. Athletic, workout gear, active, strong", "laid back, casual, non-athletic, inactive"
Style: Boudoir, "boudoir shot of {prompt}. Intimate, sensual, classy, tasteful", "public, conservative, modest, non-intimate"
Style: Silhouette, "silhouette photo of {prompt}. Dramatic, backlighting, mysterious, creative", "frontlit, clear, detailed, revealing"
Style: Maternity, "maternity shot of {prompt}. Pregnancy, baby bump, motherhood, glowing", "non-pregnant, childless, pre-pregnancy, post-pregnancy"
Style: Black and White, "black and white photo of {prompt}. Monochrome, timeless, artistic, dramatic", "color, vibrant, modern, digital"
Style: Pin-Up, "pin-up style photo of {prompt}. Retro, feminine, seductive, fun", "modern, conservative, modest, non-vintage"
Style: Headshot, "headshot of {prompt}. Professional, clear, neutral background, focused", "full body, casual, distracting background, unfocused"
Style: Full Body, "full body shot of {prompt}. Whole outfit, clear, sharp, balanced", "close up, cropped, blurry, unbalanced"
Style: High Fashion, "high fashion photo of {prompt}. Designer clothes, dramatic poses, avant-garde", "casual, candid, natural, mainstream fashion"
Style: Business, "business photo of {prompt}. Professional attire, workplace setting, confident", "casual, relaxed, non-work, insecure"
Style: Beach, "beach photo of {prompt}. Swimwear, sand, ocean, relaxed", "urban, winter, formal, stressed"
Style: Lingerie, "lingerie shot of {prompt}. Intimate apparel, sensual, feminine, seductive", "outerwear, modest, masculine, non-sensual"
Style: Athletic, "athletic shot of {prompt}. Sportswear, action, energy, strength", "leisure, inactive, weak, non-sporty"
Style: Close-up, "close-up photo of {prompt}. Detailed, intimate, clear, personal", "wide shot, distant, blurry, impersonal"
Style: Nature, "nature shot with {prompt}. Outdoors, greenery, natural light, fresh", "indoor, city, artificial light, stale"
Style: Studio, "studio shot of {prompt}. Controlled lighting, plain background, clear", "outdoor, natural light, busy background, unclear"
Style: Street, "street shot of {prompt}. Urban, casual, candid, trendy", "rural, formal, posed, traditional"
Style: Dance, "dance photo of {prompt}. Movement, grace, energy, rhythm", "static, clumsy, lethargic, off-beat"
Style: Vintage, "vintage style photo of {prompt}. Retro, nostalgic, old-fashioned, timeless", "modern, futuristic, trendy, transient"
Style: Low Light, "low light photo of {prompt}. Ambient, moody, dramatic, shadowy", "bright, cheerful, flat, clear"
Style: Underwater, "underwater photo of {prompt}. Aquatic, serene, dreamlike, floaty", "land, hectic, realistic, heavy"
Style: Action, "action shot of {prompt}. Movement, energy, dynamic, intense", "still, calm, static, gentle"
Style: Fashion, "fashion shot of {prompt}. Trendy outfit, styled, runway-ready, chic", "plain, unstyled, out of style, ordinary"
Style: Aerial, "aerial shot of {prompt}. Birds-eye view, grand, adventurous, stunning", "ground level, confined, cautious, underwhelming"
Style: Music, "music-related shot of {prompt}. Playing an instrument, singing, energetic, passionate", "quiet, uninterested, uninvolved, lackluster"
Style: Abstract, "abstract photo of {prompt}. Artistic, unique, creative, unconventional", "concrete, literal, conventional, uncreative"
Style: Fine Art, "fine art photo of {prompt}. Conceptual, creative, artistic, aesthetic", "commercial, literal, uncreative, unaesthetic"
Style: Cityscape, "cityscape shot with {prompt}. Urban, skyline, architectural, dynamic", "rural, landscape, natural, static"
Style: Landscape, "landscape shot with {prompt}. Scenic, outdoors, grand, beautiful", "indoor, close-up, confined, unattractive"
Style: Macro, "macro shot of {prompt}. Extremely close-up, detailed, intricate, revealing", "wide shot, undetailed, simple, concealing"
Style: Golden Hour, "golden hour shot of {prompt}. Warm light, sunset/sunrise, magical, serene", "midday, harsh light, mundane, agitated"
Style: Blue Hour, "blue hour shot of {prompt}. Cool light, twilight, peaceful, moody", "midday, harsh light, chaotic, flat"
Style: Night, "night shot of {prompt}. Dark, lit, moody, mysterious", "daytime, bright, cheerful, clear"
Style: Reflection, "reflection shot of {prompt}. Mirror image, symmetry, creative, thoughtful", "direct, asymmetrical, uncreative, thoughtless"
Style: Backlit, "backlit photo of {prompt}. Silhouette, dramatic, artistic, shadowy", "frontlit, flat, unartistic, clear"
Style: Overhead, "overhead shot of {prompt}. Top-down view, unique perspective, revealing", "low angle, ordinary perspective, concealing"
Can't render this file because it contains an unexpected character in line 171 and column 80.
+79 -5
View File
@@ -1,9 +1,28 @@
// Some manual types I use to facilitate developing on top of
// Comfy's Litegraph implementation.
import type { ContextMenuItem, LGraphNode } from '../web/types/litegraph'
import type {
ContextMenuItem,
LGraphNode,
IWidget,
LGraph,
} from '../../../web/types/litegraph'
export type { ContextMenuItem } from '../web/types/litegraph'
export type {
ComfyExtension,
ComfyObjectInfo,
ComfyObjectInfoConfig,
} from '../../../web/types/comfy'
export type {
ContextMenuItem,
IWidget,
LLink,
INodeInputSlot,
INodeOutputSlot,
} from '../../../web/types/litegraph'
export type VectorWidget = IWidget<number[], { default: number[] }>
export interface NodeData {
category: str
description: str
@@ -16,18 +35,72 @@ export interface NodeData {
output_node: boolean
}
export interface ExtendedLGraphNode {
export interface ComfyDialog {
element: Element
close: () => void
show: (html: str) => void
}
export interface ComfySettingsDialog {
app: ComfyApp
element: Element
settingsValues: Record<string, unknown>
settingsLookup: Record<string, unknown>
load: () => Promise<void>
setSettingValueAsync: (id: string, value: unknown) => Promise<void>
}
export interface ComfyUI {
app: ComfyApp
dialog: ComfyDialog
settings: ComfySettingsDialog
autoQueueMode: 'instant' | 'change'
batchCount: number
lastQueueSize: number
graphHasChanged: boolean
queue: ComfyList
history: ComfyList
}
/**Very incomplete Comfy App definition*/
interface ComfyApp {
graph: LGraph
queueItems: { number: number; batchCount: number }[]
processingQueue: boolean
ui: ComfyUI
extensions: ComfyExtension[]
nodeOutputs: Record<string, unknown>
nodePreviewImages: Record<string, Image>
shiftDown: boolean
isImageNode: (node: LGraphNodeExtended) => boolean
queuePrompt: (number: number, batchCount: number) => Promise<void>
/** Loads workflow data from the specified file*/
handleFile: (file: File) => Promise<void>
}
export type { ComfyApp as App }
export interface LGraphNodeExtension {
addDOMWidget: (
name: string,
type: string,
element: Element,
options: Record<string, unknown>,
) => IWidget
onNodeCreated: () => void
getExtraMenuOptions: () => ContextMenuItem[]
prototype: LGraphNodeExtended
}
export type LGraphNodeExtended = LGraphNode & LGraphNodeExtension
export interface NodeType /*extends LGraphNode*/ {
category: str
comfyClass: str
length: 0
name: str
nodeData: NodeData
prototype: LGraphNode & ExtendedLGraphNode
prototype: LGraphNodeExtended
title: str
type: str
}
@@ -37,13 +110,14 @@ export interface NodeInput {
}
// NOTE: for prototype overriding
export type OnDrawWidgetParams = Parameters<IWidget['draw']>
export type OnDrawForegroundParams = Parameters<LGraphNode['onDrawForeground']>
export type OnMouseDownParams = Parameters<LGraphNode['onMouseDown']>
export type OnConnectionsChangeParams = Parameters<
LGraphNode['onConnectionsChange']
>
export type OnNodeCreatedParams = Parameters<
ExtendedLGraphNode['onNodeCreated']
LGraphNodeExtension['onNodeCreated']
>
export interface DocumentationOptions {
+10 -1
View File
@@ -5,5 +5,14 @@
* @typedef {import("./shared.d.ts").OnDrawForegroundParams} OnDrawForegroundParams
* @typedef {import("./shared.d.ts").OnMouseDownParams} OnMouseDownParams
* @typedef {import("./shared.d.ts").OnConnectionsChangeParams} OnConnectionsChangeParams
* @typedef {import("./shared.d.ts").getExtraMenuOptionsParams} getExtraMenuOptionsParams
* @typedef {import("./shared.d.ts").ContextMenuItem} ContextMenuItem
* @typedef {import("./shared.d.ts").IWidget} IWidget
* @typedef {import("./shared.d.ts").VectorWidget} VectorWidget
* @typedef {import("./shared.d.ts").LGraphNodeExtended} LGraphNode
* @typedef {import("./shared.d.ts").LLink} LLink
* @typedef {import("./shared.d.ts").App} App
* @typedef {import("./shared.d.ts").OnDrawWidgetParams} OnDrawWidgetParams
* @typedef {import("./shared.d.ts").INodeInputSlot} INodeInputSlot
* @typedef {import("./shared.d.ts").INodeOutputSlot} INodeOutputSlot
*/
+850 -232
View File
File diff suppressed because it is too large Load Diff
+669 -329
View File
File diff suppressed because it is too large Load Diff
+356 -122
View File
@@ -1,62 +1,225 @@
import { app } from '../../scripts/app.js'
import * as shared from './comfy_shared.js'
import { infoLogger } from './comfy_shared.js'
import { MtbWidgets } from './mtb_widgets.js'
import { ComfyWidgets } from '../../scripts/widgets.js'
import * as mtb_widgets from './mtb_widgets.js'
export class Constant extends LiteGraph.LGraphNode {
constructor() {
super()
this.uuid = shared.makeUUID()
this.collapsable = true
/**
* @typedef {'number'|'string'|'vector2'|'vector3'|'vector4'|'color'} ConstantType
* @typedef {import ("../../../web/types/litegraph.d.ts").LGraphNode} Node
* @typedef {{x:number,y:number,z?:number,w?:number}} VectorValue
* @typedef {}
*
*/
// this avoid serializing the node when converting to prompt
this.isVirtualNode = true
this.shape = LiteGraph.BOX_SHAPE
this.serialize_widgets = true
// Properties
this.addProperty('type', 'number')
this.addProperty('value', 0)
// Inputs and outputs
this.addOutput('Output', '*')
// Widget for selecting the type
this.addWidget(
'combo',
'Type',
this.properties.type,
(value) => {
this.properties.type = value
this.updateWidgets()
this.updateOutputType()
},
{
values: ['number', 'string', 'vector2', 'vector3', 'vector4', 'color'],
},
)
// Initialize the node
this.updateWidgets()
this.updateOutputType()
/**
* @param {number} size - The number of axis of the vector (2,3 or 4)
* @param {number} val - The default scalar value to fill the vector with
* @returns {VectorValue} vector
* */
const initVector = (size, val = 0.0) => {
const res = {}
for (let i = 0; i < size; i++) {
const axis = mtb_widgets.VECTOR_AXIS[i]
res[axis] = val
}
return res
}
/**
*
* @extends {Node}
* @classdesc Wrapper for the python node
*/
export class ConstantJs {
constructor(python_node) {
// this.uuid = shared.makeUUID()
const wrapper = this
python_node.shape = LiteGraph.BOX_SHAPE
python_node.serialize_widgets = true
const onNodeCreated = python_node.prototype.onNodeCreated
python_node.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this) : undefined
this.addProperty('type', 'number')
this.addProperty('value', 0)
this.removeInput(0)
this.removeOutput(0)
this.addOutput('Output', '*')
// bind our wrapper
this.configure = wrapper.configure.bind(this)
// this.applyToGraph = wrapper.applyToGraph.bind(this)
this.updateWidgets = wrapper.updateWidgets.bind(this)
this.convertValue = wrapper.convertValue.bind(this)
// this.updateOutput = wrapper.updateOutput.bind(this)
this.updateOutputType = wrapper.updateOutputType.bind(this)
// this.updateTargetWidgets = wrapper.updateTargetWidgets.bind(this)
this.addWidget(
'combo',
'Type',
this.properties.type,
(value) => {
this.properties.type = value
this.updateWidgets()
this.updateOutputType()
},
{
values: [
// 'number',
'float',
'int',
'string',
'vector2',
'vector3',
'vector4',
'color',
],
},
)
this.updateWidgets()
this.updateOutputType()
for (let n = 0; n < this.inputs.length; n++) {
this.removeInput(n)
}
this.inputs = []
return r
}
return
}
// NOTE: this is called onPrompt
applyToGraph() {
this.updateTargetWidgets()
}
// applyToGraph() {
// infoLogger('Updating values for backend')
// this.updateTargetWidgets()
// }
// NOTE: deserialization happens here
configure(info) {
super.configure(info)
// super.configure(info)
infoLogger('Configure Constant', { info, node: this })
this.properties.type = info.properties.type
this.properties.value = info.properties.value
shared.infoLogger('Configure Constant', { info, node: this })
this.pos = info.pos
this.order = info.order
this.updateWidgets()
this.updateOutputType()
}
/**
* Convert the old value type to the new one, falling back to some default
* @param {ConstantType} propType - The target type
*/
convertValue(propType) {
switch (propType) {
case 'color': {
if (typeof this.properties.value !== 'string') {
this.properties.value = '#ffffff'
} else if (this.properties.value[0] !== '#') {
this.properties.value = '#ff0000'
}
break
}
case 'int': {
if (typeof this.properties.value === 'object') {
this.properties.value = Number.parseInt(this.properties.value.x)
} else {
this.properties.value = Number.parseInt(this.properties.value) || 0
}
break
}
case 'float': {
if (typeof this.properties.value === 'object') {
this.properties.value = Number.parseFloat(this.properties.value.x)
} else {
this.properties.value =
Number.parseFloat(this.properties.value) || 0.0
}
break
}
case 'string': {
if (typeof this.properties.value !== 'string') {
this.properties.value = JSON.stringify(this.properties.value)
}
break
}
case 'vector2':
case 'vector3':
case 'vector4': {
const numInputs = Number.parseInt(propType.charAt(6))
if (!this.properties.value) {
this.properties.value = initVector(numInputs) // Array.from({ length: numInputs }, () => 0.0)
} else if (typeof this.properties.value === 'string') {
try {
const parsed = JSON.parse(this.properties.value)
const newVec = {}
for (
let i = 0;
i < Object.keys(mtb_widgets.VECTOR_AXIS).length;
i++
) {
const axis = mtb_widgets.VECTOR_AXIS[i]
if (Object.keys(parsed).includes(axis)) {
newVec[axis] = parsed[axis]
}
}
this.properties.value = newVec
} catch (e) {
shared.errorLogger(e)
infoLogger(
`Couldn't parse string to vec (${this.properties.value})`,
)
this.properties.value = initVector(numInputs)
}
} else if (typeof this.properties.value === 'number') {
const newVec = initVector(numInputs)
newVec.x = Number.parseFloat(this.properties.value)
this.properties.value = newVec
}
if (
typeof this.properties.value === 'object' &&
Object.keys(this.properties.value).length !== numInputs
) {
const current = Object.keys(this.properties.value)
if (current.length < numInputs) {
infoLogger('current value smaller than target, adjusting')
for (let index = current.length; index < numInputs; index++) {
this.properties.value[mtb_widgets.VECTOR_AXIS[index]] = 0.0
}
} else {
infoLogger('current value greater than target, adjusting')
const newVal = {}
for (let index = 0; index < numInputs; index++) {
newVal[mtb_widgets.VECTOR_AXIS[index]] =
this.properties.value[mtb_widgets.VECTOR_AXIS[index]]
}
this.properties.value = newVal
}
}
break
}
default:
break
}
}
/**
* Remove all widgets but the comboBox for selecting the type
* then recreate the appropriate widget from scratch
*/
updateWidgets() {
// Remove existing widgets
// NOTE: Remove existing widgets
for (let i = 1; i < this.widgets.length; i++) {
const element = this.widgets[i]
if (element.onRemove) {
@@ -66,28 +229,113 @@ export class Constant extends LiteGraph.LGraphNode {
}
this.widgets.splice(1)
this.widgets[0].value = this.properties.type
this.convertValue(this.properties.type)
switch (this.properties.type) {
case 'color': {
if (typeof this.properties.value !== 'string') {
this.properties.value = '#ffffff'
}
const col_widget = this.addCustomWidget(
MtbWidgets.COLOR('Value', this.properties.value || '#ff0000'),
MtbWidgets.COLOR('Value', this.properties.value),
)
col_widget.callback = (col) => {
this.properties.value = col
this.updateOutput()
// this.updateOutput()
}
break
}
case 'number':
case 'int': {
const f_widget = this.addCustomWidget(
ComfyWidgets.INT(
this,
'Value',
[
'',
{
default: this.properties.value,
callback: (val) => console.log('VALUE', val),
},
],
app,
),
)
f_widget.widget.callback = (val) => {
this.properties.value = val
}
break
}
case 'float': {
this.addWidget('number', 'Value', this.properties.value, (val) => {
this.properties.value = val
})
break
}
case 'string': {
mtb_widgets.addMultilineWidget(
this,
'Value',
{
defaultVal: this.properties.value,
},
(v) => {
this.properties.value = v
// this.updateOutput()
},
)
break
}
case 'vector2':
case 'vector3':
case 'vector4': {
const numInputs = Number.parseInt(this.properties.type.charAt(6))
const node = this
const v_widget = mtb_widgets.addVectorWidget(
this,
'Value',
this.properties.value, // value
numInputs, // vector_size
function (v) {
node.properties.value = v
// this.updateOutput()
},
)
break
}
// NOTE: this is not reached anymore, kept for reference
case 'number': {
if (typeof this.properties.value !== 'number') {
this.properties.value = 0.0
}
this.addWidget('number', 'Value', this.properties.value, (value) => {
this.properties.value = value
this.updateOutput()
})
const n_widget = this.addWidget(
'number',
'Value',
this.properties.force_int
? Number.parseInt(this.properties.value)
: this.properties.value,
(value) => {
this.properties.value = this.properties.force_int
? Number.parseInt(value)
: value
// this.updateOutput()
},
)
//override the callback
const origCallback = n_widget.callback
const node = this
n_widget.callback = function (val) {
const r = origCallback ? origCallback.apply(this, [val]) : undefined
if (node.properties.force_int) {
// TODO: rework this, a it makes it harder to manipulate
this.value = Number.parseInt(this.value)
node.properties.value = Number.parseInt(this.value)
}
infoLogger('NEW NUMBER', this.value)
return r
}
this.addWidget(
'toggle',
'Convert to Integer',
@@ -98,51 +346,6 @@ export class Constant extends LiteGraph.LGraphNode {
},
)
break
case 'string': {
if (typeof this.properties.value !== 'string') {
this.properties.value = `${this.properties.value}`
}
shared.addMultilineWidget(
this,
'Value',
{
defaultVal: this.properties.value,
},
(v) => {
this.properties.value = v
this.updateOutput()
},
)
break
}
case 'vector2':
case 'vector3':
case 'vector4': {
const numInputs = Number.parseInt(this.properties.type.charAt(6))
if (['string', 'number'].includes(typeof this.properties.value)) {
this.properties.value = Array.from({ length: numInputs }, () => 0.0)
} else if (this.properties.value.length !== numInputs) {
if (this.properties.value.length > numInputs) {
this.properties.value = this.properties.value.slice(0, numInputs)
} else {
this.properties.value = this.properties.value.concat(
new Array(numInputs - this.properties.value.length).fill(0.0),
)
}
}
for (let i = 0; i < numInputs; i++) {
this.addWidget(
'number',
`Value ${i + 1}`,
this.properties.value[i] || 0,
(value) => {
this.properties.value[i] = value
this.updateOutput()
},
)
}
break
}
default:
break
@@ -154,20 +357,28 @@ export class Constant extends LiteGraph.LGraphNode {
this.updateTargetWidgets([link.id])
}
}
updateOutputType() {
const cur_type = this.outputs[0].type
infoLogger('Updating output type')
const rm_if_mismatch = (type) => {
if (cur_type !== type) {
if (this.outputs[0].type !== type) {
for (let i = 0; i < this.outputs.length; i++) {
this.removeOutput(i)
}
this.addOutput('output', type)
// this.setOutputDataType(0, type)
}
}
switch (this.properties.type) {
case 'color':
rm_if_mismatch('COLOR')
break
case 'float':
rm_if_mismatch('FLOAT')
break
case 'int':
rm_if_mismatch('INT')
break
case 'number':
if (this.properties.force_int) {
rm_if_mismatch('INT')
@@ -178,6 +389,11 @@ export class Constant extends LiteGraph.LGraphNode {
case 'string':
rm_if_mismatch('STRING')
break
// case 'vector2':
// case 'vector3':
// case 'vector4':
// rm_if_mismatch('FLOAT')
// break
case 'vector2':
rm_if_mismatch('VECTOR2')
break
@@ -190,7 +406,7 @@ export class Constant extends LiteGraph.LGraphNode {
default:
break
}
this.updateOutput()
// this.updateOutput()
}
/**
@@ -198,6 +414,7 @@ export class Constant extends LiteGraph.LGraphNode {
* since Constant is a virtual node.
*/
updateTargetWidgets(u_links) {
infoLogger('Updating target widgets')
if (!app.graph.links) return
const links = u_links || this.outputs[0].links
if (!links) return
@@ -210,12 +427,16 @@ export class Constant extends LiteGraph.LGraphNode {
const tgt_widget = tgt_node.widgets.filter(
(w) => w.name === tgt_input.name,
)
if (!tgt_widget) return
// infoLogger('Constant Target Node', tgt_node)
// infoLogger('Constant Target Input', tgt_input)
if (!tgt_widget || tgt_widget.length === 0) return
tgt_widget[0].value = this.properties.value
}
}
updateOutput() {
infoLogger('Updating output value')
const value = this.properties.value
switch (this.properties.type) {
@@ -223,40 +444,53 @@ export class Constant extends LiteGraph.LGraphNode {
this.setOutputData(0, value)
break
case 'number':
this.setOutputData(0, Number.parseFloat(value))
if (this.properties.force_int) {
this.setOutputData(0, Number.parseInt(value))
} else {
this.setOutputData(0, Number.parseFloat(value))
}
break
case 'string':
this.setOutputData(0, value.toString())
break
case 'vector2':
if (value.length >= 2) {
this.setOutputData(0, value.slice(0, 2))
}
break
case 'vector3':
if (value.length >= 3) {
this.setOutputData(0, value.slice(0, 3))
}
break
case 'vector4':
if (value.length >= 4) {
this.setOutputData(0, value.slice(0, 4))
}
this.setOutputData(0, value)
break
// case 'vector2':
// this.setOutputData(0, value.slice(0, 2))
// break
// case 'vector3':
// this.setOutputData(0, value.slice(0, 3))
// break
// case 'vector4':
// this.setOutputData(0, value.slice(0, 4))
// break
default:
break
}
infoLogger('New Value', this.value)
this.updateTargetWidgets()
}
}
app.registerExtension({
name: 'mtb.constant',
// app.registerExtension({
// name: 'mtb.constant',
// registerCustomNodes() {
// LiteGraph.registerNodeType('Constant (mtb)', Constant)
//
// Constant.category = 'mtb/utils'
// Constant.title = 'Constant (mtb)'
// },
// })
async beforeRegisterNodeDef(nodeType, nodeData, _app) {
if (nodeData.name === 'Constant (mtb)') {
new ConstantJs(nodeType)
}
},
// NOTE: old js only registration
//
// registerCustomNodes() {
// LiteGraph.registerNodeType('Constant (mtb)', Constant)
//
// Constant.category = 'mtb/utils'
// Constant.title = 'Constant (mtb)'
// },
})
+200 -166
View File
@@ -1,187 +1,221 @@
// Reference the shared typedefs file
/// <reference path="../types/typedefs.js" />
import { app } from '../../scripts/app.js'
import { infoLogger } from './comfy_shared.js'
function B0(t) { return (1 - t) ** 3 / 6; }
function B1(t) { return (3 * t ** 3 - 6 * t ** 2 + 4) / 6; }
function B2(t) { return (-3 * t ** 3 + 3 * t ** 2 + 3 * t + 1) / 6; }
function B3(t) { return t ** 3 / 6; }
function B0(t) {
return (1 - t) ** 3 / 6
}
function B1(t) {
return (3 * t ** 3 - 6 * t ** 2 + 4) / 6
}
function B2(t) {
return (-3 * t ** 3 + 3 * t ** 2 + 3 * t + 1) / 6
}
function B3(t) {
return t ** 3 / 6
}
class CurveWidget {
constructor(inputName, defaultValue) {
this.name = inputName || "Curve";
this._value = defaultValue || [{ x: 0, y: 0 }, { x: 1, y: 1 }];
this.type = "FLOAT_CURVE";
this.selectedPointIndex = null;
this.resize
}
constructor(...args) {
const [inputName, opts] = args
drawBSpline(ctx, width, height, posY) {
const n = this._value.length - 1;
const numSegments = n - 2;
const numPoints = this._value.length;
if (numPoints < 4) {
this.drawLinear(ctx, width, height, posY);
} else {
for (let j = 0; j <= numSegments; j++) {
for (let t = 0; t <= 1; t += 0.01) {
let pt = this.getBSplinePoint(j, t);
let x = pt.x * width;
let y = posY + height - pt.y * height;
this.name = inputName || 'Curve'
if (t === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
}
ctx.stroke();
this.type = 'FLOAT_CURVE'
this.selectedPointIndex = null
this.options = opts
this.value = this.value || { 0: { x: 0, y: 0 }, 1: { x: 1, y: 1 } }
}
drawBSpline(ctx, width, height, posY) {
const n = this.value.length - 1
const numSegments = n - 2
const numPoints = this.value.length
if (numPoints < 4) {
this.drawLinear(ctx, width, height, posY)
} else {
for (let j = 0; j <= numSegments; j++) {
for (let t = 0; t <= 1; t += 0.01) {
let pt = this.getBSplinePoint(j, t)
let x = pt.x * width
let y = posY + height - pt.y * height
if (t === 0) ctx.moveTo(x, y)
else ctx.lineTo(x, y)
}
}
ctx.stroke()
}
}
drawLinear(ctx, width, height, posY) {
for (let i = 0; i < Object.keys(this.value).length - 1; i++) {
let p1 = this.value[i]
let p2 = this.value[i + 1]
ctx.moveTo(p1.x * width, posY + height - p1.y * height)
ctx.lineTo(p2.x * width, posY + height - p2.y * height)
}
ctx.stroke()
}
getBSplinePoint(i, t) {
// Control points for this segment
const p0 = this.value[i]
const p1 = this.value[i + 1]
const p2 = this.value[i + 2]
const p3 = this.value[i + 3]
const x = B0(t) * p0.x + B1(t) * p1.x + B2(t) * p2.x + B3(t) * p3.x
const y = B0(t) * p0.y + B1(t) * p1.y + B2(t) * p2.y + B3(t) * p3.y
return { x, y }
}
/**
* @param {OnDrawWidgetParams} args
*/
draw(...args) {
const hide = this.type !== 'FLOAT_CURVE'
if (hide) {
return
}
drawLinear(ctx, width, height, posY) {
for (let i = 0; i < this._value.length - 1; i++) {
let p1 = this._value[i];
let p2 = this._value[i + 1];
ctx.moveTo(p1.x * width, posY + height - p1.y * height);
ctx.lineTo(p2.x * width, posY + height - p2.y * height);
}
ctx.stroke();
const [ctx, node, width, posY, height] = args
const [cw, ch] = this.computeSize(width)
ctx.beginPath()
ctx.fillStyle = '#000'
ctx.strokeStyle = '#fff'
ctx.lineWidth = 2
// normalized coordinates -> canvas coordinates
for (let i = 0; i < Object.keys(this.value || {}).length - 1; i++) {
let p1 = this.value[i]
let p2 = this.value[i + 1]
ctx.moveTo(p1.x * cw, posY + ch - p1.y * ch)
ctx.lineTo(p2.x * cw, posY + ch - p2.y * ch)
}
ctx.stroke()
// points
Object.values(this.value || {}).forEach((point) => {
ctx.beginPath()
ctx.arc(point.x * cw, posY + ch - point.y * ch, 5, 0, 2 * Math.PI)
ctx.fill()
})
}
mouse(event, pos, node) {
let x = pos[0] - node.pos[0]
let y = pos[1] - node.pos[1]
const width = node.size[0]
const height = 300 // TODO: compute
const posY = node.pos[1]
const localPos = { x: pos[0], y: pos[1] - LiteGraph.NODE_WIDGET_HEIGHT }
if (event.type === LiteGraph.pointerevents_method + 'down') {
console.debug('Checking if a point was clicked')
const clickedPointIndex = this.detectPoint(localPos, width, height)
if (clickedPointIndex !== null) {
this.selectedPointIndex = clickedPointIndex
} else {
this.addPoint(localPos, width, height)
}
return true
} else if (
event.type === LiteGraph.pointerevents_method + 'move' &&
this.selectedPointIndex !== null
) {
this.movePoint(this.selectedPointIndex, localPos, width, height)
return true
} else if (
event.type === LiteGraph.pointerevents_method + 'up' &&
this.selectedPointIndex !== null
) {
this.selectedPointIndex = null
return true
}
return false
}
callback(...args) {
//value, that, node, pos, event) {
}
detectPoint(localPos, width, height) {
const threshold = 20 // TODO: extract
const keys = Object.keys(this.value)
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const p = this.value[key]
const px = p.x * width
const py = height - p.y * height
if (
Math.abs(localPos.x - px) < threshold &&
Math.abs(localPos.y - py) < threshold
) {
return key
}
}
return null
}
addPoint(localPos, width, height) {
// add a new point based on click position
const normalizedPoint = {
x: localPos.x / width,
y: 1 - localPos.y / height,
}
getBSplinePoint(i, t) {
// Control points for this segment
const p0 = this._value[i];
const p1 = this._value[i + 1];
const p2 = this._value[i + 2];
const p3 = this._value[i + 3];
const x = B0(t) * p0.x + B1(t) * p1.x + B2(t) * p2.x + B3(t) * p3.x;
const y = B0(t) * p0.y + B1(t) * p1.y + B2(t) * p2.y + B3(t) * p3.y;
return { x, y };
const keys = Object.keys(this.value)
let insertIndex = keys.length
for (let i = 0; i < keys.length; i++) {
if (normalizedPoint.x < this.value[keys[i]].x) {
insertIndex = i
break
}
}
// shift
for (let i = keys.length; i > insertIndex; i--) {
this.value[i] = this.value[i - 1]
}
draw(ctx, node, width, posY, height) {
const [cw, ch] = this.computeSize(width)
this.value[insertIndex] = normalizedPoint
}
ctx.beginPath();
ctx.fillStyle = "#000";
//ctx.fillRect(0, posY, cw, ch);
ctx.strokeStyle = "#fff";
ctx.lineWidth = 2;
movePoint(index, localPos, width, height) {
const point = this.value[index]
point.x = Math.max(0, Math.min(1, localPos.x / width))
point.y = Math.max(0, Math.min(1, 1 - localPos.y / height))
// normalized coordinates -> canvas coordinates
for (let i = 0; i < this._value.length - 1; i++) {
let p1 = this._value[i];
let p2 = this._value[i + 1];
ctx.moveTo(p1.x * cw, posY + ch - p1.y * ch);
ctx.lineTo(p2.x * cw, posY + ch - p2.y * ch);
}
ctx.stroke();
// this.drawBSpline(ctx, width, height, posY);
this.value[index] = point
}
computeSize(width) {
return [width, 300]
}
// points
this._value.forEach(point => {
ctx.beginPath();
ctx.arc(point.x * cw, posY + ch - point.y * ch, 5, 0, 2 * Math.PI);
ctx.fill();
});
}
mouse(event, pos, node) {
// console.debug(event.type, pos, node)
let x = pos[0] - node.pos[0]
let y = pos[1] - node.pos[1]
let width = node.size[0]
const height = 300; // TODO: compute
const posY = node.pos[1];
const localPos = { x: pos[0], y: pos[1] - LiteGraph.NODE_WIDGET_HEIGHT };
if (event.type === LiteGraph.pointerevents_method + "down") {
console.debug("Checking if a point was clicked");
const clickedPointIndex = this.detectPoint(localPos, width, height);
if (clickedPointIndex !== null) {
this.selectedPointIndex = clickedPointIndex;
} else {
this.addPoint(localPos, width, height);
}
return true;
} else if (event.type === LiteGraph.pointerevents_method + "move" && this.selectedPointIndex !== null) {
this.movePoint(this.selectedPointIndex, localPos, width, height);
return true;
} else if (event.type === LiteGraph.pointerevents_method + "up" && this.selectedPointIndex !== null) {
this.selectedPointIndex = null;
return true;
}
return false;
}
detectPoint(localPos, width, height) {
const threshold = 20; // TODO: extract
for (let i = 0; i < this._value.length; i++) {
const p = this._value[i];
const px = p.x * width;
const py = height - p.y * height;
if (Math.abs(localPos.x - px) < threshold && Math.abs(localPos.y - py) < threshold) {
return i;
}
}
return null;
}
addPoint(localPos, width, height) {
// add a new point based on click position
const normalizedPoint = { x: localPos.x / width, y: 1 - localPos.y / height };
this._value.push(normalizedPoint);
this._value.sort((a, b) => a.x - b.x);
this.value = JSON.stringify(this._value);
}
movePoint(index, localPos, width, height) {
const point = this._value[index];
point.x = Math.max(0, Math.min(1, localPos.x / width));
point.y = Math.max(0, Math.min(1, 1 - localPos.y / height));
this._value[index] = point;
this.value = JSON.stringify(this._value);
}
computeSize(width) {
return [width, 300];
}
configure(data) {
console.log(data)
}
value() {
console.debug('Returning value', this._value)
return this._value
}
setValue(value) {
console.debug('Setting value', value)
this._value = value
}
configure(data) {
}
}
app.registerExtension({
name: 'mtb.curves',
getCustomWidgets: function () {
name: 'mtb.curves',
getCustomWidgets: () => {
return {
/**
* @param {LGraphNode} node
* @param {str} inputName
* @param {[str,*]} inputData
* @param {*} app
*
*/
FLOAT_CURVE: (node, inputName, inputData, app) => {
// const c = node.widgets.find((w) => w.type === "FLOAT_CURVE")
const wid = node.addCustomWidget(new CurveWidget(inputName, inputData))
return {
FLOAT_CURVE: (node, inputName, inputData, app) => {
console.debug('Registering float curve widget');
return {
widget: node.addCustomWidget(
new CurveWidget(inputName, inputData[1]?.default)
),
minWidth: 150,
minHeight: 30,
}
},
widget: wid,
minWidth: 150,
minHeight: 30,
}
},
},
}
},
})
+45 -24
View File
@@ -7,10 +7,12 @@
*
*/
// Reference the shared typedefs file
/// <reference path="../types/typedefs.js" />
import { app } from '../../scripts/app.js'
import * as shared from './comfy_shared.js'
import { log } from './comfy_shared.js'
import { MtbWidgets } from './mtb_widgets.js'
// TODO: respect inputs order...
@@ -25,10 +27,17 @@ function escapeHtml(unsafe) {
}
app.registerExtension({
name: 'mtb.Debug',
/**
* @param {NodeType} nodeType
* @param {NodeData} nodeData
* @param {*} app
*/
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === 'Debug (mtb)') {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
this.options = {}
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
@@ -37,24 +46,29 @@ app.registerExtension({
}
const onConnectionsChange = nodeType.prototype.onConnectionsChange
nodeType.prototype.onConnectionsChange = function (
type,
index,
connected,
link_info,
) {
/**
* @param {OnConnectionsChangeParams} args
*/
nodeType.prototype.onConnectionsChange = function (...args) {
const [_type, index, connected, link_info, ioSlot] = args
const r = onConnectionsChange
? onConnectionsChange.apply(this, arguments)
? onConnectionsChange.apply(this, args)
: undefined
// TODO: remove all widgets on disconnect once computed
shared.dynamic_connection(this, index, connected, 'anything_', '*')
shared.dynamic_connection(this, index, connected, 'anything_', '*', {
link: link_info,
ioSlot: ioSlot,
})
//- infer type
if (link_info) {
const fromNode = this.graph._nodes.find(
(otherNode) => otherNode.id === link_info.origin_id,
)
const type = fromNode.outputs[link_info.origin_slot].type
// const fromNode = this.graph._nodes.find(
// (otherNode) => otherNode.id === link_info.origin_id,
// )
// const fromNode = app.graph.getNodeById(link_info.origin_id)
const { from } = shared.nodesFromLink(this, link_info)
if (!from || this.inputs.length === 0) return
const type = from.outputs[link_info.origin_slot].type
this.inputs[index].type = type
// this.inputs[index].label = type.toLowerCase()
}
@@ -67,14 +81,12 @@ app.registerExtension({
}
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (message) {
nodeType.prototype.onExecuted = async function (data) {
onExecuted?.apply(this, arguments)
const prefix = 'anything_'
if (this.widgets) {
// const pos = this.widgets.findIndex((w) => w.name === "anything_1");
// if (pos !== -1) {
for (let i = 0; i < this.widgets.length; i++) {
if (this.widgets[i].name !== 'output_to_console') {
this.widgets[i].onRemoved?.()
@@ -83,8 +95,8 @@ app.registerExtension({
this.widgets.length = 1
}
let widgetI = 1
if (message.text) {
for (const txt of message.text) {
if (data.text) {
for (const txt of data.text) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_STRING(`${prefix}_${widgetI}`, escapeHtml(txt)),
)
@@ -92,23 +104,32 @@ app.registerExtension({
widgetI++
}
}
if (message.b64_images) {
for (const img of message.b64_images) {
if (data.b64_images) {
for (const img of data.b64_images) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_IMG(`${prefix}_${widgetI}`, img),
)
w.parent = this
widgetI++
}
// this.onResize?.(this.size);
// this.resize?.(this.size)
}
this.setSize(this.computeSize())
if (data.geometry) {
for (const geom of data.geometry) {
console.log('Adding geom', geom, typeof geom)
const w = this.addCustomWidget(
await MtbWidgets.DEBUG_GEOM(this, `${prefix}_${widgetI}`, geom),
)
w.parent = this
widgetI++
}
}
// this.setSize(this.computeSize())
this.onRemoved = function () {
// When removing this node we need to remove the input from the DOM
for (let y in this.widgets) {
for (const y in this.widgets) {
if (this.widgets[y].canvas) {
this.widgets[y].canvas.remove()
}
+3 -3
View File
File diff suppressed because one or more lines are too long
-3
View File
File diff suppressed because one or more lines are too long
+29
View File
@@ -0,0 +1,29 @@
/**
* File: geometry_nodes.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
import { app } from '../../scripts/app.js'
app.registerExtension({
name: 'mtb.geometry_nodes',
init: () => {},
async beforeRegisterNodeDef(nodeType, nodeData, ...args) {
switch (nodeData.name) {
case 'Geometry Load (mtb)': {
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, nodeType, nodeData, ...args)
console.log('Executed Load Geometry', ...args)
console.log('Message:', message)
}
break
}
}
},
})
+296 -295
View File
@@ -13,40 +13,40 @@ import { api } from '../../scripts/api.js'
import { app } from '../../scripts/app.js'
import { LocalStorageManager } from './comfy_shared.js'
const styles = {
lighbox: {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
background: 'rgba(0,0,0,0.5)',
display: 'none',
justifyContent: 'center',
alignItems: 'center',
zIndex: 999,
},
lightboxBtn: (extra) => ({
position: 'absolute',
top: '50%',
background: 'none',
border: 'none',
color: '#fff',
zIndex: 1000,
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'auto',
...extra,
}),
img_list: {
minHeight: '30px',
maxHeight: '300px',
width: '100vw',
position: 'absolute',
bottom: 0,
zIndex: 10,
background: '#333',
overflow: 'auto',
},
lighbox: {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
background: 'rgba(0,0,0,0.5)',
display: 'none',
justifyContent: 'center',
alignItems: 'center',
zIndex: 999,
},
lightboxBtn: (extra) => ({
position: 'absolute',
top: '50%',
background: 'none',
border: 'none',
color: '#fff',
zIndex: 1000,
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'auto',
...extra,
}),
img_list: {
minHeight: '30px',
maxHeight: '300px',
width: '100vw',
position: 'absolute',
bottom: 0,
zIndex: 10,
background: '#333',
overflow: 'auto',
},
}
let currentImageIndex = 0
@@ -58,298 +58,299 @@ const storage = new LocalStorageManager('mtb')
let activated = storage.get('image_feed', false)
app.registerExtension({
name: 'mtb.ImageFeed',
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.imageFeed.enabled',
name: '[⚡mtb] Enable image feed',
type: 'boolean',
defaultValue: true,
attrs: {
style: {
fontFamily: 'monospace',
},
},
async onChange(value) {
storage.set('image_feed', value)
activated = value
},
})
},
init: async () => {
if (!activated) {
return
}
const pythongossFeed = app.extensions.find(
(e) => e.name === 'pysssss.ImageFeed',
)
if (pythongossFeed) {
console.warn(
"[mtb] - Aborting the loading of mtb's imageFeed in favor of pysssss.ImageFeed",
)
activated = false // just in case other methods are added later on
return
}
// - HTML & CSS
//- lightbox
const lightboxContainer = document.createElement('div')
Object.assign(lightboxContainer.style, styles.lighbox)
name: 'mtb.ImageFeed',
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.Main.image-feed-enabled',
category: ['mtb', 'Main', 'image-feed-enabled'],
name: 'Enable Image Feed',
type: 'boolean',
defaultValue: false,
attrs: {
style: {
fontFamily: 'monospace',
},
},
async onChange(value) {
storage.set('image_feed', value)
activated = value
},
})
},
init: async () => {
if (!activated) {
return
}
const pythongossFeed = app.extensions.find(
(e) => e.name === 'pysssss.ImageFeed',
)
if (pythongossFeed) {
console.warn(
"[mtb] - Aborting the loading of mtb's imageFeed in favor of pysssss.ImageFeed",
)
activated = false // just in case other methods are added later on
return
}
// - HTML & CSS
//- lightbox
const lightboxContainer = document.createElement('div')
Object.assign(lightboxContainer.style, styles.lighbox)
const lightboxImage = document.createElement('img')
Object.assign(lightboxImage.style, {
maxHeight: '100%',
maxWidth: '100%',
borderRadius: '5px',
})
const lightboxImage = document.createElement('img')
Object.assign(lightboxImage.style, {
maxHeight: '100%',
maxWidth: '100%',
borderRadius: '5px',
})
// previous and next buttons
const lightboxPrevBtn = document.createElement('button')
const lightboxNextBtn = document.createElement('button')
// previous and next buttons
const lightboxPrevBtn = document.createElement('button')
const lightboxNextBtn = document.createElement('button')
lightboxPrevBtn.textContent = '❮'
lightboxNextBtn.textContent = '❯'
lightboxPrevBtn.textContent = '❮'
lightboxNextBtn.textContent = '❯'
Object.assign(lightboxPrevBtn.style, styles.lightboxBtn({ left: '0%' }))
Object.assign(lightboxNextBtn.style, styles.lightboxBtn({ right: '0%' }))
Object.assign(lightboxPrevBtn.style, styles.lightboxBtn({ left: '0%' }))
Object.assign(lightboxNextBtn.style, styles.lightboxBtn({ right: '0%' }))
// close button
const lightboxCloseBtn = document.createElement('button')
Object.assign(
lightboxCloseBtn.style,
styles.lightboxBtn({ right: '0', top: '0' }),
)
lightboxCloseBtn.textContent = '❌'
// close button
const lightboxCloseBtn = document.createElement('button')
Object.assign(
lightboxCloseBtn.style,
styles.lightboxBtn({ right: '0', top: '0' }),
)
lightboxCloseBtn.textContent = '❌'
const lightboxButtons = document.createElement('div')
Object.assign(lightboxButtons.style, {
position: 'absolute',
top: '0%',
right: '0%',
// transform: "translate(50%, -50%)",
height: '100%',
width: '100%',
background: 'none',
border: 'none',
color: '#fff',
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'none',
})
const lightboxButtons = document.createElement('div')
Object.assign(lightboxButtons.style, {
position: 'absolute',
top: '0%',
right: '0%',
// transform: "translate(50%, -50%)",
height: '100%',
width: '100%',
background: 'none',
border: 'none',
color: '#fff',
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'none',
})
lightboxButtons.append(lightboxPrevBtn, lightboxNextBtn, lightboxCloseBtn)
lightboxContainer.append(lightboxButtons, lightboxImage)
lightboxButtons.append(lightboxPrevBtn, lightboxNextBtn, lightboxCloseBtn)
lightboxContainer.append(lightboxButtons, lightboxImage)
//- image list
const imageListContainer = document.createElement('div')
Object.assign(imageListContainer.style, styles.img_list)
//- image list
const imageListContainer = document.createElement('div')
Object.assign(imageListContainer.style, styles.img_list)
const createImgListBtn = (text, style) => {
const btn = document.createElement('button')
btn.type = 'button'
btn.textContent = text
Object.assign(btn.style, {
...style,
border: 'none',
color: '#fff',
background: 'none',
height: '20px',
cursor: 'pointer',
position: 'absolute',
top: '5px',
fontSize: '12px',
lineHeight: '12px',
})
imageListContainer.append(btn)
return btn
}
const showBtn = document.createElement('button')
const closeBtn = createImgListBtn('❌', {
width: '20px',
textIndent: '-4px',
right: '5px',
})
const loadButton = createImgListBtn('Load Session History', {
right: '90px',
})
const clearButton = createImgListBtn('Clear', {
right: '30px',
})
const createImgListBtn = (text, style) => {
const btn = document.createElement('button')
btn.type = 'button'
btn.textContent = text
Object.assign(btn.style, {
...style,
border: 'none',
color: '#fff',
background: 'none',
height: '20px',
cursor: 'pointer',
position: 'absolute',
top: '5px',
fontSize: '12px',
lineHeight: '12px',
})
imageListContainer.append(btn)
return btn
}
const showBtn = document.createElement('button')
const closeBtn = createImgListBtn('❌', {
width: '20px',
textIndent: '-4px',
right: '5px',
})
const loadButton = createImgListBtn('Load Session History', {
right: '90px',
})
const clearButton = createImgListBtn('Clear', {
right: '30px',
})
//- tools popup button
showBtn.classList.add('comfy-settings-btn')
Object.assign(showBtn.style, {
right: '16px',
cursor: 'pointer',
display: 'none',
})
//- tools popup button
showBtn.classList.add('comfy-settings-btn')
Object.assign(showBtn.style, {
right: '16px',
cursor: 'pointer',
display: 'none',
})
//- append to DOM
document.body.append(imageListContainer)
//- append to DOM
document.body.append(imageListContainer)
showBtn.textContent = '🖼'
showBtn.onclick = () => {
imageListContainer.style.display = 'block'
showBtn.style.display = 'none'
}
document.querySelector('.comfy-settings-btn').after(showBtn)
document.querySelector('.comfy-settings-btn').after(lightboxContainer)
showBtn.textContent = '🖼'
showBtn.onclick = () => {
imageListContainer.style.display = 'block'
showBtn.style.display = 'none'
}
document.querySelector('.comfy-settings-btn').after(showBtn)
document.querySelector('.comfy-settings-btn').after(lightboxContainer)
// for (const { output } of history) {
// if (output?.images) {
// for (const src of output.images) {
// const img = document.createElement("img");
// const but = document.createElement("button");
// for (const { output } of history) {
// if (output?.images) {
// for (const src of output.images) {
// const img = document.createElement("img");
// const but = document.createElement("button");
//- callbacks
closeBtn.onclick = () => {
imageListContainer.style.display = 'none'
showBtn.style.display = 'unset'
}
//- callbacks
closeBtn.onclick = () => {
imageListContainer.style.display = 'none'
showBtn.style.display = 'unset'
}
clearButton.onclick = () => {
imageListContainer.replaceChildren(closeBtn, clearButton, loadButton)
}
clearButton.onclick = () => {
imageListContainer.replaceChildren(closeBtn, clearButton, loadButton)
}
lightboxNextBtn.onclick = () => {
currentImageIndex = (currentImageIndex + 1) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
lightboxNextBtn.onclick = () => {
currentImageIndex = (currentImageIndex + 1) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
// Modify the lightboxPrevBtn onclick callback
lightboxPrevBtn.onclick = () => {
currentImageIndex =
(currentImageIndex - 1 + imageUrls.length) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
// Modify the lightboxPrevBtn onclick callback
lightboxPrevBtn.onclick = () => {
currentImageIndex =
(currentImageIndex - 1 + imageUrls.length) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
lightboxCloseBtn.onclick = () => {
lightboxContainer.style.display = 'none'
}
lightboxImage.onclick = lightboxNextBtn.onclick
/**
* This is the function that creates the image buttons for the image list
* They are wrapped in a button so that they can be clicked and open
* the image in the lightbox.
* @param {*} src
*/
const createImageBtn = (src) => {
console.debug(`making image ${src.filename}`)
const img = document.createElement('img')
const but = document.createElement('button')
lightboxCloseBtn.onclick = () => {
lightboxContainer.style.display = 'none'
}
lightboxImage.onclick = lightboxNextBtn.onclick
/**
* This is the function that creates the image buttons for the image list
* They are wrapped in a button so that they can be clicked and open
* the image in the lightbox.
* @param {*} src
*/
const createImageBtn = (src) => {
console.debug(`making image ${src.filename}`)
const img = document.createElement('img')
const but = document.createElement('button')
Object.assign(but.style, {
height: '120px',
width: '120px',
border: 'none',
padding: 0,
margin: 0,
})
Object.assign(img.style, {
width: '100%',
height: '100%',
objectFit: 'cover',
})
Object.assign(but.style, {
height: '120px',
width: '120px',
border: 'none',
padding: 0,
margin: 0,
})
Object.assign(img.style, {
width: '100%',
height: '100%',
objectFit: 'cover',
})
img.src = `/view?filename=${encodeURIComponent(src.filename)}&type=${
src.type
}&subfolder=${encodeURIComponent(src.subfolder)}`
img.src = `/view?filename=${encodeURIComponent(src.filename)}&type=${
src.type
}&subfolder=${encodeURIComponent(src.subfolder)}`
imageUrls.push(img.src)
imageUrls.push(img.src)
console.debug(img.src)
console.debug(img.src)
img.onload = () => {
but.style.width = `${120 * (img.naturalWidth / img.naturalHeight)}px`
}
img.onload = () => {
but.style.width = `${120 * (img.naturalWidth / img.naturalHeight)}px`
}
but.onclick = () => {
lightboxContainer.style.display = 'flex'
// add the same image to the lightbox
lightboxImage.src = img.src
// lighboxContainer.replaceChildren(lightboxButtons, img);
}
but.onclick = () => {
lightboxContainer.style.display = 'flex'
// add the same image to the lightbox
lightboxImage.src = img.src
// lighboxContainer.replaceChildren(lightboxButtons, img);
}
// add right click menu
but.addEventListener('contextmenu', (e) => {
e.preventDefault()
// add right click menu
but.addEventListener('contextmenu', (e) => {
e.preventDefault()
if (image_menu) {
image_menu.remove()
}
if (image_menu) {
image_menu.remove()
}
image_menu = document.createElement('div')
Object.assign(image_menu.style, {
position: 'absolute',
top: `${e.clientY}px`,
left: `${e.clientX}px`,
background: '#333',
color: '#fff',
padding: '5px',
borderRadius: '5px',
zIndex: 999,
})
const load_img = document.createElement('button')
load_img.textContent = 'Load'
load_img.onclick = () => {
app.handleFile(img.src)
}
image_menu = document.createElement('div')
Object.assign(image_menu.style, {
position: 'absolute',
top: `${e.clientY}px`,
left: `${e.clientX}px`,
background: '#333',
color: '#fff',
padding: '5px',
borderRadius: '5px',
zIndex: 999,
})
const load_img = document.createElement('button')
load_img.textContent = 'Load'
load_img.onclick = () => {
app.handleFile(img.src)
}
image_menu.appendChild(load_img)
document.body.appendChild(image_menu)
})
image_menu.appendChild(load_img)
document.body.appendChild(image_menu)
})
but.append(img)
imageListContainer.prepend(but)
}
but.append(img)
imageListContainer.prepend(but)
}
loadButton.onclick = async () => {
const all_history = await api.getHistory()
for (const history of all_history.History) {
if (history.outputs) {
for (const key of Object.keys(history.outputs)) {
console.debug(key)
if (history.outputs[key].images) {
for (const im of history.outputs[key].images) {
console.debug(im)
createImageBtn(im)
}
}
}
// for (const src of outputs.outputs.images) {
// console.debug(src)
// makeImage(`${src.subfolder}/${src.filename}`)
// }
}
}
}
loadButton.onclick = async () => {
const all_history = await api.getHistory()
for (const history of all_history.History) {
if (history.outputs) {
for (const key of Object.keys(history.outputs)) {
console.debug(key)
if (history.outputs[key].images) {
for (const im of history.outputs[key].images) {
console.debug(im)
createImageBtn(im)
}
}
}
// for (const src of outputs.outputs.images) {
// console.debug(src)
// makeImage(`${src.subfolder}/${src.filename}`)
// }
}
}
}
///////-------
///////-------
// const all_history = await api.getHistory()
// for (const history of all_history.History) {
// if (history.outputs) {
// for (const key of Object.keys(history.outputs)) {
// for (const im of history.outputs[key].images) {
// makeImage(im)
// }
// }
// // for (const src of outputs.outputs.images) {
// // console.debug(src)
// // makeImage(`${src.subfolder}/${src.filename}`)
// // }
// }
// }
// const all_history = await api.getHistory()
// for (const history of all_history.History) {
// if (history.outputs) {
// for (const key of Object.keys(history.outputs)) {
// for (const im of history.outputs[key].images) {
// makeImage(im)
// }
// }
// // for (const src of outputs.outputs.images) {
// // console.debug(src)
// // makeImage(`${src.subfolder}/${src.filename}`)
// // }
// }
// }
//- Hook into the API
api.addEventListener('executed', ({ detail }) => {
if (detail?.output?.images) {
for (const src of detail.output.images) {
console.debug(`Adding ${src} to image feed`)
createImageBtn(src)
}
}
})
},
//- Hook into the API
api.addEventListener('executed', ({ detail }) => {
if (detail?.output?.images) {
for (const src of detail.output.images) {
console.debug(`Adding ${src} to image feed`)
createImageBtn(src)
}
}
})
},
})
+256
View File
@@ -0,0 +1,256 @@
import { app } from '../../scripts/app.js'
import { api } from '../../scripts/api.js'
// import * as shared from './comfy_shared.js'
import {
// defineCSSClass,
ensureMTBStyles,
makeElement,
makeSelect,
makeSlider,
renderSidebar,
} from './mtb_ui.js'
const offset = 0
let currentWidth = 200
let currentMode = 'input'
let currentSort = 'None'
const IMAGE_NODES = ['LoadImage']
const updateImage = (node, image) => {
if (IMAGE_NODES.includes(node.type)) {
const w = node.widgets?.find((w) => w.name === 'image')
if (w) {
w.value = image
w.callback()
}
}
}
const getImgsFromUrls = (urls, target) => {
const imgs = []
if (urls === undefined) {
return imgs
}
for (const [key, url] of Object.entries(urls)) {
const a = makeElement('img')
a.src = url
a.width = currentWidth
if (currentMode === 'input') {
a.onclick = (_e) => {
const selected = app.canvas.selected_nodes
if (selected && Object.keys(selected).length === 0) {
app.extensionManager.toast.add({
severity: 'warn',
summary: 'No LoadImage node selected!',
detail:
'For now the only action when clicking images in the sidebar is to set the image on all selected LoadImage nodes.',
life: 5000,
})
return
}
for (const [_id, node] of Object.entries(app.canvas.selected_nodes)) {
updateImage(node, key)
}
}
} else {
a.onclick = (_e) =>
// window.MTB?.notify?.("Output import isn't supported yet...", 5000)
app.extensionManager.toast.add({
severity: 'warn',
summary: 'Outputs not supported',
detail:
'For now only inputs can be clicked to load the image on the active LoadImage node.',
life: 5000,
})
}
imgs.push(a)
}
if (target !== undefined) {
target.append(...imgs)
}
return imgs
}
const getUrls = async () => {
const count = await api.getSetting('mtb.io-sidebar.count')
console.log('Sidebar count', count)
const inputs = await api.fetchApi('/mtb/actions', {
method: 'POST',
body: JSON.stringify({
name: 'getUserImages',
// mode, count, offset
args: [currentMode, count, offset, currentSort],
}),
})
const output = await inputs.json()
return output?.result || {}
}
//NOTE: do not load if using the old ui
if (window?.__COMFYUI_FRONTEND_VERSION__) {
// NOTE: removed this for now since I'm not actually exposing anything a client
// cannot already access from "/view"...
// let exposed = false
const sidebar_extension = {
name: 'mtb.io-sidebar',
// init: async () => {
// try {
// const res = await api.fetchApi('/mtb/server-info')
// const msg = await res.json()
// exposed = msg.exposed
// } catch (e) {
// console.error('Error:', e)
// }
// },
init: () => {
let handle
const version = window?.__COMFYUI_FRONTEND_VERSION__
console.log(`%c ${version}`, 'background: orange; color: white;')
ensureMTBStyles()
app.ui.settings.addSetting({
id: 'mtb.io-sidebar.count',
category: ['mtb', 'Input & Output Sidebar', 'count'],
name: 'Number of images to fetch',
type: 'number',
defaultValue: 1000,
tooltip:
"This setting affects the input/output sidebar to determine how many images to fetch per pagination (pagination is not yet supported so for now it's the static total)",
attrs: {
style: {
// fontFamily: 'monospace',
},
},
})
app.ui.settings.addSetting({
id: 'mtb.io-sidebar.img-size',
category: ['mtb', 'Input & Output Sidebar', 'img-size'],
name: 'Resolution of the images',
type: 'number',
defaultValue: 512,
tooltip: "It's recommended to keep it at 512px",
attrs: {
style: {
// fontFamily: 'monospace',
},
},
})
app.ui.settings.addSetting({
id: 'mtb.io-sidebar.sort',
category: ['mtb', 'Input & Output Sidebar', 'sort'],
name: 'Default sort mode',
type: 'combo',
onChange: (v) => {
// alert(`Sort is now ${v}`)
currentSort = v
},
defaultValue: 'Modified',
// tooltip: "It's recommended to keep it at 512px",
options: [
'None',
'Modified',
'Modified-Reverse',
'Name',
'Name-Reverse',
],
})
app.extensionManager.registerSidebarTab({
id: 'mtb-inputs-outputs',
icon: 'pi pi-images',
title: 'Input & Outputs',
tooltip: 'MTB: Browse inputs and outputs directories.',
type: 'custom',
// this is run everytime the tab's diplay is toggled on.
render: async (el) => {
if (handle) {
handle.unregister()
handle = undefined
}
if (el.parentNode) {
el.parentNode.style.overflowY = 'clip'
}
const urls = await getUrls(currentMode)
let imgs = {}
const cont = makeElement('div.mtb_sidebar')
const imgGrid = makeElement('div.mtb_img_grid')
const selector = makeSelect(['input', 'output'], currentMode)
selector.addEventListener('change', async (e) => {
const newMode = e.target.value
const changed = newMode !== currentMode
currentMode = newMode
if (changed) {
imgGrid.innerHTML = ''
const urls = await getUrls()
if (urls) {
imgs = getImgsFromUrls(urls, imgGrid)
}
}
})
const imgTools = makeElement('div.mtb_tools')
const orderSelect = makeSelect(
['None', 'Modified', 'Modified-Reverse', 'Name', 'Name-Reverse'],
currentSort,
)
orderSelect.addEventListener('change', async (e) => {
const newSort = e.target.value
const changed = newSort !== currentSort
currentSort = newSort
if (changed) {
imgGrid.innerHTML = ''
const urls = await getUrls()
if (urls) {
imgs = getImgsFromUrls(urls, imgGrid)
}
}
})
const sizeSlider = makeSlider(64, 1024, currentWidth, 1)
imgTools.appendChild(orderSelect)
imgTools.appendChild(sizeSlider)
imgs = getImgsFromUrls(urls, imgGrid)
sizeSlider.addEventListener('input', (e) => {
currentWidth = e.target.value
for (const img of imgs) {
img.style.width = `${e.target.value}px`
}
})
handle = renderSidebar(el, cont, [selector, imgGrid, imgTools])
},
destroy: () => {
if (handle) {
handle.unregister()
handle = undefined
}
},
})
},
}
app.registerExtension(sidebar_extension)
}
+28
View File
@@ -0,0 +1,28 @@
// NOTE: this will be the LT part of mtb API system
// I need to properly publish the source and fix a few things before
// import { app } from '../../scripts/app.js'
// // import { api } from '../../scripts/api.js'
//
// import * as shared from './comfy_shared.js'
// import { createOutliner } from './dist/mtb_inspector.js'
//
// if (window?.__COMFYUI_FRONTEND_VERSION__) {
// const version = window?.__COMFYUI_FRONTEND_VERSION__
// console.log(`%c ${version}`, 'background: orange; color: white;')
//
// const panel = app.extensionManager.registerSidebarTab({
// id: 'mtb-nodes',
// icon: 'pi pi-bolt',
// title: 'MTB',
// tooltip: 'MTB: API outliner',
// type: 'custom',
// // this is run everytime the tab's diplay is toggled on.
// render: (el) => {
// const outliner = createOutliner(el)
// const inputs = shared.getAPIInputs()
// console.log('INPUTS', inputs)
// outliner.$$set({ inputs })
// },
// })
// }
+504
View File
@@ -0,0 +1,504 @@
/**
* Adds a named stylesheet to the document with an optional ability to replace an existing one.
*
* @param {string} name - The unique name (ID) of the stylesheet.
* @param {string} css - The CSS rules as a string.
* @param {boolean} [force=false] - Whether to replace the existing stylesheet if it exists.
* @returns {void}
*/
export function addNamedStyleSheet(name, css, force = false) {
const existingStyleSheet = document.getElementById(name)
if (existingStyleSheet && !force) {
console.debug(
`Stylesheet with name "${name}" already exists. Skipping addition.`,
)
return
}
if (existingStyleSheet && force) {
console.debug(`Stylesheet with name "${name}" exists. Replacing...`)
existingStyleSheet.remove()
}
const styleElement = document.createElement('style')
styleElement.id = name
styleElement.type = 'text/css'
styleElement.appendChild(document.createTextNode(css))
document.head.appendChild(styleElement)
console.debug(`Stylesheet with name "${name}" added.`)
}
export const ensureMTBStyles = () => {
const S = {
fg: 'var(--fg-color)',
bgi: 'var(--comfy-input-bg)',
bgm: 'var(--comfy-menu-bg)',
border: 'var(--comfy-border)',
borderHover: 'var(--comfy-border-hover)',
box: 'var(--comfy-box)',
accent: 'var(--p-button-text-primary-color)',
}
const common = `
.mtb_sidebar {
display: flex;
flex-direction: column;
background: ${S.bgm};
}
.mtb_img_grid {
display: flex;
flex-wrap: wrap;
overflow: scroll;
gap: 1em;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
}
.mtb_tools {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
width: 100%;
}
`
const inputs = `
/* SELECT */
.mtb_select {
appearance: none;
display: grid;
grid-template-areas: "select";
padding: 10px;
background-color: ${S.bgi};
border: none;
border-radius: 5px;
font-size: 14px;
color: ${S.fg};
cursor: pointer;
width: 100%;
}
@supports (-moz-appearance:none) {
.mtb_select{
grid-area: select;
background: ${S.bgi} url('data:image/gif;base64,R0lGODlhBgAGAKEDAFVVVX9/f9TU1CgmNyH5BAEKAAMALAAAAAAGAAYAAAIODA4hCDKWxlhNvmCnGwUAOw==') right center no-repeat !important;
background-position: calc(100% - 5px) center !important;
-moz-appearance:none !important;
}
/* styling the dropdown arrow for browsers that support it */
.mtb_select:after {
content: "";
width: 0.8em;
height: 0.5em;
background-color: ${S.fg};
clip-path: polygon(100% 0%, 0 0%, 50% 100%);
}
.mtb_select:focus {
outline: none;
border-color: #0056b3;
}
.mtb_select > option {
padding: 10px;
background-color: ${S.bgi};
border:none;
color: ${S.fg};
}
.mtb_select > option:hover {
background-color: red;
color: ${S.fg};
}
/* SLIDER */
.mtb_slider[type="range"] {
-webkit-appearance: none;
appearance: none;
width: 100%;
height: 10px;
background: ${S.bgm};
border-radius: 5px;
outline: none;
opacity: 0.7;
transition: opacity .2s;
padding: 1em;
}
/* slider track */
.mtb_slider[type="range"]::-webkit-slider-runnable-track,
.mtb_slider[type="range"]::-moz-range-track {
width: 100%;
height: 10px;
background: ${S.bgi};
border-radius: 5px;
}
/* progress */
.mtb_slider[type="range"]::-moz-range-progress {
background-color: ${S.accent};
height:10px;
border-radius: 5px;
}
/* slider thumb (the handle) */
.mtb_slider[type="range"]::-webkit-slider-thumb,
.mtb_slider[type="range"]::-moz-range-thumb
{
-webkit-appearance: none;
appearance: none;
width: 15px;
height: 15px;
border-radius: 50%;
background: ${S.fg};
border: none;
cursor: pointer;
filter: drop-shadow(1px 1px 4px black);
}
.mtb_slider[type="range"]:focus {
opacity: 1;
}
.mtb_slider[type=range]:-moz-focusring{
outline: 1px solid red;
outline-offset: -1px;
}
.mtb_slider[type="range"]:hover::-webkit-slider-thumb,
.mtb_slider[type="range"]:active::-webkit-slider-thumb {
background-color: ${S.accent};
}
`
addNamedStyleSheet(
'mtb_ui',
`
${common}
${inputs}
`,
)
}
/**
* Creates a DOM element with optional styles, class, and id.
*
* @param {string} kind - The tag name of the element. Supports class and id syntax (e.g. 'div.class#id').
* @param {Object} [style] - CSS styles to apply to the element.
* @returns {HTMLElement} - The created DOM element.
*/
export const makeElement = (kind, style) => {
let [real_kind, className] = kind.split('.')
let id
if (className?.includes('#')) {
;[className, id] = className.split('#')
}
const el = document.createElement(real_kind)
if (style) {
Object.assign(el.style, style)
}
if (className) {
el.classList.add(...className.split(' ')) // Support multiple classes
}
if (id) {
el.id = id
}
return el
}
/**
* Clears all child elements of the given parent element.
*
* @param {HTMLElement} el - The parent element whose children should be removed.
*/
export const clearElement = (el) => {
while (el.firstChild) {
el.removeChild(el.firstChild)
}
}
/**
* Creates a labeled element (input, select, etc.).
*
* @param {HTMLElement} el - The element to label.
* @param {string} labelText - The label text.
* @returns {HTMLDivElement} - A div containing the label and the element.
*/
export const makeLabeledElement = (el, labelText) => {
const wrapper = makeElement('div.mtb_labeled_element', {
marginBottom: '1em',
})
const label = makeElement('label', {
display: 'block',
marginBottom: '0.5em',
})
label.textContent = labelText
wrapper.appendChild(label)
wrapper.appendChild(el)
return wrapper
}
/**
* Converts a camelCase CSS property to kebab-case.
*
* @param {string} prop - The camelCase CSS property.
* @returns {string} - The kebab-case CSS property.
*/
const camelToKebab = (prop) =>
prop.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)
/**
* Parses the style string into an object of CSS property-value pairs.
*
* @param {string} styleString - The CSS rule text (e.g., "color: red; background-color: blue;").
* @returns {Object} - An object with camelCase CSS properties.
*/
const parseStyleString = (styleString) => {
const styleObj = {}
for (const rule of styleString.split(';')) {
const [property, value] = rule.split(':').map((item) => item.trim())
if (property && value) {
const camelProp = property.replace(/-([a-z])/g, (g) => g[1].toUpperCase())
styleObj[camelProp] = value
}
}
return styleObj
}
/**
* Defines a new CSS class with the provided styles, or skips if the class already exists.
*
* @param {string} className - The name of the CSS class to define.
* @param {Object} classStyles - An object containing camelCase CSS property-value pairs.
*/
export function defineCSSClass(className, classStyles) {
const styleSheets = document.styleSheets
let classExists = false
let existingStyleString = ''
const classExistsInStyleSheet = (styleSheet) => {
const rules = styleSheet.rules || styleSheet.cssRules
for (const rule of rules) {
if (rule.selectorText === `.${className}`) {
classExists = true
existingStyleString = rule.style.cssText // Capture existing styles
return true
}
}
return false
}
for (const styleSheet of styleSheets) {
if (classExistsInStyleSheet(styleSheet)) {
console.debug(`Class ${className} already exists, merging styles...`)
break
}
}
const existingStyles = classExists
? parseStyleString(existingStyleString)
: {}
const mergedStyles = { ...existingStyles, ...classStyles }
const stylesString = Object.entries(mergedStyles)
.map(([key, value]) => `${camelToKebab(key)}: ${value};`)
.join(' ')
if (!classExists) {
console.debug(`Defining new class ${className}...`)
if (styleSheets[0].insertRule) {
styleSheets[0].insertRule(`.${className} { ${stylesString} }`, 0)
} else if (styleSheets[0].addRule) {
styleSheets[0].addRule(`.${className}`, stylesString, 0)
}
} else {
console.debug(`Updating existing class ${className} with merged styles...`)
for (const styleSheet of styleSheets) {
const rules = styleSheet.rules || styleSheet.cssRules
for (const rule of rules) {
if (rule.selectorText === `.${className}`) {
rule.style.cssText = stylesString // Update the existing rule
}
}
}
}
console.debug(
`Class ${className} has been defined/updated with styles:`,
mergedStyles,
)
}
/**
* Renders a sidebar and ensures it resizes correctly when the window is resized.
*
* @param {HTMLElement} el - The element where the sidebar is rendered.
* @param {HTMLElement} cont - The content container of the sidebar.
* @param {HTMLElement[]} elems - Array of elements to append to the sidebar.
* @returns {Object} - A handle with a method to unregister the resize event.
*/
export const renderSidebar = (el, cont, elems) => {
el.appendChild(cont)
if (!el.parentNode) {
return
}
el.parentNode.style.overflowY = 'clip'
cont.style.height = `${el.parentNode.offsetHeight}px`
const resizeHandler = () => {
cont.style.height = `${el.parentNode.offsetHeight}px`
}
window.addEventListener('resize', resizeHandler)
for (const elem of elems) {
cont.appendChild(elem)
}
return {
unregister: () => {
window.removeEventListener('resize', resizeHandler)
},
}
}
/**
* Creates a <select> dropdown with given options.
*
* @param {string[]} options - The options for the select element.
* @param {string} [current] - The currently selected option (optional).
* @returns {HTMLSelectElement} - The created <select> element.
*/
export const makeSelect = (options, current = undefined) => {
const selector = makeElement('select.mtb_select', {
width: 'auto',
margin: '1em',
})
for (const option of options) {
const opt = makeElement('option')
opt.value = option
opt.innerHTML = option
selector.appendChild(opt)
}
if (current !== undefined) {
if (options.includes(current)) {
selector.value = current
} else {
console.error(
`You tried to select an option that doesn't exist (${current}). Options: ${options}`,
)
}
}
return selector
}
/**
* Creates an <input type="range"> slider element with given parameters.
*
* @param {number} min - Minimum value of the slider.
* @param {number} max - Maximum value of the slider.
* @param {number} [value] - Initial value of the slider.
* @param {number} [step] - Step value for the slider.
* @returns {HTMLInputElement} - The created slider element.
*/
export const makeSlider = (min, max, value = undefined, step = undefined) => {
const slider = makeElement('input.mtb_slider', {
width: '100%',
})
slider.type = 'range'
slider.min = min || 0
slider.max = max || 100
slider.value = value || slider.min
slider.step = step || 1
return slider
}
/**
* Creates a button element.
*
* @param {string} label - The label for the button.
* @param {Object} [style] - Optional styles to apply to the button.
* @param {Function} [onClick] - Optional click handler.
* @returns {HTMLButtonElement} - The created button element.
*/
export const makeButton = (label, style = {}, onClick = undefined) => {
const button = makeElement('button.mtb_button', style)
button.textContent = label
if (onClick) {
button.addEventListener('click', onClick)
}
return button
}
/**
* Creates a resizable splitter between two elements.
*
* @param {HTMLElement} el1 - The first element.
* @param {HTMLElement} el2 - The second element.
* @param {'vertical' | 'horizontal'} direction - Splitter direction (vertical or horizontal).
* @param {'absolute' | 'normal'} mode - Splitter mode: 'absolute' for free resizing, 'normal' for layout-based resizing.
* @returns {HTMLDivElement} - The container with resizable splitter.
*/
export const makeSplitter = (
el1,
el2,
direction = 'vertical',
mode = 'normal',
) => {
const container = makeElement('div.mtb_splitter_container', {
display: mode === 'absolute' ? 'block' : 'flex',
flexDirection: direction === 'vertical' ? 'row' : 'column',
position: mode === 'absolute' ? 'relative' : 'static',
height: '100%',
width: '100%',
})
const handle = makeElement('div.mtb_splitter_handle', {
backgroundColor: '#ccc',
cursor: direction === 'vertical' ? 'col-resize' : 'row-resize',
width: direction === 'vertical' ? '5px' : '100%',
height: direction === 'horizontal' ? '5px' : '100%',
})
let isResizing = false
handle.addEventListener('mousedown', () => {
isResizing = true
})
window.addEventListener('mouseup', () => {
isResizing = false
})
window.addEventListener('mousemove', (e) => {
if (!isResizing) return
if (direction === 'vertical') {
const newWidth = e.clientX - container.offsetLeft
el1.style.width = `${newWidth}px`
el2.style.width = `${container.offsetWidth - newWidth}px`
} else {
const newHeight = e.clientY - container.offsetTop
el1.style.height = `${newHeight}px`
el2.style.height = `${container.offsetHeight - newHeight}px`
}
})
container.appendChild(el1)
container.appendChild(handle)
container.appendChild(el2)
return container
}
+438 -112
View File
@@ -3,19 +3,24 @@
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
* Copyright (c) 2023-2025 Mel Massadian
*
*/
/// <reference path="../types/typedefs.js" />
// TODO: Use the builtin addDOMWidget everywhere appropriate
import { app } from '../../scripts/app.js'
import { api } from '../../scripts/api.js'
import * as mtb_ui from './mtb_ui.js'
import { GeometryPreview } from './mtb_3d.js'
import parseCss from './extern/parse-css.js'
import * as shared from './comfy_shared.js'
import { log } from './comfy_shared.js'
import { Constant } from './constant.js'
import { infoLogger } from './comfy_shared.js'
import { NumberInputWidget } from './numberInput.js'
// NOTE: new widget types registered by MTB Widgets
const newTypes = [/*'BOOL'*/ , 'COLOR', 'BBOX']
@@ -55,7 +60,250 @@ const calculateTextDimensions = (ctx, value, width, fontSize = 16) => {
return { textHeight, maxLineWidth }
}
export function addMultilineWidget(node, name, opts, callback) {
const inputEl = document.createElement('textarea')
inputEl.className = 'comfy-multiline-input'
inputEl.value = opts.defaultVal
inputEl.placeholder = opts.placeholder || name
const widget = node.addDOMWidget(name, 'textmultiline', inputEl, {
getValue() {
return inputEl.value
},
setValue(v) {
inputEl.value = v
},
})
widget.inputEl = inputEl
inputEl.addEventListener('input', () => {
callback?.(widget.value)
widget.callback?.(widget.value)
})
widget.onRemove = () => {
inputEl.remove()
}
return { minWidth: 400, minHeight: 200, widget }
}
export const VECTOR_AXIS = {
0: 'x',
1: 'y',
2: 'z',
3: 'w',
}
export function addVectorWidgetW(
node,
name,
value,
vector_size,
_callback,
app,
) {
// const inputEl = document.createElement('div')
// const vecEl = document.createElement('div')
//
// inputEl.style.background = 'red'
//
// inputEl.className = 'comfy-vector-container'
// vecEl.className = 'comfy-vector-input'
//
// vecEl.style.display = 'flex'
// inputEl.appendChild(vecEl)
const inputs = []
for (let i = 0; i < vector_size; i++) {
// const input = document.createElement('input')
// input.type = 'number'
// input.value = value[VECTOR_AXIS[i]]
const input = node.addWidget(
'number',
`${name}_${VECTOR_AXIS[i]}`,
value[VECTOR_AXIS[i]],
(val) => {},
)
inputs.push(input)
// vecEl.appendChild(input)
}
//
// const widget = node.addDOMWidget(name, 'vector', inputEl, {
// getValue() {
// return JSON.stringify(widget._value)
// },
// setValue(v) {
// widget._value = v
// },
// afterResize(node, widget) {
// console.log('After resize', { that: this, node, widget })
// },
// })
//
// console.log('prev callback', widget.callback)
// widget.callback = callback
// widget._value = value
//
// for (let i = 0; i < vector_size; i++) {
// const input = inputs[i]
// input.addEventListener('change', (event) => {
// widget._value[VECTOR_AXIS[i]] = Number.parseFloat(event.target.value)
// widget.callback?.(widget._value)
// node.graph._version++
// node.setDirtyCanvas(true, true)
// })
// }
// // document.body.append(inputEl)
//
// widget.inputEl = inputEl
// widget.vecEl = vecEl
//
// inputEl.addEventListener('input', () => {
// widget.callback?.(widget.value)
// })
//
return { minWidth: 400, minHeight: 200, widget }
}
export function addVectorWidget(node, name, value, vector_size, callback, app) {
const inputEl = document.createElement('div')
const vecEl = document.createElement('div')
inputEl.className = 'comfy-vector-container'
vecEl.className = 'comfy-vector-input'
vecEl.id = 'vecEl'
vecEl.style.display = 'flex'
vecEl.style.flexDirection = 'column'
inputEl.appendChild(vecEl)
const inputs = []
//
// for (let i = 0; i < vector_size; i++) {
// const input = document.createElement('input')
// input.type = 'number'
// input.value = value[VECTOR_AXIS[i]]
// inputs.push(input)
// vecEl.appendChild(input)
// }
const widget = node.addDOMWidget(name, 'vector', inputEl, {
getValue() {
return JSON.stringify(widget._value)
},
setValue(v) {
widget._value = v
},
})
const vec = new NumberInputWidget('vecEl', vector_size, true)
vec.setValue(...Object.values(value))
vec.onChange = (value) => {
for (let i = 0; i < value.length; i++) {
const val = value[i]
widget._value[VECTOR_AXIS[i]] = Number.parseFloat(val)
}
widget.callback?.(widget._value)
// widget._value[VECTOR_AXIS[index]] = Number.parseFloat(value)
}
// console.log('prev callback', widget.callback)
widget.callback = callback
widget._value = value
// for (let i = 0; i < vector_size; i++) {
// const input = inputs[i]
// input.addEventListener('change', (event) => {
// widget._value[VECTOR_AXIS[i]] = Number.parseFloat(event.target.value)
// widget.callback?.(widget._value)
// node.graph._version++
// node.setDirtyCanvas(true, true)
// })
// }
widget.inputEl = inputEl
widget.vecEl = vecEl
widget.vec = vec
return { minWidth: 400, minHeight: 200 * vector_size, widget }
}
export const MtbWidgets = {
//TODO: complete this properly
/**
* Creates a vector widget.
* @param {string} key - The key for the widget.
* @param {number[]} [val] - The initial value for the widget.
* @param {number} size - The size of the vector.
* @returns {VectorWidget} The vector widget.
*/
VECTOR: (key, val, size) => {
infoLogger('Adding VECTOR widget', { key, val, size })
/** @type {VectorWidget} */
const widget = {
name: key,
type: `vector${size}`,
y: 0,
options: { default: Array.from({ length: size }, () => 0.0) },
_value: val || Array.from({ length: size }, () => 0.0),
draw: (ctx, node, width, widgetY, height) => {
ctx.textAlign = 'left'
ctx.strokeStyle = outline_color
ctx.fillStyle = background_color
ctx.beginPath()
if (show_text)
ctx.roundRect(margin, y, widget_width - margin * 2, H, [H * 0.5])
else ctx.rect(margin, y, widget_width - margin * 2, H)
ctx.fill()
if (show_text) {
if (!w.disabled) ctx.stroke()
ctx.fillStyle = text_color
if (!w.disabled) {
ctx.beginPath()
ctx.moveTo(margin + 16, y + 5)
ctx.lineTo(margin + 6, y + H * 0.5)
ctx.lineTo(margin + 16, y + H - 5)
ctx.fill()
ctx.beginPath()
ctx.moveTo(widget_width - margin - 16, y + 5)
ctx.lineTo(widget_width - margin - 6, y + H * 0.5)
ctx.lineTo(widget_width - margin - 16, y + H - 5)
ctx.fill()
}
ctx.fillStyle = secondary_text_color
ctx.fillText(w.label || w.name, margin * 2 + 5, y + H * 0.7)
ctx.fillStyle = text_color
ctx.textAlign = 'right'
if (w.type === 'number') {
ctx.fillText(
Number(w.value).toFixed(
w.options.precision !== undefined ? w.options.precision : 3,
),
widget_width - margin * 2 - 20,
y + H * 0.7,
)
} else {
let v = w.value
if (w.options.values) {
let values = w.options.values
if (values.constructor === Function) values = values()
if (values && values.constructor !== Array) v = values[w.value]
}
ctx.fillText(v, widget_width - margin * 2 - 20, y + H * 0.7)
}
}
},
get value() {
return this._value
},
set value(val) {
this._value = val
this.callback?.(this._value)
},
}
return widget
},
BBOX: (key, val) => {
/** @type {import("./types/litegraph").IWidget} */
const widget = {
@@ -66,7 +314,7 @@ export const MtbWidgets = {
value: val?.default || [0, 0, 0, 0],
options: {},
draw: function (ctx, node, widget_width, widgetY, height) {
draw: function (ctx, _node, widget_width, widgetY, _height) {
const hide = this.type !== 'BBOX' && app.canvas.ds.scale > 0.5
const show_text = true
@@ -76,13 +324,13 @@ export const MtbWidgets = {
const secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR
const H = LiteGraph.NODE_WIDGET_HEIGHT
let margin = 15
let numWidgets = 4 // Number of stacked widgets
const margin = 15
const numWidgets = 4 // Number of stacked widgets
if (hide) return
for (let i = 0; i < numWidgets; i++) {
let currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
const currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
ctx.textAlign = 'left'
ctx.strokeStyle = outline_color
@@ -192,7 +440,7 @@ export const MtbWidgets = {
this.type == 'BBOX'
) {
let delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0
if (event.click_time < 200 && delta == 0) {
if (event.click_time < 200 && delta === 0) {
this.prompt(
'Value',
this.value,
@@ -341,12 +589,15 @@ export const MtbWidgets = {
w.inputEl = document.createElement('img')
w.inputEl.src = w.value
w.inputEl.onload = function () {
w.inputEl.onload = () => {
w.inputRatio = w.inputEl.naturalWidth / w.inputEl.naturalHeight
}
document.body.appendChild(w.inputEl)
return w
},
DEBUG_GEOM: async (node, name, val) => {
return await GeometryPreview(node, name, val)
},
DEBUG_STRING: (name, val) => {
const fontSize = 16
const w = {
@@ -411,77 +662,82 @@ const mtb_widgets = {
name: 'mtb.widgets',
init: async () => {
log('Registering mtb.widgets')
infoLogger('Registering mtb.widgets')
try {
const res = await api.fetchApi('/mtb/debug')
const res = await api.fetchApi('/mtb/server-info')
const msg = await res.json()
if (!window.MTB) {
window.MTB = {}
}
window.MTB.DEBUG = msg.enabled
window.MTB.DEBUG = msg.debug
} catch (e) {
console.error('Error:', error)
console.error('Error:', e)
}
},
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.Debug.enabled',
name: '[⚡mtb] Enable Debug (py and js)',
id: 'mtb.postshot.path',
category: ['mtb', 'PostShot', 'path'],
name: 'Path to Postshot CLI',
type: 'string',
defaultValue: 'C:/Program Files/Jawset Postshot/bin/postshot-cli.exe',
tooltip: 'The path to the postshot CLI',
})
app.ui.settings.addSetting({
id: 'mtb.Main.debug-enabled',
category: ['mtb', 'Main', 'debug-enabled'],
name: 'Enable Debug (py and js)',
type: 'boolean',
defaultValue: false,
tooltip:
'This will enable debug messages in the console and in the python console respectively',
'This will enable debug messages in the console and in the python console respectively, no need to restart the server, but do reload the webui',
attrs: {
style: {
fontFamily: 'monospace',
// fontFamily: 'monospace',
},
},
async onChange(value) {
if (value) {
console.log('Enabled DEBUG mode')
}
if (!window.MTB) {
window.MTB = {}
}
window.MTB.DEBUG = value
if (value) {
infoLogger('Enabled DEBUG mode')
}
await api
.fetchApi('/mtb/debug', {
.fetchApi('/mtb/server-info', {
method: 'POST',
body: JSON.stringify({
enabled: value,
debug: value,
}),
})
.then((response) => {})
.then((_response) => {})
.catch((error) => {
console.error('Error:', error)
})
},
})
},
registerCustomNodes() {
LiteGraph.registerNodeType('Constant (mtb)', Constant)
Constant.category = 'mtb/utils'
Constant.title = 'Constant (mtb)'
},
getCustomWidgets: function () {
getCustomWidgets: () => {
return {
BOOL: (node, inputName, inputData, app) => {
console.debug('Registering bool')
// BOOL: (node, inputName, inputData, _app) => {
// console.debug('Registering bool')
//
// return {
// widget: node.addCustomWidget(
// MtbWidgets.BOOL(inputName, inputData[1]?.default || false),
// ),
// minWidth: 150,
// minHeight: 30,
// }
// },
return {
widget: node.addCustomWidget(
MtbWidgets.BOOL(inputName, inputData[1]?.default || false),
),
minWidth: 150,
minHeight: 30,
}
},
COLOR: (node, inputName, inputData, app) => {
COLOR: (node, inputName, inputData, _app) => {
console.debug('Registering color')
return {
widget: node.addCustomWidget(
@@ -503,15 +759,15 @@ const mtb_widgets = {
}
},
/**
* @param {import("./types/comfy").NodeType} nodeType
* @param {import("./types/comfy").NodeDef} nodeData
* @param {NodeType} nodeType
* @param {NodeData} nodeData
* @param {import("./types/comfy").App} app
*/
async beforeRegisterNodeDef(nodeType, nodeData, app) {
// const rinputs = nodeData.input?.required
let has_custom = false
if (nodeData.input && nodeData.input.required) {
if (nodeData.input?.required) {
for (const i of Object.keys(nodeData.input.required)) {
const input_type = nodeData.input.required[i][0]
@@ -524,10 +780,8 @@ const mtb_widgets = {
if (has_custom) {
//- Add widgets on node creation
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
nodeType.prototype.onNodeCreated = function (...args) {
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
this.serialize_widgets = true
this.setSize?.(this.computeSize())
@@ -545,8 +799,8 @@ const mtb_widgets = {
? origGetExtraMenuOptions.apply(this, arguments)
: undefined
if (this.widgets) {
let toInput = []
let toWidget = []
const toInput = []
const toWidget = []
for (const w of this.widgets) {
if (w.type === shared.CONVERTED_TYPE) {
//- This is already handled by widgetinputs.js
@@ -592,12 +846,11 @@ const mtb_widgets = {
//- Extending Python Nodes
switch (nodeData.name) {
//TODO: remove this non sense
case 'Get Batch From History (mtb)': {
case 'Get Batch From History (mtb)':
case 'Get Batch From History V2 (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
const r = onNodeCreated ? onNodeCreated.apply(this, []) : undefined
const internal_count = this.widgets.find(
(w) => w.name === 'internal_count',
)
@@ -617,6 +870,22 @@ const mtb_widgets = {
break
}
case 'Postshot Train (mtb)':
case 'Postshot Export (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function (...args) {
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
const { postshot_cli } = shared.getNamedWidget(this, 'postshot_cli')
shared.hideWidgetForGood(this, postshot_cli)
api.getSetting('mtb.postshot.path').then((p) => {
postshot_cli._value = p
})
}
break
}
case 'Save Gif (mtb)':
case 'Save Animated Image (mtb)': {
const onExecuted = nodeType.prototype.onExecuted
@@ -639,7 +908,7 @@ const mtb_widgets = {
imgURLs = imgURLs.concat(
message.gif.map((params) => {
return api.apiURL(
'/view?' + new URLSearchParams(params).toString(),
`/view?${new URLSearchParams(params).toString()}`,
)
}),
)
@@ -648,7 +917,7 @@ const mtb_widgets = {
imgURLs = imgURLs.concat(
message.apng.map((params) => {
return api.apiURL(
'/view?' + new URLSearchParams(params).toString(),
`/view?${new URLSearchParams(params).toString()}`,
)
}),
)
@@ -676,37 +945,71 @@ const mtb_widgets = {
}
case 'Animation Builder (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
nodeType.prototype.onNodeCreated = function (...args) {
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
this.changeMode(LiteGraph.ALWAYS)
const raw_iteration = this.widgets.find(
(w) => w.name === 'raw_iteration',
)
const raw_loop = this.widgets.find((w) => w.name === 'raw_loop')
const total_frames = this.widgets.find(
(w) => w.name === 'total_frames',
)
const loop_count = this.widgets.find((w) => w.name === 'loop_count')
const { raw_iteration, raw_loop, total_frames, loop_count } =
shared.getNamedWidget(
this,
'raw_iteration',
'raw_loop',
'total_frames',
'loop_count',
)
shared.hideWidgetForGood(this, raw_iteration)
shared.hideWidgetForGood(this, raw_loop)
raw_iteration._value = 0
const value_preview = this.addCustomWidget(
MtbWidgets['DEBUG_STRING']('value_preview', 'Idle'),
)
value_preview.parent = this
// const value_preview = this.addCustomWidget(
// MtbWidgets.DEBUG_STRING('value_preview', 'Idle'),
// )
const loop_preview = this.addCustomWidget(
MtbWidgets['DEBUG_STRING']('loop_preview', 'Iteration: Idle'),
const dom_value_preview = mtb_ui.makeElement('p', {
fontWeigth: '700',
textAlign: 'center',
fontSize: '1.5em',
margin: 0,
})
const value_preview = this.addDOMWidget(
'value_preview',
'DISPLAY',
dom_value_preview,
{
hideOnZoom: false,
setValue: (val) => {
if (val) {
value_preview.element.innerHTML = val
}
},
},
)
loop_preview.parent = this
value_preview.value = 'Idle'
const dom_loop_preview = mtb_ui.makeElement('p', {
textAlign: 'center',
margin: 0,
})
const loop_preview = this.addDOMWidget(
'loop_preview',
'DISPLAY',
dom_loop_preview,
{
hideOnZoom: false,
setValue: (val) => {
if (val) {
dom_loop_preview.innerHTML = val
}
},
getValue: () => {
dom_loop_preview.innerHTML
},
},
)
loop_preview.value = 'Iteration: Idle'
const onReset = () => {
raw_iteration.value = 0
@@ -718,14 +1021,11 @@ const mtb_widgets = {
app.canvas.setDirty(true)
}
const reset_button = this.addWidget(
'button',
`Reset`,
'reset',
onReset,
)
// reset button
this.addWidget('button', 'Reset', 'reset', onReset)
const run_button = this.addWidget('button', `Queue`, 'queue', () => {
// run button
this.addWidget('button', 'Queue', 'queue', () => {
onReset() // this could maybe be a setting or checkbox
app.queuePrompt(0, total_frames.value * loop_count.value)
window.MTB?.notify?.(
@@ -765,9 +1065,9 @@ const mtb_widgets = {
}
case 'Interpolate Clip Sequential (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
nodeType.prototype.onNodeCreated = function (...args) {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
? onNodeCreated.apply(this, ...args)
: undefined
const addReplacement = () => {
const input = this.addInput(
@@ -775,23 +1075,18 @@ const mtb_widgets = {
'STRING',
'',
)
console.log(input)
// console.log(input)
this.addWidget('STRING', `replacement_${this.widgets.length}`, '')
}
//- add
this.addWidget('button', '+', 'add', function (value, widget, node) {
console.log('Button clicked', value, widget, node)
this.addWidget('button', '+', 'add', (value, widget, node) => {
// console.log('Button clicked', value, widget, node)
addReplacement()
})
//- remove
this.addWidget(
'button',
'-',
'remove',
function (value, widget, node) {
console.log(`Button clicked: ${value}`, widget, node)
},
)
this.addWidget('button', '-', 'remove', (value, widget, node) => {
// console.log(`Button clicked: ${value}`, widget, node)
})
return r
}
@@ -810,10 +1105,7 @@ const mtb_widgets = {
method: 'POST',
body: JSON.stringify({
name: 'getStyles',
args:
node.widgets && node.widgets[0].value
? node.widgets[0].value
: '',
args: node.widgets?.[0].value ? node.widgets[0].value : '',
}),
})
@@ -887,6 +1179,10 @@ const mtb_widgets = {
shared.setupDynamicConnections(nodeType, 'video', 'VIDEO')
break
}
case 'Interpolate Condition (mtb)': {
shared.setupDynamicConnections(nodeType, 'condition', 'CONDITIONING')
break
}
case 'Psd Save (mtb)': {
shared.setupDynamicConnections(nodeType, 'input_', 'PSDLAYER')
break
@@ -898,17 +1194,21 @@ const mtb_widgets = {
case 'Stack Images (mtb)':
case 'Concat Images (mtb)': {
shared.setupDynamicConnections(nodeType, 'image', 'IMAGE')
break
}
case 'Audio Sequence (mtb)':
case 'Audio Stack (mtb)': {
shared.setupDynamicConnections(nodeType, 'audio', 'AUDIO')
break
}
case 'Batch Float Assemble (mtb)':
case 'Batch Float Math (mtb)':
case 'Plot Batch Float (mtb)': {
shared.setupDynamicConnections(nodeType, 'floats', 'FLOATS')
break
}
case 'Batch Merge (mtb)': {
shared.setupDynamicConnections(nodeType, 'batches', 'IMAGE')
break
}
// TODO: remove this, recommend pythongoss's version that is much better
@@ -918,13 +1218,13 @@ const mtb_widgets = {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
this.addInput(`x`, '*')
this.addInput('x', '*')
return r
}
const onConnectionsChange = nodeType.prototype.onConnectionsChange
nodeType.prototype.onConnectionsChange = function (
type,
_type,
index,
connected,
link_info,
@@ -932,16 +1232,14 @@ const mtb_widgets = {
const r = onConnectionsChange
? onConnectionsChange.apply(this, arguments)
: undefined
shared.dynamic_connection(this, index, connected, 'var_', '*', [
'x',
'y',
'z',
])
shared.dynamic_connection(this, index, connected, 'var_', '*', {
nameArray: ['x', 'y', 'z'],
})
//- infer type
if (link_info) {
const fromNode = this.graph._nodes.find(
(otherNode) => otherNode.id == link_info.origin_id,
(otherNode) => otherNode.id !== link_info.origin_id,
)
const type = fromNode.outputs[link_info.origin_slot].type
this.inputs[index].type = type
@@ -956,6 +1254,34 @@ const mtb_widgets = {
break
}
case 'Batch Shape (mtb)':
case 'Mask To Image (mtb)':
case 'Text To Image (mtb)': {
shared.addMenuHandler(nodeType, function (_app, options) {
/** @type {ContextMenuItem} */
const item = {
content: 'swap colors',
title: 'Swap BG/FG Color ⚡',
callback: (_menuItem) => {
const color_w = this.widgets.find((w) => w.name === 'color')
const bg_w = this.widgets.find(
(w) => w.name === 'background' || w.name === 'bg_color',
)
const color = color_w.value
const bg = bg_w.value
color_w.value = bg
bg_w.value = color
},
}
options.push(item)
return [item]
})
break
}
case 'Save Tensors (mtb)': {
const onDrawBackground = nodeType.prototype.onDrawBackground
nodeType.prototype.onDrawBackground = function (ctx, canvas) {
+246
View File
@@ -0,0 +1,246 @@
// web/note_plus.constants.js
export const DEFAULT_CSS = ''
export const DEFAULT_HTML = `<p style='color:red;font-family:monospace'>
Note+
</p>`
export const DEFAULT_MD = '## Note+'
export const DEFAULT_MODE = 'markdown'
export const DEFAULT_THEME = 'one_dark'
export const DEMO_CONTENT = `
# @mtb/svelte-markdown.
## This is a subheader
[![embedded test](https://github.com/melMass/comfy_mtb/actions/workflows/test_embedded.yml/badge.svg)](https://github.com/melMass/comfy_mtb/actions/workflows/test_embedded.yml)
![home](https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873)
<details>
<summary>More details about the inception of the project</summary>
\`\`\`js
class YesMan{
constructor(){
this.started = false
}
}
\`\`\`
</details>
This is a paragraph. If it goes over the maximum width it will not automatically wrap unless it reaches the max-w of \`prose\` check [styles](/styles) for more info.
This component is useful for building some tools on top. Or even just a static system using svelte at its core. My personal blog is fully powered by **@mtb/svelte-markdown**
| And this is | A table |
|-------------|---------|
| With two | columns |
We also support github callout:
> [!NOTE]
> Highlights information that users should take into account, even when skimming.
> [!TIP]
> Optional information to help a user be more successful.
> [!IMPORTANT]
> Crucial information necessary for users to succeed.
> [!WARNING]
> Critical content demanding immediate user attention due to potential risks.
> [!CAUTION]
> Negative potential consequences of an action.
`
export const THEMES = [
'ambiance',
'chaos',
'chrome',
'cloud9_day',
'cloud9_night',
'cloud9_night_low_color',
'cloud_editor',
'cloud_editor_dark',
'clouds',
'clouds_midnight',
'cobalt',
'crimson_editor',
'dawn',
'dracula',
'dreamweaver',
'eclipse',
'github',
'github_dark',
'gob',
'gruvbox',
'gruvbox_dark_hard',
'gruvbox_light_hard',
'idle_fingers',
'iplastic',
'katzenmilch',
'kr_theme',
'kuroir',
'merbivore',
'merbivore_soft',
'mono_industrial',
'monokai',
'nord_dark',
'one_dark',
'pastel_on_dark',
'solarized_dark',
'solarized_light',
'sqlserver',
'terminal',
'textmate',
'tomorrow',
'tomorrow_night',
'tomorrow_night_blue',
'tomorrow_night_bright',
'tomorrow_night_eighties',
'twilight',
'vibrant_ink',
'vscode',
]
export const CSS_RESET = `
* {
font-family: monospace;
line-height: 1.25em;
}
.shiki{
padding: 1em;
width: 100%;
}
.markdown-callout-title {
.octicon{
fill:white;
}
/* background: var(--current-color); */
color: var(--current-color);
font-weight: bold;
/* border-start-end-radius: var(--radius); */
/* border-start-start-radius: var(--radius); */
padding: 0.5em;
padding-inline-start: 1em;
}
.markdown-callout-content {
padding: 1em;
}
.markdown-callout {
--radius: 8px;
--current-color: purple;
/* border-start-end-radius: var(--radius); */
/* border-start-start-radius: var(--radius); */
border-left: 3px solid var(--current-color);
margin-bottom: 1em;
margin-top: 1em;
}
.markdown-callout-tip {
--text-color: whitesmoke;
--current-color: #50e3c2;
}
.markdown-callout-note {
--text-color: whitesmoke;
--current-color: #0070f3;
}
.markdown-callout-important {
--text-color: whitesmoke;
--current-color: #7928ca;
}
.markdown-callout-warning {
--current-color: #f5a623;
}
.markdown-callout-caution {
--current-color: #e60000;
}
.note-plus-preview {
display:flex;
flex-direction:column;
align-items: flex-start;
width:95%;
margin-left: 20px;
margin-top:20px;
/*background-color: rgba(255,0,0,0.5)!important;*/
}
/* allowed to be selected*/
h1, h2, h3, h4, h5, h6,a, p, ul, ol, dl, blockquote,details,summary {
pointer-events:auto;
user-select:text;
}
h1, h2, h3, h4, h5, h6 {
display:inline-block;
margin: 0;
padding: 0;
font-weight: normal;
}
p, ul, ol, dl, blockquote {
margin: 0.3em;
padding: 0;
}
ul, ol {
padding-left: 1em;
}
a {
color: inherit;
text-decoration: none;
pointer-events: all;
color: cyan;
}
img {
padding: 1em 0;
max-width: 100%;
}
iframe {
max-width: 100%;
height: auto;
border:none;
pointer-events:all;
}
blockquote {
border-left: 4px solid #ccc;
padding-left: 1em;
margin-left: 0;
font-style: italic;
}
pre, code {
font-family: monospace;
}
table {
border-collapse: collapse;
width: 100%;
border-bottom: 1px solid #000;
margin: 1em 0;
}
th, td {
border-left: 1px solid #000;
border-right: 1px solid #000;
padding: 8px;
text-align: left;
}
th {
border: 1px solid #000;
background-color: rgba(0,0,0,0.5);
}
input[type="checkbox"] {
margin-right: 10px;
}
`
+390 -253
View File
@@ -1,155 +1,122 @@
/// <reference path="../types/typedefs.js" />
import { app } from '../../scripts/app.js'
import * as shared from './comfy_shared.js'
import { infoLogger, successLogger, errorLogger } from './comfy_shared.js'
import {
DEFAULT_CSS,
DEFAULT_HTML,
DEFAULT_MD,
DEFAULT_MODE,
DEFAULT_THEME,
THEMES,
CSS_RESET,
DEMO_CONTENT,
} from './note_plus.constants.js'
import { LocalStorageManager } from './comfy_shared.js'
const DEFAULT_CSS = ''
const DEFAULT_HTML = `<p style='color:red;font-family:monospace'>
Note+
</p>`
const DEFAULT_MD = '## Note+'
const DEFAULT_MODE = 'markdown'
const DEFAULT_THEME = 'one_dark'
const storage = new LocalStorageManager('mtb')
const CSS_RESET = `
* {
font-family: monospace;
line-height: 1.25em;
/**
* Uses `@mtb/markdown-parser` (a fork of marked)
* It is statically stored to avoid having
* more than 1 instance ever.
* The size difference between both libraries...
* ╭───┬────────────────────────────────┬──────────╮
* │ # │ name │ size │
* ├───┼────────────────────────────────┼──────────┤
* │ 0 │ web-dist/mtb_markdown_plus.mjs │ 1.2 MB │ <- with shiki
* │ 1 │ web-dist/mtb_markdown.mjs │ 44.7 KB │
* ╰───┴────────────────────────────────┴──────────╯
*/
let useShiki = storage.get('np-use-shiki', false)
const makeResizable = (dialog) => {
dialog.style.resize = 'both'
dialog.style.transformOrigin = 'top left'
dialog.style.overflow = 'auto'
}
h1, h2, h3, h4, h5, h6 {
margin: 0;
padding: 0;
font-weight: normal;
const makeDraggable = (dialog, handle) => {
let offsetX = 0
let offsetY = 0
let isDragging = false
const onMouseMove = (e) => {
if (isDragging) {
dialog.style.left = `${e.clientX - offsetX}px`
dialog.style.top = `${e.clientY - offsetY}px`
}
}
const onMouseUp = () => {
isDragging = false
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
}
handle.addEventListener('mousedown', (e) => {
isDragging = true
offsetX = e.clientX - dialog.offsetLeft
offsetY = e.clientY - dialog.offsetTop
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
})
}
p, ul, ol, dl, blockquote {
margin: 0.3em;
padding: 0;
}
ul, ol {
padding-left: 1em;
}
a {
color: inherit;
text-decoration: none;
pointer-events: all;
color: cyan;
}
img {
padding: 1em 0;
max-width: 100%;
}
iframe {
width: 100%;
height: auto;
border:none;
pointer-events:all;
}
blockquote {
border-left: 4px solid #ccc;
padding-left: 1em;
margin-left: 0;
font-style: italic;
}
pre, code {
font-family: monospace;
}
table {
border-collapse: collapse;
width: 100%;
border-bottom: 1px solid #000;
margin: 1em 0;
}
th, td {
border-left: 1px solid #000;
border-right: 1px solid #000;
padding: 8px;
text-align: left;
}
th {
border: 1px solid #000;
background-color: rgba(0,0,0,0.5);
}
input[type="checkbox"] {
margin-right: 10px;
}
`
const themes = [
'ambiance',
'chaos',
'chrome',
'cloud9_day',
'cloud9_night',
'cloud9_night_low_color',
'cloud_editor',
'cloud_editor_dark',
'clouds',
'clouds_midnight',
'cobalt',
'crimson_editor',
'dawn',
'dracula',
'dreamweaver',
'eclipse',
'github',
'github_dark',
'gob',
'gruvbox',
'gruvbox_dark_hard',
'gruvbox_light_hard',
'idle_fingers',
'iplastic',
'katzenmilch',
'kr_theme',
'kuroir',
'merbivore',
'merbivore_soft',
'mono_industrial',
'monokai',
'nord_dark',
'one_dark',
'pastel_on_dark',
'solarized_dark',
'solarized_light',
'sqlserver',
'terminal',
'textmate',
'tomorrow',
'tomorrow_night',
'tomorrow_night_blue',
'tomorrow_night_bright',
'tomorrow_night_eighties',
'twilight',
'vibrant_ink',
'vscode',
]
/** @extends {LGraphNode} */
class NotePlus extends LiteGraph.LGraphNode {
// same values as the comfy note
color = LGraphCanvas.node_colors.yellow.color
bgcolor = LGraphCanvas.node_colors.yellow.bgcolor
groupcolor = LGraphCanvas.node_colors.yellow.groupcolor
/* NOTE: this is not serialized and only there to make multiple
* note+ nodes in the same graph unique.
*/
uuid
/** Stores the dialog observer*/
resizeObserver
/** Live update the preview*/
live = true
/** DOM height by adding child size together*/
calculated_height = 0
/** ????*/
_raw_html
/** might not be needed anymore */
inner
/** the dialog DOM widget*/
dialog
/** widgets*/
/** used to store the raw value and display the parsed html at the same time*/
html_widget
/** hidden widgets for serialization*/
css_widget
edit_mode_widget
theme_widget
editorsContainer
/** ACE editors instances*/
html_editor
css_editor
constructor() {
super()
this.uuid = shared.makeUUID()
infoLogger('Constructing Note+ instance')
shared.ensureMarkdownParser((_p) => {
this.updateHTML()
})
// - litegraph settings
this.collapsable = true
this.isVirtualNode = true
@@ -159,35 +126,30 @@ class NotePlus extends LiteGraph.LGraphNode {
// - default values, serialization is done through widgets
this._raw_html = DEFAULT_MODE === 'html' ? DEFAULT_HTML : DEFAULT_MD
// - mardown converter
this.markdownConverter = new showdown.Converter({
tables: true,
strikethrough: true,
emoji: true,
ghCodeBlocks: true,
tasklists: true,
ghMentions: true,
smoothLivePreview: true,
simplifiedAutoLink: true,
parseImgDimensions: true,
openLinksInNewWindow: true,
})
// - state
this.live = true
this.calculated_height = 0
// - add widgets
const inner = document.createElement('div')
inner.style.margin = '0'
inner.style.padding = '0'
inner.style.pointerEvents = 'none'
this.html_widget = this.addDOMWidget('HTML', 'html', inner, {
const cinner = document.createElement('div')
this.inner = document.createElement('div')
cinner.append(this.inner)
this.inner.classList.add('note-plus-preview')
cinner.style.margin = '0'
cinner.style.padding = '0'
this.html_widget = this.addDOMWidget('HTML', 'html', cinner, {
setValue: (val) => {
this._raw_html = val
},
getValue: () => this._raw_html,
getMinHeight: () => this.calculated_height, // (the edit button),
onDraw: () => {
// HACK: dirty hack for now until it's addressed upstream...
this.html_widget.element.style.pointerEvents = 'none'
// NOTE: not sure about this, it avoid the visual "bugs" but scrolling over the wrong area will affect zoom...
// this.html_widget.element.style.overflow = 'scroll'
},
hideOnZoom: false,
})
@@ -197,22 +159,48 @@ class NotePlus extends LiteGraph.LGraphNode {
}
/**
*
* @param {CanvasRenderingContext2D} ctx
* @param {LGraphCanvas} graphcanvas
* @returns
* @param {CanvasRenderingContext2D} ctx canvas context
* @param {any} _graphcanvas
*/
onDrawForeground(ctx, _graphcanvas) {
if (this.flags.collapsed) return
this.drawEditIcon(ctx)
this.drawSideHandle(ctx)
// Define the size and position of the icon
const iconSize = 14 // Size of the icon
const iconMargin = 8 // Margin from the edges
const x = this.size[0] - iconSize - iconMargin
const y = iconMargin * 1.5
// DEBUG BACKGROUND
// ctx.fillStyle = 'rgba(0, 255, 0, 0.3)'
// const rect = this.rect
// ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
}
drawSideHandle(ctx) {
const handleRect = this.sideHandleRect
const chamfer = 20
ctx.beginPath()
// top left
ctx.moveTo(handleRect.x, handleRect.y + chamfer)
// top right
ctx.lineTo(handleRect.x + handleRect.width, handleRect.y)
// bottom right
ctx.lineTo(
handleRect.x + handleRect.width,
handleRect.y + handleRect.height,
)
// bottom left
ctx.lineTo(handleRect.x, handleRect.y + handleRect.height - chamfer)
ctx.closePath()
ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'
ctx.fill()
}
drawEditIcon(ctx) {
const rect = this.iconRect
// DEBUG ICON POSITION
// ctx.fillStyle = 'rgba(0, 255, 0, 0.3)'
// ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
// Create a new Path2D object from SVG path data
const pencilPath = new Path2D(
'M21.28 6.4l-9.54 9.54c-.95.95-3.77 1.39-4.4.76-.63-.63-.2-3.45.75-4.4l9.55-9.55a2.58 2.58 0 1 1 3.64 3.65z',
)
@@ -220,41 +208,73 @@ class NotePlus extends LiteGraph.LGraphNode {
'M11 4H6a4 4 0 0 0-4 4v10a4 4 0 0 0 4 4h11c2.21 0 3-1.8 3-4v-5',
)
// Draw the paths
ctx.save()
ctx.translate(x, y) // Position the icon on the canvas
ctx.scale(iconSize / 32, iconSize / 32) // Scale the icon to the desired size
ctx.strokeStyle = 'rgba(255,255,255,0.3)'
ctx.translate(rect.x, rect.y)
ctx.scale(rect.width / 32, rect.height / 32)
ctx.strokeStyle = 'rgba(255,255,255,0.4)'
ctx.lineCap = 'round'
ctx.lineJoin = 'round'
ctx.lineWidth = 2.4
ctx.stroke(pencilPath)
ctx.stroke(folderPath)
ctx.restore()
}
onMouseDown(_e, localPos, _graphcanvas) {
// Check if the click is within the pencil icon bounds
const iconSize = 14
const iconMargin = 8
const iconX = this.size[0] - iconSize - iconMargin
const iconY = iconMargin * 1.5
if (
localPos[0] > iconX &&
localPos[0] < iconX + iconSize &&
localPos[1] > iconY &&
localPos[1] < iconY + iconSize
) {
// Pencil icon was clicked, open the editor
this.openEditorDialog()
return true // Return true to indicate the event was handled
/**
* @param {number} x
* @param {number} y
* @param {{x:number,y:number,width:number,height:number}} rect
* @returns {}
*/
inRect(x, y, rect) {
rect = rect || this.iconRect
return (
x >= rect.x &&
x <= rect.x + rect.width &&
y >= rect.y &&
y <= rect.y + rect.height
)
}
get rect() {
return {
x: 0,
y: 0,
width: this.size[0],
height: this.size[1],
}
}
get sideHandleRect() {
const w = this.size[0]
const h = this.size[1]
return false // Return false to let the event propagate
const bw = 32
const bho = 64
return {
x: w - bw,
y: bho,
width: bw,
height: h - bho * 1.5,
}
}
get iconRect() {
const iconSize = 32
const iconMargin = 16
return {
x: this.size[0] - iconSize - iconMargin,
y: iconMargin * 1.5,
width: iconSize,
height: iconSize,
}
}
onMouseDown(_e, localPos, _graphcanvas) {
if (this.inRect(localPos[0], localPos[1])) {
this.openEditorDialog()
return true
}
return false
}
/* Hidden widgets to store note+ settings in the workflow (stripped in API)*/
setupSerializationWidgets() {
infoLogger('Setup Serializing widgets')
@@ -283,15 +303,36 @@ class NotePlus extends LiteGraph.LGraphNode {
shared.hideWidgetForGood(this, this.css_widget)
shared.hideWidgetForGood(this, this.theme_widget)
}
setupDialog() {
infoLogger('Setup dialog')
// this.addWidget('button', 'Edit', 'Edit', this.openEditorDialog.bind(this))
this.dialog = new app.ui.dialog.constructor()
this.dialog.element.classList.add('comfy-settings')
Object.assign(this.dialog.element.style, {
position: 'absolute',
boxShadow: 'none',
})
const subcontainer = this.dialog.textElement.parentElement
if (subcontainer) {
Object.assign(subcontainer.style, {
width: '100%',
})
}
const closeButton = this.dialog.element.querySelector('button')
closeButton.textContent = 'CANCEL'
closeButton.id = 'cancel-editor-dialog'
closeButton.title =
"Cancel the changes since last opened (doesn't support live mode)"
closeButton.disabled = this.live
closeButton.style.background = this.live
? 'repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px)'
: ''
const saveButton = document.createElement('button')
saveButton.textContent = 'SAVE'
saveButton.onclick = () => {
@@ -313,32 +354,54 @@ class NotePlus extends LiteGraph.LGraphNode {
closeEditorDialog(accept) {
infoLogger('Closing editor dialog', accept)
if (accept) {
if (accept && !this.live) {
this.updateHTML(this.html_editor.getValue())
this.updateCSS(this.css_editor.getValue())
}
if (this.resizeObserver) {
this.resizeObserver.disconnect()
this.resizeObserver = null
}
this.teardownEditors()
this.dialog.close()
}
/**
* @param {HTMLElement} elem
*/
hookResize(elem) {
if (!this.resizeObserver) {
const observer = () => {
this.html_editor.resize()
this.css_editor.resize()
Object.assign(this.editorsContainer.style, {
minHeight: `${(this.dialog.element.clientHeight / 100) * 50}px`, //'200px',
})
}
this.resizeObserver = new ResizeObserver(observer).observe(elem)
}
}
openEditorDialog() {
infoLogger(`Current edit mode ${this.edit_mode_widget.value}`)
this.hookResize(this.dialog.element)
const container = document.createElement('div')
Object.assign(container.style, {
display: 'flex',
gap: '10px',
flexDirection: 'column',
})
const editorsContainer = document.createElement('div')
Object.assign(editorsContainer.style, {
this.editorsContainer = document.createElement('div')
Object.assign(this.editorsContainer.style, {
display: 'flex',
gap: '10px',
flexDirection: 'row',
minHeight: this.dialog.element.offsetHeight, //'200px',
width: '100%',
})
container.append(editorsContainer)
container.append(this.editorsContainer)
this.dialog.show('')
this.dialog.textElement.append(container)
@@ -346,30 +409,39 @@ class NotePlus extends LiteGraph.LGraphNode {
const aceHTML = document.createElement('div')
aceHTML.id = 'noteplus-html-editor'
Object.assign(aceHTML.style, {
width: '300px',
height: '300px',
// backgroundColor: 'rgb(30,30,30)',
// color: 'whitesmoke',
width: '100%',
height: '100%',
minWidth: '300px',
minHeight: 'inherit',
})
editorsContainer.append(aceHTML)
this.editorsContainer.append(aceHTML)
const aceCSS = document.createElement('div')
aceCSS.id = 'noteplus-css-editor'
Object.assign(aceCSS.style, {
width: '300px',
height: '300px',
// backgroundColor: 'rgb(30,30,30)',
// color: 'whitesmoke',
width: '100%',
height: '100%',
minHeight: 'inherit',
})
editorsContainer.append(aceCSS)
this.editorsContainer.append(aceCSS)
const live_edit = document.createElement('input')
live_edit.type = 'checkbox'
live_edit.checked = this.live
live_edit.onchange = () => {
this.live = live_edit.checked
const cancel_button = this.dialog.element.querySelector(
'#cancel-editor-dialog',
)
if (cancel_button) {
cancel_button.disabled = this.live
cancel_button.style.background = this.live
? 'repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px)'
: ''
}
}
//- "Dynamic" elements
@@ -388,15 +460,14 @@ class NotePlus extends LiteGraph.LGraphNode {
const md = this.html_editor.getValue()
this.edit_mode_widget.value = 'html'
select_mode.value = 'html'
const html = this.markdownConverter.makeHtml(md)
this.html_widget.value = html
this.html_editor.setValue(html)
this.html_editor.session.setMode('ace/mode/html')
this.updateHTML(this.html_widget.value)
convert_to_html.remove()
MTB.mdParser.parse(md).then((content) => {
this.html_widget.value = content
this.html_editor.setValue(content)
this.html_editor.session.setMode('ace/mode/html')
this.updateHTML(this.html_widget.value)
convert_to_html.remove()
})
}
firstButton.before(convert_to_html)
}
} else {
@@ -406,6 +477,19 @@ class NotePlus extends LiteGraph.LGraphNode {
}
}
select_mode.value = this.edit_mode_widget.value
// the header for dragging the dialog
const header = document.createElement('div')
header.style.padding = '8px'
header.style.cursor = 'move'
header.style.backgroundColor = 'rgba(0,0,0,0.5)'
header.style.userSelect = 'none'
header.style.borderBottom = '1px solid #ddd'
header.textContent = 'MTB Note+ Editor'
container.prepend(header)
makeDraggable(this.dialog.element, header)
makeResizable(this.dialog.element)
}
//- combobox
let theme_select = this.dialog.element.querySelector('#theme_select')
@@ -421,7 +505,7 @@ class NotePlus extends LiteGraph.LGraphNode {
option.textContent = label
theme_select.append(option)
}
for (const t of themes) {
for (const t of THEMES) {
addOption(t)
}
@@ -491,54 +575,59 @@ class NotePlus extends LiteGraph.LGraphNode {
onCreate() {
errorLogger('NotePlus onCreate')
}
configure(info) {
super.configure(info)
infoLogger('Restoring serialized values', info)
// - update view from serialzed data
restoreNodeState(info) {
this.html_widget.element.id = `note-plus-${this.uuid}`
this.setMode(this.edit_mode_widget.value)
this.setTheme(this.theme_widget.value)
this.updateHTML(this.html_widget.value)
this.updateCSS(this.css_widget.value)
this.setSize(info.size)
if (info?.size) {
this.setSize(info.size)
}
}
configure(info) {
super.configure(info)
infoLogger('Restoring serialized values', info)
this.restoreNodeState(info)
// - update view from serialzed data
}
onNodeCreated() {
infoLogger('Node created', this.uuid)
this.html_widget.element.id = `note-plus-${this.uuid}`
this.setMode(this.edit_mode_widget.value)
this.setTheme(this.theme_widget.value)
this.updateHTML(this.html_widget.value) // widget is populated here since we called super
this.updateCSS(this.css_widget.value)
this.restoreNodeState({})
// this.html_widget.element.id = `note-plus-${this.uuid}`
// this.setMode(this.edit_mode_widget.value)
// this.setTheme(this.theme_widget.value)
// this.updateHTML(this.html_widget.value) // widget is populated here since we called super
// this.updateCSS(this.css_widget.value)
}
onRemoved() {
infoLogger('Node removed', this.uuid)
}
getExtraMenuOptions() {
const options = []
// {
// content: string;
// callback?: ContextMenuEventListener;
// /** Used as innerHTML for extra child element */
// title?: string;
// disabled?: boolean;
// has_submenu?: boolean;
// submenu?: {
// options: ContextMenuItem[];
// } & IContextMenuOptions;
// className?: string;
// }
options.push({
content: `Set to ${
this.edit_mode_widget.value === 'html' ? 'markdown' : 'html'
}`,
callback: () => {
this.edit_mode_widget.value =
this.edit_mode_widget.value === 'html' ? 'markdown' : 'html'
this.updateHTML(this.html_widget.value)
},
})
const currentMode = this.edit_mode_widget.value
const newMode = currentMode === 'html' ? 'markdown' : 'html'
return options
const debugItems = window.MTB?.DEBUG
? [
{
content: 'Replace with demo content (debug)',
callback: () => {
this.html_widget.value = DEMO_CONTENT
},
},
]
: []
return [
...debugItems,
{
content: `Set to ${newMode}`,
callback: () => {
this.edit_mode_widget.value = newMode
this.updateHTML(this.html_widget.value)
},
},
]
}
_setupEditor(editor) {
@@ -663,17 +752,44 @@ class NotePlus extends LiteGraph.LGraphNode {
// this.setSize(this.computeSize())
}
updateHTML(val) {
const cleanHTML = DOMPurify.sanitize(val, { ADD_TAGS: ['iframe'] })
this.html_widget.value = cleanHTML
parserInitiated() {
if (window.MTB?.mdParser) return true
return false
}
// update our widget preview
if (this.edit_mode_widget.value === 'html') {
this.html_widget.element.innerHTML = cleanHTML
} else if (this.edit_mode_widget.value === 'markdown') {
this.html_widget.element.innerHTML =
this.markdownConverter.makeHtml(cleanHTML)
/** to easilty swap purification methods*/
purify(content) {
return DOMPurify.sanitize(content, {
ADD_TAGS: ['iframe', 'detail', 'summary'],
})
}
updateHTML(val) {
if (!this.parserInitiated()) {
return
}
val = val || this.html_widget.value
const isHTML = this.edit_mode_widget.value === 'html'
const cleanHTML = this.purify(val)
const value = isHTML
? cleanHTML
: cleanHTML.replaceAll('&gt;', '>').replaceAll('&lt;', '<')
// .replaceAll('&amp;', '&')
// .replaceAll('&quot;', '"')
// .replaceAll('&#039;', "'")
this.html_widget.value = value
if (isHTML) {
this.inner.innerHTML = value
} else {
MTB.mdParser.parse(value).then((e) => {
this.inner.innerHTML = e
})
}
// this.html_widget.element.innerHTML = `<div id="note-plus-spacer"></div>${value}`
this.calculateHeight()
// this.setSize(this.computeSize())
}
@@ -681,6 +797,27 @@ class NotePlus extends LiteGraph.LGraphNode {
app.registerExtension({
name: 'mtb.noteplus',
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.noteplus.use-shiki',
category: ['mtb', 'Note+', 'use-shiki'],
name: 'Use shiki to highlight code',
tooltip:
'This will load a larger version of @mtb/markdown-parser that bundles shiki, it supports all shiki transformers (supported langs: html,css,python,markdown)',
type: 'boolean',
defaultValue: false,
attrs: {
style: {
// fontFamily: 'monospace',
},
},
async onChange(value) {
storage.set('np-use-shiki', value)
useShiki = value
},
})
},
registerCustomNodes() {
LiteGraph.registerNodeType('Note Plus (mtb)', NotePlus)
+334
View File
@@ -0,0 +1,334 @@
// This is a vanillajs implementation of Houdini's number input widgets.
// It basically popup a visual sensitivity slider of steps to use as incr/decr
// TODO: Convert it to IWidget
// import styles from "./style.module.css";
function getValidNumber(numberInput) {
let num =
isNaN(numberInput.value) || numberInput.value === ''
? 0
: parseFloat(numberInput.value)
return num
}
/**
* Number input widgets
*/
export class NumberInputWidget {
constructor(containerId, numberOfInputs = 1, isDebug = false) {
this.container = document.getElementById(containerId)
this.numberOfInputs = numberOfInputs
this.currentInput = null // Store the currently active input
this.threshold = 30
this.mouseSensitivityMultiplier = 0.05
this.debug = isDebug
//- states
this.initialMouseX
this.lastMouseX
this.activeStep = 1
this.accumulatedDelta = 0
this.stepLocked = false
this.thresholdExceeded = false
this.isDragging = false
const styleTagId = 'mtb-constant-style'
let styleTag = document.head.querySelector(`#${styleTagId}`)
if (!styleTag) {
styleTag = document.createElement('style')
styleTag.type = 'text/css'
styleTag.id = styleTagId
styleTag.innerHTML = `
.${containerId}{
margin-top: 20px;
margin-bottom: 20px;
}
.sensitivity-menu {
display: none;
position: absolute;
/* Additional styling */
}
.sensitivity-menu .step {
cursor: pointer;
padding: 0.5em;
/* Add more styling as needed */
}
.sensitivity-menu {
font-family: monospace;
background: var(--bg-color);
border: 1px solid var(--fg-color);
/* Highlight for the active step */
}
.number-input {
background: var(--bg-color);
color: var(--fg-color)
}
.sensitivity-menu .step.active {
background-color:var(--drag-text);
/* Highlight for the active step */
}
.sensitivity-menu .step.locked {
background-color: #f00;
/* Change to your preferred color for the locked state */
}
#debug-container {
transform: translateX(50%);
width: 50%;
text-align: center;
font-family: monospace;
}
`
document.head.appendChild(styleTag)
}
this.createWidgetElements()
this.initializeEventListeners()
}
setLabel(str) {
this.label.textContent = str
}
setValue(...values) {
if (values.length !== this.numberInputs.length) {
console.error('Number of values does not match the number of inputs.')
console.error(
`You provided ${values.length} but the input want ${this.numberInputs.length}`,
{ values },
)
return
}
// Set each input value
this.numberInputs.forEach((input, index) => {
input.value = values[index]
})
}
getValue() {
const value = []
this.numberInputs.forEach((input, index) => {
value.push(Number.parseFloat(input.value) || 0.0)
})
return value
}
resetValues() {
for (const input of numberInputs) {
input.value = 0
}
this.onChange?.(this.getValue())
}
createWidgetElements() {
this.label = document.createElement('label')
this.label.textContent = 'Control All:'
this.label.className = 'widget-label'
this.container.appendChild(this.label)
this.label.addEventListener('mousedown', (event) => {
if (event.button === 1) {
this.currentInput = null
this.handleMouseDown(event)
}
})
this.label.addEventListener('contextmenu', (event) => {
event.preventDefault()
this.resetValues()
})
this.numberInputs = []
// create linked inputs
for (let i = 0; i < this.numberOfInputs; i++) {
const numberInput = document.createElement('input')
numberInput.type = 'number'
numberInput.className = 'number-input' //styles.numberInput; //"number-input";
numberInput.step = 'any'
this.container.appendChild(numberInput)
this.numberInputs.push(numberInput)
numberInput.addEventListener('mousedown', (event) => {
if (event.button === 1) {
this.currentInput = numberInput
this.handleMouseDown(event)
}
})
}
this.sensitivityMenu = document.createElement('div')
this.sensitivityMenu.className = 'sensitivity-menu' //styles.sensitivityMenu; //"sensitivity-menu";
this.container.appendChild(this.sensitivityMenu)
// create steps
const stepsValues = [0.001, 0.01, 0.1, 1, 10, 100]
stepsValues.forEach((value) => {
const step = document.createElement('div')
step.className = 'step' //styles.step //"step";
step.dataset.step = value
step.textContent = value.toString()
this.sensitivityMenu.appendChild(step)
})
this.steps = this.sensitivityMenu.getElementsByClassName('step') //styles.step)
if (this.debug) {
this.debugContainer = document.createElement('div')
this.debugContainer.id = 'debug-container' //styles.debugContainer //"debugContainer";
document.body.appendChild(this.debugContainer)
}
}
showSensitivityMenu(pageX, pageY) {
this.sensitivityMenu.style.display = 'block'
this.sensitivityMenu.style.left = `${pageX}px`
this.sensitivityMenu.style.top = `${pageY}px`
this.initialMouseX = pageX
this.lastMouseX = pageX
this.isDragging = true
this.thresholdExceeded = false
this.stepLocked = false
this.updateDebugInfo()
}
updateDebugInfo() {
if (this.debug) {
this.debugContainer.innerHTML = `
<div>Active Step: ${this.activeStep}</div>
<div>Initial Mouse X: ${this.initialMouseX}</div>
<div>Last Mouse X: ${this.lastMouseX}</div>
<div>Accumulated Delta: ${this.accumulatedDelta}</div>
<div>Threshold Exceeded: ${this.thresholdExceeded}</div>
<div>Step Locked: ${this.stepLocked}</div>
<div>Number Input Value: ${this.currentInput?.value}</div>
`
}
}
handleMouseDown(event) {
if (event.button === 1) {
this.showSensitivityMenu(
event.target.offsetWidth,
event.target.offsetHeight,
)
event.preventDefault()
}
}
handleMouseUp(event) {
if (event.button === 1) {
this.resetWidgetState()
}
}
handleClickOutside(event) {
if (event.target !== this.numberInput) {
this.resetWidgetState()
}
}
handleMouseMove(event) {
if (this.sensitivityMenu.style.display === 'block') {
const relativeY = event.pageY - 300 // this.sensitivityMenu.offsetTop
const horizontalDistanceFromInitial = Math.abs(
event.target.offsetWidth - this.initialMouseX,
)
// Unlock if the mouse moves back towards the initial position
if (horizontalDistanceFromInitial < this.threshold) {
this.thresholdExceeded = false
this.stepLocked = false
this.accumulatedDelta = 0
}
// Update step only if it is not locked
if (!this.stepLocked) {
for (let step of this.steps) {
step.classList.remove('active') //styles.active)
step.classList.remove('locked') //styles.locked)
if (
relativeY >= step.offsetTop &&
relativeY <= step.offsetTop + step.offsetHeight
) {
step.classList.add('active') //styles.active)
this.setActiveStep(parseFloat(step.dataset.step))
}
}
}
if (this.stepLocked) {
this.sensitivityMenu
.querySelector('.step.active')
?.classList.add('locked')
}
this.updateStepValue(event.pageX)
}
}
initializeEventListeners() {
document.addEventListener('mousemove', (event) =>
this.handleMouseMove(event),
)
document.addEventListener('mouseup', (event) => this.handleMouseUp(event))
document.addEventListener('click', (event) =>
this.handleClickOutside(event),
)
}
setActiveStep(val) {
if (this.activeStep !== val) {
this.activeStep = val
this.stepLocked = false
this.accumulatedDelta = 0
this.thresholdExceeded = false
}
}
resetWidgetState() {
this.sensitivityMenu.style.display = 'none'
this.isDragging = false
this.lastMouseX = undefined
this.thresholdExceeded = false
this.stepLocked = false
this.updateDebugInfo()
}
updateStepValue(mouseX) {
if (this.isDragging && this.lastMouseX !== undefined) {
const deltaX = mouseX - this.lastMouseX
this.accumulatedDelta += deltaX
if (
!this.thresholdExceeded &&
Math.abs(this.accumulatedDelta) > this.threshold
) {
this.thresholdExceeded = true
this.stepLocked = true
}
if (this.thresholdExceeded && this.stepLocked) {
// frequency of value changes
if (
Math.abs(this.accumulatedDelta) * this.mouseSensitivityMultiplier >=
1
) {
const valueChange = Math.sign(this.accumulatedDelta) * this.activeStep
if (this.currentInput) {
this.currentInput.value =
getValidNumber(this.currentInput) + valueChange
this.onChange?.(this.getValue())
} else {
this.numberInputs.forEach((input) => {
input.value = getValidNumber(input) + valueChange
})
}
this.accumulatedDelta = 0
}
}
this.lastMouseX = mouseX
}
this.updateDebugInfo()
}
}
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
Submodule wiki updated: a3327c786b...a402de4af9