Compare commits

...
162 Commits
Author SHA1 Message Date
melMass 49c64c74eb ci: 💄 encoding 2023-08-13 00:15:12 +02:00
Mel Massadian 2ecd4700d7 merge: 🔀 pull request #50 from melMass/dev/august-refactor 2023-08-12 23:56:08 +02:00
melMass ea5d73d48c fix: 🚀 pending fixes
should be ready to go
2023-08-12 23:53:53 +02:00
melMass 30d6cfe812 fix: 🚑️ image resize infinite loop 2023-08-12 23:41:58 +02:00
melMass 610afe031f fix: ✨ update example files 2023-08-12 23:41:24 +02:00
melMass a4d99d966b feat: 💫 export to prores -> export with ffmpeg 2023-08-12 00:35:02 +02:00
melMass 4fc84d615d fix: 🐛 simplify install steps 2023-08-12 00:11:54 +02:00
melMass 8523392df7 fix: ✨ refactor 2023-08-11 22:22:07 +02:00
melMass dbdb872b74 feat: 🔥 add any to string & refactor 2023-08-10 23:31:46 +02:00
melMass 40560f8154 fix: 🐛 debug rgba 2023-08-10 23:22:05 +02:00
melMass e7f72f9825 fix: 🎨 rename fun to generate 2023-08-10 22:58:12 +02:00
melMass 11444662b9 fix: ✨ refactor existing 2023-08-10 22:54:19 +02:00
melMass 2eccba4e33 fix: ⚡️ move getbatchfromhistory to graphutils
Fixes #59
2023-08-10 16:34:36 +02:00
melMass 5ec5511433 feat: ✨ add UI for interpolate clip sequential 2023-08-09 21:59:46 +02:00
melMass 630b492347 fix: 🚧 wip dependency installer UI
Will allow to install missing deps/models from the endpoint:
/mtb/status
2023-08-09 14:33:58 +02:00
melMass 4f30829e06 refactor: 🚧 tidy 2023-08-08 23:16:29 +02:00
Mel Massadian 414beb99a1 ci: 🚀 only fetch controlnet_preprocessor deps
A true install seems to requires CUDA, I can probably change the image too.
2023-08-08 22:40:53 +02:00
melMass 3f14b1676d feat: ✨ add portable reqs 2023-08-08 21:29:28 +02:00
melMass 9c2e8ac57c Merge branch 'main' into dev/august-refactor 2023-08-08 18:10:39 +02:00
melMass 4dd5321852 fix: ⬇️ download_antelopev2
the url used in insightface returns 404.
fixes #55
2023-08-07 23:53:34 +02:00
melMass 91f60d4c46 fix: 🚑️ frontend pushed too early
Since I mistakenly pushed some js code from a PR
some nodes weren't working anymore...

This fix that and the model path for face_restore nodes
if installed using the manager, with a fallback for now..
2023-08-07 21:24:23 +02:00
melMass fb644847ca feat: ✨ add border extension
The maths are still not correct I need to debug it in isolation
2023-08-07 20:49:47 +02:00
Mel Massadian 84ac8ac852 fix: 🚑️ missing input 2023-08-07 02:59:16 +02:00
Mel Massadian 63b3aece2b ci: 🚀 add controlnetpreprocessors to tests 2023-08-07 00:39:32 +02:00
Mel Massadian a54d7d5346 feat: 🎨 update node list 2023-08-06 00:34:42 +02:00
melMass 13d255a730 refactor: ♻️ get batch from history 2023-08-05 13:31:54 +02:00
melMass 2bc7ae88bf feat: ✨ use PIL for gif saving 2023-08-05 13:31:30 +02:00
melMass 0fb2d4da90 fix: 🐛 image feed zorder 2023-08-05 13:28:01 +02:00
melMass cfb3b237cf revertible: 💄 use BOOLEAN instead of BOOL
Since this commit:
https://github.com/comfyanonymous/ComfyUI/commit/9534f0f8a5a026654492da378f84d2cdc589ed01

Input <-> widget is possible on booleans.
Locally I edited it but forgot about it not being in comfy

This commit is reversable since I'm not yet sure of all the impacts
2023-08-05 13:08:18 +02:00
melMass 3d5075fea2 fix: 🐛 shell command bug
Since we always build a string shell should always be true
2023-08-04 14:44:52 +02:00
Mel Massadian 098d74a3cd docs: 📝 link the actual action instead of badge 2023-08-03 14:33:15 +02:00
Mel Massadian e74314b04e docs: 📝 add action badge 2023-08-03 14:28:38 +02:00
Mel Massadian d4f791d7a1 ci: ✨ remove unused input 2023-08-03 14:26:02 +02:00
Mel Massadian 2ff04672da ci: ✨ use the same cwd as manager 2023-08-03 14:22:26 +02:00
melMass b854a302ce fix: 🚑️ remove pipe mode from the install.py
I added a `path` argument to mimic what pipe did.
2023-08-03 13:12:56 +02:00
Mel Massadian 512de6023e feat: ✨ install fix
- removed un-needed dependencies
- added a ci to test comfy-embedded
- fixed wheel order install
2023-08-01 03:24:27 +02:00
Mel Massadian c5bbe83008 test: 🧪 remove sha input 2023-07-31 18:57:41 +02:00
Mel Massadian 7b3afca817 test: 🧪 ci for comfy embedded 2023-07-31 18:50:51 +02:00
Mel Massadian bbfcb62c39 ci: 🎨 no brace glob 2023-07-30 18:09:24 +02:00
Mel Massadian a22fd01d66 ci: 🎨 extract txt 2023-07-30 18:06:34 +02:00
Mel Massadian 8e5b7765cc ci: 🎨 also push wheels_order to releases
I will use it directly from the installer
2023-07-30 17:56:39 +02:00
melMass 36d8e6bdb0 fix: ⚡️ colab install 2023-07-30 02:55:06 +02:00
melMass 3dadc119f4 chore: 🚧 more info for bug reports 2023-07-30 02:16:12 +02:00
melMass ffa1a87b91 fix: 🚑️ install typo 2023-07-30 02:06:41 +02:00
melMass 346ff649d5 ci: ✨ individual wheels 2023-07-30 01:41:14 +02:00
Mel Massadian 247fbfbc21 fix: 🔥 manage pip from install only, remove requirements.txt (#38) 2023-07-30 01:20:05 +02:00
melMass 9b24eddd9c chore: ✨ use wheel order if present 2023-07-29 00:55:10 +02:00
melMass 505314294f ci: ✨ store order of install for wheels 2023-07-29 00:25:24 +02:00
melMass f5cd56ce86 fix: 🎨 use image ratio for imagefeed 2023-07-28 22:14:22 +02:00
Mel Massadian cbcacbe3c9 docs: 📝 update imagefeed preview 2023-07-28 22:12:43 +02:00
Mel Massadian 7c020bab28 docs: 📝 fix typo and add more details 2023-07-28 21:33:39 +02:00
melMass 9e751a242f chore: 🎉 bump version 2023-07-28 20:54:44 +02:00
melMass 0e311cf2c6 fix: ✨ various small things
- removed border on imagefeed images.
- don't load mtb.imageFeed if the user has pythongoss's version already.
- fix the promptserver issue when importing mtb from a jupyter notebook
- fix: if the user doesn't have the facemodels downloaded it would crash
- added an internal counter to batchfromhistory to invalidate it at each
  frame, which might not be a good idea.
2023-07-28 20:47:27 +02:00
Mel Massadian 889f08c08b fix: 📝 last release (#36) 2023-07-28 20:26:37 +02:00
Mel Massadian 5d661b2509 fix: 📝 narrow requirements
The protobuf issue is only valid on windows as we must use the old
TF lib to get usable speeds for FILM interpolation. WSL, windows and mac don't need that trick.

Fixes #28
2023-07-27 01:30:13 +02:00
Mel Massadian be162a2047 docs: 📝 add readme for web extensions features 2023-07-25 15:20:57 +02:00
Doug White 4ea26ed8de Fix unclickable image gallery buttons in Firefox (#34) 2023-07-25 12:03:32 +02:00
melMass c237737420 chore: 👷 remove stale example 2023-07-25 02:30:37 +02:00
Mel Massadian 232cf8966c docs: 📝 link to the proper lang instructions (#33) 2023-07-25 02:05:57 +02:00
melMass 96a0618c59 docs: 📝 update readmes 2023-07-25 00:43:21 +02:00
melMass d143e83dba fix: ✨ Separate FaceAnalysis model loading
This closes #19

It is indeed much faster.
2023-07-25 00:29:39 +02:00
melMass 3dfe98c795 fix: ⚡️ update examples to match wiki 2023-07-24 23:43:02 +02:00
melMass c0cc5572d8 ci: 🐛 fix size
it was ignoring the last line, I also ignore the git folder itself
2023-07-24 22:24:38 +02:00
Mel Massadian 8695cd3f1b merge: 🔀 pull request #32 from melMass/dev/next 2023-07-24 21:56:21 +02:00
melMass cf865529ab chore: 🚀 bump version 2023-07-24 21:53:36 +02:00
melMass 3b9190a69b ci: 🚀 Remove large files from release
following @WASasquatch advice
2023-07-24 21:46:44 +02:00
melMass 9a4eda3ef5 feat: 🚧 jupyter seems to require an __init__ there 2023-07-24 21:43:55 +02:00
melMass a2ecc11ebd feat: ⚡️ use notify
and push wip examples
2023-07-24 21:42:37 +02:00
melMass 7e9c97ecb4 feat: ✨ first version of Notify
This is a very simple toast notification system that I will start to
use where it makes sense. It's completely standalone and can be used
by adding it to web/extensions and then calling windows.MTB.notify(),
it even works in the console
2023-07-24 20:34:07 +02:00
melMass 3de160af25 feat: ⚡️ add an "actions" endpoint 2023-07-24 20:25:53 +02:00
melMass 3801a443bc refactor: ✨ cleaned up frontend code a bit 2023-07-24 20:20:26 +02:00
Mel Massadian bbdac97e49 docs: 📝 added lang links 2023-07-24 17:43:44 +02:00
melMass 50d51c70d0 fix: 🎨 improve a bit the HTML response of endpoints 2023-07-23 17:11:09 +02:00
melMass 55c9736a9b fix: 🐛 caching issues
Fonts and styles where searched for each rerun.
This makes it require a restart to update either but it's not a big deal
in these cases IMO.
thanks to @ltdrdata for finding this issue!
2023-07-23 16:43:25 +02:00
melMass 21729b2784 refactor: ⚡️ remove empty inits 2023-07-23 15:13:46 +02:00
melMass 8d3cc39b72 feat: ✨ add Unsplash Image node 2023-07-23 04:50:56 +02:00
melMass abf1e82adb fix: 🔥 remove notice
we don't use this anymore
2023-07-23 03:13:54 +02:00
melMass 10d05031b1 docs: 📝 add comfyforum example
Shows a lot of the new nodes but require ComfyUI-Workflow-Component
2023-07-23 01:21:20 +02:00
melMass 7142b284ad feat: ✨ add back Save Tensors 2023-07-23 01:20:06 +02:00
melMass 11128ff85a feat: ✨ add TransformImage node 2023-07-23 01:19:19 +02:00
melMass a393793cfa fix: 🔥 use BOOL everywhere 2023-07-22 20:09:31 +02:00
Mel Massadian 119b4d6e16 fix: 🔥 properly match built wheels 2023-07-22 19:07:56 +02:00
Mel Massadian c34de0ab35 merge: 🔀 pull request #22 from melMass/dev/next-release 2023-07-22 18:43:24 +02:00
melMass 7be37dbbfa feat: ✨ update install instructions 2023-07-22 18:41:59 +02:00
melMass 0df55def29 fix: ✨ also try to copy web if symlink fails 2023-07-22 18:19:32 +02:00
melMass b40730ddbc fix: ✨ install process tested in comfy-manager (embed, colab) 2023-07-22 18:02:49 +02:00
melMass 3c66de2500 fix: 🚀 try to support remote install too 2023-07-22 06:10:17 +02:00
melMass ee17d57c3d test: 🔧 pipe detection 2023-07-22 05:04:34 +02:00
melMass 7335003346 fix: 💄 save gif issues 2023-07-22 04:56:10 +02:00
melMass fccf313489 fix: 🚑️ always use latest for now
more simple, also double check deps there, it's not a big deal
and should solve issues, tested in colab
2023-07-22 04:02:36 +02:00
melMass 7e301e2a06 fix: 🐛 install logic 2023-07-22 03:45:05 +02:00
melMass dad3966ba2 feat: 🚀 add install script
still needs testing
2023-07-22 03:25:42 +02:00
melMass 4e6b877199 fix: 🎉 remove tests & add missing docs 2023-07-22 01:29:58 +02:00
melMass c794d6a071 fix: ⚡️ update node_list
cc @ltdrdata 👀
2023-07-22 01:27:40 +02:00
melMass 18402e3be1 fix: 🚑️ set debug level from endpoint 2023-07-22 01:22:24 +02:00
melMass 4d8ddaca32 refactor: ♻️ removes a few nodes, moved other around 2023-07-22 01:21:46 +02:00
melMass 0950f9914c fix: 🐛 add base64 prefix to outputs
For now I'm using the DEBUG_IMG widget for both Debug and Save Gif.
This is done using a DOM element, using the core ui.images freezes the
image.
2023-07-22 01:19:28 +02:00
melMass c2e83794fa fix: 🎨 refactor and add Gif preview on node 2023-07-22 01:17:54 +02:00
melMass 68c250e890 refactor: ♻️ remove test 2023-07-22 00:21:28 +02:00
melMass 44eaae5c79 feat: 🚧 add my CLIs
just convenience tools, not exposed but usable from CI etc...
still need some work.
2023-07-22 00:12:13 +02:00
melMass 27500ca432 fix: ✨ Various widgets issues
major thanks to @pythongosssss, for his past work and help on this.
Still needs some cleanup
2023-07-21 23:44:47 +02:00
melMass 9aa934f70f fix: 🔥 deprecate some nodes and fix image list 2023-07-21 23:43:46 +02:00
melMass 91bb95da91 feat: ✨comfy_widget shared utils 2023-07-21 23:40:51 +02:00
melMass e480d07117 refactor: 🚧 remove color_widget
Widgets registration will be done in a single extension
2023-07-21 23:40:08 +02:00
melMass b27b8ef91f feat: 🚀 debug node
Still needs some work, especially in widget drawing, but already
useful as is, so it will do for now
2023-07-21 23:39:20 +02:00
melMass 67d3783ac9 fix: 🐛 crop nodes 2023-07-21 23:38:19 +02:00
melMass 8a59508ff9 fix: 🐛 tensor2pil 2023-07-21 23:37:12 +02:00
melMass aa551ebe57 feat: ✨ add FitNumber node
quite useful in conjunction to AnimationBuilder
2023-07-21 23:36:37 +02:00
melMass 95afbdbf76 feat: 🔥 add API endpoints 2023-07-21 16:33:46 +02:00
melMass d2b396236a feat: ✨ categorize
They now all live under mtb/ in the node creation context menu.
2023-07-20 00:26:34 +02:00
melMass 0cc54e58ec chore: ✨ before categorize 2023-07-20 00:00:22 +02:00
Mel Massadian 3c3c4380bd docs: 📝 fold each comfy mode 2023-07-18 21:40:26 +02:00
Mel Massadian 46eab5ca2f docs: 📝 add more description to examples 2023-07-18 21:30:42 +02:00
Mel Massadian cbe67edd4b docs: 📝 add model notice 2023-07-18 03:58:38 +02:00
Mel Massadian b5176ca0ee docs: 📝 add preview for examples 2023-07-18 03:56:17 +02:00
melMass b9c1d3df7a feat: 🚀 add a few examples 2023-07-18 03:37:30 +02:00
melMass ab09ccadd9 fix: ⚡️ a few missing __doc__ 2023-07-18 03:13:32 +02:00
melMass 5f5297f80d feat: ✨ added a way to export the node list
This is still wip to see what could fit ComfyUI-manager
2023-07-18 03:08:52 +02:00
melMass 6168b3a2ac fix: ⚡️ from tensor2np always returning a list 2023-07-17 22:52:25 +02:00
melMass 69e59ba798 Merge branch 'main' into dev/next-release 2023-07-16 23:43:51 +02:00
melMass cde72938d5 feat: ✨ WIP batch from history
Barely tested, and not much safe guards (I need to analyze more
history sessions first, but the basic idea is there)
2023-07-16 23:42:45 +02:00
melMass 38f61473bc feat: ✨ extract node names using ast
In case a file can't be loaded this still allow to get the expected
nodes that would be loaded
2023-07-16 23:41:36 +02:00
Mel Massadian 710a638a81 chore: ✨ add more issue templates (#25) 2023-07-16 23:36:42 +02:00
Mel Massadian f927bc7c9a chore: ✨ add bug report template 2023-07-16 23:30:30 +02:00
melMass da559b9eaf docs: 📝 add jp and cn (using deep translation) 2023-07-16 20:49:16 +02:00
Mel Massadian f634fe0e6b chore: 🍻 create FUNDING.yml 2023-07-16 18:18:39 +02:00
Mel Massadian cd1b603565 chore: 🍻 add bmc to readme 2023-07-16 17:06:12 +02:00
melMass 3faadc4b8a feat: 🔥 add batch support for load image sequence 2023-07-15 03:04:32 +02:00
melMass 629e2b5f5f feat: 🎨 add support for image.size(0) == 0
Attempt at ignoring a branch if the image size is 0.
2023-07-15 00:39:15 +02:00
melMass c225da5f29 fix: 🚑️ TF by default fills vram
This was causing all kind of issues
2023-07-15 00:33:22 +02:00
Mel Massadian b0fb5222cb docs: 📝 update readme (#15) 2023-07-09 18:04:01 +02:00
melMass da3e6f47c6 fix: ✨ leftovers
- Removed ifnude (nsfw detection)
- Cleaned some imports

Should help #14
2023-07-09 14:11:14 +02:00
melMass 95797e823e fix: ✨ handle non fork gdown in model dll
Also fix a dumb mistake from earlier tests..
2023-07-08 01:43:56 +02:00
Mel Massadian 1e28606427 merge: 🎉 pull request #11 from dev/frame_interpolation 2023-07-07 14:54:44 +02:00
melMass b78be8fd3c chore: 📝 extra files from another branch
Docker branch
2023-07-07 14:27:49 +02:00
melMass 00510ed0b8 fix: ✨ properly add the submodules 2023-07-07 14:24:51 +02:00
melMass 1622cbcb9d fix: 📌 remove sad talker for now
Something went wrong with submodules
2023-07-07 14:22:40 +02:00
melMass 2b16d7f893 Merge branch 'main' into dev/frame_interpolation 2023-07-06 22:44:40 +02:00
melMass 99eb5ae0c7 feat: ✨ image feed
forked from @pythongosssss with a few changes:
- a light box
- a way to load history images (i.e current session images)
2023-07-06 22:44:20 +02:00
melMass 1a92ef734d fix: 🎨 narrow requirements
Pip was backtracking 100 versions of tb-build in comfy-embed..
This fixes that
2023-07-06 22:37:37 +02:00
melMass 9752f3e9de fix: 🚀 use the comfy util to handle graph interruption 2023-07-06 20:45:44 +02:00
melMass 2f455aaca5 fix: 🔥 much faster (using GPU) on windows
Linux should already work fine
2023-07-06 20:24:05 +02:00
melMass be5a655cfa fix: 🐛 uint8 to uint16 2023-07-06 17:52:27 +02:00
melMass e04e77eb09 feat: ✨ FILM interpolation nodes 2023-07-06 17:45:16 +02:00
Mel Massadian 7585624de5 merge: 🎉 pull request #8 from dev/small-fixes
- adds `Restore Face node`
2023-07-06 00:21:51 +02:00
melMass b779bc39ac fix: ✨ add missing requirements
tested in python-embed mode too
2023-07-06 00:19:18 +02:00
melMass 4c41fe7af9 chore: 🚀 push leftovers
this PR is mostly done
2023-07-06 00:11:52 +02:00
melMass 7fd99c25c4 fix: 📝 don't propagate base logs 2023-07-05 21:10:18 +02:00
melMass fee48adff3 fix: 🐛 bg upscaler in gfpgan
I was just not returning from tensor2np 🦀☠️
2023-07-05 21:09:00 +02:00
melMass 2e592d5566 Merge branch 'main' into dev/small-fixes 2023-07-05 17:24:16 +02:00
melMass 217e8a1546 feat: ✨ add an headless option for model downloads
This should help with #9, i.e Google Colab mode
2023-07-05 17:03:07 +02:00
melMass 8ef48a013a feat: 🐛 support batch count > 1 for restore face 2023-07-04 01:30:52 +02:00
melMass 88cdcc6a87 feat: 🚧 wrapper for GFPGAN bg upscaler
this hooks into comfy's core upscaler model loader.
It seems to work, as in it doesn't fail but it's not producing the
proper results.
2023-07-04 00:38:33 +02:00
melMass e24863d1f9 fix: 📝 separate debug / info better 2023-07-03 02:04:06 +02:00
melMass 7538c2c4ba fix: 🔥 change log level of the base logger
fixes #6
2023-07-03 01:46:25 +02:00
melMass 3a6e545050 feat: ✨ add GFPGAN (FaceRestore) 2023-07-03 01:45:34 +02:00
melMass 6ef308a870 fix: ✨ handle externs dynamicly 2023-07-03 01:07:00 +02:00
melMass 8e267c0204 fix: 🐛 separate faceswap model load
closes #5
2023-07-02 21:13:00 +02:00
Mel Massadian f8dc768635 docs: 📝 update README.md
add instructions in case #2 happens
2023-06-29 15:09:27 +02:00
melMass d982b69a58 install: 🚧 handle symlink errors
should fix #2
2023-06-29 11:10:12 +02:00
melMass c3b9fd4afe docs: 📝 updated instructions 2023-06-29 00:08:59 +02:00
Mel Massadian e4e6415018 Update README.md 2023-06-28 23:58:26 +02:00
70 changed files with 9466 additions and 1008 deletions
+34
View File
@@ -0,0 +1,34 @@
# Include any files or directories that you don't want to be copied to your
# container here (e.g., local build artifacts, temporary files, etc.).
#
# For more help, visit the .dockerignore file reference guide at
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
**/.DS_Store
**/__pycache__
**/.venv
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/bin
**/charts
**/docker-compose*
**/compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
+5
View File
@@ -0,0 +1,5 @@
* @melMass
extern/GFPGAN/* @TencentARC
extern/SadTalker/* @OpenTalker
nodes/deep_bump.py @HugoTini
web/imageFeed.js @pythongosssss @melMass
+14
View File
@@ -0,0 +1,14 @@
# These are supported funding model platforms
github: [melMass]
custom: ["https://www.buymeacoffee.com/melmass"]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
+67
View File
@@ -0,0 +1,67 @@
name: 🐞 Bug Report
title: "[bug] "
description: Report a bug
labels: ["type: 🐛 bug", "status: 🧹 needs triage"]
body:
- type: markdown
attributes:
value: |
## Before submiting an issue
- Make sure to read the README & INSTALL instructions.
- Please search for [existing issues](https://github.com/melMass/comfy_mtb/issues?q=is%3Aissue) around your problem before filing a report.
### Try using the debug mode to get more info
If you use the env variable `MTB_DEBUG=true`, debug message from the extension will appear in the terminal.
- type: textarea
id: description
attributes:
label: Describe the bug
description: A clear description of what the bug is. Include screenshots if applicable.
placeholder: Bug description
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: Reproduction
description: Steps to reproduce the behavior.
placeholder: |
1. Add node xxx ...
2. Connect to xxx ...
3. See error
- type: textarea
id: expected-behavior
attributes:
label: Expected behavior
description: A clear description of what you expected to happen.
- type: textarea
id: info
attributes:
label: Platform and versions
description: "informations about the environment you run Comfy in"
render: sh
placeholder: |
- OS: [e.g. Linux]
- Comfy Mode [e.g. custom env, standalone, google colab]
validations:
required: true
- type: textarea
id: logs
attributes:
label: Console output
description: Paste the console output without backticks
render: sh
- type: textarea
id: context
attributes:
label: Additional context
description: Add any other context about the problem here.
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
@@ -0,0 +1,35 @@
name: 💡 Feature Request
title: "[feat] "
description: Suggest an idea
labels: ["type: 🤚 feature request"]
body:
- type: textarea
id: problem
attributes:
label: Describe the problem
description: A clear description of the problem this feature would solve
placeholder: "I'm always frustrated when..."
validations:
required: true
- type: textarea
id: solution
attributes:
label: "Describe the solution you'd like"
description: A clear description of what change you would like
placeholder: "I would like to..."
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: "Any alternative solutions you've considered"
- type: textarea
id: context
attributes:
label: Additional context
description: Add any other context about the problem here.
+11 -6
View File
@@ -27,17 +27,15 @@ jobs:
steps:
- name: ♻️ Checking out the repository
uses: actions/checkout@v3
- name: "🐍 Setting up Python"
- name: '🐍 Setting up Python'
uses: actions/setup-python@v4
with:
python-version: "3.10.9"
python-version: '3.10.9'
- name: 📦 Building and Bundling wheels
shell: bash
run: |
python -m pip wheel --no-cache-dir -r requirements-wheels.txt -w ./wheels > build.log
cat build.log
python -m pip wheel --no-cache-dir -r reqs.txt -w ./wheels 2>&1 | tee build.log
# find source wheels
packages=$(cat build.log | awk -F 'Building wheels for collected packages: ' '{print $2}')
@@ -45,6 +43,13 @@ jobs:
IFS=', ' read -r -a package_array <<< "$packages"
# Save reversed package_array to wheel_order.txt
reversed_array=()
for ((idx=${#package_array[@]}-1; idx>=0; idx--)); do
reversed_array+=("${package_array[idx]}")
done
printf '%s\n' "${reversed_array[@]}" > ./wheels/wheel_order.txt
printf "Autodetect this source package: \e[32m%s\e[0m\n" "${package_array[@]}"
# Iterate through the wheel files and remove those that are not source built
@@ -71,4 +76,4 @@ jobs:
uses: actions/cache/save@v3
with:
path: ${{ env.archive_name }}.zip
key: ${{ env.archive_name }}
key: ${{ env.archive_name }}-${{ hashFiles('reqs.txt') }}
+40 -4
View File
@@ -6,7 +6,7 @@ on:
name:
description: Release tag / name ?
required: true
default: "latest"
default: 'latest'
type: string
environment:
description: Environment to run tests against
@@ -27,8 +27,36 @@ jobs:
- name: ♻️ Checking out the repository
uses: actions/checkout@v3
with:
submodules: "recursive"
submodules: 'recursive'
path: ${{ env.repo_name }}
# - name: 📝 Prepare file with paths to remove
# run: |
# find ${{ env.repo_name }} -type f -size +10M > .release_ignore
# find ${{ env.repo_name }} -type d -empty >> .release_ignore
# shell: bash
- name: 🗑️ Remove files and directories listed in .release_ignore
shell: bash
run: |
release_ignore="${{ env.repo_name }}/.release_ignore"
if [ -f "$release_ignore" ]; then
while IFS= read -r entry || [ -n "$entry" ]; do
target="${{ env.repo_name }}/$entry"
if [ -e "$target" ]; then
if [ -f "$target" ]; then
rm "$target"
elif [ -d "$target" ]; then
rm -r "$target"
fi
else
echo "Warning: $entry does not exist in the repository. Skipping removal."
fi
done < "$release_ignore"
else
echo "No .release_ignore file found. Skipping removal of files and directories."
fi
- name: 📦 Building custom comfy nodes
shell: bash
run: |
@@ -70,10 +98,18 @@ jobs:
id: cache
with:
path: ${{ env.archive_name }}.zip
key: ${{ env.archive_name }}
key: ${{ env.archive_name }}-${{ hashFiles('reqs.txt') }}
- name: 📦 Unzip wheels
shell: bash
run: |
mkdir -p wheels
unzip -j ${{ env.archive_name }}.zip "**/*.whl" -d wheels
unzip -j ${{ env.archive_name }}.zip "**/*.txt" -d wheels
if: success()
- name: ✅ Add wheels to release
uses: softprops/action-gh-release@v1
with:
tag_name: ${{ inputs.name }}
files: |
${{ env.archive_name }}.zip
wheels/*.whl
wheels/wheel_order.txt
+71
View File
@@ -0,0 +1,71 @@
name: 🧪 Test Comfy Portable
on: workflow_dispatch
jobs:
install-comfy:
runs-on: windows-latest
env:
repo_name: ${{ github.event.repository.name }}
steps:
- name: ⚡️ Restore Cache if Available
id: cache-comfy
uses: actions/cache/restore@v3
with:
path: ComfyUI_windows_portable
key: ${{ runner.os }}-comfy-env
- name: 🚡 Download and Extract Comfy
id: download-extract-comfy
if: steps.cache-comfy.outputs.cache-hit != 'true'
shell: bash
run: |
mkdir comfy_temp
curl -L -o comfy_temp/comfyui.7z https://github.com/comfyanonymous/ComfyUI/releases/download/latest/ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z
7z x comfy_temp/comfyui.7z -o./comfy_temp
# mv comfy_temp/ComfyUI_windows_portable/python_embeded .
# mv comfy_temp/ComfyUI_windows_portable/ComfyUI .
# mv comfy_temp/ComfyUI_windows_portable/update .
ls
mv comfy_temp/ComfyUI_windows_portable .
- name: 💾 Store cache
uses: actions/cache/save@v3
if: steps.cache-comfy.outputs.cache-hit != 'true'
with:
path: ComfyUI_windows_portable
key: ${{ runner.os }}-comfy-env
- name: ⏬ Install other extensions
shell: bash
run: |
export COMFY_PYTHON="${GITHUB_WORKSPACE}/ComfyUI_windows_portable/python_embeded/python.exe"
cd "${GITHUB_WORKSPACE}/ComfyUI_windows_portable/ComfyUI/custom_nodes"
git clone https://github.com/Fannovel16/comfy_controlnet_preprocessors
cd comfy_controlnet_preprocessors
$COMFY_PYTHON -m pip install -r requirements.txt
- name: ♻️ Checking out comfy_mtb to custom_nodes
uses: actions/checkout@v3
with:
submodules: 'recursive'
path: ComfyUI_windows_portable/ComfyUI/custom_nodes/${{ env.repo_name }}
- name: 📦 Install mtb nodes
shell: bash
run: |
# run install
export COMFY_PYTHON="${GITHUB_WORKSPACE}/ComfyUI_windows_portable/python_embeded/python.exe"
cd "${GITHUB_WORKSPACE}/ComfyUI_windows_portable/ComfyUI/custom_nodes"
$COMFY_PYTHON ${{ env.repo_name }}/install.py -w
- name: ⏬ Import mtb_nodes
shell: bash
run: |
export COMFY_PYTHON="${GITHUB_WORKSPACE}/ComfyUI_windows_portable/python_embeded/python.exe"
cd "${GITHUB_WORKSPACE}/ComfyUI_windows_portable/ComfyUI"
$COMFY_PYTHON -s main.py --quick-test-for-ci --cpu
$COMFY_PYTHON -m pip freeze
+3 -1
View File
@@ -1,3 +1,5 @@
__pycache__
*.py[cod]
*.onnx
*.onnx
wheels/
node_modules/
+9 -3
View File
@@ -1,3 +1,9 @@
[submodule "extern/SadTalker"]
path = extern/SadTalker
url = https://github.com/OpenTalker/SadTalker.git
[submodule "extern/google-FILM"]
path = extern/frame_interpolation
url = https://github.com/google-research/frame-interpolation
[submodule "extern/GFPGAN"]
path = extern/GFPGAN
url = https://github.com/TencentARC/GFPGAN.git
[submodule "extern/frame_interpolation"]
path = extern/frame_interpolation
url = https://github.com/google-research/frame-interpolation
+6
View File
@@ -0,0 +1,6 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"useTabs": false
}
+4
View File
@@ -0,0 +1,4 @@
extern/frame_interpolation/moment.gif
extern/frame_interpolation/photos
extern/GFPGAN/inputs
.git
+93
View File
@@ -0,0 +1,93 @@
# 安装
- [安装](#安装)
- [自动安装(推荐)](#自动安装推荐)
- [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
@@ -0,0 +1,93 @@
# インストール
- [インストール](#インストール)
- [自動インストール (推奨)](#自動インストール-推奨)
- [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>
+91
View File
@@ -0,0 +1,91 @@
# Installation
- [Installation](#installation)
- [Automatic Install (Recommended)](#automatic-install-recommended)
- [ComfyUI Manager](#comfyui-manager)
- [Virtual Env](#virtual-env)
- [Models Download](#models-download)
- [Web Extensions](#web-extensions)
- [Old installation method (MANUAL)](#old-installation-method-manual)
- [Dependencies](#dependencies)
## Automatic Install (Recommended)
### ComfyUI Manager
As of version 0.1.0, this extension is meant to be installed with the [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager), which helps a lot with handling the various install issues faced by various environments.
### Virtual Env
There is also an experimental one liner install using the following command from ComfyUI's root. It will download the code, install the dependencies and run the install script:
```bash
curl -sSL "https://raw.githubusercontent.com/username/repo/main/install.py" | python3 -
```
## Models Download
Some nodes require extra models to be downloaded, you can interactively do it using the same python environment as above:
```bash
python scripts/download_models.py
```
then follow the prompt or just press enter to download every models.
> **Note**
> You can use the following to download all models without prompt:
```bash
python scripts/download_models.py -y
```
### Web Extensions
On first run the script [tries to symlink](https://github.com/melMass/comfy_mtb/blob/d982b69a58c05ccead9c49370764beaa4549992a/__init__.py#L45-L61) the [web extensions](https://github.com/melMass/comfy_mtb/tree/main/web) to your comfy `web/extensions` folder. In case it fails you can manually copy the mtb folder to `ComfyUI/web/extensions` it only provides a color widget for now shared by a few nodes:
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
## Old installation method (MANUAL)
### Dependencies
<details><summary><h4>Custom Virtualenv (I use this mainly)</h4></summary>
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
```
</details>
<details><summary><h4>Comfy-portable / standalone (from ComfyUI releases)</h4></summary>
If you use the `python-embeded` from ComfyUI standalone then you are not able to pip install dependencies with binaries when they don't have wheels, in this case check the last [release](https://github.com/melMass/comfy_mtb/releases) there is a bundle for linux and windows with prebuilt wheels (only the ones that require building from source), check [this issue (#1)](https://github.com/melMass/comfy_mtb/issues/1) for more info.
![image](https://github.com/melMass/comfy_mtb/assets/7041726/2934fa14-3725-427c-8b9e-2b4f60ba1b7b)
</details>
<details><summary><h4>Google Colab</h4></summary>
Add a new code cell just after the **Run ComfyUI with localtunnel (Recommended Way)** header (before the code cell)
![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
```
If after running this, colab complains about needing to restart runtime, do it, and then do not rerun earlier cells, just the one to run the localtunnel. (you might have to add a cell with `%cd ComfyUI` first...)
> **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>
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Mel Massadian
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+99
View File
@@ -0,0 +1,99 @@
# 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
@@ -0,0 +1,96 @@
# 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)
+76 -30
View File
@@ -1,51 +1,97 @@
## MTB Nodes
# MTB Nodes
Feel free to do whatever you want with this codebase, I'm mainly using Comfy to build POCs to implement in [MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs). And a lot of nodes are inspired by existing ones from the community or builtin
Just beware of the licenses of some libraries (deepbump for instance is [GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE))
[![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)
## Install
<!-- omit in toc -->
From within the python environment you already use for ComfyUI install the requirements.
```bash
pip install -r comfy_mtb/requirements.txt
```
**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)
## Screenshots
<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>
- **FaceSwap [roop]** (using [roop](https://github.com/s0md3v/roop/))
The face index allow you to choose which face to replace as you can see here:
![ComfyUI_909](https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42)
[**Install Guide**](./INSTALL.md) | [**Examples**](https://github.com/melMass/comfy_mtb/wiki/Examples)
- **Style Loader**: A111 like csv styles in Comfy
![image](https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8)
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.
- **Color Correction**: basic color correction node
![image](https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef)
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).
- **Image Remove Background [RemBG]**: (using [rembg](https://github.com/danielgatis/rembg))
![image](https://github.com/melMass/comfy_mtb/assets/7041726/e69253b4-c03c-45e9-92b5-aa46fb887be8)
- [Node List](#node-list)
- [bbox](#bbox)
- [colors](#colors)
- [face detection / swapping](#face-detection--swapping)
- [image interpolation (animation)](#image-interpolation-animation)
- [image ops](#image-ops)
- [latent utils](#latent-utils)
- [misc utils](#misc-utils)
- [textures](#textures)
- [Comfy Resources](#comfy-resources)
# Node List
### Node List
- `Latent Lerp`: Linear Interpolate between two latents,
- `Int to Number`: Supplement for WASSuite number nodes,
## bbox
- `Bounding Box`: BBox constructor (custom type),
- `Crop`: Crop image from BBox,
- `Uncrop`: Uncrop image from BBox,
- `ImageBlur`: Blur the input image,
- `Denoise`: Denoise the input image,
- `ImageCompare`: Compare image,
- `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,
- `Modulo`: Modulo (useful for loops),
- `Color Correct`: Basic color correction tools
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=345/>
## face detection / swapping
- `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)
> **Note**
> The face index allow you to choose which face to replace as you can see here:
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42" width=320/>
- `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)
- `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 src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834" width=400/>
- `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.
## 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
## misc utils
- `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
## textures
### Comfy Resources
- `DeepBump`: Normal & height maps generation from single pictures
# Comfy Resources
**Guides**:
- [Official Examples (eng)](https://comfyanonymous.github.io/ComfyUI_examples/)
+264 -18
View File
@@ -1,16 +1,67 @@
import traceback
from .log import log, blue_text, get_summary, get_label
from .utils import here
import importlib
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
###
# File: __init__.py
# Project: comfy_mtb
# Author: Mel Massadian
# Copyright (c) 2023 Mel Massadian
#
###
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"
import traceback
from .log import log, blue_text, cyan_text, get_summary, get_label
from .utils import here
from .utils import comfy_dir
import importlib
import os
import ast
import json
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
NODE_CLASS_MAPPINGS_DEBUG = {}
__version__ = "0.1.4"
def extract_nodes_from_source(filename):
source_code = ""
with open(filename, "r") as file:
source_code = file.read()
nodes = []
try:
parsed = ast.parse(source_code)
for node in ast.walk(parsed):
if isinstance(node, ast.Assign) and len(node.targets) == 1:
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
except SyntaxError:
log.error("Failed to parse")
return nodes
def load_nodes():
errors = []
nodes = []
nodes_failed = []
for filename in (here / "nodes").iterdir():
if filename.suffix == ".py":
module_name = filename.stem
@@ -21,17 +72,20 @@ def load_nodes():
)
_nodes = getattr(module, "__nodes__")
nodes.extend(_nodes)
log.debug(f"Imported {module_name} nodes")
except AttributeError:
pass # wip nodes
except Exception:
error_message = traceback.format_exc().splitlines()[-1]
errors.append(f"Failed to import {module_name} because {error_message}")
errors.append(
f"Failed to import module {module_name} because {error_message}"
)
# Read __nodes__ variable from the source file
nodes_failed.extend(extract_nodes_from_source(filename))
if errors:
log.error(
log.info(
f"Some nodes failed to load:\n\t"
+ "\n\t".join(errors)
+ "\n\n"
@@ -39,36 +93,228 @@ def load_nodes():
+ "If you think this is a bug, please report it on the github page (https://github.com/melMass/comfy_mtb/issues)"
)
return nodes
return (nodes, nodes_failed)
# - REGISTER WEB EXTENSIONS
web_extensions_root = utils.comfy_dir / "web" / "extensions"
web_extensions_root = comfy_dir / "web" / "extensions"
web_mtb = web_extensions_root / "mtb"
if web_mtb.exists():
log.debug(f"Web extensions folder found at {web_mtb}")
if not os.path.islink(web_mtb.as_posix()):
log.warn(
f"Web extensions folder at {web_mtb} is not a symlink, if updating please delete it before"
)
elif web_extensions_root.exists():
os.symlink((here / "web"), web_mtb.as_posix())
web_tgt = here / "web"
src = web_tgt.as_posix()
dst = web_mtb.as_posix()
try:
if os.name == "nt":
import _winapi
_winapi.CreateJunction(src, dst)
else:
os.symlink(web_tgt.as_posix(), web_mtb.as_posix())
except OSError:
log.warn(f"Failed to create symlink to {web_mtb}, trying to copy it")
try:
import shutil
shutil.copytree(web_tgt, web_mtb)
log.info(f"Successfully copied {web_tgt} to {web_mtb}")
except Exception as e:
log.warn(
f"Failed to symlink and copy {web_tgt} to {web_mtb}. Please copy the folder manually."
)
log.warn(e)
except Exception as e:
log.warn(
f"Failed to create symlink to {web_mtb}. Please copy the folder manually."
)
log.warn(e)
else:
log.error(
log.warn(
f"Comfy root probably not found automatically, please copy the folder {web_mtb} manually in the web/extensions folder of ComfyUI"
)
# - REGISTER NODES
nodes = load_nodes()
nodes, failed = load_nodes()
for node_class in nodes:
class_name = node_class.__name__
class_name = node_class.__name__
node_name = f"{get_label(class_name)} (mtb)"
NODE_CLASS_MAPPINGS[node_name] = node_class
NODE_CLASS_MAPPINGS_DEBUG[node_name] = node_class.__doc__
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
if os.environ.get("MTB_EXPORT"):
with open(here / "node_list.json", "w") as f:
f.write(
json.dumps(
{
k: NODE_CLASS_MAPPINGS_DEBUG[k]
for k in sorted(NODE_CLASS_MAPPINGS_DEBUG.keys())
},
indent=4,
)
)
log.debug(
log.info(
f"Loaded the following nodes:\n\t"
+ "\n\t".join(
f"{k}: {blue_text(get_summary(doc)) if doc else '-'}"
f"{cyan_text(k)}: {blue_text(get_summary(doc)) if doc else '-'}"
for k, doc in NODE_CLASS_MAPPINGS_DEBUG.items()
)
)
# - ENDPOINT
from server import PromptServer
from .log import log
from aiohttp import web
from importlib import reload
import logging
from .endpoint import endlog
if hasattr(PromptServer, "instance"):
restore_deps = ["basicsr"]
swap_deps = ["insightface", "onnxruntime"]
node_dependency_mapping = {
"FaceSwap": swap_deps,
"LoadFaceSwapModel": swap_deps,
"LoadFaceAnalysisModel": restore_deps,
}
@PromptServer.instance.routes.get("/mtb/status")
async def get_full_library(request):
from . import endpoint
reload(endpoint)
endlog.debug("Getting node registration status")
# Check if the request prefers HTML content
if "text/html" in request.headers.get("Accept", ""):
# # Return an HTML page
html_response = endpoint.render_table(
NODE_CLASS_MAPPINGS_DEBUG, title="Registered"
)
html_response += endpoint.render_table(
{
k: {"dependencies": node_dependency_mapping.get(k)}
if node_dependency_mapping.get(k)
else "-"
for k in failed
},
title="Failed to load",
)
return web.Response(
text=endpoint.render_base_template("MTB", html_response),
content_type="text/html",
)
return web.json_response(
{
"registered": NODE_CLASS_MAPPINGS_DEBUG,
"failed": failed,
}
)
@PromptServer.instance.routes.post("/mtb/debug")
async def set_debug(request):
json_data = await request.json()
enabled = json_data.get("enabled")
if enabled:
os.environ["MTB_DEBUG"] = "true"
log.setLevel(logging.DEBUG)
log.debug("Debug mode set from API (/mtb/debug POST route)")
elif "MTB_DEBUG" in os.environ:
# del os.environ["MTB_DEBUG"]
os.environ.pop("MTB_DEBUG")
log.setLevel(logging.INFO)
return web.json_response(
{"message": f"Debug mode {'set' if enabled else 'unset'}"}
)
@PromptServer.instance.routes.get("/mtb")
async def get_home(request):
from . import 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/debug">debug</a>
<a href="/mtb/status">status</a>
</div>
"""
return web.Response(
text=endpoint.render_base_template("MTB", html_response),
content_type="text/html",
)
# Return JSON for other requests
return web.json_response({"message": "Welcome to MTB!"})
@PromptServer.instance.routes.get("/mtb/debug")
async def get_debug(request):
from . import endpoint
reload(endpoint)
enabled = "MTB_DEBUG" in os.environ
# 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>
"""
return web.Response(
text=endpoint.render_base_template("Debug", html_response),
content_type="text/html",
)
# Return JSON for other requests
return web.json_response({"enabled": enabled})
@PromptServer.instance.routes.get("/mtb/actions")
async def no_route(request):
from . import endpoint
if "text/html" in request.headers.get("Accept", ""):
html_response = """
<h1>Actions has no get for now...</h1>
"""
return web.Response(
text=endpoint.render_base_template("Actions", html_response),
content_type="text/html",
)
return web.json_response({"message": "actions has no get for now"})
@PromptServer.instance.routes.post("/mtb/actions")
async def do_action(request):
from . import endpoint
reload(endpoint)
return await endpoint.do_action(request)
# - WAS Dictionary
MANIFEST = {
"name": "MTB Nodes", # The title that will be displayed on Node Class menu,. and Node Class view
"version": (0, 1, 0), # Version of the custom_node or sub module
"author": "Mel Massadian", # Author or organization of the custom_node or sub module
"project": "https://github.com/melMass/comfy_mtb", # The address that the `name` value will link to on Node Class Views
"description": "Set of nodes that enhance your animation workflow and provide a range of useful tools including features such as manipulating bounding boxes, perform color corrections, swap faces in images, interpolate frames for smooth animation, export to ProRes format, apply various image operations, work with latent spaces, generate QR codes, and create normal and height maps for textures.",
}
+185
View File
@@ -0,0 +1,185 @@
from .utils import here, run_command, comfy_mode
from aiohttp import web
from .log import mklog
import sys
endlog = mklog("mtb endpoint")
# - ACTIONS
import requirements
def ACTIONS_installDependency(dependency_names=None):
if dependency_names is None:
return {"error": "No dependency name provided"}
endlog.debug(f"Received Install Dependency request for {dependency_names}")
reqs = []
if comfy_mode == "embeded":
reqs = list(requirements.parse((here / "reqs_portable.txt").read_text()))
else:
reqs = list(requirements.parse((here / "reqs.txt").read_text()))
print([x.specs for x in reqs])
print(
"\n".join([f"{x.line} {''.join(x.specs[0] if x.specs else '')}" for x in reqs])
)
for dependency_name in dependency_names:
for req in reqs:
if req.name == dependency_name:
endlog.debug(f"Dependency {dependency_name} installed")
break
return {"success": True}
def ACTIONS_getStyles(style_name=None):
from .nodes.conditions import StylesLoader
styles = StylesLoader.options
match_list = ["name"]
if styles:
filtered_styles = {
key: value
for key, value in styles.items()
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
return {"error": "No styles found"}
async def do_action(request) -> web.Response:
endlog.debug("Init action request")
request_data = await request.json()
name = request_data.get("name")
args = request_data.get("args")
endlog.debug(f"Received action request: {name} {args}")
method_name = f"ACTIONS_{name}"
method = globals().get(method_name)
if callable(method):
result = method(args) if args else 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_")
]
return web.json_response(
{"error": "Invalid method name.", "available_methods": available_methods}
)
# - HTML UTILS
def dependencies_button(name, dependencies):
deps = ",".join([f"'{x}'" for x in dependencies])
return f"""
<button class="dependency-button" onclick="window.mtb_action('installDependency',[{deps}])">Install {name} deps</button>
"""
def render_table(table_dict, sort=True, title=None):
table_dict = sorted(
table_dict.items(), key=lambda item: item[0]
) # Sort the dictionary by keys
table_rows = ""
for name, item in table_dict:
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 += "</td></tr>"
else:
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:
table_rows += f"<tr><td>{name}</td><td>{item}</td></tr>"
return f"""
<div class="table-container">
{"" if title is None else f"<h1>{title}</h1>"}
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{table_rows}
</tbody>
</table>
</div>
"""
def render_base_template(title, content):
css_content = ""
css_path = here / "html" / "style.css"
if css_path:
with open(css_path, "r") as css_file:
css_content = css_file.read()
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>
<html>
<head>
<title>{title}</title>
<style>
{css_content}
</style>
</head>
<script type="module">
import {{ api }} from '/scripts/api.js'
const mtb_action = async (action, args) =>{{
console.log(`Sending ${{action}} with args: ${{args}}`)
}}
window.mtb_action = async (action, args) =>{{
console.log(`Sending ${{action}} with args: ${{args}} to the API`)
const res = await api.fetchApi('/actions', {{
method: 'POST',
body: JSON.stringify({{
name: action,
args,
}}),
}})
const output = await res.json()
console.debug(`Received ${{action}} response:`, output)
if (output?.result?.error){{
alert(`An error occured: {{output?.result?.error}}`)
}}
return output?.result
}}
</script>
<body>
<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">
<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}
</a>
</header>
<main>
{content}
</main>
<footer>
<!-- Shared footer content here -->
</footer>
</body>
</html>
"""
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+12
View File
@@ -0,0 +1,12 @@
# Examples
All the examples use the [RevAnimated model 1.22](https://civitai.com/models/7371?modelVersionId=46846)
## 01 Faceswap
This example showcase the `Face Swap` & `Restore Face` nodes to replace the character with Georges Lucas's face.
The face reference image is using the `Load Image From Url` node to avoid bundling input images.
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/272af7d6-f01c-478e-a82f-926e772d7209" width=500/>
## 02 FILM interpolation
This example showcase the FILM interpolation implementation. Here we do text replacement on the condition of two distinct images sharing the same model, input latent & seed to get relatively close images.
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/4c28dd87-89fc-4d27-910a-0a1fcf28cdc0" width=500/>
Vendored Submodule
+1
Submodule extern/GFPGAN added at 2eac203389
-1
Submodule extern/SadTalker deleted from 4c38d1f595
Vendored Submodule
+1
+133
View File
@@ -0,0 +1,133 @@
html {
height: 100%;
margin: 0;
padding: 0;
background-color: rgb(33, 33, 33);
color: whitesmoke;
}
a {
color: whitesmoke;
}
.table-container {
width: 70%;
height: 100%;
overflow: auto;
}
table {
border-collapse: collapse;
}
th,
td {
padding: 10px;
text-align: left;
}
th {
background-color: rgb(45, 45, 45);
/* Light gray background for header row */
font-weight: bold;
}
tr:nth-child(even) {
background-color: rgb(45, 45, 45);
/* Alternate row background color */
}
tr:hover {
background-color: #797979;
/* Highlight color on hover */
}
td:nth-child(2) {
/* Applies to the second column (Description) */
width: 80%;
/* Adjust the width as needed */
word-wrap: break-word;
/* Allow long words to be broken and wrapped to the next line */
}
.mtb_logo {
display: flex;
flex-direction: column;
align-items: center;
}
/* Styling for WebKit-based browsers (Chrome, Edge) */
.table-container::-webkit-scrollbar {
width: 10px;
/* Set the width of the scrollbar */
}
.table-container::-webkit-scrollbar-thumb {
background-color: #797979;
/* Color of the scrollbar thumb */
}
/* Styling for Firefox */
.table-container {
scrollbar-width: thin;
/* Set the width of the scrollbar */
}
.table-container::-webkit-scrollbar-thumb {
background-color: #797979;
/* Color of the scrollbar thumb */
}
/* Optionally, you can also style the scrollbar track (background) */
.table-container::-webkit-scrollbar-track {
background-color: #f2f2f2;
}
body {
margin: 0;
padding: 0;
font-family: monospace;
height: 100%;
background-color: rgb(33, 33, 33);
}
.title {
font-size: 2.5em;
font-weight: 700;
}
header {
display: flex;
align-items: center;
vertical-align: middle;
justify-content: space-between;
background-color: rgb(12, 12, 12);
padding: 1em;
margin: 0;
}
main {
display: flex;
align-items: center;
vertical-align: middle;
justify-content: center;
padding: 1em;
margin: 0;
height: 80%;
}
.flex-container {
display: flex;
flex-direction: column;
}
.menu {
font-size: 3em;
text-align: center;
}
+632
View File
@@ -0,0 +1,632 @@
import requests
import os
import ast
import argparse
import sys
import subprocess
from importlib import import_module
import platform
from pathlib import Path
import sys
import stat
import threading
import signal
from contextlib import suppress
from queue import Queue, Empty
from contextlib import contextmanager
here = Path(__file__).parent
executable = sys.executable
# - detect mode
mode = None
if os.environ.get("COLAB_GPU"):
mode = "colab"
elif "python_embeded" in executable:
mode = "embeded"
elif ".venv" in executable:
mode = "venv"
if mode is None:
mode = "unknown"
# - Constants
repo_url = "https://github.com/melmass/comfy_mtb.git"
repo_owner = "melmass"
repo_name = "comfy_mtb"
short_platform = {
"windows": "win_amd64",
"linux": "linux_x86_64",
}
current_platform = platform.system().lower()
# region ansi
# ANSI escape sequences for text styling
ANSI_FORMATS = {
"reset": "\033[0m",
"bold": "\033[1m",
"dim": "\033[2m",
"italic": "\033[3m",
"underline": "\033[4m",
"blink": "\033[5m",
"reverse": "\033[7m",
"strike": "\033[9m",
}
ANSI_COLORS = {
"black": "\033[30m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"white": "\033[37m",
"bright_black": "\033[30;1m",
"bright_red": "\033[31;1m",
"bright_green": "\033[32;1m",
"bright_yellow": "\033[33;1m",
"bright_blue": "\033[34;1m",
"bright_magenta": "\033[35;1m",
"bright_cyan": "\033[36;1m",
"bright_white": "\033[37;1m",
"bg_black": "\033[40m",
"bg_red": "\033[41m",
"bg_green": "\033[42m",
"bg_yellow": "\033[43m",
"bg_blue": "\033[44m",
"bg_magenta": "\033[45m",
"bg_cyan": "\033[46m",
"bg_white": "\033[47m",
"bg_bright_black": "\033[40;1m",
"bg_bright_red": "\033[41;1m",
"bg_bright_green": "\033[42;1m",
"bg_bright_yellow": "\033[43;1m",
"bg_bright_blue": "\033[44;1m",
"bg_bright_magenta": "\033[45;1m",
"bg_bright_cyan": "\033[46;1m",
"bg_bright_white": "\033[47;1m",
}
def apply_format(text, *formats):
"""Apply ANSI escape sequences for the specified formats to the given text."""
formatted_text = text
for format in formats:
formatted_text = f"{ANSI_FORMATS.get(format, '')}{formatted_text}{ANSI_FORMATS.get('reset', '')}"
return formatted_text
def apply_color(text, color=None, background=None):
"""Apply ANSI escape sequences for the specified color and background to the given text."""
formatted_text = text
if color:
formatted_text = f"{ANSI_COLORS.get(color, '')}{formatted_text}{ANSI_FORMATS.get('reset', '')}"
if background:
formatted_text = f"{ANSI_COLORS.get(background, '')}{formatted_text}{ANSI_FORMATS.get('reset', '')}"
return formatted_text
def print_formatted(text, *formats, color=None, background=None, **kwargs):
"""Print the given text with the specified formats, color, and background."""
formatted_text = apply_format(text, *formats)
formatted_text = apply_color(formatted_text, color, background)
file = kwargs.get("file", sys.stdout)
header = "[mtb install] "
# Handle console encoding for Unicode characters (utf-8)
encoded_header = header.encode(sys.stdout.encoding, errors="replace").decode(
sys.stdout.encoding
)
encoded_text = formatted_text.encode(sys.stdout.encoding, errors="replace").decode(
sys.stdout.encoding
)
print(
" " * len(encoded_header)
if kwargs.get("no_header")
else apply_color(apply_format(encoded_header, "bold"), color="yellow"),
encoded_text,
file=file,
)
# endregion
# region utils
def enqueue_output(out, queue):
for char in iter(lambda: out.read(1), b""):
queue.put(char)
out.close()
def run_command(cmd, ignored_lines_start=None):
if ignored_lines_start is None:
ignored_lines_start = []
if isinstance(cmd, str):
shell_cmd = cmd
elif isinstance(cmd, list):
shell_cmd = ""
for arg in cmd:
if isinstance(arg, Path):
arg = arg.as_posix()
shell_cmd += f"{arg} "
else:
raise ValueError(
"Invalid 'cmd' argument. It must be a string or a list of arguments."
)
process = subprocess.Popen(
shell_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
shell=True,
)
# Create separate threads to read standard output and standard error streams
stdout_queue = Queue()
stderr_queue = Queue()
stdout_thread = threading.Thread(
target=enqueue_output, args=(process.stdout, stdout_queue)
)
stderr_thread = threading.Thread(
target=enqueue_output, args=(process.stderr, stderr_queue)
)
stdout_thread.daemon = True
stderr_thread.daemon = True
stdout_thread.start()
stderr_thread.start()
interrupted = False
def signal_handler(signum, frame):
nonlocal interrupted
interrupted = True
print("Command execution interrupted.")
# Register the signal handler for keyboard interrupts (SIGINT)
signal.signal(signal.SIGINT, signal_handler)
stdout_buffer = ""
stderr_buffer = ""
# Process output from both streams until the process completes or interrupted
while not interrupted and (
process.poll() is None or not stdout_queue.empty() or not stderr_queue.empty()
):
with suppress(Empty):
stdout_char = stdout_queue.get_nowait()
stdout_buffer += stdout_char
if stdout_char == "\n":
if not any(
stdout_buffer.startswith(ign) for ign in ignored_lines_start
):
print(stdout_buffer.strip())
stdout_buffer = ""
with suppress(Empty):
stderr_char = stderr_queue.get_nowait()
stderr_buffer += stderr_char
if stderr_char == "\n":
print(stderr_buffer.strip())
stderr_buffer = ""
# Print any remaining content in buffers
if stdout_buffer and not any(
stdout_buffer.startswith(ign) for ign in ignored_lines_start
):
print(stdout_buffer.strip())
if stderr_buffer:
print(stderr_buffer.strip())
return_code = process.returncode
if return_code == 0 and not interrupted:
print("Command executed successfully!")
else:
if not interrupted:
print(f"Command failed with return code: {return_code}")
# endregion
try:
import requirements
except ImportError:
print_formatted("Installing requirements-parser...", "italic", color="yellow")
run_command([sys.executable, "-m", "pip", "install", "requirements-parser"])
import requirements
print_formatted("Done.", "italic", color="green")
try:
from tqdm import tqdm
except ImportError:
print_formatted("Installing tqdm...", "italic", color="yellow")
run_command([sys.executable, "-m", "pip", "install", "--upgrade", "tqdm"])
from tqdm import tqdm
pip_map = {
"onnxruntime-gpu": "onnxruntime",
"opencv-contrib": "cv2",
"tb-nightly": "tensorboard",
"protobuf": "google.protobuf",
# Add more mappings as needed
}
def is_pipe():
if not sys.stdin.isatty():
return False
if sys.platform == "win32":
try:
import msvcrt
return msvcrt.get_osfhandle(0) != -1
except ImportError:
return False
else:
try:
mode = os.fstat(0).st_mode
return (
stat.S_ISFIFO(mode)
or stat.S_ISREG(mode)
or stat.S_ISBLK(mode)
or stat.S_ISSOCK(mode)
)
except OSError:
return False
@contextmanager
def suppress_std():
with open(os.devnull, "w") as devnull:
old_stdout = sys.stdout
old_stderr = sys.stderr
sys.stdout = devnull
sys.stderr = devnull
try:
yield
finally:
sys.stdout = old_stdout
sys.stderr = old_stderr
# Get the version from __init__.py
def get_local_version():
init_file = os.path.join(os.path.dirname(__file__), "__init__.py")
if os.path.isfile(init_file):
with open(init_file, "r") as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if (
isinstance(target, ast.Name)
and target.id == "__version__"
and isinstance(node.value, ast.Str)
):
return node.value.s
return None
def download_file(url, file_name):
with requests.get(url, stream=True) as response:
response.raise_for_status()
total_size = int(response.headers.get("content-length", 0))
with open(file_name, "wb") as file, tqdm(
desc=file_name.stem,
total=total_size,
unit="B",
unit_scale=True,
unit_divisor=1024,
) as progress_bar:
for chunk in response.iter_content(chunk_size=8192):
file.write(chunk)
progress_bar.update(len(chunk))
def get_requirements(path: Path):
with open(path.resolve(), "r") as requirements_file:
requirements_txt = requirements_file.read()
try:
parsed_requirements = requirements.parse(requirements_txt)
except AttributeError:
print_formatted(
f"Failed to parse {path}. Please make sure the file is correctly formatted.",
"bold",
color="red",
)
return
return parsed_requirements
def try_import(requirement):
dependency = requirement.name.strip()
import_name = pip_map.get(dependency, dependency)
installed = False
pip_name = dependency
pip_spec = "".join(specs[0]) if (specs := requirement.specs) else ""
try:
with suppress_std():
import_module(import_name)
print_formatted(
f"\t✅ Package {pip_name} already installed (import name: '{import_name}').",
"bold",
color="green",
no_header=True,
)
installed = True
except ImportError:
print_formatted(
f"\t⛔ Package {pip_name} is missing (import name: '{import_name}').",
"bold",
color="red",
no_header=True,
)
return (installed, pip_name, pip_spec, import_name)
def import_or_install(requirement, dry=False):
installed, pip_name, pip_spec, import_name = try_import(requirement)
pip_install_name = pip_name + pip_spec
if not installed:
print_formatted(f"Installing package {pip_name}...", "italic", color="yellow")
if dry:
print_formatted(
f"Dry-run: Package {pip_install_name} would be installed (import name: '{import_name}').",
color="yellow",
)
else:
try:
run_command([sys.executable, "-m", "pip", "install", pip_install_name])
print_formatted(
f"Package {pip_install_name} installed successfully using pip package name (import name: '{import_name}')",
"bold",
color="green",
)
except subprocess.CalledProcessError as e:
print_formatted(
f"Failed to install package {pip_install_name} using pip package name (import name: '{import_name}'). Error: {str(e)}",
"bold",
color="red",
)
def get_github_assets(tag=None):
if tag:
tag_url = (
f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/tags/{tag}"
)
else:
tag_url = (
f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
)
response = requests.get(tag_url)
if response.status_code == 404:
# print_formatted(
# f"Tag version '{apply_color(version,'cyan')}' not found for {owner}/{repo} repository."
# )
print_formatted("Error retrieving the release assets.", color="red")
sys.exit()
tag_data = response.json()
tag_name = tag_data["name"]
return tag_data, tag_name
# Install dependencies from requirements.txt
def install_dependencies(dry=False):
parsed_requirements = get_requirements(here / "reqs.txt")
if not parsed_requirements:
return
print_formatted(
"Installing dependencies from reqs.txt...", "italic", color="yellow"
)
for requirement in parsed_requirements:
import_or_install(requirement, dry=dry)
if __name__ == "__main__":
full = False
if len(sys.argv) == 1:
print_formatted(
"No arguments provided, doing a full install/update...",
"italic",
color="yellow",
)
full = True
# Parse command-line arguments
parser = argparse.ArgumentParser(description="Comfy_mtb install script")
parser.add_argument(
"--path",
"-p",
type=str,
help="Path to clone the repository to (i.e the absolute path to ComfyUI/custom_nodes)",
)
parser.add_argument(
"--wheels", "-w", action="store_true", help="Install wheel dependencies"
)
parser.add_argument(
"--requirements", "-r", action="store_true", help="Install requirements.txt"
)
parser.add_argument(
"--dry",
action="store_true",
help="Print what will happen without doing it (still making requests to the GH Api)",
)
# - keep
# parser.add_argument(
# "--version",
# default=get_local_version(),
# help="Version to check against the GitHub API",
# )
print_formatted("mtb install", "bold", color="yellow")
args = parser.parse_args()
# wheels_directory = here / "wheels"
print_formatted(f"Detected environment: {apply_color(mode,'cyan')}")
if args.path:
clone_dir = Path(args.path)
if not clone_dir.exists():
print_formatted(
"The path provided does not exist on disk... It must be pointing to ComfyUI's custom_nodes directory"
)
sys.exit()
else:
repo_dir = clone_dir / repo_name
if not repo_dir.exists():
print_formatted(f"Cloning to {repo_dir}...", "italic", color="yellow")
run_command(["git", "clone", "--recursive", repo_url, repo_dir])
else:
print_formatted(
f"Directory {repo_dir} already exists, we will update it..."
)
run_command(["git", "pull", "-C", repo_dir])
# os.chdir(clone_dir)
here = clone_dir
full = True
# Install dependencies from requirements.txt
# if args.requirements or mode == "venv":
# if (not args.wheels and mode not in ["colab", "embeded"]) and not full:
# print_formatted(
# "Skipping wheel installation. Use --wheels to install wheel dependencies. (only needed for Comfy embed)",
# "italic",
# color="yellow",
# )
# install_dependencies(dry=args.dry)
# sys.exit()
# if mode in ["colab", "embeded"]:
# print_formatted(
# f"Downloading and installing release wheels since we are in a Comfy {apply_color(mode,'cyan')} environment",
# "italic",
# color="yellow",
# )
# if full:
# print_formatted(
# f"Downloading and installing release wheels since no arguments where provided",
# "italic",
# color="yellow",
# )
print_formatted("Checking environment...", "italic", color="yellow")
missing_deps = []
if parsed_requirements := get_requirements(here / "reqs.txt"):
for requirement in parsed_requirements:
installed, pip_name, pip_spec, import_name = try_import(requirement)
if not installed:
missing_deps.append(pip_name.split("-")[0])
if not missing_deps:
print_formatted(
"All requirements are already installed. Enjoy 🚀",
"italic",
color="green",
)
sys.exit()
# # - Get the tag version from the GitHub API
# tag_data, tag_name = get_github_assets(tag=None)
# # - keep
# version = args.version
# # Compare the local and tag versions
# if version and tag_name:
# if re.match(r"v?(\d+(\.\d+)+)", version) and re.match(
# r"v?(\d+(\.\d+)+)", tag_name
# ):
# version_parts = [int(part) for part in version.lstrip("v").split(".")]
# tag_version_parts = [int(part) for part in tag_name.lstrip("v").split(".")]
# if version_parts > tag_version_parts:
# print_formatted(
# f"Local version ({version}) is greater than the release version ({tag_name}).",
# "bold",
# "yellow",
# )
# sys.exit()
# matching_assets = [
# asset
# for asset in tag_data["assets"]
# if asset["name"].endswith(".whl")
# and (
# "any" in asset["name"] or short_platform[current_platform] in asset["name"]
# )
# ]
# if not matching_assets:
# print_formatted(
# f"Unsupported operating system: {current_platform}", color="yellow"
# )
# wheel_order_asset = next(
# (asset for asset in tag_data["assets"] if asset["name"] == "wheel_order.txt"),
# None,
# )
# if wheel_order_asset is not None:
# print_formatted(
# "⚙️ Sorting the release wheels using wheels order", "italic", color="yellow"
# )
# response = requests.get(wheel_order_asset["browser_download_url"])
# if response.status_code == 200:
# wheel_order = [line.strip() for line in response.text.splitlines()]
# def get_order_index(val):
# try:
# return wheel_order.index(val)
# except ValueError:
# return len(wheel_order)
# matching_assets = sorted(
# matching_assets,
# key=lambda x: get_order_index(x["name"].split("-")[0]),
# )
# else:
# print("Failed to fetch wheel_order.txt. Status code:", response.status_code)
# missing_deps_urls = []
# for whl_file in matching_assets:
# # check if installed
# missing_deps_urls.append(whl_file["browser_download_url"])
install_cmd = [sys.executable, "-m", "pip", "install"]
# - Install all deps
if not args.dry:
if platform.system() == "Windows":
wheel_cmd = install_cmd + ["-r", (here / "reqs_windows.txt")]
else:
wheel_cmd = install_cmd + ["-r", (here / "reqs.txt")]
run_command(wheel_cmd)
print_formatted(
"✅ Successfully installed all dependencies.", "italic", color="green"
)
else:
print_formatted(
f"Would have run the following command:\n\t{apply_color(' '.join(install_cmd),'cyan')}",
"italic",
color="yellow",
)
+28 -8
View File
@@ -1,9 +1,20 @@
import logging
import re
import os
base_log_level = logging.DEBUG if os.environ.get("MTB_DEBUG") else logging.INFO
# Custom object that discards the output
class NullWriter:
def write(self, text):
pass
class Formatter(logging.Formatter):
grey = "\x1b[38;20m"
cyan = "\x1b[36;20m"
purple = "\x1b[35;20m"
yellow = "\x1b[33;20m"
red = "\x1b[31;20m"
bold_red = "\x1b[31;1m"
@@ -12,8 +23,8 @@ class Formatter(logging.Formatter):
format = "[%(name)s] | %(levelname)s -> %(message)s"
FORMATS = {
logging.DEBUG: grey + format + reset,
logging.INFO: grey + format + reset,
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,
@@ -25,21 +36,26 @@ class Formatter(logging.Formatter):
return formatter.format(record)
def mklog(name, level=logging.DEBUG):
def mklog(name, level=base_log_level):
logger = logging.getLogger(name)
logger.setLevel(level)
# create console handler with a higher log level
for handler in logger.handlers:
logger.removeHandler(handler)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setLevel(level)
ch.setFormatter(Formatter())
logger.addHandler(ch)
# Disable log propagation
logger.propagate = False
return logger
# - The main app logger
log = mklog(__package__)
log = mklog(__package__, base_log_level)
def log_user(arg):
@@ -54,6 +70,10 @@ def blue_text(text):
return f"\033[94m{text}\033[0m"
def cyan_text(text):
return f"\033[96m{text}\033[0m"
def get_label(label):
words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
return " ".join(words).strip()
+46
View File
@@ -0,0 +1,46 @@
{
"Animation Builder (mtb)": "Convenient way to manage basic animation maths at the core of many of my workflows",
"Any To String (mtb)": "Tries to take any input and convert it to a string",
"Bbox (mtb)": "The bounding box (BBOX) custom type used by other nodes",
"Bbox From Mask (mtb)": "From a mask extract the bounding box",
"Blur (mtb)": "Blur an image using a Gaussian filter.",
"Color Correct (mtb)": "Various color correction methods",
"Colored Image (mtb)": "Constant color image of given size",
"Concat Images (mtb)": "Add images to batch",
"Crop (mtb)": "Crops an image and an optional mask 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\n ",
"Debug (mtb)": "Experimental node to debug any Comfy values, support for more types and widgets is planned",
"Deep Bump (mtb)": "Normal & height maps generation from single pictures",
"Export With Ffmpeg (mtb)": "Export with FFmpeg (Experimental)",
"Face Swap (mtb)": "Face swap using deepinsight/insightface models",
"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.",
"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 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.",
"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.",
"Latent Lerp (mtb)": "Linear interpolation (blend) between two latent vectors",
"Load Face Analysis Model (mtb)": "Loads a face analysis model",
"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 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",
"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",
"Save Image Grid (mtb)": "Save all the images in the input batch as a grid of images.",
"Save Image Sequence (mtb)": "Save an image sequence to a folder. The current frame is used to determine which image to save.\n\n This is merely a wrapper around the `save_images` function with formatting for the output folder and filename.\n ",
"Save Tensors (mtb)": "Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy",
"Smart Step (mtb)": "Utils to control the steps start/stop of the KAdvancedSampler in percentage",
"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 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"
}
View File
+44
View File
@@ -0,0 +1,44 @@
from ..log import log
class AnimationBuilder:
"""Convenient way to manage basic animation maths at the core of many of my workflows"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"total_frames": ("INT", {"default": 100, "min": 0}),
# "fps": ("INT", {"default": 12, "min": 0}),
"scale_float": ("FLOAT", {"default": 1.0, "min": 0.0}),
"loop_count": ("INT", {"default": 1, "min": 0}),
"raw_iteration": ("INT", {"default": 0, "min": 0}),
"raw_loop": ("INT", {"default": 0, "min": 0}),
},
}
RETURN_TYPES = ("INT", "FLOAT", "INT", "BOOLEAN")
RETURN_NAMES = ("frame", "0-1 (scaled)", "count", "loop_ended")
CATEGORY = "mtb/animation"
FUNCTION = "build_animation"
def build_animation(
self,
total_frames=100,
# fps=12,
scale_float=1.0,
loop_count=1, # set in js
raw_iteration=0, # set in js
raw_loop=0, # set in js
):
frame = raw_iteration % (total_frames)
scaled = (frame / (total_frames - 1)) * scale_float
# if frame == 0:
# log.debug("Reseting history")
# PromptServer.instance.prompt_queue.wipe_history()
log.debug(f"frame: {frame}/{total_frames} scaled: {scaled}")
return (frame, scaled, raw_loop, (frame == (total_frames - 1)))
__nodes__ = [AnimationBuilder]
+22 -124
View File
@@ -1,4 +1,3 @@
from ..utils import pil2tensor
from ..utils import here
from ..log import log
import folder_paths
@@ -10,9 +9,6 @@ import csv
class SmartStep:
"""Utils to control the steps start/stop of the KAdvancedSampler in percentage"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -35,7 +31,7 @@ class SmartStep:
RETURN_TYPES = ("INT", "INT", "INT")
RETURN_NAMES = ("step", "start", "end")
FUNCTION = "do_step"
CATEGORY = "conditioning"
CATEGORY = "mtb/conditioning"
def do_step(self, step, start_percent, end_percent):
start = int(step * start_percent / 100)
@@ -62,37 +58,35 @@ class StylesLoader:
options = {}
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
input_dir = Path(folder_paths.base_path) / "styles"
if not input_dir.exists():
install_default_styles()
if not cls.options:
input_dir = Path(folder_paths.base_path) / "styles"
if not input_dir.exists():
install_default_styles()
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:
parsed = csv.reader(f)
for row in parsed:
log.debug(f"Adding style {row[0]}")
cls.options[row[0]] = (row[1], row[2])
else:
log.debug(f"Using cached styles (count: {len(cls.options)})")
if not (files := [f for f in input_dir.iterdir() if f.suffix == ".csv"]):
log.error(
"No styles found in the styles folder, place at least one csv file in the styles folder"
)
return {
"required": {
"style_name": (["error"],),
}
}
for file in files:
with open(file, "r", encoding="utf8") as f:
parsed = csv.reader(f)
for row in parsed:
log.debug(f"Adding style {row[0]}")
cls.options[row[0]] = (row[1], row[2])
return {
"required": {
"style_name": (list(cls.options.keys()),),
}
}
CATEGORY = "conditioning"
CATEGORY = "mtb/conditioning"
RETURN_TYPES = ("STRING", "STRING")
RETURN_NAMES = ("positive", "negative")
@@ -102,100 +96,4 @@ class StylesLoader:
return (self.options[style_name][0], self.options[style_name][1])
class TextToImage:
"""Utils to convert text to image using a font
The tool looks for any .ttf file in the Comfy folder hierarchy.
"""
fonts = {}
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
fonts = list(Path(folder_paths.base_path).glob("**/*.ttf"))
if not fonts:
log.error(
"No fonts found in the fonts folder, place at least one ttf file in the fonts folder"
)
return {
"required": {
"font": (["error"],),
}
}
for font in fonts:
log.debug(f"Adding font {font}")
cls.fonts[font.stem] = font.as_posix()
return {
"required": {
"text": (
"STRING",
{"default": "Hello world!"},
),
"font": ((sorted(cls.fonts.keys())),),
"wrap": (
"INT",
{"default": 120, "min": 0, "max": 8096, "step": 1},
),
"font_size": (
"INT",
{"default": 12, "min": 1, "max": 100, "step": 1},
),
"width": (
"INT",
{"default": 512, "min": 1, "max": 1000, "step": 1},
),
"height": (
"INT",
{"default": 512, "min": 1, "max": 8096, "step": 1},
),
# "position": (["INT"], {"default": 0, "min": 0, "max": 100, "step": 1}),
"color": (
"COLOR",
{"default": "black"},
),
"background": (
"COLOR",
{"default": "white"},
),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "text_to_image"
CATEGORY = "utils"
def text_to_image(
self, text, font, wrap, font_size, width, height, color, background
):
from PIL import Image, ImageDraw, ImageFont
import textwrap
font = self.fonts[font]
font = ImageFont.truetype(font, font_size)
if wrap == 0:
wrap = width / font_size
lines = textwrap.wrap(text, width=wrap)
log.debug(f"Lines: {lines}")
line_height = font.getsize("hg")[1]
img_height = height # line_height * len(lines)
img_width = width # max(font.getsize(line)[0] for line in lines)
img = Image.new("RGBA", (img_width, img_height), background)
draw = ImageDraw.Draw(img)
y_text = 0
for line in lines:
width, height = font.getsize(line)
draw.text((0, y_text), line, color, font=font)
y_text += height
# img.save(os.path.join(folder_paths.base_path, f'{str(uuid.uuid4())}.png'))
return (pil2tensor(img),)
__nodes__ = [SmartStep, TextToImage, StylesLoader]
__nodes__ = [SmartStep, StylesLoader]
+117 -51
View File
@@ -1,18 +1,19 @@
import torch
from ..utils import tensor2pil, pil2tensor
from PIL import Image, ImageFilter, ImageDraw
from ..utils import tensor2pil, pil2tensor, tensor2np, np2tensor
from PIL import Image, ImageFilter, ImageDraw, ImageChops
import numpy as np
from ..log import log
class BoundingBox:
class Bbox:
"""The bounding box (BBOX) custom type used by other nodes"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
# "bbox": ("BBOX",),
"x": ("INT", {"default": 0, "max": 10000000, "min": 0, "step": 1}),
"y": ("INT", {"default": 0, "max": 10000000, "min": 0, "step": 1}),
"width": (
@@ -28,16 +29,15 @@ class BoundingBox:
RETURN_TYPES = ("BBOX",)
FUNCTION = "do_crop"
CATEGORY = "image/crop"
CATEGORY = "mtb/crop"
def do_crop(self, x, y, width, height):
def do_crop(self, x, y, width, height): # bbox
return (x, y, width, height)
# return bbox
class BBoxFromMask:
class BboxFromMask:
"""From a mask extract the bounding box"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
@@ -59,13 +59,25 @@ class BBoxFromMask:
"image (optional)",
)
FUNCTION = "extract_bounding_box"
CATEGORY = "image/crop"
CATEGORY = "mtb/crop"
def extract_bounding_box(self, mask: torch.Tensor, image=None):
# if image != None:
# if mask.size(0) != image.size(0):
# if mask.size(0) != 1:
# log.error(
# f"Batch count mismatch for mask and image, it can either be 1 mask for X images, or X masks for X images (mask: {mask.shape} | image: {image.shape})"
# )
mask = tensor2pil(mask)
# raise Exception(
# f"Batch count mismatch for mask and image, it can either be 1 mask for X images, or X masks for X images (mask: {mask.shape} | image: {image.shape})"
# )
_mask = tensor2pil(1.0 - mask)[0]
# we invert it
alpha_channel = np.array(_mask)
alpha_channel = np.array(mask)
non_zero_indices = np.nonzero(alpha_channel)
min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
@@ -74,11 +86,16 @@ class BBoxFromMask:
# Create a bounding box tuple
if image != None:
# Convert the image to a NumPy array
image = image.numpy()
# Crop the image from the bounding box
image = image[:, min_y:max_y, min_x:max_x]
image = torch.from_numpy(image)
imgs = tensor2np(image)
out = []
for img in imgs:
# Crop the image from the bounding box
img = img[min_y:max_y, min_x:max_x, :]
log.debug(f"Cropped image to shape {img.shape}")
out.append(img)
image = np2tensor(out)
log.debug(f"Cropped images shape: {image.shape}")
bounding_box = (min_x, min_y, max_x - min_x, max_y - min_y)
return (
bounding_box,
@@ -92,8 +109,6 @@ class Crop:
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
The BBOX input takes precedence over the tuple input
"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
@@ -120,12 +135,11 @@ class Crop:
RETURN_TYPES = ("IMAGE", "MASK", "BBOX")
FUNCTION = "do_crop"
CATEGORY = "image/crop"
CATEGORY = "mtb/crop"
def do_crop(
self, image: torch.Tensor, mask=None, x=0, y=0, width=256, height=256, bbox=None
):
image = image.numpy()
if mask:
mask = mask.numpy()
@@ -144,13 +158,43 @@ class Crop:
)
# def calculate_intersection(rect1, rect2):
# x_left = max(rect1[0], rect2[0])
# y_top = max(rect1[1], rect2[1])
# x_right = min(rect1[2], rect2[2])
# y_bottom = min(rect1[3], rect2[3])
# return (x_left, y_top, x_right, y_bottom)
def bbox_check(bbox, target_size=None):
if not target_size:
return bbox
new_bbox = (
bbox[0],
bbox[1],
min(target_size[0] - bbox[0], bbox[2]),
min(target_size[1] - bbox[1], bbox[3]),
)
if new_bbox != bbox:
log.warn(f"BBox too big, constrained to {new_bbox}")
return new_bbox
def bbox_to_region(bbox, target_size=None):
bbox = bbox_check(bbox, target_size)
# to region
return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
class 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
The BBOX input takes precedence over the tuple input"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
@@ -169,7 +213,7 @@ class Uncrop:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_crop"
CATEGORY = "image/crop"
CATEGORY = "mtb/crop"
def do_crop(self, image, crop_image, bbox, border_blending):
def inset_border(image, border_width=20, border_color=(0)):
@@ -182,41 +226,63 @@ class Uncrop:
)
return bordered_image
image = tensor2pil(image)
crop_img = tensor2pil(crop_image)
crop_img = crop_img.convert("RGB")
single = image.size(0) == 1
if image.size(0) != crop_image.size(0):
if not single:
raise ValueError(
"The Image batch count is greater than 1, but doesn't match the crop_image batch count. If using batches they should either match or only crop_image must be greater than 1"
)
# uncrop the image based on the bounding box
bb_x, bb_y, bb_width, bb_height = bbox
images = tensor2pil(image)
crop_imgs = tensor2pil(crop_image)
out_images = []
for i, crop in enumerate(crop_imgs):
if single:
img = images[0]
else:
img = images[i]
if border_blending > 1.0:
border_blending = 1.0
elif border_blending < 0.0:
border_blending = 0.0
# uncrop the image based on the bounding box
bb_x, bb_y, bb_width, bb_height = bbox
blend_ratio = (max(crop_img.size) / 2) * float(border_blending)
paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size)
# log.debug(f"Paste region: {paste_region}")
# new_region = adjust_paste_region(img.size, paste_region)
# log.debug(f"Adjusted paste region: {new_region}")
# # Check if the adjusted paste region is different from the original
blend = image.convert("RGBA")
mask = Image.new("L", image.size, 0)
crop_img = crop.convert("RGB")
mask_block = Image.new("L", (bb_width, bb_height), 255)
mask_block = inset_border(mask_block, int(blend_ratio / 2), (0))
log.debug(f"Crop image size: {crop_img.size}")
log.debug(f"Image size: {img.size}")
mask.paste(mask_block, (bb_x, bb_y, bb_x + bb_width, bb_y + bb_height))
blend.paste(crop_img, (bb_x, bb_y, bb_x + bb_width, bb_y + bb_height))
if border_blending > 1.0:
border_blending = 1.0
elif border_blending < 0.0:
border_blending = 0.0
mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4))
mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4))
blend_ratio = (max(crop_img.size) / 2) * float(border_blending)
blend.putalpha(mask)
image = Image.alpha_composite(image.convert("RGBA"), blend)
blend = img.convert("RGBA")
mask = Image.new("L", img.size, 0)
return (pil2tensor(image.convert("RGB")),)
mask_block = Image.new("L", (bb_width, bb_height), 255)
mask_block = inset_border(mask_block, int(blend_ratio / 2), (0))
mask.paste(mask_block, paste_region)
log.debug(f"Blend size: {blend.size} | kind {blend.mode}")
log.debug(f"Crop image size: {crop_img.size} | kind {crop_img.mode}")
log.debug(f"BBox: {paste_region}")
blend.paste(crop_img, paste_region)
mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4))
mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4))
blend.putalpha(mask)
img = Image.alpha_composite(img.convert("RGBA"), blend)
out_images.append(img.convert("RGB"))
return (pil2tensor(out_images),)
__nodes__ = [
BBoxFromMask,
BoundingBox,
Crop,
Uncrop
]
__nodes__ = [BboxFromMask, Bbox, Crop, Uncrop]
+121
View File
@@ -0,0 +1,121 @@
from ..utils import tensor2pil
from ..log import log
import io, base64
import torch
import folder_paths
from typing import Optional
from pathlib import Path
class Debug:
"""Experimental node to debug any Comfy values, support for more types and widgets is planned"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"anything_1": ("*")},
}
RETURN_TYPES = ("STRING",)
FUNCTION = "do_debug"
CATEGORY = "mtb/debug"
OUTPUT_NODE = True
def do_debug(self, **kwargs):
output = {
"ui": {"b64_images": [], "text": []},
"result": ("A"),
}
for k, v in kwargs.items():
anything = v
text = ""
if isinstance(anything, torch.Tensor):
log.debug(f"Tensor: {anything.shape}")
# write the images to temp
image = tensor2pil(anything)
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")
)
output["ui"]["b64_images"] += b64_imgs
log.debug(f"Input {k} contains {len(b64_imgs)} images")
elif isinstance(anything, bool):
log.debug(f"Input {k} contains boolean: {anything}")
output["ui"]["text"] += ["True" if anything else "False"]
else:
text = str(anything)
log.debug(f"Input {k} contains text: {text}")
output["ui"]["text"] += [text]
return output
class SaveTensors:
"""Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy"""
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "mtb/debug"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"filename_prefix": ("STRING", {"default": "ComfyPickle"}),
},
"optional": {
"image": ("IMAGE",),
"mask": ("MASK",),
"latent": ("LATENT",),
},
}
FUNCTION = "save"
OUTPUT_NODE = True
RETURN_TYPES = ()
CATEGORY = "mtb/debug"
def save(
self,
filename_prefix,
image: Optional[torch.Tensor] = None,
mask: Optional[torch.Tensor] = None,
latent: Optional[torch.Tensor] = None,
):
(
full_output_folder,
filename,
counter,
subfolder,
filename_prefix,
) = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
full_output_folder = Path(full_output_folder)
if image is not None:
image_file = f"{filename}_image_{counter:05}.pt"
torch.save(image, full_output_folder / image_file)
# np.save(full_output_folder/ image_file, image.cpu().numpy())
if mask is not None:
mask_file = f"{filename}_mask_{counter:05}.pt"
torch.save(mask, full_output_folder / mask_file)
# np.save(full_output_folder/ mask_file, mask.cpu().numpy())
if latent is not None:
# for latent we must use pickle
latent_file = f"{filename}_latent_{counter:05}.pt"
torch.save(latent, full_output_folder / latent_file)
# pickle.dump(latent, open(full_output_folder/ latent_file, "wb"))
# np.save(full_output_folder/ latent_file, latent[""].cpu().numpy())
return f"{filename_prefix}_{counter:05}"
__nodes__ = [Debug, SaveTensors]
+4 -9
View File
@@ -241,9 +241,6 @@ def normals_to_height(normals_img, seamless, progress_callback):
class DeepBump:
"""Normal & height maps generation from single pictures"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -264,14 +261,14 @@ class DeepBump:
"LARGEST",
],
),
"normals_to_height_seamless": (["TRUE", "FALSE"],),
"normals_to_height_seamless": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "apply"
CATEGORY = "image processing"
CATEGORY = "mtb/textures"
def apply(
self,
@@ -279,7 +276,7 @@ class DeepBump:
mode="Color to Normals",
color_to_normals_overlap="SMALL",
normals_to_curvature_blur_radius="SMALL",
normals_to_height_seamless="TRUE",
normals_to_height_seamless=True,
):
image = utils_inference.tensor2pil(image)
@@ -295,9 +292,7 @@ class DeepBump:
in_img, normals_to_curvature_blur_radius, None
)
if mode == "Normals to Height":
out_img = normals_to_height(
in_img, normals_to_height_seamless == "TRUE", None
)
out_img = normals_to_height(in_img, normals_to_height_seamless, None)
out_img = (np.transpose(out_img, (1, 2, 0)) * 255).astype(np.uint8)
+262
View File
@@ -0,0 +1,262 @@
from gfpgan import GFPGANer
import cv2
import numpy as np
import os
from pathlib import Path
import folder_paths
from ..utils import pil2tensor, np2tensor, tensor2np
from basicsr.utils import imwrite
from PIL import Image
import torch
from ..log import NullWriter, log
from comfy import model_management
import comfy
import comfy.utils
from typing import Tuple
class LoadFaceEnhanceModel:
"""Loads a GFPGan or RestoreFormer model for face enhancement."""
def __init__(self) -> None:
pass
@classmethod
def get_models_root(cls):
fr = Path(folder_paths.models_dir) / "face_restore"
if fr.exists():
return (fr, None)
um = Path(folder_paths.models_dir) / "upscale_models"
return (fr, um) if um.exists() else (None, None)
@classmethod
def get_models(cls):
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.")
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"
)
if um_models_path.exists():
return [
x
for x in um_models_path.iterdir()
if x.name.endswith(".pth")
and ("GFPGAN" in x.name or "RestoreFormer" in x.name)
]
return []
return [
x
for x in fr_models_path.iterdir()
if x.name.endswith(".pth")
and ("GFPGAN" in x.name or "RestoreFormer" in x.name)
]
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_name": (
[x.name for x in cls.get_models()],
{"default": "None"},
),
"upscale": ("INT", {"default": 1}),
},
"optional": {"bg_upsampler": ("UPSCALE_MODEL", {"default": None})},
}
RETURN_TYPES = ("FACEENHANCE_MODEL",)
RETURN_NAMES = ("model",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
def load_model(self, model_name, upscale=2, bg_upsampler=None):
basic = "RestoreFormer" not in model_name
fr_root, um_root = self.get_models_root()
if bg_upsampler is not None:
log.warning(
f"Upscale value overridden to {bg_upsampler.scale} from bg_upsampler"
)
upscale = bg_upsampler.scale
bg_upsampler = BGUpscaleWrapper(bg_upsampler)
sys.stdout = NullWriter()
model = GFPGANer(
model_path=(
(fr_root if fr_root.exists() else um_root) / model_name
).as_posix(),
upscale=upscale,
arch="clean" if basic else "RestoreFormer", # or original for v1.0 only
channel_multiplier=2, # 1 for v1.0 only
bg_upsampler=bg_upsampler,
)
sys.stdout = sys.__stdout__
return (model,)
class BGUpscaleWrapper:
def __init__(self, upscale_model) -> None:
self.upscale_model = upscale_model
def enhance(self, img: Image.Image, outscale=2):
device = model_management.get_torch_device()
self.upscale_model.to(device)
tile = 128 + 64
overlap = 8
imgt = np2tensor(img)
imgt = imgt.movedim(-1, -3).to(device)
steps = imgt.shape[0] * comfy.utils.get_tiled_scale_steps(
imgt.shape[3], imgt.shape[2], tile_x=tile, tile_y=tile, overlap=overlap
)
log.debug(f"Steps: {steps}")
pbar = comfy.utils.ProgressBar(steps)
s = comfy.utils.tiled_scale(
imgt,
lambda a: self.upscale_model(a),
tile_x=tile,
tile_y=tile,
overlap=overlap,
upscale_amount=self.upscale_model.scale,
pbar=pbar,
)
self.upscale_model.cpu()
s = torch.clamp(s.movedim(-3, -1), min=0, max=1.0)
return (tensor2np(s)[0],)
import sys
class RestoreFace:
"""Uses GFPGan to restore faces"""
def __init__(self) -> None:
pass
RETURN_TYPES = ("IMAGE",)
FUNCTION = "restore"
CATEGORY = "mtb/facetools"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"model": ("FACEENHANCE_MODEL",),
# Input are aligned faces
"aligned": ("BOOLEAN", {"default": False}),
# Only restore the center face
"only_center_face": ("BOOLEAN", {"default": False}),
# Adjustable weights
"weight": ("FLOAT", {"default": 0.5}),
"save_tmp_steps": ("BOOLEAN", {"default": True}),
}
}
def do_restore(
self,
image: torch.Tensor,
model: GFPGANer,
aligned,
only_center_face,
weight,
save_tmp_steps,
) -> torch.Tensor:
pimage = tensor2np(image)[0]
width, height = pimage.shape[1], pimage.shape[0]
source_img = cv2.cvtColor(np.array(pimage), cv2.COLOR_RGB2BGR)
sys.stdout = NullWriter()
cropped_faces, restored_faces, restored_img = model.enhance(
source_img,
has_aligned=aligned,
only_center_face=only_center_face,
paste_back=True,
# TODO: weight has no effect in 1.3 and 1.4 (only tested these for now...)
weight=weight,
)
sys.stdout = sys.__stdout__
log.warning(f"Weight value has no effect for now. (value: {weight})")
if save_tmp_steps:
self.save_intermediate_images(cropped_faces, restored_faces, height, width)
output = None
if restored_img is not None:
output = Image.fromarray(cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB))
# imwrite(restored_img, save_restore_path)
return pil2tensor(output)
def restore(
self,
image: torch.Tensor,
model: GFPGANer,
aligned=False,
only_center_face=False,
weight=0.5,
save_tmp_steps=True,
) -> Tuple[torch.Tensor]:
out = [
self.do_restore(
image[i], model, aligned, only_center_face, weight, save_tmp_steps
)
for i in range(image.size(0))
]
return (torch.cat(out, dim=0),)
def get_step_image_path(self, step, idx):
(
full_output_folder,
filename,
counter,
_subfolder,
_filename_prefix,
) = folder_paths.get_save_image_path(
f"{step}_{idx:03}",
folder_paths.temp_directory,
)
file = f"{filename}_{counter:05}_.png"
return os.path.join(full_output_folder, file)
def save_intermediate_images(self, cropped_faces, restored_faces, height, width):
for idx, (cropped_face, restored_face) in enumerate(
zip(cropped_faces, restored_faces)
):
face_id = idx + 1
file = self.get_step_image_path("cropped_faces", face_id)
imwrite(cropped_face, file)
file = self.get_step_image_path("cropped_faces_restored", face_id)
imwrite(restored_face, file)
file = self.get_step_image_path("cropped_faces_compare", face_id)
# save comparison image
cmp_img = np.concatenate((cropped_face, restored_face), axis=1)
imwrite(cmp_img, file)
__nodes__ = [RestoreFace, LoadFaceEnhanceModel]
+130 -80
View File
@@ -1,36 +1,69 @@
# region imports
from ifnude import detect
import onnxruntime
from pathlib import Path
from PIL import Image
from typing import List, Set, Tuple
from typing import List, Set, Union, Optional
import cv2
import folder_paths
import glob
import insightface
import numpy as np
import onnxruntime
import os
import tempfile
import torch
from insightface.model_zoo.inswapper import INSwapper
from ..utils import pil2tensor, tensor2pil, download_antelopev2
from ..log import mklog, NullWriter
import sys
import comfy.model_management as model_management
from ..utils import pil2tensor, tensor2pil
from ..log import mklog
# endregion
logger = mklog(__name__)
providers = onnxruntime.get_available_providers()
log = mklog(__name__)
# region roop node
class FaceSwap:
"""Face swap using deepinsight/insightface models"""
class LoadFaceAnalysisModel:
"""Loads a face analysis model"""
model = None
model_path = None
models = []
def __init__(self) -> None:
pass
@staticmethod
def get_models() -> List[str]:
models_path = os.path.join(folder_paths.models_dir, "insightface/*")
models = glob.glob(models_path)
models = [
Path(x).name for x in models if x.endswith(".onnx") or x.endswith(".pth")
]
return models
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"faceswap_model": (
["antelopev2", "buffalo_l", "buffalo_m", "buffalo_sc"],
{"default": "buffalo_l"},
),
},
}
RETURN_TYPES = ("FACE_ANALYSIS_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
def load_model(self, faceswap_model: str):
if faceswap_model == "antelopev2":
download_antelopev2()
face_analyser = insightface.app.FaceAnalysis(
name=faceswap_model,
root=os.path.join(folder_paths.models_dir, "insightface"),
)
return (face_analyser,)
class LoadFaceSwapModel:
"""Loads a faceswap model"""
@staticmethod
def get_models() -> List[Path]:
@@ -43,42 +76,83 @@ class FaceSwap:
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"reference": ("IMAGE",),
"faces_index": ("STRING", {"default": "0"}),
"faceswap_model": (
[x.name for x in cls.get_models()],
{"default": "None"},
),
},
"optional": {"debug": (["true", "false"], {"default": "false"})},
}
RETURN_TYPES = ("FACESWAP_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/facetools"
def load_model(self, faceswap_model: str):
model_path = os.path.join(
folder_paths.models_dir, "insightface", faceswap_model
)
log.info(f"Loading model {model_path}")
return (
INSwapper(
model_path,
onnxruntime.InferenceSession(
path_or_bytes=model_path,
providers=onnxruntime.get_available_providers(),
),
),
)
# region roop node
class FaceSwap:
"""Face swap using deepinsight/insightface models"""
model = None
model_path = None
def __init__(self) -> None:
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"reference": ("IMAGE",),
"faces_index": ("STRING", {"default": "0"}),
"faceanalysis_model": ("FACE_ANALYSIS_MODEL", {"default": "None"}),
"faceswap_model": ("FACESWAP_MODEL", {"default": "None"}),
},
"optional": {},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "swap"
CATEGORY = "face"
CATEGORY = "mtb/facetools"
def swap(
self,
image: torch.Tensor,
reference: torch.Tensor,
faces_index: str,
faceswap_model: str,
debug: str,
faceanalysis_model,
faceswap_model,
):
def do_swap(img):
img = tensor2pil(img)
ref = tensor2pil(reference)
model_management.throw_exception_if_processing_interrupted()
img = tensor2pil(img)[0]
ref = tensor2pil(reference)[0]
face_ids = {
int(x) for x in faces_index.strip(",").split(",") if x.isnumeric()
}
model = self.getFaceSwapModel(faceswap_model)
swapped = swap_face(ref, img, model, face_ids)
sys.stdout = NullWriter()
swapped = swap_face(faceanalysis_model, ref, img, faceswap_model, face_ids)
sys.stdout = sys.__stdout__
return pil2tensor(swapped)
batch_count = image.size(0)
logger.info(f"Running insightface swap (batch size: {batch_count})")
log.info(f"Running insightface swap (batch size: {batch_count})")
if reference.size(0) != 1:
raise ValueError("Reference image must have batch size 1")
@@ -86,38 +160,28 @@ class FaceSwap:
image = do_swap(image)
else:
image = [do_swap(image[i]) for i in range(batch_count)]
image = torch.cat(image, dim=0)
image_batch = [do_swap(image[i]) for i in range(batch_count)]
image = torch.cat(image_batch, dim=0)
return (image,)
def getFaceSwapModel(self, model_path: str):
model_path = os.path.join(folder_paths.models_dir, "insightface", model_path)
if self.model_path is None or self.model_path != model_path:
logger.info(f"Loading model {model_path}")
self.model_path = model_path
self.model = insightface.model_zoo.get_model(
model_path, providers=providers
)
else:
logger.info("Using cached model")
logger.info("Model loaded")
return self.model
# endregion
# region face swap utils
def get_face_single(img_data: np.ndarray, face_index=0, det_size=(640, 640)):
face_analyser = insightface.app.FaceAnalysis(name="buffalo_l", providers=providers)
def get_face_single(
face_analyser, img_data: np.ndarray, face_index=0, det_size=(640, 640)
):
face_analyser.prepare(ctx_id=0, det_size=det_size)
face = face_analyser.get(img_data)
if len(face) == 0 and det_size[0] > 320 and det_size[1] > 320:
log.debug("No face ed, trying again with smaller image")
det_size_half = (det_size[0] // 2, det_size[1] // 2)
return get_face_single(img_data, face_index=face_index, det_size=det_size_half)
return get_face_single(
face_analyser, img_data, face_index=face_index, det_size=det_size_half
)
try:
return sorted(face, key=lambda x: x.bbox[0])[face_index]
@@ -125,59 +189,45 @@ def get_face_single(img_data: np.ndarray, face_index=0, det_size=(640, 640)):
return None
def convert_to_sd(img) -> Tuple[bool, str]:
chunks = detect(img)
shapes = [chunk["score"] > 0.7 for chunk in chunks]
return [any(shapes), tempfile.NamedTemporaryFile(delete=False, suffix=".png")]
def swap_face(
source_img: Image.Image,
target_img: Image.Image,
face_swapper_model=None,
faces_index: Set[int] = None,
face_analyser,
source_img: Union[Image.Image, List[Image.Image]],
target_img: Union[Image.Image, List[Image.Image]],
face_swapper_model,
faces_index: Optional[Set[int]] = None,
) -> Image.Image:
if faces_index is None:
faces_index = {0}
logger.info(f"Swapping faces: {faces_index}")
log.debug(f"Swapping faces: {faces_index}")
result_image = target_img
converted = convert_to_sd(target_img)
scale, fn = converted[0], converted[1]
if face_swapper_model is not None and not scale:
if isinstance(source_img, str): # source_img is a base64 string
import base64, io
if (
"base64," in source_img
): # check if the base64 string has a data URL scheme
base64_data = source_img.split("base64,")[-1]
img_bytes = base64.b64decode(base64_data)
else:
# if no data URL scheme, just decode
img_bytes = base64.b64decode(source_img)
source_img = Image.open(io.BytesIO(img_bytes))
source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
source_face = get_face_single(source_img, face_index=0)
if face_swapper_model is not None:
cv_source_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
cv_target_img = cv2.cvtColor(np.array(target_img), cv2.COLOR_RGB2BGR)
source_face = get_face_single(face_analyser, cv_source_img, face_index=0)
if source_face is not None:
result = target_img
result = cv_target_img
for face_num in faces_index:
target_face = get_face_single(target_img, face_index=face_num)
target_face = get_face_single(
face_analyser, cv_target_img, face_index=face_num
)
if target_face is not None:
sys.stdout = NullWriter()
result = face_swapper_model.get(result, target_face, source_face)
sys.stdout = sys.__stdout__
else:
logger.warning(f"No target face found for {face_num}")
log.warning(f"No target face found for {face_num}")
result_image = Image.fromarray(cv2.cvtColor(result, cv2.COLOR_BGR2RGB))
else:
logger.warning("No source face found")
log.warning("No source face found")
else:
logger.error("No face swap model provided")
log.error("No face swap model provided")
return result_image
# endregion face swap utils
__nodes__ = [FaceSwap]
__nodes__ = [FaceSwap, LoadFaceSwapModel, LoadFaceAnalysisModel]
-66
View File
@@ -1,66 +0,0 @@
import qrcode
from ..utils import pil2tensor
from PIL import Image
class QrCode:
"""Basic QR Code generator"""
def __init__(self):
pass
@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": (("True", "False"), {"default": "False"}),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_qr"
CATEGORY = "fun"
def do_qr(self, url, width, height, error_correct, box_size, border, invert):
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 == "True" else (0, 0, 0)
fill_color = (0, 0, 0) if invert == "True" 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),)
__nodes__ = [QrCode]
+286
View File
@@ -0,0 +1,286 @@
import qrcode
from ..utils import pil2tensor
from ..utils import comfy_dir
from typing import cast
from PIL import Image
from ..log import log
# class MtbExamples:
# """MTB Example Images"""
# def __init__(self):
# pass
# @classmethod
# @lru_cache(maxsize=1)
# def get_root(cls):
# return here / "examples" / "samples"
# @classmethod
# def INPUT_TYPES(cls):
# input_dir = cls.get_root()
# files = [f.name for f in input_dir.iterdir() if f.is_file()]
# return {
# "required": {"image": (sorted(files),)},
# }
# RETURN_TYPES = ("IMAGE", "MASK")
# FUNCTION = "do_mtb_examples"
# CATEGORY = "fun"
# def do_mtb_examples(self, image, index):
# image_path = (self.get_root() / image).as_posix()
# i = Image.open(image_path)
# i = ImageOps.exif_transpose(i)
# image = i.convert("RGB")
# image = np.array(image).astype(np.float32) / 255.0
# image = torch.from_numpy(image)[None,]
# if "A" in i.getbands():
# mask = np.array(i.getchannel("A")).astype(np.float32) / 255.0
# mask = 1.0 - torch.from_numpy(mask)
# else:
# mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
# return (image, mask)
# @classmethod
# def IS_CHANGED(cls, image):
# image_path = (cls.get_root() / image).as_posix()
# m = hashlib.sha256()
# with open(image_path, "rb") as f:
# m.update(f.read())
# return m.digest().hex()
class UnsplashImage:
"""Unsplash Image given a keyword and a size"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"width": ("INT", {"default": 512, "max": 8096, "min": 0, "step": 1}),
"height": ("INT", {"default": 512, "max": 8096, "min": 0, "step": 1}),
"random_seed": ("INT", {"default": 0, "max": 1e5, "min": 0, "step": 1}),
},
"optional": {
"keyword": ("STRING", {"default": "nature"}),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_unsplash_image"
CATEGORY = "mtb/generate"
def do_unsplash_image(self, width, height, random_seed, keyword=None):
import requests
import io
base_url = "https://source.unsplash.com/random/"
if width and height:
base_url += f"/{width}x{height}"
if keyword:
keyword = keyword.replace(" ", "%20")
base_url += f"?{keyword}&{random_seed}"
else:
base_url += f"?&{random_seed}"
try:
log.debug(f"Getting unsplash image from {base_url}")
response = requests.get(base_url)
response.raise_for_status()
image = Image.open(io.BytesIO(response.content))
return (
pil2tensor(
image,
),
)
except requests.exceptions.RequestException as e:
print("Error retrieving image:", e)
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
height = lower - upper
return width, height
class TextToImage:
"""Utils to convert text to image using a font
The tool looks for any .ttf file in the Comfy folder hierarchy.
"""
fonts = {}
def __init__(self):
# - This is executed when the graph is executed, we could conditionaly reload fonts there
pass
@classmethod
def CACHE_FONTS(cls):
font_extensions = ["*.ttf", "*.otf", "*.woff", "*.woff2", "*.eot"]
fonts = []
for extension in font_extensions:
fonts.extend(comfy_dir.glob(f"**/{extension}"))
if not fonts:
log.warn(
"> No fonts found in the comfy folder, place at least one font file somewhere in ComfyUI's hierarchy"
)
else:
log.debug(f"> Found {len(fonts)} fonts")
for font in fonts:
log.debug(f"Adding font {font}")
cls.fonts[font.stem] = font.as_posix()
@classmethod
def INPUT_TYPES(cls):
if not cls.fonts:
cls.CACHE_FONTS()
else:
log.debug(f"Using cached fonts (count: {len(cls.fonts)})")
return {
"required": {
"text": (
"STRING",
{"default": "Hello world!"},
),
"font": ((sorted(cls.fonts.keys())),),
"wrap": (
"INT",
{"default": 120, "min": 0, "max": 8096, "step": 1},
),
"font_size": (
"INT",
{"default": 12, "min": 1, "max": 2500, "step": 1},
),
"width": (
"INT",
{"default": 512, "min": 1, "max": 8096, "step": 1},
),
"height": (
"INT",
{"default": 512, "min": 1, "max": 8096, "step": 1},
),
# "position": (["INT"], {"default": 0, "min": 0, "max": 100, "step": 1}),
"color": (
"COLOR",
{"default": "black"},
),
"background": (
"COLOR",
{"default": "white"},
),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "text_to_image"
CATEGORY = "mtb/generate"
def text_to_image(
self, text, font, wrap, font_size, width, height, color, background
):
from PIL import Image, ImageDraw, ImageFont
import textwrap
font = self.fonts[font]
font = cast(ImageFont.FreeTypeFont, ImageFont.truetype(font, font_size))
if wrap == 0:
wrap = width / font_size
lines = textwrap.wrap(text, width=wrap)
log.debug(f"Lines: {lines}")
line_height = bbox_dim(font.getbbox("hg"))[1]
img_height = height # line_height * len(lines)
img_width = width # max(font.getsize(line)[0] for line in lines)
img = Image.new("RGBA", (img_width, img_height), background)
draw = ImageDraw.Draw(img)
y_text = 0
# - bbox is [left, upper, right, lower]
for line in lines:
width, height = bbox_dim(font.getbbox(line))
draw.text((0, y_text), line, color, font=font)
y_text += height
# img.save(os.path.join(folder_paths.base_path, f'{str(uuid.uuid4())}.png'))
return (pil2tensor(img),)
__nodes__ = [
QrCode,
UnsplashImage,
TextToImage
# MtbExamples,
]
+211 -45
View File
@@ -1,69 +1,235 @@
from ..log import log
from PIL import Image
import urllib.request
import urllib.parse
import torch
import folder_paths
import os
import json
from comfy.cli_args import args
from ..utils import pil2tensor, apply_easing
import io
import numpy as np
class SaveTensors:
"""Debug node that will probably be removed in the future"""
def get_image(filename, subfolder, folder_type):
log.debug(f"Getting image {filename} from {subfolder} of {folder_type}")
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
with urllib.request.urlopen(
f"http://{args.listen}:{args.port}/view?{url_values}"
) as response:
return io.BytesIO(response.read())
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "output"
class GetBatchFromHistory:
"""Very experimental node to load images from the history of the server.
Queue items without output are ignored in the count."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"filename_prefix": ("STRING", {"default": "ComfyPickle"}),
"enable": ("BOOLEAN", {"default": True}),
"count": ("INT", {"default": 1, "min": 0}),
"offset": ("INT", {"default": 0, "min": -1e9, "max": 1e9}),
"internal_count": ("INT", {"default": 0}),
},
"optional": {
"image": ("IMAGE",),
"mask": ("MASK",),
"latent": ("LATENT",),
"passthrough_image": ("IMAGE",),
},
}
FUNCTION = "save"
OUTPUT_NODE = True
RETURN_TYPES = ()
CATEGORY = "utils"
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
CATEGORY = "mtb/animation"
FUNCTION = "load_from_history"
def save(
def load_from_history(
self,
filename_prefix,
image: torch.Tensor = None,
mask: torch.Tensor = None,
latent: torch.Tensor = None,
enable=True,
count=0,
offset=0,
internal_count=0, # hacky way to invalidate the node
passthrough_image=None,
):
(
full_output_folder,
filename,
counter,
subfolder,
filename_prefix,
) = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
if not enable or count == 0:
if passthrough_image is not None:
log.debug("Using passthrough image")
return (passthrough_image,)
log.debug("Load from history is disabled for this iteration")
return (torch.zeros(0),)
frames = []
if image is not None:
image_file = f"{filename}_image_{counter:05}.pt"
torch.save(image, os.path.join(full_output_folder, image_file))
# np.save(os.path.join(full_output_folder, image_file), image.cpu().numpy())
with urllib.request.urlopen(
f"http://{args.listen}:{args.port}/history"
) as response:
return self.load_batch_frames(response, offset, count, frames)
if mask is not None:
mask_file = f"{filename}_mask_{counter:05}.pt"
torch.save(mask, os.path.join(full_output_folder, mask_file))
# np.save(os.path.join(full_output_folder, mask_file), mask.cpu().numpy())
def load_batch_frames(self, response, offset, count, frames):
history = json.loads(response.read())
if latent is not None:
# for latent we must use pickle
latent_file = f"{filename}_latent_{counter:05}.pt"
torch.save(latent, os.path.join(full_output_folder, latent_file))
# pickle.dump(latent, open(os.path.join(full_output_folder, latent_file), "wb"))
output_images = []
# np.save(os.path.join(full_output_folder, latent_file), latent[""].cpu().numpy())
for run in history.values():
for node_output in run["outputs"].values():
if "images" in node_output:
for image in node_output["images"]:
image_data = get_image(
image["filename"], image["subfolder"], image["type"]
)
output_images.append(image_data)
return f"{filename_prefix}_{counter:05}"
if not output_images:
return (torch.zeros(0),)
# Directly get desired range of images
start_index = max(len(output_images) - offset - count, 0)
end_index = len(output_images) - offset
selected_images = output_images[start_index:end_index]
frames = [Image.open(image) for image in selected_images]
if not frames:
return (torch.zeros(0),)
elif len(frames) != count:
log.warning(f"Expected {count} images, got {len(frames)} instead")
output = pil2tensor(frames)
return (output,)
__nodes__ = [
SaveTensors,
]
class AnyToString:
"""Tries to take any input and convert it to a string"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"input": ("*")},
}
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):
return (f"Numpy array of shape {input.shape} and dtype {input.dtype}",)
elif isinstance(input, dict):
return (f"Dictionary of {len(input)} items, with keys {input.keys()}",)
else:
log.debug(f"Falling back to string conversion of {input}")
return (str(input),)
class StringReplace:
"""Basic string replacement"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"string": ("STRING", {"forceInput": True}),
"old": ("STRING", {"default": ""}),
"new": ("STRING", {"default": ""}),
}
}
FUNCTION = "replace_str"
RETURN_TYPES = ("STRING",)
CATEGORY = "mtb/string"
def replace_str(self, string: str, old: str, new: str):
log.debug(f"Current string: {string}")
log.debug(f"Find string: {old}")
log.debug(f"Replace string: {new}")
string = string.replace(old, new)
log.debug(f"New string: {string}")
return (string,)
class FitNumber:
"""Fit the input float using a source and target range"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"value": ("FLOAT", {"default": 0, "forceInput": True}),
"clamp": ("BOOLEAN", {"default": False}),
"source_min": ("FLOAT", {"default": 0.0}),
"source_max": ("FLOAT", {"default": 1.0}),
"target_min": ("FLOAT", {"default": 0.0}),
"target_max": ("FLOAT", {"default": 1.0}),
"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",
],
{"default": "Linear"},
),
}
}
FUNCTION = "set_range"
RETURN_TYPES = ("FLOAT",)
CATEGORY = "mtb/math"
def set_range(
self,
value: float,
clamp: bool,
source_min: float,
source_max: float,
target_min: float,
target_max: float,
easing: str,
):
normalized_value = (value - source_min) / (source_max - source_min)
eased_value = apply_easing(normalized_value, easing)
# - Convert the eased value to the target range
res = target_min + (target_max - target_min) * eased_value
if clamp:
if target_min > target_max:
res = max(min(res, target_min), target_max)
else:
res = max(min(res, target_max), target_min)
return (res,)
__nodes__ = [StringReplace, FitNumber, GetBatchFromHistory, AnyToString]
+154
View File
@@ -0,0 +1,154 @@
from typing import List
from pathlib import Path
import os
import glob
import folder_paths
from ..log import log
import torch
from frame_interpolation.eval import util, interpolator
import numpy as np
import comfy
import comfy.utils
import tensorflow as tf
import comfy.model_management as model_management
class LoadFilmModel:
"""Loads a FILM model"""
@staticmethod
def get_models() -> List[Path]:
models_path = os.path.join(folder_paths.models_dir, "FILM/*")
models = glob.glob(models_path)
models = [Path(x) for x in models if x.endswith(".onnx") or x.endswith(".pth")]
return models
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"film_model": (
["L1", "Style", "VGG"],
{"default": "Style"},
),
},
}
RETURN_TYPES = ("FILM_MODEL",)
FUNCTION = "load_model"
CATEGORY = "mtb/frame iterpolation"
def load_model(self, film_model: str):
model_path = Path(folder_paths.models_dir) / "FILM" / film_model
if not (model_path / "saved_model.pb").exists():
model_path = model_path / "saved_model"
if not model_path.exists():
log.error(f"Model {model_path} does not exist")
raise ValueError(f"Model {model_path} does not exist")
log.info(f"Loading model {model_path}")
return (interpolator.Interpolator(model_path.as_posix(), None),)
class FilmInterpolation:
"""Google Research FILM frame interpolation for large motion"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": ("IMAGE",),
"interpolate": ("INT", {"default": 2, "min": 1, "max": 50}),
"film_model": ("FILM_MODEL",),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_interpolation"
CATEGORY = "mtb/frame iterpolation"
def do_interpolation(
self,
images: torch.Tensor,
interpolate: int,
film_model: interpolator.Interpolator,
):
n = images.size(0)
# check if images is an empty tensor and return it...
if n == 0:
return (images,)
# check if tensorflow GPU is available
available_gpus = tf.config.list_physical_devices("GPU")
if not len(available_gpus):
log.warning(
"Tensorflow GPU not available, falling back to CPU this will be very slow"
)
else:
log.debug(f"Tensorflow GPU available, using {available_gpus}")
num_frames = (n - 1) * (2 ** (interpolate) - 1)
log.debug(f"Will interpolate into {num_frames} frames")
in_frames = [images[i] for i in range(n)]
out_tensors = []
pbar = comfy.utils.ProgressBar(num_frames)
for frame in util.interpolate_recursively_from_memory(
in_frames, interpolate, film_model
):
out_tensors.append(
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)
log.debug(f"Returning {len(out_tensors)} tensors")
log.debug(f"Output shape {out_tensors.shape}")
log.debug(f"Output type {out_tensors.dtype}")
return (out_tensors,)
class ConcatImages:
"""Add images to batch"""
RETURN_TYPES = ("IMAGE",)
FUNCTION = "concat_images"
CATEGORY = "mtb/image"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"imageA": ("IMAGE",),
"imageB": ("IMAGE",),
},
}
@classmethod
def concatenate_tensors(cls, A: torch.Tensor, B: torch.Tensor):
# Get the batch sizes of A and B
batch_size_A = A.size(0)
batch_size_B = B.size(0)
# Concatenate the tensors along the batch dimension
concatenated = torch.cat((A, B), dim=0)
# Update the batch size in the concatenated tensor
concatenated_size = list(concatenated.size())
concatenated_size[0] = batch_size_A + batch_size_B
concatenated = concatenated.view(*concatenated_size)
return concatenated
def concat_images(self, imageA: torch.Tensor, imageB: torch.Tensor):
log.debug(f"Concatenating A ({imageA.shape}) and B ({imageB.shape})")
return (self.concatenate_tensors(imageA, imageB),)
__nodes__ = [LoadFilmModel, FilmInterpolation, ConcatImages]
+141 -241
View File
@@ -1,32 +1,27 @@
import torch
from skimage.filters import gaussian
from skimage.restoration import denoise_tv_chambolle
from skimage.util import compare_images
from skimage.color import rgb2hsv, hsv2rgb
import numpy as np
import torchvision.transforms.functional as F
from PIL import Image, ImageChops
from ..utils import tensor2pil, pil2tensor, img_np_to_tensor, img_tensor_to_np
import cv2
import torch.nn.functional as F
from PIL import Image
from ..utils import tensor2pil, pil2tensor, tensor2np
import torch
from ..log import log
import folder_paths
from PIL.PngImagePlugin import PngInfo
import json
import os
import math
try:
from cv2.ximgproc import guidedFilter
except ImportError:
log.error("guidedFilter not found, use opencv-contrib-python")
# try:
# from cv2.ximgproc import guidedFilter
# except ImportError:
# log.warning("cv2.ximgproc.guidedFilter not found, use opencv-contrib-python")
class ColorCorrect:
"""Various color correction methods"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -66,7 +61,7 @@ class ColorCorrect:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "correct"
CATEGORY = "image/postprocessing"
CATEGORY = "mtb/image processing"
@staticmethod
def gamma_correction_tensor(image, gamma):
@@ -88,19 +83,21 @@ class ColorCorrect:
@staticmethod
def hsv_adjustment(image: torch.Tensor, hue, saturation, value):
image = tensor2pil(image)
hsv_image = image.convert("HSV")
images = tensor2pil(image)
out = []
for img in images:
hsv_image = img.convert("HSV")
h, s, v = hsv_image.split()
h, s, v = hsv_image.split()
h = h.point(lambda x: (x + hue * 255) % 256)
s = s.point(lambda x: int(x * saturation))
v = v.point(lambda x: int(x * value))
h = h.point(lambda x: (x + hue * 255) % 256)
s = s.point(lambda x: int(x * saturation))
v = v.point(lambda x: int(x * value))
hsv_image = Image.merge("HSV", (h, s, v))
rgb_image = hsv_image.convert("RGB")
return pil2tensor(rgb_image)
hsv_image = Image.merge("HSV", (h, s, v))
rgb_image = hsv_image.convert("RGB")
out.append(rgb_image)
return pil2tensor(out)
@staticmethod
def hsv_adjustment_tensor_not_working(image: torch.Tensor, hue, saturation, value):
@@ -180,70 +177,9 @@ class ColorCorrect:
return (image,)
class HsvToRgb:
"""Convert HSV image to RGB"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "convert"
CATEGORY = "image/postprocessing"
def convert(self, image):
image = image.numpy()
image = image.squeeze()
# image = image.transpose(1,2,3,0)
image = hsv2rgb(image)
image = np.expand_dims(image, axis=0)
# image = image.transpose(3,0,1,2)
return (torch.from_numpy(image),)
class RgbToHsv:
"""Convert RGB image to HSV"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "convert"
CATEGORY = "image/postprocessing"
def convert(self, image):
image = image.numpy()
image = np.squeeze(image)
image = rgb2hsv(image)
image = np.expand_dims(image, axis=0)
return (torch.from_numpy(image),)
class ImageCompare:
"""Compare two images and return a difference image"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -259,7 +195,7 @@ class ImageCompare:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "compare"
CATEGORY = "image"
CATEGORY = "mtb/image"
def compare(self, imageA: torch.Tensor, imageB: torch.Tensor, mode):
imageA = imageA.numpy()
@@ -274,43 +210,38 @@ class ImageCompare:
return (torch.from_numpy(image),)
class Denoise:
"""Denoise an image using total variation minimization."""
import requests
def __init__(self):
pass
class LoadImageFromUrl:
"""Load an image from the given URL"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"weight": (
"FLOAT",
{"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01},
"url": (
"STRING",
{
"default": "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a7/Example.jpg/800px-Example.jpg"
},
),
}
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "denoise"
CATEGORY = "image/postprocessing"
FUNCTION = "load"
CATEGORY = "mtb/IO"
def denoise(self, image: torch.Tensor, weight):
image = image.numpy()
image = image.squeeze()
image = denoise_tv_chambolle(image, weight=weight)
image = np.expand_dims(image, axis=0)
return (torch.from_numpy(image),)
def load(self, url):
# get the image from the url
image = Image.open(requests.get(url, stream=True).raw)
return (pil2tensor(image),)
class Blur:
"""Blur an image using a Gaussian filter."""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -329,7 +260,7 @@ class Blur:
RETURN_TYPES = ("IMAGE",)
FUNCTION = "blur"
CATEGORY = "image/postprocessing"
CATEGORY = "mtb/image processing"
def blur(self, image: torch.Tensor, sigmaX, sigmaY):
image = image.numpy()
@@ -340,37 +271,34 @@ class Blur:
# https://github.com/lllyasviel/AdverseCleaner/blob/main/clean.py
def deglaze_np_img(np_img):
y = np_img.copy()
for _ in range(64):
y = cv2.bilateralFilter(y, 5, 8, 8)
for _ in range(4):
y = guidedFilter(np_img, y, 4, 16)
return y
# def deglaze_np_img(np_img):
# y = np_img.copy()
# for _ in range(64):
# y = cv2.bilateralFilter(y, 5, 8, 8)
# for _ in range(4):
# y = guidedFilter(np_img, y, 4, 16)
# return y
class DeglazeImage:
"""Remove adversarial noise from images"""
# class DeglazeImage:
# """Remove adversarial noise from images"""
@classmethod
def INPUT_TYPES(cls):
return {"required": {"image": ("IMAGE",)}}
# @classmethod
# def INPUT_TYPES(cls):
# return {"required": {"image": ("IMAGE",)}}
CATEGORY = "image"
# CATEGORY = "mtb/image processing"
RETURN_TYPES = ("IMAGE",)
FUNCTION = "deglaze_image"
# RETURN_TYPES = ("IMAGE",)
# FUNCTION = "deglaze_image"
def deglaze_image(self, image):
return (img_np_to_tensor(deglaze_np_img(img_tensor_to_np(image))),)
# def deglaze_image(self, image):
# return (np2tensor(deglaze_np_img(tensor2np(image))),)
class MaskToImage:
"""Converts a mask (alpha) to an RGB image with a color and background"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
@@ -381,14 +309,14 @@ class MaskToImage:
}
}
CATEGORY = "image/mask"
CATEGORY = "mtb/generate"
RETURN_TYPES = ("IMAGE",)
FUNCTION = "render_mask"
def render_mask(self, mask, color, background):
mask = img_tensor_to_np(mask)
mask = tensor2np(mask)
mask = Image.fromarray(mask).convert("L")
image = Image.new("RGBA", mask.size, color=color)
@@ -422,7 +350,7 @@ class ColoredImage:
}
}
CATEGORY = "image"
CATEGORY = "mtb/generate"
RETURN_TYPES = ("IMAGE",)
@@ -439,48 +367,50 @@ class ColoredImage:
class ImagePremultiply:
"""Premultiply image with mask"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"mask": ("MASK",),
"invert": (["True", "False"], {"default": "False"}),
"invert": ("BOOLEAN", {"default": False}),
}
}
CATEGORY = "image"
CATEGORY = "mtb/image"
RETURN_TYPES = ("IMAGE",)
FUNCTION = "premultiply"
def premultiply(self, image, mask, invert):
invert = invert == "True"
image = tensor2pil(image)
mask = tensor2pil(mask).convert("L")
images = tensor2pil(image)
if invert:
mask = ImageChops.invert(mask)
masks = tensor2pil(mask) # .convert("L")
else:
masks = tensor2pil(1.0 - mask)
image.putalpha(mask)
single = False
if len(mask) == 1:
single = True
masks = [x.convert("L") for x in masks]
out = []
for i, img in enumerate(images):
cur_mask = masks[0] if single else masks[i]
img.putalpha(cur_mask)
out.append(img)
# if invert:
# image = Image.composite(image,Image.new("RGBA", image.size, color=(0,0,0,0)), mask)
# else:
# image = Image.composite(Image.new("RGBA", image.size, color=(0,0,0,0)), image, mask)
return (pil2tensor(image),)
return (pil2tensor(out),)
class ImageResizeFactor:
"""
Extracted mostly from WAS Node Suite, with a few edits (most notably multiple image support) and less features.
"""
def __init__(self):
pass
"""Extracted mostly from WAS Node Suite, with a few edits (most notably multiple image support) and less features."""
@classmethod
def INPUT_TYPES(cls):
@@ -491,10 +421,18 @@ class ImageResizeFactor:
"FLOAT",
{"default": 2, "min": 0.01, "max": 16.0, "step": 0.01},
),
"supersample": (["true", "false"], {"default": "true"}),
"supersample": ("BOOLEAN", {"default": True}),
"resampling": (
["lanczos", "nearest", "bilinear", "bicubic"],
{"default": "lanczos"},
[
"nearest",
"linear",
"bilinear",
"bicubic",
"trilinear",
"area",
"nearest-exact",
],
{"default": "nearest"},
),
},
"optional": {
@@ -502,100 +440,65 @@ class ImageResizeFactor:
},
}
CATEGORY = "image"
CATEGORY = "mtb/image"
RETURN_TYPES = ("IMAGE", "MASK")
FUNCTION = "resize"
def resize_image(
self,
image: torch.Tensor,
factor: float = 0.5,
supersample=False,
resample="lanczos",
mask=None,
) -> torch.Tensor:
batch_count = 1
img = tensor2pil(image)
if isinstance(img, list):
log.debug("Multiple images detected (list)")
out = []
for im in img:
im = self.resize_image(
pil2tensor(im), factor, supersample, resample, mask
)
out.append(im)
return torch.cat(out, dim=0)
elif isinstance(img, torch.Tensor):
if len(image.shape) > 3:
batch_count = image.size(0)
if batch_count > 1:
log.debug("Multiple images detected (batch count)")
out = [
self.resize_image(image[i], factor, supersample, resample, mask)
for i in range(batch_count)
]
return torch.cat(out, dim=0)
log.debug("Resizing image")
# Get the current width and height of the image
current_width, current_height = img.size
log.debug(f"Current width: {current_width}, Current height: {current_height}")
# Calculate the new width and height based on the given mode and parameters
new_width, new_height = int(factor * current_width), int(
factor * current_height
)
log.debug(f"New width: {new_width}, New height: {new_height}")
# Define a dictionary of resampling filters
resample_filters = {"nearest": 0, "bilinear": 2, "bicubic": 3, "lanczos": 1}
# Apply supersample
if supersample == "true":
super_size = (new_width * 8, new_height * 8)
log.debug(f"Applying supersample: {super_size}")
img = img.resize(
super_size, resample=Image.Resampling(resample_filters[resample])
)
# Resize the image using the given resampling filter
resized_image = img.resize(
(new_width, new_height),
resample=Image.Resampling(resample_filters[resample]),
)
return pil2tensor(resized_image)
def resize(
self,
image: torch.Tensor,
factor: float,
supersample: str,
supersample: bool,
resampling: str,
mask=None,
):
log.debug(f"Resizing image with factor {factor} and resampling {resampling}")
supersample = supersample == "true"
batch_count = image.size(0)
log.debug(f"Batch count: {batch_count}")
if batch_count == 1:
log.debug("Batch count is 1, returning single image")
return (self.resize_image(image, factor, supersample, resampling),)
# Check if the tensor has the correct dimension
if len(image.shape) not in [3, 4]: # HxWxC or BxHxWxC
raise ValueError("Expected image tensor of shape (H, W, C) or (B, H, W, C)")
# Transpose to CxHxW or BxCxHxW for PyTorch
if len(image.shape) == 3:
image = image.permute(2, 0, 1).unsqueeze(0) # CxHxW
else:
log.debug("Batch count is greater than 1, returning multiple images")
images = [
self.resize_image(image[i], factor, supersample, resampling)
for i in range(batch_count)
]
images = torch.cat(images, dim=0)
return (images,)
image = image.permute(0, 3, 1, 2) # BxCxHxW
# Compute new dimensions
B, C, H, W = image.shape
new_H, new_W = int(H * factor), int(W * factor)
import math
align_corner_filters = ("linear", "bilinear", "bicubic", "trilinear")
# Resize the image
resized_image = F.interpolate(
image,
size=(new_H, new_W),
mode=resampling,
align_corners=resampling in align_corner_filters,
)
# Optionally supersample
if supersample:
resized_image = F.interpolate(
resized_image,
scale_factor=2,
mode=resampling,
align_corners=resampling in align_corner_filters,
)
# Transpose back to the original format: BxHxWxC or HxWxC
if len(image.shape) == 4:
resized_image = resized_image.permute(0, 2, 3, 1)
else:
resized_image = resized_image.squeeze(0).permute(1, 2, 0)
# Apply mask if provided
if mask is not None:
if len(mask.shape) != len(resized_image.shape):
raise ValueError(
"Mask tensor should have the same dimensions as the image tensor"
)
resized_image = resized_image * mask
return (resized_image,)
class SaveImageGrid:
@@ -611,7 +514,7 @@ class SaveImageGrid:
"required": {
"images": ("IMAGE",),
"filename_prefix": ("STRING", {"default": "ComfyUI"}),
"save_intermediate": (["true", "false"], {"default": "false"}),
"save_intermediate": ("BOOLEAN", {"default": False}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
@@ -621,7 +524,7 @@ class SaveImageGrid:
OUTPUT_NODE = True
CATEGORY = "image"
CATEGORY = "mtb/IO"
def create_image_grid(self, image_list):
total_images = len(image_list)
@@ -652,11 +555,10 @@ class SaveImageGrid:
self,
images,
filename_prefix="Grid",
save_intermediate="false",
save_intermediate=False,
prompt=None,
extra_pnginfo=None,
):
save_intermediate = save_intermediate == "true"
(
full_output_folder,
filename,
@@ -703,15 +605,13 @@ class SaveImageGrid:
__nodes__ = [
ColorCorrect,
HsvToRgb,
RgbToHsv,
ImageCompare,
Denoise,
Blur,
DeglazeImage,
# DeglazeImage,
MaskToImage,
ColoredImage,
ImagePremultiply,
ImageResizeFactor,
SaveImageGrid,
LoadImageFromUrl,
]
+195
View File
@@ -0,0 +1,195 @@
from ..utils import tensor2np, PIL_FILTER_MAP
import uuid
import folder_paths
from ..log import log
import comfy.model_management as model_management
import subprocess
import torch
from pathlib import Path
import numpy as np
from PIL import Image
from typing import Optional, List
class ExportWithFfmpeg:
"""Export with FFmpeg (Experimental)"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"images": ("IMAGE",),
# "frames": ("FRAMES",),
"fps": ("FLOAT", {"default": 24, "min": 1}),
"prefix": ("STRING", {"default": "export"}),
"format": (["mov", "mp4", "mkv", "avi"], {"default": "mov"}),
"codec": (
["prores_ks", "libx264", "libx265"],
{"default": "prores_ks"},
),
}
}
RETURN_TYPES = ("VIDEO",)
OUTPUT_NODE = True
FUNCTION = "export_prores"
CATEGORY = "mtb/IO"
def export_prores(
self,
images: torch.Tensor,
fps: float,
prefix: str,
format: str,
codec: str,
):
if images.size(0) == 0:
return ("",)
output_dir = Path(folder_paths.get_output_directory())
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
file_ext = format
file_id = f"{prefix}_{uuid.uuid4()}.{file_ext}"
log.debug(f"Exporting to {output_dir / file_id}")
frames = tensor2np(images)
log.debug(f"Frames type {type(frames[0])}")
log.debug(f"Exporting {len(frames)} frames")
frames = [frame.astype(np.uint16) * 257 for frame in frames]
height, width, _ = frames[0].shape
out_path = (output_dir / file_id).as_posix()
# Prepare the FFmpeg command
command = [
"ffmpeg",
"-y",
"-f",
"rawvideo",
"-vcodec",
"rawvideo",
"-s",
f"{width}x{height}",
"-pix_fmt",
pix_fmt,
"-r",
str(fps),
"-i",
"-",
"-c:v",
codec,
"-r",
str(fps),
"-y",
out_path,
]
process = subprocess.Popen(command, stdin=subprocess.PIPE)
for frame in frames:
model_management.throw_exception_if_processing_interrupted()
process.stdin.write(frame.tobytes())
process.stdin.close()
process.wait()
return (out_path,)
def prepare_animated_batch(
batch: torch.Tensor,
pingpong=False,
resize_by=1.0,
resample_filter: Optional[Image.Resampling] = None,
image_type=np.uint8,
) -> List[Image.Image]:
images = tensor2np(batch)
images = [frame.astype(image_type) for frame in images]
height, width, _ = batch[0].shape
if pingpong:
reversed_frames = images[::-1]
images.extend(reversed_frames)
pil_images = [Image.fromarray(frame) for frame in images]
# Resize frames if necessary
if abs(resize_by - 1.0) > 1e-6:
new_width = int(width * resize_by)
new_height = int(height * resize_by)
pil_images_resized = [
frame.resize((new_width, new_height), resample=resample_filter)
for frame in pil_images
]
pil_images = pil_images_resized
return pil_images
# todo: deprecate for apng
class SaveGif:
"""Save the images from the batch as a GIF"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"fps": ("INT", {"default": 12, "min": 1, "max": 120}),
"resize_by": ("FLOAT", {"default": 1.0, "min": 0.1}),
"optimize": ("BOOLEAN", {"default": False}),
"pingpong": ("BOOLEAN", {"default": False}),
},
"optional": {
"resample_filter": (list(PIL_FILTER_MAP.keys()),),
},
}
RETURN_TYPES = ()
OUTPUT_NODE = True
CATEGORY = "mtb/IO"
FUNCTION = "save_gif"
def save_gif(
self,
image,
fps=12,
resize_by=1.0,
optimize=False,
pingpong=False,
resample_filter=None,
):
if image.size(0) == 0:
return ("",)
if resample_filter is not None:
resample_filter = PIL_FILTER_MAP.get(resample_filter)
pil_images = prepare_animated_batch(
image,
pingpong,
resize_by,
resample_filter,
)
ruuid = uuid.uuid4()
ruuid = ruuid.hex[:10]
out_path = f"{folder_paths.output_directory}/{ruuid}.gif"
# Create the GIF from PIL images
pil_images[0].save(
out_path,
save_all=True,
append_images=pil_images[1:],
optimize=optimize,
duration=int(1000 / fps),
loop=0,
)
results = [{"filename": f"{ruuid}.gif", "subfolder": "", "type": "output"}]
return {"ui": {"gif": results}}
__nodes__ = [SaveGif, ExportWithFfmpeg]
+4 -4
View File
@@ -1,9 +1,8 @@
import torch
class LatentLerp:
"""Linear interpolation (blend) between two latent vectors"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
@@ -18,7 +17,7 @@ class LatentLerp:
RETURN_TYPES = ("LATENT",)
FUNCTION = "lerp_latent"
CATEGORY = "latent"
CATEGORY = "mtb/latent"
def lerp_latent(self, A, B, t):
a = A.copy()
@@ -28,6 +27,7 @@ class LatentLerp:
return (a,)
__nodes__ = [
LatentLerp,
]
]
+79 -31
View File
@@ -1,57 +1,105 @@
from rembg import remove
from ..utils import pil2tensor, tensor2pil
from PIL import Image
import comfy.utils
class ImageRemoveBackgroundRembg:
def __init__(self):
pass
"""Removes the background from the input using Rembg."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image": ("IMAGE",),
"alpha_matting": (["True","False"], {"default":"False"},),
"alpha_matting_foreground_threshold": ("INT", {"default":240, "min": 0, "max": 255},),
"alpha_matting_background_threshold": ("INT", {"default":10, "min": 0, "max": 255},),
"alpha_matting_erode_size": ("INT", {"default":10, "min": 0, "max": 255},),
"post_process_mask": (["True","False"], {"default":"False"},),
"bgcolor": ("COLOR", {"default":"black"},),
"alpha_matting": (
"BOOLEAN",
{"default": False},
),
"alpha_matting_foreground_threshold": (
"INT",
{"default": 240, "min": 0, "max": 255},
),
"alpha_matting_background_threshold": (
"INT",
{"default": 10, "min": 0, "max": 255},
),
"alpha_matting_erode_size": (
"INT",
{"default": 10, "min": 0, "max": 255},
),
"post_process_mask": (
"BOOLEAN",
{"default": False},
),
"bgcolor": (
"COLOR",
{"default": "#000000"},
),
},
}
RETURN_TYPES = ("IMAGE","MASK","IMAGE",)
RETURN_NAMES = ("Image (rgba)","Mask","Image",)
RETURN_TYPES = (
"IMAGE",
"MASK",
"IMAGE",
)
RETURN_NAMES = (
"Image (rgba)",
"Mask",
"Image",
)
FUNCTION = "remove_background"
CATEGORY = "image"
CATEGORY = "mtb/image"
# bgcolor: Optional[Tuple[int, int, int, int]]
def remove_background(self, image, alpha_matting, alpha_matting_foreground_threshold, alpha_matting_background_threshold, alpha_matting_erode_size, post_process_mask, bgcolor):
image = remove(
data=tensor2pil(image),
alpha_matting=alpha_matting == "True",
def remove_background(
self,
image,
alpha_matting,
alpha_matting_foreground_threshold,
alpha_matting_background_threshold,
alpha_matting_erode_size,
post_process_mask,
bgcolor,
):
pbar = comfy.utils.ProgressBar(image.size(0))
images = tensor2pil(image)
out_img = []
out_mask = []
out_img_on_bg = []
for img in images:
img_rm = remove(
data=img,
alpha_matting=alpha_matting,
alpha_matting_foreground_threshold=alpha_matting_foreground_threshold,
alpha_matting_background_threshold=alpha_matting_background_threshold,
alpha_matting_erode_size=alpha_matting_erode_size,
session=None,
only_mask=False,
post_process_mask=post_process_mask == "True",
bgcolor=None
post_process_mask=post_process_mask,
bgcolor=None,
)
# extract the alpha to a new image
mask = image.getchannel(3)
# add our bgcolor behind the image
image_on_bg = Image.new("RGBA", image.size, bgcolor)
image_on_bg.paste(image, mask=mask)
return (pil2tensor(image), pil2tensor(mask), pil2tensor(image_on_bg))
# extract the alpha to a new image
mask = img_rm.getchannel(3)
# add our bgcolor behind the image
image_on_bg = Image.new("RGBA", img_rm.size, bgcolor)
image_on_bg.paste(img_rm, mask=mask)
out_img.append(img_rm)
out_mask.append(mask)
out_img_on_bg.append(image_on_bg)
pbar.update(1)
return (pil2tensor(out_img), pil2tensor(out_mask), pil2tensor(out_img_on_bg))
__nodes__ = [
ImageRemoveBackgroundRembg,
]
]
+71 -10
View File
@@ -1,26 +1,87 @@
class IntToNumber:
"""Node addon for the WAS Suite. Converts a "comfy" INT to a NUMBER."""
def __init__(self):
pass
class IntToBool:
"""Basic int to bool conversion"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"int": ("INT", {"default": 0, "min": 0, "max": 1e9, "step": 1}),
"int": (
"INT",
{
"default": 0,
},
),
}
}
RETURN_TYPES = ("BOOLEAN",)
FUNCTION = "int_to_bool"
CATEGORY = "mtb/number"
def int_to_bool(self, int):
return (bool(int),)
class IntToNumber:
"""Node addon for the WAS Suite. Converts a "comfy" INT to a NUMBER."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"int": (
"INT",
{
"default": 0,
"min": -1e9,
"max": 1e9,
"step": 1,
"forceInput": True,
},
),
}
}
RETURN_TYPES = ("NUMBER",)
FUNCTION = "int_to_number"
CATEGORY = "number"
CATEGORY = "mtb/number"
def int_to_number(self, int):
return (int,)
class FloatToNumber:
"""Node addon for the WAS Suite. Converts a "comfy" FLOAT to a NUMBER."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"float": (
"FLOAT",
{
"default": 0,
"min": -1e9,
"max": 1e9,
"step": 1,
"forceInput": True,
},
),
}
}
RETURN_TYPES = ("NUMBER",)
FUNCTION = "float_to_number"
CATEGORY = "mtb/number"
def float_to_number(self, float):
return (float,)
return (int,)
__nodes__ = [
IntToNumber,
]
__nodes__ = [
FloatToNumber,
IntToBool,
IntToNumber,
]
+110
View File
@@ -0,0 +1,110 @@
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
class 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
"""
@classmethod
def INPUT_TYPES(cls):
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}),
"shear": (
"FLOAT",
{"default": 0, "step": 1, "min": -4096, "max": 4096},
),
"border_handling": (
["edge", "constant", "reflect", "symmetric"],
{"default": "edge"},
),
"constant_color": ("COLOR", {"default": "#000000"}),
},
}
FUNCTION = "transform"
RETURN_TYPES = ("IMAGE",)
CATEGORY = "mtb/transform"
def transform(
self,
image: torch.Tensor,
x: float,
y: float,
zoom: float,
angle: float,
shear: float,
border_handling="edge",
constant_color=None,
):
x = int(x)
y = int(y)
angle = int(angle)
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()
new_height, new_width = int(frame_height * zoom), int(frame_width * zoom)
log.debug(f"New height: {new_height}, New width: {new_width}")
# - Calculate diagonal of the original image
diagonal = sqrt(frame_width**2 + frame_height**2)
max_padding = ceil(diagonal * zoom - min(frame_width, frame_height))
# Calculate padding for zoom
pw = int(frame_width - new_width)
ph = int(frame_height - new_height)
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)]
constant_color = hex_to_rgb(constant_color)
log.debug(f"Fill Tuple: {constant_color}")
for img in tensor2pil(image):
img = TF.pad(
img, # transformed_frame,
padding=padding,
padding_mode=border_handling,
fill=constant_color or 0,
)
img = cast(
Image.Image,
TF.affine(img, angle=angle, scale=zoom, translate=[x, y], shear=shear),
)
left = abs(padding[0])
upper = abs(padding[1])
right = img.width - abs(padding[2])
bottom = img.height - abs(padding[3])
# log.debug("crop is [:,top:bottom, left:right] for tensors")
log.debug("crop is [left, top, right, bottom] for PIL")
log.debug(f"crop is {left}, {upper}, {right}, {bottom}")
img = img.crop((left, upper, right, bottom))
transformed_images.append(img)
return (pil2tensor(transformed_images),)
__nodes__ = [TransformImage]
+142 -40
View File
@@ -10,96 +10,189 @@ from pathlib import Path
import json
from ..log import log
class 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.
Use -1 to load all matching frames as a batch.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"path": ("STRING",{"default":"videos/####.png"}),
"current_frame": ("INT",{"default":0, "min":0, "max": 9999999},),
"path": ("STRING", {"default": "videos/####.png"}),
"current_frame": (
"INT",
{"default": 0, "min": -1, "max": 9999999},
),
}
}
CATEGORY = "video"
CATEGORY = "mtb/IO"
FUNCTION = "load_image"
RETURN_TYPES = ("IMAGE", "MASK", "INT",)
RETURN_NAMES = ("image", "mask", "current_frame",)
RETURN_TYPES = (
"IMAGE",
"MASK",
"INT",
)
RETURN_NAMES = (
"image",
"mask",
"current_frame",
)
def load_image(self, path=None, current_frame=0):
load_all = current_frame == -1
if load_all:
log.debug(f"Loading all frames from {path}")
frames = resolve_all_frames(path)
log.debug(f"Found {len(frames)} frames")
imgs = []
masks = []
for frame in frames:
img, mask = img_from_path(frame)
imgs.append(img)
masks.append(mask)
out_img = torch.cat(imgs, dim=0)
out_mask = torch.cat(masks, dim=0)
return (
out_img,
out_mask,
)
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)
i = Image.open(image_path)
i = ImageOps.exif_transpose(i)
image = i.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if 'A' in i.getbands():
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
mask = 1. - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return (image, mask, current_frame,)
image, mask = img_from_path(image_path)
return (
image,
mask,
current_frame,
)
@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):
if os.path.exists(image_path):
m = hashlib.sha256()
with open(image_path, 'rb') as f:
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
import glob
def img_from_path(path):
img = Image.open(path)
img = ImageOps.exif_transpose(img)
image = img.convert("RGB")
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image)[None,]
if "A" in img.getbands():
mask = np.array(img.getchannel("A")).astype(np.float32) / 255.0
mask = 1.0 - torch.from_numpy(mask)
else:
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
return (
image,
mask,
)
def resolve_all_frames(pattern):
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)
log.debug(f"Found pattern: {frame_pattern}")
matching_files = glob.glob(os.path.join(folder_path, frame_pattern))
log.debug(f"Found {len(matching_files)} matching files")
frame_regex = re.escape(file_pattern).replace(r"\#", r"(\d+)")
frame_number_regex = re.compile(frame_regex)
for file in matching_files:
match = frame_number_regex.search(file)
if match:
frame_number = match.group(1)
log.debug(f"Found frame number: {frame_number}")
# resolved_file = pattern.replace("*" * frame_number.count("#"), frame_number)
frames.append(file)
frames.sort() # Sort frames alphabetically
return frames
def resolve_path(path, frame):
hashes = path.count("#")
padded_number = str(frame).zfill(hashes)
return re.sub("#+", padded_number, path)
class 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.
"""
def __init__(self):
self.output_dir = folder_paths.get_output_directory()
self.type = "output"
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"images": ("IMAGE", ),
"filename_prefix": ("STRING", {"default": "Sequence"}),
"current_frame": ("INT", {"default": 0, "min": 0, "max": 9999999}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
return {
"required": {
"images": ("IMAGE",),
"filename_prefix": ("STRING", {"default": "Sequence"}),
"current_frame": ("INT", {"default": 0, "min": 0, "max": 9999999}),
},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
}
RETURN_TYPES = ()
FUNCTION = "save_images"
OUTPUT_NODE = True
CATEGORY = "image"
CATEGORY = "mtb/IO"
def save_images(self, images, filename_prefix="Sequence", current_frame=0, prompt=None, extra_pnginfo=None):
def save_images(
self,
images,
filename_prefix="Sequence",
current_frame=0,
prompt=None,
extra_pnginfo=None,
):
# full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
# results = list()
# for image in images:
@@ -120,30 +213,39 @@ class SaveImageSequence:
# "type": self.type
# })
# counter += 1
if len(images) > 1:
raise ValueError("Can only save one image at a time")
resolved_path = Path(self.output_dir) / filename_prefix
resolved_path.mkdir(parents=True, exist_ok=True)
resolved_img = resolved_path / f"{filename_prefix}_{current_frame:05}.png"
output_image = images[0].cpu().numpy()
img = Image.fromarray(np.clip(output_image * 255., 0, 255).astype(np.uint8))
img = Image.fromarray(np.clip(output_image * 255.0, 0, 255).astype(np.uint8))
metadata = PngInfo()
if prompt is not None:
metadata.add_text("prompt", json.dumps(prompt))
if extra_pnginfo is not None:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
img.save(resolved_img, pnginfo=metadata, compress_level=4)
return { "ui": { "images": [ { "filename": resolved_img.name, "subfolder": resolved_path.name, "type": self.type } ] } }
return {
"ui": {
"images": [
{
"filename": resolved_img.name,
"subfolder": resolved_path.name,
"type": self.type,
}
]
}
}
__nodes__ = [
LoadImageSequence,
SaveImageSequence,
]
]
+18
View File
@@ -0,0 +1,18 @@
{
"exclude": [
"**/node_modules",
"**/__pycache__",
],
"ignore": [
"extern"
],
"defineConstant": {
"DEBUG": true
},
"venvPath": "../../../.venv/",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
"pythonVersion": "3.10",
"pythonPlatform": "All",
"reportOptionalMemberAccess": "none"
}
+7
View File
@@ -0,0 +1,7 @@
onnxruntime-gpu==1.15.1
qrcode[pil]
rembg==2.0.50
tensorflow
facexlib==0.3.0
insightface==0.7.3
basicsr==1.4.2
+18
View File
@@ -0,0 +1,18 @@
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/pycocotools-2.0.6-cp310-cp310-win_amd64.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/future-0.18.3-py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/filterpy-1.4.5-py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/easydict-1.10-py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/gdown-4.7.1-py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/basicsr-1.4.2-py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/mmcv-2.0.0-py2.py3-none-any.whl
https://github.com/melMass/comfy_mtb/releases/download/v0.1.3/insightface-0.7.3-cp310-cp310-win_amd64.whl
onnxruntime-gpu==1.15.1
qrcode[pil]
rembg==2.0.50
# on windows non WSL 2.10 is the last version with GPU support
tensorflow==2.10.1;
tb-nightly==2.12.0a20230126; platform_system == "Windows"
facexlib==0.3.0
# the old tf version on windows comes with a breaking protobuf version
protobuf==3.19.6
-3
View File
@@ -1,3 +0,0 @@
insightface==0.7.3
mmcv==2.0.0
mmdet==3.0.0
-9
View File
@@ -1,9 +0,0 @@
onnxruntime-gpu
imageio
qrcode[pil]
numpy==1.23.5
ifnude==0.0.3
insightface==0.7.3
mmcv==2.0.0
mmdet==3.0.0
rembg==2.0.37
+112
View File
@@ -0,0 +1,112 @@
from pathlib import Path
from PIL import Image
from PIL.PngImagePlugin import PngImageFile, PngInfo
import json
from pprint import pprint
import argparse
from rich.console import Console
from rich.progress import Progress
from rich_argparse import RichHelpFormatter
def parse_a111(params, verbose=False):
# params = [p.split(": ") for p in params.split("\n")]
params = params.split("\n")
prompt = params[0].strip()
neg = params[1].split(":")[1].strip()
settings = {}
try:
settings = {
s.split(":")[0].strip(): s.split(":")[1].strip()
for s in params[2].split(",")
}
except IndexError:
settings = {"raw": params[2].strip()}
if verbose:
print(f"PROMPT: {prompt}")
print(f"NEG: {neg}")
print("SETTINGS:")
pprint(settings, indent=4)
return {"prompt": prompt, "negative": neg, "settings": settings}
import glob
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Crude metadata extractor from A111 pngs",
formatter_class=RichHelpFormatter
)
parser.add_argument("inputs", nargs="*", help="Input image files")
parser.add_argument("--output", help="Output JSON file")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose mode")
parser.add_argument(
"--glob", help="Enable glob pattern matching", metavar="PATTERN"
)
args = parser.parse_args()
# - checks
if not args.glob and not args.inputs:
parser.error("Either --glob flag or inputs must be provided.")
if args.glob:
glob_pattern = args.glob
try:
pattern_path = str(Path(glob_pattern).expanduser().resolve())
if not any(glob.glob(pattern_path)):
raise ValueError(f"No files found for glob pattern: {glob_pattern}")
except Exception as e:
console = Console()
console.print(
f"[bold red]Error: Invalid glob pattern '{glob_pattern}': {e}[/bold red]"
)
exit(1)
else:
glob_pattern = None
input_files = []
if glob_pattern:
input_files = list(glob.glob(str(Path(glob_pattern).expanduser().resolve())))
else:
input_files = [Path(p) for p in args.inputs]
console = Console()
console.print("Input Files:", style="bold", end=" ")
console.print(f"{len(input_files):03d} files", style="cyan")
# for input_file in args.inputs:
# console.print(f"- {input_file}", style="cyan")
console.print("\nOutput File:", style="bold", end=" ")
console.print(f"{Path(args.output).resolve().absolute()}", style="cyan")
with Progress(console=console, auto_refresh=True) as progress:
# files = Path(pth).rglob("*.png")
unique_info = {}
last = None
task = progress.add_task("[cyan]Extracting meta...", total=len(input_files) + 1)
for p in input_files:
im = Image.open(p)
parsed = parse_a111(im.info["parameters"], args.verbose)
if parsed != last:
unique_info[Path(p).stem] = parsed
last = parsed
progress.update(task, advance=1)
progress.refresh()
unique_info = json.dumps(unique_info, indent=4)
with open(args.output, "w") as f:
f.write(unique_info)
progress.update(task, advance=1)
progress.refresh()
console.print("\nProcessing completed!", style="bold green")
+213
View File
@@ -0,0 +1,213 @@
import argparse
import json
from PIL import Image, PngImagePlugin
from rich.console import Console
from rich import print
from rich_argparse import RichHelpFormatter
import os
from pathlib import Path
console = Console()
# BNK_CutoffSetRegions
# BNK_CutoffRegionsToConditioning
# BNK_CutoffBasePrompt
# Extracts metadata from a PNG image and returns it as a dictionary
def extract_metadata(image_path):
image = Image.open(image_path)
prompt = image.info.get("prompt", "")
workflow = image.info.get("workflow", "")
if workflow:
workflow = json.loads(workflow)
if prompt:
prompt = json.loads(prompt)
console.print(f"Metadata extracted from [cyan]{image_path}[/cyan].")
return {
"prompt": prompt,
"workflow": workflow,
}
# Embeds metadata into a PNG image
def embed_metadata(image_path, metadata):
image = Image.open(image_path)
o_metadata = image.info
pnginfo = PngImagePlugin.PngInfo()
if prompt := metadata.get("prompt"):
pnginfo.add_text("prompt", json.dumps(prompt))
elif "prompt" in o_metadata:
pnginfo.add_text("prompt", o_metadata["prompt"])
if workflow := metadata.get("workflow"):
pnginfo.add_text("workflow", json.dumps(workflow))
elif "workflow" in o_metadata:
pnginfo.add_text("workflow", o_metadata["workflow"])
imgp = Path(image_path)
output = imgp.with_stem(f"{imgp.stem}_comfy_embed")
index = 1
while output.exists():
output = imgp.with_stem(f"{imgp.stem}_{index}_comfy_embed").with_suffix(".png")
index += 1
image.save(output, pnginfo=pnginfo)
console.print(f"Metadata embedded into [cyan]{output}[/cyan].")
# CLI subcommand: extract
def extract(args):
input_files = []
for input_path in args.input:
if os.path.isdir(input_path):
folder_path = input_path
input_files.extend(
[
os.path.join(folder_path, file_name)
for file_name in os.listdir(folder_path)
if file_name.lower().endswith((".png", ".jpg", ".jpeg"))
]
)
else:
input_files.append(input_path)
if len(input_files) == 1:
metadata = extract_metadata(input_files[0])
if args.print_output:
print(json.dumps(metadata, indent=4))
else:
if not args.output:
output = Path(input_files[0]).with_suffix(".json")
index = 1
while output.exists():
output = (
Path(input_files[0])
.with_stem(f"{Path(input_files[0]).stem}_{index}")
.with_suffix(".json")
)
index += 1
else:
output = args.output
with open(output, "w") as file:
json.dump(metadata, file, indent=4)
console.print(f"Metadata extracted and saved to [cyan]{output}[/cyan].")
else:
metadata_dict = {}
for input_file in input_files:
metadata = extract_metadata(input_file)
filename = os.path.basename(input_file)
output = (
Path(args.output) / f"{filename}.json"
if args.output
else Path(input_file).with_suffix(".json")
)
index = 1
while output.exists():
output = Path(args.output).parent / f"{filename}_{index}.json"
index += 1
with open(output, "w") as file:
json.dump(metadata, file, indent=4)
metadata_dict[filename] = metadata
if args.output:
with open(args.output, "w") as file:
json.dump(metadata_dict, file, indent=4)
console.print(
f"Metadata extracted and saved to [cyan]{args.output}[/cyan]."
)
else:
console.print("Multiple metadata files created.")
# CLI subcommand: embed
def embed(args):
input_files = []
for input_path in args.input:
if os.path.isdir(input_path):
folder_path = input_path
input_files.extend(
[
os.path.join(folder_path, file_name)
for file_name in os.listdir(folder_path)
if file_name.lower().endswith(".json")
]
)
else:
input_files.append(input_path)
for input_file in input_files:
with open(input_file) as file:
metadata = json.load(file)
image_path = input_file.replace(".json", ".png")
if args.output:
output_dir = args.output
if os.path.isdir(output_dir):
output_path = os.path.join(output_dir, os.path.basename(image_path))
index = 1
while os.path.exists(output_path):
output_path = os.path.join(
output_dir,
f"{os.path.basename(image_path)}_{index}.png",
)
index += 1
else:
output_path = output_dir
else:
output_path = image_path.replace(".png", "_comfy_embed.png")
embed_metadata(image_path, metadata)
# os.rename(image_path, output_path)
console.print(f"Metadata embedded into [cyan]{output_path}[/cyan].")
if __name__ == "__main__":
# Create the main CLI parser
parser = argparse.ArgumentParser(
prog="image-metadata-cli", formatter_class=RichHelpFormatter
)
subparsers = parser.add_subparsers(title="subcommands")
# Parser for the "extract" subcommand
extract_parser = subparsers.add_parser(
"extract",
help="Extract metadata from PNG image(s) or folder",
formatter_class=RichHelpFormatter,
)
extract_parser.add_argument(
"input", nargs="+", help="Input PNG image file(s) or folder path"
)
extract_parser.add_argument(
"--print",
dest="print_output",
action="store_true",
help="Print the output to stdout",
)
extract_parser.add_argument("--output", help="Output JSON file(s) or directory")
extract_parser.set_defaults(func=extract)
# Parser for the "embed" subcommand
embed_parser = subparsers.add_parser(
"embed",
help="Embed metadata into PNG image(s) or folder",
formatter_class=RichHelpFormatter,
)
embed_parser.add_argument(
"input", nargs="+", help="Input JSON file(s) or folder path"
)
embed_parser.add_argument("--output", help="Output PNG image file(s) or directory")
embed_parser.set_defaults(func=embed)
# Parse the command-line arguments and execute the appropriate subcommand
args = parser.parse_args()
if hasattr(args, "func"):
try:
args.func(args)
except ValueError as e:
console.print(f"[bold red]Error:[/bold red] {str(e)}")
else:
parser.print_help()
+63 -4
View File
@@ -2,6 +2,8 @@ import os
import requests
from rich.console import Console
from tqdm import tqdm
import subprocess
import sys
try:
import folder_paths
@@ -26,6 +28,25 @@ models_to_download = {
],
"destination": "insightface",
},
"GFPGAN (face enhancement)": {
"size": 332,
"download_url": [
"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth",
"https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.4.pth"
# TODO: provide a way to selectively download models from "packs"
# https://github.com/TencentARC/GFPGAN/releases/download/v0.1.0/GFPGANv1.pth
# https://github.com/TencentARC/GFPGAN/releases/download/v0.2.0/GFPGANCleanv1-NoCE-C2.pth
# https://github.com/TencentARC/GFPGAN/releases/download/v1.3.4/RestoreFormer.pth
],
"destination": "face_restore",
},
"FILM: Frame Interpolation for Large Motion": {
"size": 402,
"download_url": [
"https://drive.google.com/drive/folders/131_--QrieM4aQbbLWrUtbO2cGbX8-war"
],
"destination": "FILM",
},
}
console = Console()
@@ -41,6 +62,35 @@ def download_model(download_url, destination):
return
filename = os.path.basename(urlparse(download_url).path)
response = None
if "drive.google.com" in download_url:
try:
import gdown
except ImportError:
print("Installing gdown")
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
"git+https://github.com/melMass/gdown@main",
]
)
import gdown
if "/folders/" in download_url:
# download folder
try:
gdown.download_folder(download_url, output=destination, resume=True)
except TypeError:
gdown.download_folder(download_url, output=destination)
return
# download from google drive
gdown.download(download_url, destination, quiet=False, resume=True)
return
response = requests.get(download_url, stream=True)
total_size = int(response.headers.get("content-length", 0))
@@ -93,7 +143,7 @@ def handle_interrupt():
console.print("Interrupted by user.", style="bold red")
def main(models_to_download):
def main(models_to_download, skip_input=False):
try:
models_to_download_selected = {}
@@ -129,13 +179,16 @@ def main(models_to_download):
console.print("No new models to download.")
return
models_to_download_selected = ask_user_for_downloads(
models_to_download_selected
models_to_download_selected = (
ask_user_for_downloads(models_to_download_selected)
if not skip_input
else models_to_download_selected
)
for model_name, model_details in models_to_download_selected.items():
download_url = model_details["download_url"]
destination = model_details["destination"]
console.print(f"Downloading {model_name}...")
download_model(download_url, destination)
except KeyboardInterrupt:
@@ -143,4 +196,10 @@ def main(models_to_download):
if __name__ == "__main__":
main(models_to_download)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-y", "--yes", action="store_true", help="skip user input")
args = parser.parse_args()
main(models_to_download, args.yes)
+142
View File
@@ -0,0 +1,142 @@
import glob
from pathlib import Path
import uuid
import sys
from typing import List
sys.path.append((Path(__file__).parent / "extern").as_posix())
import argparse
from rich_argparse import RichHelpFormatter
from rich.console import Console
from rich.progress import Progress
import numpy as np
import subprocess
def write_prores_444_video(output_file, frames: List[np.ndarray], fps):
# Convert float images to the range of 0-65535 (12-bit color depth)
frames = [(frame * 65535).clip(0, 65535).astype(np.uint16) for frame in frames]
height, width, _ = frames[0].shape
# Prepare the FFmpeg command
command = [
"ffmpeg",
"-y", # Overwrite output file if it already exists
"-f",
"rawvideo",
"-vcodec",
"rawvideo",
"-s",
f"{width}x{height}",
"-pix_fmt",
"rgb48le",
"-r",
str(fps),
"-i",
"-",
"-c:v",
"prores_ks",
"-profile:v",
"4",
"-pix_fmt",
"yuva444p10le",
"-r",
str(fps),
"-y", # Overwrite output file if it already exists
output_file,
]
process = subprocess.Popen(command, stdin=subprocess.PIPE)
for frame in frames:
process.stdin.write(frame.tobytes())
process.stdin.close()
process.wait()
if __name__ == "__main__":
default_output = f"./output_{uuid.uuid4()}.mov"
parser = argparse.ArgumentParser(
description="FILM frame interpolation", formatter_class=RichHelpFormatter
)
parser.add_argument("inputs", nargs="*", help="Input image files")
parser.add_argument("--output", help="Output JSON file", default=default_output)
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose mode")
parser.add_argument(
"--glob", help="Enable glob pattern matching", metavar="PATTERN"
)
parser.add_argument(
"--interpolate", type=int, default=4, help="Time for interpolated frames"
)
parser.add_argument("--fps", type=int, default=30, help="Out FPS")
align = 64
block_width = 2
block_height = 2
args = parser.parse_args()
# - checks
if not args.glob and not args.inputs:
parser.error("Either --glob flag or inputs must be provided.")
if args.glob:
glob_pattern = args.glob
try:
pattern_path = str(Path(glob_pattern).expanduser().resolve())
if not any(glob.glob(pattern_path)):
raise ValueError(f"No files found for glob pattern: {glob_pattern}")
except Exception as e:
console = Console()
console.print(
f"[bold red]Error: Invalid glob pattern '{glob_pattern}': {e}[/bold red]"
)
exit(1)
else:
glob_pattern = None
input_files: List[Path] = []
if glob_pattern:
input_files = [
Path(p)
for p in list(glob.glob(str(Path(glob_pattern).expanduser().resolve())))
]
else:
input_files = [Path(p) for p in args.inputs]
console = Console()
console.print("Input Files:", style="bold", end=" ")
console.print(f"{len(input_files):03d} files", style="cyan")
# for input_file in args.inputs:
# console.print(f"- {input_file}", style="cyan")
console.print("\nOutput File:", style="bold", end=" ")
console.print(f"{Path(args.output).resolve().absolute()}", style="cyan")
with Progress(console=console, auto_refresh=True) as progress:
from frame_interpolation.eval import util
from frame_interpolation.eval import util, interpolator
# files = Path(pth).rglob("*.png")
model = interpolator.Interpolator(
"G:/MODELS/FILM/pretrained_models/film_net/Style", None
) # [2,2]
task = progress.add_task("[cyan]Interpolating frames...", total=1)
frames = list(
util.interpolate_recursively_from_files(
[x.as_posix() for x in input_files], args.interpolate, model
)
)
# mediapy.write_video(args.output, frames, fps=args.fps)
write_prores_444_video(args.output, frames, fps=args.fps)
progress.update(task, advance=1)
progress.refresh()
+434 -25
View File
@@ -3,58 +3,467 @@ import numpy as np
import torch
from pathlib import Path
import sys
from typing import List
import signal
from contextlib import suppress
from queue import Queue, Empty
import subprocess
import threading
import os
import math
try:
from .log import log
except ImportError:
try:
from log import log
log.warn("Imported log without relative path")
except ImportError:
import logging
log = logging.getLogger("comfy mtb utils")
log.warn("[comfy mtb] You probably called the file outside a module.")
# region MISC Utilities
def hex_to_rgb(hex_color):
try:
hex_color = hex_color.lstrip("#")
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
except ValueError:
log.error(f"Invalid hex color: {hex_color}")
return (0, 0, 0)
def add_path(path, prepend=False):
if isinstance(path, list):
for p in path:
add_path(p, prepend)
return
if isinstance(path, Path):
path = path.resolve().as_posix()
if path not in sys.path:
if prepend:
sys.path.insert(0, path)
else:
sys.path.append(path)
# Get the absolute path of the parent directory of the current script
def enqueue_output(out, queue):
for line in iter(out.readline, b""):
queue.put(line)
out.close()
def run_command(cmd):
if isinstance(cmd, str):
shell_cmd = cmd
elif isinstance(cmd, list):
shell_cmd = ""
for arg in cmd:
if isinstance(arg, Path):
arg = arg.as_posix()
shell_cmd += f"{arg} "
else:
raise ValueError(
"Invalid 'cmd' argument. It must be a string or a list of arguments."
)
process = subprocess.Popen(
shell_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
shell=True,
)
# Create separate threads to read standard output and standard error streams
stdout_queue = Queue()
stderr_queue = Queue()
stdout_thread = threading.Thread(
target=enqueue_output, args=(process.stdout, stdout_queue)
)
stderr_thread = threading.Thread(
target=enqueue_output, args=(process.stderr, stderr_queue)
)
stdout_thread.daemon = True
stderr_thread.daemon = True
stdout_thread.start()
stderr_thread.start()
interrupted = False
def signal_handler(signum, frame):
nonlocal interrupted
interrupted = True
print("Command execution interrupted.")
# Register the signal handler for keyboard interrupts (SIGINT)
signal.signal(signal.SIGINT, signal_handler)
# Process output from both streams until the process completes or interrupted
while not interrupted and (
process.poll() is None or not stdout_queue.empty() or not stderr_queue.empty()
):
with suppress(Empty):
stdout_line = stdout_queue.get_nowait()
if stdout_line.strip() != "":
print(stdout_line.strip())
with suppress(Empty):
stderr_line = stderr_queue.get_nowait()
if stderr_line.strip() != "":
print(stderr_line.strip())
return_code = process.returncode
if return_code == 0 and not interrupted:
print("Command executed successfully!")
else:
if not interrupted:
print(f"Command failed with return code: {return_code}")
# todo use the requirements library
reqs_map = {
"onnxruntime": "onnxruntime-gpu==1.15.1",
"basicsr": "basicsr==1.4.2",
"rembg": "rembg==2.0.50",
"qrcode": "qrcode[pil]",
}
def import_install(package_name):
from pip._internal import main as pip_main
try:
__import__(package_name)
except ImportError:
package_spec = reqs_map.get(package_name)
if package_spec is None:
print(f"Installing {package_name}")
package_spec = package_name
pip_main(["install", package_spec])
__import__(package_name)
# endregion
# region GLOBAL VARIABLES
# - detect mode
comfy_mode = None
if os.environ.get("COLAB_GPU"):
comfy_mode = "colab"
elif "python_embeded" in sys.executable:
comfy_mode = "embeded"
elif ".venv" in sys.executable:
comfy_mode = "venv"
# - Get the absolute path of the parent directory of the current script
here = Path(__file__).parent.resolve()
# Construct the absolute path to the ComfyUI directory
# - Construct the absolute path to the ComfyUI directory
comfy_dir = here.parent.parent
# Construct the path to the font file
# - Construct the path to the font file
font_path = here / "font.ttf"
# Add extern folder to path
add_path(here / "extern")
add_path(here / "extern" / "SadTalker")
# - Add extern folder to path
extern_root = here / "extern"
add_path(extern_root)
for pth in extern_root.iterdir():
if pth.is_dir():
add_path(pth)
# Add the ComfyUI directory and custom nodes path to the sys.path list
# - Add the ComfyUI directory and custom nodes path to the sys.path list
add_path(comfy_dir)
add_path((comfy_dir / "custom_nodes"))
# Tensor to PIL (grabbed from WAS Suite)
def tensor2pil(image: torch.Tensor) -> Image.Image:
return Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
PIL_FILTER_MAP = {
"nearest": Image.Resampling.NEAREST,
"box": Image.Resampling.BOX,
"bilinear": Image.Resampling.BILINEAR,
"hamming": Image.Resampling.HAMMING,
"bicubic": Image.Resampling.BICUBIC,
"lanczos": Image.Resampling.LANCZOS,
}
# endregion
# Convert PIL to Tensor (grabbed from WAS Suite)
def pil2tensor(image: Image.Image) -> torch.Tensor:
# region TENSOR UTILITIES
def tensor2pil(image: torch.Tensor) -> List[Image.Image]:
batch_count = image.size(0) if len(image.shape) > 3 else 1
if batch_count > 1:
out = []
for i in range(batch_count):
out.extend(tensor2pil(image[i]))
return out
return [
Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
]
def pil2tensor(image: Image.Image | List[Image.Image]) -> torch.Tensor:
if isinstance(image, list):
return torch.cat([pil2tensor(img) for img in image], dim=0)
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def img_np_to_tensor(img_np):
return torch.from_numpy(img_np / 255.0)[None,]
def img_tensor_to_np(img_tensor):
img_tensor = img_tensor.clone()
img_tensor = img_tensor * 255.0
return img_tensor.squeeze(0).numpy().astype(np.float32)
def np2tensor(img_np: np.ndarray | List[np.ndarray]) -> torch.Tensor:
if isinstance(img_np, list):
return torch.cat([np2tensor(img) for img in img_np], dim=0)
return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
def tensor2np(tensor: torch.Tensor) -> List[np.ndarray]:
batch_count = tensor.size(0) if len(tensor.shape) > 3 else 1
if batch_count > 1:
out = []
for i in range(batch_count):
out.extend(tensor2np(tensor[i]))
return out
return [np.clip(255.0 * tensor.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)]
# endregion
# region MODEL Utilities
def download_antelopev2():
antelopev2_url = "https://drive.google.com/uc?id=18wEUfMNohBJ4K3Ly5wpTejPfDzp-8fI8"
try:
import gdown
import folder_paths
log.debug("Loading antelopev2 model")
dest = Path(folder_paths.models_dir) / "insightface"
archive = dest / "antelopev2.zip"
final_path = dest / "models" / "antelopev2"
if not final_path.exists():
log.info(f"antelopev2 not found, downloading to {dest}")
gdown.download(
antelopev2_url,
archive.as_posix(),
resume=True,
)
log.info(f"Unzipping antelopev2 to {final_path}")
if archive.exists():
# we unzip it
import zipfile
with zipfile.ZipFile(archive.as_posix(), "r") as zip_ref:
zip_ref.extractall(final_path.parent.as_posix())
except Exception as e:
log.error(
f"Could not load or download antelopev2 model, download it manually from {antelopev2_url}"
)
raise e
# endregion
# region UV Utilities
def create_uv_map_tensor(width=512, height=512):
u = torch.linspace(0.0, 1.0, steps=width)
v = torch.linspace(0.0, 1.0, steps=height)
U, V = torch.meshgrid(u, v)
uv_map = torch.zeros(height, width, 3, dtype=torch.float32)
uv_map[:, :, 0] = U.t()
uv_map[:, :, 1] = V.t()
return uv_map.unsqueeze(0)
# endregion
# region ANIMATION Utilities
def apply_easing(value, easing_type):
if value < 0 or value > 1:
raise ValueError("The value should be between 0 and 1.")
if easing_type == "Linear":
return value
# Back easing functions
def easeInBack(t):
s = 1.70158
return t * t * ((s + 1) * t - s)
def easeOutBack(t):
s = 1.70158
return ((t - 1) * t * ((s + 1) * t + s)) + 1
def easeInOutBack(t):
s = 1.70158 * 1.525
if t < 0.5:
return (t * t * (t * (s + 1) - s)) * 2
return ((t - 2) * t * ((s + 1) * t + s) + 2) * 2
# Elastic easing functions
def easeInElastic(t):
if t == 0:
return 0
if t == 1:
return 1
p = 0.3
s = p / 4
return -(math.pow(2, 10 * (t - 1)) * math.sin((t - 1 - s) * (2 * math.pi) / p))
def easeOutElastic(t):
if t == 0:
return 0
if t == 1:
return 1
p = 0.3
s = p / 4
return math.pow(2, -10 * t) * math.sin((t - s) * (2 * math.pi) / p) + 1
def easeInOutElastic(t):
if t == 0:
return 0
if t == 1:
return 1
p = 0.3 * 1.5
s = p / 4
t = t * 2
if t < 1:
return -0.5 * (
math.pow(2, 10 * (t - 1)) * math.sin((t - 1 - s) * (2 * math.pi) / p)
)
return (
0.5 * math.pow(2, -10 * (t - 1)) * math.sin((t - 1 - s) * (2 * math.pi) / p)
+ 1
)
# Bounce easing functions
def easeInBounce(t):
return 1 - easeOutBounce(1 - t)
def easeOutBounce(t):
if t < (1 / 2.75):
return 7.5625 * t * t
elif t < (2 / 2.75):
t -= 1.5 / 2.75
return 7.5625 * t * t + 0.75
elif t < (2.5 / 2.75):
t -= 2.25 / 2.75
return 7.5625 * t * t + 0.9375
else:
t -= 2.625 / 2.75
return 7.5625 * t * t + 0.984375
def easeInOutBounce(t):
if t < 0.5:
return easeInBounce(t * 2) * 0.5
return easeOutBounce(t * 2 - 1) * 0.5 + 0.5
# Quart easing functions
def easeInQuart(t):
return t * t * t * t
def easeOutQuart(t):
t -= 1
return -(t**2 * t * t - 1)
def easeInOutQuart(t):
t *= 2
if t < 1:
return 0.5 * t * t * t * t
t -= 2
return -0.5 * (t**2 * t * t - 2)
# Cubic easing functions
def easeInCubic(t):
return t * t * t
def easeOutCubic(t):
t -= 1
return t**2 * t + 1
def easeInOutCubic(t):
t *= 2
if t < 1:
return 0.5 * t * t * t
t -= 2
return 0.5 * (t**2 * t + 2)
# Circ easing functions
def easeInCirc(t):
return -(math.sqrt(1 - t * t) - 1)
def easeOutCirc(t):
t -= 1
return math.sqrt(1 - t**2)
def easeInOutCirc(t):
t *= 2
if t < 1:
return -0.5 * (math.sqrt(1 - t**2) - 1)
t -= 2
return 0.5 * (math.sqrt(1 - t**2) + 1)
# Sine easing functions
def easeInSine(t):
return -math.cos(t * (math.pi / 2)) + 1
def easeOutSine(t):
return math.sin(t * (math.pi / 2))
def easeInOutSine(t):
return -0.5 * (math.cos(math.pi * t) - 1)
easing_functions = {
"Sine In": easeInSine,
"Sine Out": easeOutSine,
"Sine In/Out": easeInOutSine,
"Quart In": easeInQuart,
"Quart Out": easeOutQuart,
"Quart In/Out": easeInOutQuart,
"Cubic In": easeInCubic,
"Cubic Out": easeOutCubic,
"Cubic In/Out": easeInOutCubic,
"Circ In": easeInCirc,
"Circ Out": easeOutCirc,
"Circ In/Out": easeInOutCirc,
"Back In": easeInBack,
"Back Out": easeOutBack,
"Back In/Out": easeInOutBack,
"Elastic In": easeInElastic,
"Elastic Out": easeOutElastic,
"Elastic In/Out": easeInOutElastic,
"Bounce In": easeInBounce,
"Bounce Out": easeOutBounce,
"Bounce In/Out": easeInOutBounce,
}
function_ease = easing_functions.get(easing_type)
if function_ease:
return function_ease(value)
log.error(f"Unknown easing type: {easing_type}")
log.error(f"Available easing types: {list(easing_functions.keys())}")
raise ValueError(f"Unknown easing type: {easing_type}")
# endregion
+32
View File
@@ -0,0 +1,32 @@
## Core
These 3 scripts cannot be used independently and must all be present to work, they are mostly enhancing the frontend of python nodes
- `comfy_shared`: library of methods used in `mtb_widgets` and `debug`
**mtb_widgets** define ui callbacks, and various widgets like the `COLOR` type:
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/5dbcb714-e1e2-4be7-b0e2-68a6c38c83de" width=400/>
or the `BOOL` type:
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7601366d-601c-4f4d-b735-1a4b076770b0" width=400/>
There is also `Debug` which is a node that should be able to display any data input, it handle a few cases and fallback to the string representation of the
data otherwise:
![debug](https://github.com/melMass/comfy_mtb/assets/7041726/1f4393e4-1c3d-4807-9501-fe8888bfae25)
## Standalone
These scripts can be taken and placed independently of `comfy_mtb` or any other files, mimicking what pythongosss did for their
- **imageFeed**: a fork of @pythongosssss ' s [image feed](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/tree/main/js), it adds support for: a lightbox to see images bigger, a way to load the current session history (in case of a web page reload), and different icons, most of the work come from the original script.
> **NOTE**
>
> The original imagefeed got updated since and offer more options, ideally I would clean my lightbox thing and PR it to pythongoss later but in the meantime the script will detect if you already use the original one and not load this fork
- ![imagefeed2-hd](https://github.com/melMass/comfy_mtb/assets/7041726/8539f46f-78e1-459a-a11c-fddd44e63ca9)
- **notify**: a basic toast notification system that I use in some places accross mtb, it can be used by simply calling `window.MTB.notify("Hello world!")`
![extract](https://github.com/melMass/comfy_mtb/assets/7041726/450c67fc-a7e9-4bea-ae49-b610d693098d)
-195
View File
@@ -1,195 +0,0 @@
// Define the Color Picker widget class
import parseCss from '/extensions/mtb/extern/parse-css.js'
import { app } from "/scripts/app.js";
import { ComfyWidgets } from "/scripts/widgets.js";
export function CUSTOM_INT(node, inputName, val, func, config = {}) {
return {
widget: node.addWidget(
"number",
inputName,
val,
func,
Object.assign({}, { min: 0, max: 4096, step: 640, precision: 0 }, config)
),
};
}
const dumb_call = (v,d,node) => {
console.log("dumb_call", {v,d,node});
}
function isColorBright (rgb, threshold=240) {
const brightess = getBrightness(rgb)
return brightess > threshold
}
function getBrightness (rgbObj) {
return Math.round(((parseInt(rgbObj[0]) * 299) + (parseInt(rgbObj[1]) * 587) + (parseInt(rgbObj[2]) * 114)) /1000)
}
/**
* @returns {import("/types/litegraph").IWidget} widget
*/
const custom = (key,val) => {
/** @type {import("/types/litegraph").IWidget} */
const widget = {}
// widget.y = 0;
widget.name = key;
widget.type = "COLOR";
widget.options = { default: "#ff0000" };
widget.value = val || "#ff0000";
widget.draw = function (ctx,
node,
widgetWidth,
widgetY,
height) {
const border = 3;
// draw a rect with a border and a fill color
ctx.fillStyle = "#000";
ctx.fillRect(0, widgetY, widgetWidth, height);
ctx.fillStyle = this.value;
ctx.fillRect(border, widgetY + border, widgetWidth - border * 2, height - border * 2);
// write the input name
// choose the fill based on the luminoisty of this.value color
const color = parseCss(this.value.default || this.value)
if (!color) {
return
}
ctx.fillStyle = isColorBright(color.values, 125) ? "#000" : "#fff";
ctx.font = "14px Arial";
ctx.textAlign = "center";
ctx.fillText(this.name, widgetWidth * 0.5, widgetY + 14);
// ctx.strokeStyle = "#fff";
// ctx.strokeRect(border, widgetY + border, widgetWidth - border * 2, height - border * 2);
// ctx.fillStyle = "#000";
// ctx.fillRect(widgetWidth/2 - border / 2 , widgetY + border / 2 , widgetWidth/2 + border / 2, height + border / 2);
// ctx.fillStyle = this.value;
// ctx.fillRect(widgetWidth/2, widgetY, widgetWidth/2, height);
}
widget.mouse = function (e, pos, node) {
if (e.type === "pointerdown") {
console.log({e,pos,node})
// get widgets of type type : "COLOR"
const widgets = node.widgets.filter(w => w.type === "COLOR");
for (const w of widgets) {
// color picker
const rect = [w.last_y, w.last_y + 32];
console.log({rect,pos})
if (pos[1] > rect[0] && pos[1] < rect[1]) {
console.log("color picker", node)
const picker = document.createElement("input");
picker.type = "color";
picker.value = this.value;
// picker.style.position = "absolute";
// picker.style.left = ( pos[0]) + "px";
// picker.style.top = ( pos[1]) + "px";
// place at screen center
// picker.style.position = "absolute";
// picker.style.left = (window.innerWidth / 2) + "px";
// picker.style.top = (window.innerHeight / 2) + "px";
// picker.style.transform = "translate(-50%, -50%)";
// picker.style.zIndex = 1000;
document.body.appendChild(picker);
picker.addEventListener("change", () => {
this.value = picker.value;
node.graph._version++;
node.setDirtyCanvas(true, true);
document.body.removeChild(picker);
});
// simulate click with screen center
const pointer_event = new MouseEvent('click', {
bubbles: false,
// cancelable: true,
pointerType: "mouse",
clientX: window.innerWidth / 2,
clientY: window.innerHeight / 2,
x: window.innerWidth / 2,
y: window.innerHeight / 2,
offsetX: window.innerWidth / 2,
offsetY: window.innerHeight / 2,
screenX: window.innerWidth / 2,
screenY: window.innerHeight / 2,
});
console.log(e)
picker.dispatchEvent(pointer_event);
}}}}
widget.computeSize = function (width) {
return [width, 32];
}
return widget;
}
app.registerExtension({
name: "mtb.ColorPicker",
init: () => {
ComfyWidgets.COLOR = function () {
return {
widget:custom("color", "#ff0000")
};
};
},
async beforeRegisterNodeDef(nodeType, nodeData, app) {
//console.log("mtb.ColorPicker", { nodeType, nodeData, app });
const rinputs = nodeData.input?.required; // object with key/value pairs, "0" is the type
// console.log(nodeData.name, { nodeType, nodeData, app });
if (!rinputs) return;
let has_color = false;
for (const [key, input] of Object.entries(rinputs)) {
if (input[0] === "COLOR") {
has_color = true;
// input[1] = { default: "#ff0000" };
}}
if (!has_color) return;
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
this.serialize_widgets = true;
// if (rinputs[0] === "COLOR") {
// console.log(nodeData.name, { nodeType, nodeData, app });
// loop through the inputs to find the color inputs
for (const [key, input] of Object.entries(rinputs)) {
if (input[0] === "COLOR") {
this.addCustomWidget(custom(key,input[1]))
}
// }
}
this.onRemoved = function () {
// When removing this node we need to remove the input from the DOM
for (let y in this.widgets) {
if (this.widgets[y].canvas) {
this.widgets[y].canvas.remove();
}
}
};
}
}
});
+318
View File
@@ -0,0 +1,318 @@
/**
* File: comfy_shared.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
import { app } from '/scripts/app.js'
export const log = (...args) => {
if (window.MTB?.DEBUG) {
console.debug(...args)
}
}
//- WIDGET UTILS
export const CONVERTED_TYPE = 'converted-widget'
export function offsetDOMWidget(
widget,
ctx,
node,
widgetWidth,
widgetY,
height
) {
const margin = 10
const elRect = ctx.canvas.getBoundingClientRect()
const transform = new DOMMatrix()
.scaleSelf(
elRect.width / ctx.canvas.width,
elRect.height / ctx.canvas.height
)
.multiplySelf(ctx.getTransform())
.translateSelf(margin, margin + widgetY)
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
Object.assign(widget.inputEl.style, {
transformOrigin: '0 0',
transform: scale,
left: `${transform.a + transform.e}px`,
top: `${transform.d + transform.f}px`,
width: `${widgetWidth - margin * 2}px`,
// height: `${(widget.parent?.inputHeight || 32) - (margin * 2)}px`,
height: `${(height || widget.parent?.inputHeight || 32) - margin * 2}px`,
position: 'absolute',
background: !node.color ? '' : node.color,
color: !node.color ? '' : 'white',
zIndex: 5, //app.graph._nodes.indexOf(node),
})
}
/**
* Extracts the type and link type from a widget config object.
* @param {*} config
* @returns
*/
export function getWidgetType(config) {
// Special handling for COMBO so we restrict links based on the entries
let type = config?.[0]
let linkType = type
if (type instanceof Array) {
type = 'COMBO'
linkType = linkType.join(',')
}
return { type, linkType }
}
export const dynamic_connection = (
node,
index,
connected,
connectionPrefix = 'input_',
connectionType = 'PSDLAYER'
) => {
// remove all non connected inputs
if (!connected && node.inputs.length > 1) {
log(`Removing input ${index} (${node.inputs[index].name})`)
if (node.widgets) {
const w = node.widgets.find((w) => w.name === node.inputs[index].name)
if (w) {
w.onRemoved?.()
node.widgets.length = node.widgets.length - 1
}
}
node.removeInput(index)
// make inputs sequential again
for (let i = 0; i < node.inputs.length; i++) {
node.inputs[i].label = `${connectionPrefix}${i + 1}`
}
}
// add an extra input
if (node.inputs[node.inputs.length - 1].link != undefined) {
log(
`Adding input ${node.inputs.length + 1} (${connectionPrefix}${
node.inputs.length + 1
})`
)
node.addInput(
`${connectionPrefix}${node.inputs.length + 1}`,
connectionType
)
}
}
/**
* Appends a callback to the extra menu options of a given node type.
* @param {*} nodeType
* @param {*} cb
*/
export function addMenuHandler(nodeType, cb) {
const getOpts = nodeType.prototype.getExtraMenuOptions
nodeType.prototype.getExtraMenuOptions = function () {
const r = getOpts.apply(this, arguments)
cb.apply(this, arguments)
return r
}
}
export function hideWidget(node, widget, suffix = '') {
widget.origType = widget.type
widget.hidden = true
widget.origComputeSize = widget.computeSize
widget.origSerializeValue = widget.serializeValue
widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
widget.type = CONVERTED_TYPE + suffix
widget.serializeValue = () => {
// Prevent serializing the widget if we have no input linked
const { link } = node.inputs.find((i) => i.widget?.name === widget.name)
if (link == null) {
return undefined
}
return widget.origSerializeValue
? widget.origSerializeValue()
: widget.value
}
// Hide any linked widgets, e.g. seed+seedControl
if (widget.linkedWidgets) {
for (const w of widget.linkedWidgets) {
hideWidget(node, w, ':' + widget.name)
}
}
}
export function showWidget(widget) {
widget.type = widget.origType
widget.computeSize = widget.origComputeSize
widget.serializeValue = widget.origSerializeValue
delete widget.origType
delete widget.origComputeSize
delete widget.origSerializeValue
// Hide any linked widgets, e.g. seed+seedControl
if (widget.linkedWidgets) {
for (const w of widget.linkedWidgets) {
showWidget(w)
}
}
}
export function convertToWidget(node, widget) {
showWidget(widget)
const sz = node.size
node.removeInput(node.inputs.findIndex((i) => i.widget?.name === widget.name))
for (const widget of node.widgets) {
widget.last_y -= LiteGraph.NODE_SLOT_HEIGHT
}
// Restore original size but grow if needed
node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
}
export function convertToInput(node, widget, config) {
hideWidget(node, widget)
const { linkType } = getWidgetType(config)
// Add input and store widget config for creating on primitive node
const sz = node.size
node.addInput(widget.name, linkType, {
widget: { name: widget.name, config },
})
for (const widget of node.widgets) {
widget.last_y += LiteGraph.NODE_SLOT_HEIGHT
}
// Restore original size but grow if needed
node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
}
export function hideWidgetForGood(node, widget, suffix = '') {
widget.origType = widget.type
widget.origComputeSize = widget.computeSize
widget.origSerializeValue = widget.serializeValue
widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
widget.type = CONVERTED_TYPE + suffix
// widget.serializeValue = () => {
// // Prevent serializing the widget if we have no input linked
// const w = node.inputs?.find((i) => i.widget?.name === widget.name);
// if (w?.link == null) {
// return undefined;
// }
// return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
// };
// Hide any linked widgets, e.g. seed+seedControl
if (widget.linkedWidgets) {
for (const w of widget.linkedWidgets) {
hideWidgetForGood(node, w, ':' + widget.name)
}
}
}
export function fixWidgets(node) {
if (node.inputs) {
for (const input of node.inputs) {
log(input)
if (input.widget || node.widgets) {
// if (newTypes.includes(input.type)) {
const matching_widget = node.widgets.find((w) => w.name === input.name)
if (matching_widget) {
// if (matching_widget.hidden) {
// log(`Already hidden skipping ${matching_widget.name}`)
// continue
// }
const w = node.widgets.find((w) => w.name === matching_widget.name)
if (w && w.type != CONVERTED_TYPE) {
log(w)
log(`hidding ${w.name}(${w.type}) from ${node.type}`)
log(node)
hideWidget(node, w)
} else {
log(`converting to widget ${w}`)
convertToWidget(node, input)
}
}
}
}
}
}
export function inner_value_change(widget, value, event = undefined) {
if (widget.type == 'number' || widget.type == 'BBOX') {
value = Number(value)
} else if (widget.type == 'BOOL') {
value = Boolean(value)
}
widget.value = value
if (
widget.options &&
widget.options.property &&
node.properties[widget.options.property] !== undefined
) {
node.setProperty(widget.options.property, value)
}
if (widget.callback) {
widget.callback(widget.value, app.canvas, node, pos, event)
}
}
//- COLOR UTILS
export function isColorBright(rgb, threshold = 240) {
const brightess = getBrightness(rgb)
return brightess > threshold
}
function getBrightness(rgbObj) {
return Math.round(
(parseInt(rgbObj[0]) * 299 +
parseInt(rgbObj[1]) * 587 +
parseInt(rgbObj[2]) * 114) /
1000
)
}
//- HTML / CSS UTILS
export function defineClass(className, classStyles) {
const styleSheets = document.styleSheets
// Helper function to check if the class exists in a style sheet
function classExistsInStyleSheet(styleSheet) {
const rules = styleSheet.rules || styleSheet.cssRules
for (const rule of rules) {
if (rule.selectorText === `.${className}`) {
return true
}
}
return false
}
// Check if the class is already defined in any of the style sheets
let classExists = false
for (const styleSheet of styleSheets) {
if (classExistsInStyleSheet(styleSheet)) {
classExists = true
break
}
}
// If the class doesn't exist, add the new class definition to the first style sheet
if (!classExists) {
if (styleSheets[0].insertRule) {
styleSheets[0].insertRule(`.${className} { ${classStyles} }`, 0)
} else if (styleSheets[0].addRule) {
styleSheets[0].addRule(`.${className}`, classStyles, 0)
}
}
}
+99
View File
@@ -0,0 +1,99 @@
/**
* File: debug.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
import { app } from '/scripts/app.js'
import * as shared from '/extensions/mtb/comfy_shared.js'
import { log } from '/extensions/mtb/comfy_shared.js'
import { MtbWidgets } from '/extensions/mtb/mtb_widgets.js'
// TODO: respect inputs order...
app.registerExtension({
name: 'mtb.Debug',
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === 'Debug (mtb)') {
const onConnectionsChange = nodeType.prototype.onConnectionsChange
nodeType.prototype.onConnectionsChange = function (
type,
index,
connected,
link_info
) {
const r = onConnectionsChange
? onConnectionsChange.apply(this, arguments)
: undefined
// TODO: remove all widgets on disconnect once computed
shared.dynamic_connection(this, index, connected, 'anything_', '*')
//- 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
this.inputs[index].type = type
// this.inputs[index].label = type.toLowerCase()
}
//- restore dynamic input
if (!connected) {
this.inputs[index].type = '*'
this.inputs[index].label = `anything_${index + 1}`
}
}
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (message) {
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++) {
this.widgets[i].onRemoved?.()
}
this.widgets.length = 0
}
let widgetI = 1
if (message.text) {
for (const txt of message.text) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_STRING(`${prefix}_${widgetI}`, txt)
)
w.parent = this
widgetI++
}
}
if (message.b64_images) {
for (const img of message.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())
}
this.onRemoved = function () {
// When removing this node we need to remove the input from the DOM
for (let y in this.widgets) {
if (this.widgets[y].canvas) {
this.widgets[y].canvas.remove()
}
this.widgets[y].onRemoved?.()
}
}
}
}
},
})
+333
View File
@@ -0,0 +1,333 @@
/**
* File: imageFeed.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
// forked from pysssss's imageFeed.js
import { api } from '/scripts/api.js'
import { app } from '/scripts/app.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',
},
}
let currentImageIndex = 0
const imageUrls = []
let image_menu = null
let activated = true
app.registerExtension({
name: 'mtb.ImageFeed',
init: async () => {
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',
})
// previous and next buttons
const lightboxPrevBtn = document.createElement('button')
const lightboxNextBtn = document.createElement('button')
lightboxPrevBtn.textContent = '❮'
lightboxNextBtn.textContent = '❯'
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 = '❌'
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)
//- 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',
})
//- 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)
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");
//- callbacks
closeBtn.onclick = () => {
imageListContainer.style.display = 'none'
showBtn.style.display = 'unset'
}
clearButton.onclick = () => {
imageListContainer.replaceChildren(closeBtn, clearButton, loadButton)
}
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
}
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',
})
img.src = `/view?filename=${encodeURIComponent(src.filename)}&type=${
src.type
}&subfolder=${encodeURIComponent(src.subfolder)}`
imageUrls.push(img.src)
console.debug(img.src)
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);
}
// add right click menu
but.addEventListener('contextmenu', (e) => {
e.preventDefault()
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.appendChild(load_img)
document.body.appendChild(image_menu)
})
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}`)
// }
}
}
}
///////-------
// 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)
}
}
})
},
})
+921
View File
@@ -0,0 +1,921 @@
/**
* File: mtb_widgets.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
import { app } from '/scripts/app.js'
import parseCss from '/extensions/mtb/extern/parse-css.js'
import * as shared from '/extensions/mtb/comfy_shared.js'
import { log } from '/extensions/mtb/comfy_shared.js'
import { api } from '/scripts/api.js'
const newTypes = [, /*'BOOL'*/ 'COLOR', 'BBOX']
export const MtbWidgets = {
BBOX: (key, val) => {
/** @type {import("./types/litegraph").IWidget} */
const widget = {
name: key,
type: 'BBOX',
// options: val,
y: 0,
value: val?.default || [0, 0, 0, 0],
options: {},
draw: function (ctx, node, widget_width, widgetY, height) {
const hide = this.type !== 'BBOX' && app.canvas.ds.scale > 0.5
const show_text = true
const outline_color = LiteGraph.WIDGET_OUTLINE_COLOR
const background_color = LiteGraph.WIDGET_BGCOLOR
const text_color = LiteGraph.WIDGET_TEXT_COLOR
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
if (hide) return
for (let i = 0; i < numWidgets; i++) {
let currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
ctx.textAlign = 'left'
ctx.strokeStyle = outline_color
ctx.fillStyle = background_color
ctx.beginPath()
if (show_text)
ctx.roundRect(margin, currentY, widget_width - margin * 2, H, [
H * 0.5,
])
else ctx.rect(margin, currentY, widget_width - margin * 2, H)
ctx.fill()
if (show_text) {
if (!this.disabled) ctx.stroke()
ctx.fillStyle = text_color
if (!this.disabled) {
ctx.beginPath()
ctx.moveTo(margin + 16, currentY + 5)
ctx.lineTo(margin + 6, currentY + H * 0.5)
ctx.lineTo(margin + 16, currentY + H - 5)
ctx.fill()
ctx.beginPath()
ctx.moveTo(widget_width - margin - 16, currentY + 5)
ctx.lineTo(widget_width - margin - 6, currentY + H * 0.5)
ctx.lineTo(widget_width - margin - 16, currentY + H - 5)
ctx.fill()
}
ctx.fillStyle = secondary_text_color
ctx.fillText(
this.label || this.name,
margin * 2 + 5,
currentY + H * 0.7
)
ctx.fillStyle = text_color
ctx.textAlign = 'right'
ctx.fillText(
Number(this.value).toFixed(
this.options?.precision !== undefined
? this.options.precision
: 3
),
widget_width - margin * 2 - 20,
currentY + H * 0.7
)
}
}
},
mouse: function (event, pos, node) {
let old_value = this.value
let x = pos[0] - node.pos[0]
let y = pos[1] - node.pos[1]
let width = node.size[0]
let H = LiteGraph.NODE_WIDGET_HEIGHT
let margin = 5
let numWidgets = 4 // Number of stacked widgets
for (let i = 0; i < numWidgets; i++) {
let currentY = y + i * (H + margin) // Adjust Y position for each widget
if (
event.type == LiteGraph.pointerevents_method + 'move' &&
this.type == 'BBOX'
) {
if (event.deltaX)
this.value += event.deltaX * 0.1 * (this.options?.step || 1)
if (this.options.min != null && this.value < this.options.min) {
this.value = this.options.min
}
if (this.options.max != null && this.value > this.options.max) {
this.value = this.options.max
}
} else if (event.type == LiteGraph.pointerevents_method + 'down') {
let values = this.options?.values
if (values && values.constructor === Function) {
values = this.options.values(w, node)
}
let values_list = null
let delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0
if (this.type == 'BBOX') {
this.value += delta * 0.1 * (this.options.step || 1)
if (this.options.min != null && this.value < this.options.min) {
this.value = this.options.min
}
if (this.options.max != null && this.value > this.options.max) {
this.value = this.options.max
}
} else if (delta) {
//clicked in arrow, used for combos
let index = -1
this.last_mouseclick = 0 //avoids dobl click event
if (values.constructor === Object)
index = values_list.indexOf(String(this.value)) + delta
else index = values_list.indexOf(this.value) + delta
if (index >= values_list.length) {
index = values_list.length - 1
}
if (index < 0) {
index = 0
}
if (values.constructor === Array) this.value = values[index]
else this.value = index
}
} //end mousedown
else if (
event.type == LiteGraph.pointerevents_method + 'up' &&
this.type == 'BBOX'
) {
let delta = x < 40 ? -1 : x > widget_width - 40 ? 1 : 0
if (event.click_time < 200 && delta == 0) {
this.prompt(
'Value',
this.value,
function (v) {
// check if v is a valid equation or a number
if (/^[0-9+\-*/()\s]+|\d+\.\d+$/.test(v)) {
try {
//solve the equation if possible
v = eval(v)
} catch (e) {}
}
this.value = Number(v)
shared.inner_value_change(this, this.value, event)
}.bind(w),
event
)
}
}
if (old_value != this.value)
setTimeout(
function () {
shared.inner_value_change(this, this.value, event)
}.bind(this),
20
)
app.canvas.setDirty(true)
}
},
computeSize: function (width) {
return [width, LiteGraph.NODE_WIDGET_HEIGHT * 4]
},
// onDrawBackground: function (ctx) {
// if (!this.flags.collapsed) return;
// this.inputEl.style.display = "block";
// this.inputEl.style.top = this.graphcanvas.offsetTop + this.pos[1] + "px";
// this.inputEl.style.left = this.graphcanvas.offsetLeft + this.pos[0] + "px";
// },
// onInputChange: function (e) {
// const property = e.target.dataset.property;
// const bbox = this.getInputData(0);
// if (!bbox) return;
// bbox[property] = parseFloat(e.target.value);
// this.setOutputData(0, bbox);
// }
}
widget.desc = 'Represents a Bounding Box with x, y, width, and height.'
return widget
},
COLOR: (key, val, compute = false) => {
/** @type {import("/types/litegraph").IWidget} */
const widget = {}
widget.y = 0
widget.name = key
widget.type = 'COLOR'
widget.options = { default: '#ff0000' }
widget.value = val || '#ff0000'
widget.draw = function (ctx, node, widgetWidth, widgetY, height) {
const hide = this.type !== 'COLOR' && app.canvas.ds.scale > 0.5
if (hide) {
return
}
const border = 3
ctx.fillStyle = '#000'
ctx.fillRect(0, widgetY, widgetWidth, height)
ctx.fillStyle = this.value
ctx.fillRect(
border,
widgetY + border,
widgetWidth - border * 2,
height - border * 2
)
const color = parseCss(this.value.default || this.value)
if (!color) {
return
}
ctx.fillStyle = shared.isColorBright(color.values, 125) ? '#000' : '#fff'
ctx.font = '14px Arial'
ctx.textAlign = 'center'
ctx.fillText(this.name, widgetWidth * 0.5, widgetY + 14)
}
widget.mouse = function (e, pos, node) {
if (e.type === 'pointerdown') {
const widgets = node.widgets.filter((w) => w.type === 'COLOR')
for (const w of widgets) {
// color picker
const rect = [w.last_y, w.last_y + 32]
if (pos[1] > rect[0] && pos[1] < rect[1]) {
const picker = document.createElement('input')
picker.type = 'color'
picker.value = this.value
picker.style.position = 'absolute'
picker.style.left = '999999px' //(window.innerWidth / 2) + "px";
picker.style.top = '999999px' //(window.innerHeight / 2) + "px";
document.body.appendChild(picker)
picker.addEventListener('change', () => {
this.value = picker.value
node.graph._version++
node.setDirtyCanvas(true, true)
picker.remove()
})
picker.click()
}
}
}
}
widget.computeSize = function (width) {
return [width, 32]
}
return widget
},
DEBUG_IMG: (name, val) => {
const w = {
name,
type: 'image',
value: val,
draw: function (ctx, node, widgetWidth, widgetY, height) {
const [cw, ch] = this.computeSize(widgetWidth)
shared.offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, ch)
},
computeSize: function (width) {
const ratio = this.inputRatio || 1
if (width) {
return [width, width / ratio + 4]
}
return [128, 128]
},
onRemoved: function () {
if (this.inputEl) {
this.inputEl.remove()
}
},
}
w.inputEl = document.createElement('img')
w.inputEl.src = w.value
w.inputEl.onload = function () {
w.inputRatio = w.inputEl.naturalWidth / w.inputEl.naturalHeight
}
document.body.appendChild(w.inputEl)
return w
},
DEBUG_STRING: (name, val) => {
const fontSize = 16
const w = {
name,
type: 'debug_text',
draw: function (ctx, node, widgetWidth, widgetY, height) {
// const [cw, ch] = this.computeSize(widgetWidth)
shared.offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, height)
},
computeSize: function (width) {
const value = this.inputEl.innerHTML
if (!value) {
return [32, 32]
}
if (!width) {
log(`No width ${this.parent.size}`)
}
const oldFont = app.ctx.font
app.ctx.font = `${fontSize}px monospace`
const words = value.split(' ')
const lines = []
let currentLine = ''
for (const word of words) {
const testLine =
currentLine.length === 0 ? word : `${currentLine} ${word}`
const testWidth = app.ctx.measureText(testLine).width
if (testWidth > width) {
lines.push(currentLine)
currentLine = word
} else {
currentLine = testLine
}
}
app.ctx.font = oldFont
if (lines.length === 0) lines.push(currentLine)
const textHeight = (lines.length + 1) * fontSize
const maxLineWidth = lines.reduce(
(maxWidth, line) =>
Math.max(maxWidth, app.ctx.measureText(line).width),
0
)
const widgetWidth = Math.max(width || this.width || 32, maxLineWidth)
const widgetHeight = textHeight * 1.5
return [widgetWidth, widgetHeight]
},
onRemoved: function () {
if (this.inputEl) {
this.inputEl.remove()
}
},
}
Object.defineProperty(w, 'value', {
get() {
return this.inputEl.innerHTML
},
set(value) {
this.inputEl.innerHTML = value
this.parent?.setSize?.(this.parent?.computeSize())
},
})
w.inputEl = document.createElement('p')
w.inputEl.style.textAlign = 'center'
w.inputEl.style.fontSize = `${fontSize}px`
w.inputEl.style.color = 'var(--input-text)'
w.inputEl.style.lineHeight = 0
w.inputEl.style.fontFamily = 'monospace'
w.value = val
document.body.appendChild(w.inputEl)
return w
},
}
/**
* @returns {import("./types/comfy").ComfyExtension} extension
*/
const mtb_widgets = {
name: 'mtb.widgets',
init: async () => {
log('Registering mtb.widgets')
try {
const res = await api.fetchApi('/mtb/debug')
const msg = await res.json()
if (!window.MTB) {
window.MTB = {}
}
window.MTB.DEBUG = msg.enabled
} catch (e) {
console.error('Error:', error)
}
},
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.Debug.enabled',
name: '[mtb] Enable Debug (py and js)',
type: 'boolean',
defaultValue: false,
tooltip:
'This will enable debug messages in the console and in the python console respectively',
attrs: {
style: {
fontFamily: 'monospace',
},
},
async onChange(value) {
if (value) {
console.log('Enabled DEBUG mode')
}
if (!window.MTB) {
window.MTB = {}
}
window.MTB.DEBUG = value
await api
.fetchApi('/mtb/debug', {
method: 'POST',
body: JSON.stringify({
enabled: value,
}),
})
.then((response) => {})
.catch((error) => {
console.error('Error:', error)
})
},
})
},
getCustomWidgets: function () {
return {
BOOL: (node, inputName, inputData, app) => {
console.debug('Registering bool')
return {
widget: node.addCustomWidget(
MtbWidgets.BOOL(inputName, inputData[1]?.default || false)
),
minWidth: 150,
minHeight: 30,
}
},
COLOR: (node, inputName, inputData, app) => {
console.debug('Registering color')
return {
widget: node.addCustomWidget(
MtbWidgets.COLOR(inputName, inputData[1]?.default || '#ff0000')
),
minWidth: 150,
minHeight: 30,
}
},
// BBOX: (node, inputName, inputData, app) => {
// console.debug("Registering bbox")
// return {
// widget: node.addCustomWidget(MtbWidgets.BBOX(inputName, inputData[1]?.default || [0, 0, 0, 0])),
// minWidth: 150,
// minHeight: 30,
// }
// }
}
},
/**
* @param {import("./types/comfy").NodeType} nodeType
* @param {import("./types/comfy").NodeDef} 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) {
for (const i of Object.keys(nodeData.input.required)) {
const input_type = nodeData.input.required[i][0]
if (newTypes.includes(input_type)) {
has_custom = true
break
}
}
}
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
this.serialize_widgets = true
this.setSize?.(this.computeSize())
this.onRemoved = function () {
// When removing this node we need to remove the input from the DOM
for (const w of this.widgets) {
if (w.canvas) {
w.canvas.remove()
}
w.onRemoved?.()
}
}
return r
}
//- Extra menus
const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions
nodeType.prototype.getExtraMenuOptions = function (_, options) {
const r = origGetExtraMenuOptions
? origGetExtraMenuOptions.apply(this, arguments)
: undefined
if (this.widgets) {
let toInput = []
let toWidget = []
for (const w of this.widgets) {
if (w.type === shared.CONVERTED_TYPE) {
//- This is already handled by widgetinputs.js
// toWidget.push({
// content: `Convert ${w.name} to widget`,
// callback: () => shared.convertToWidget(this, w),
// });
} else if (newTypes.includes(w.type)) {
const config = nodeData?.input?.required[w.name] ||
nodeData?.input?.optional?.[w.name] || [w.type, w.options || {}]
toInput.push({
content: `Convert ${w.name} to input`,
callback: () => shared.convertToInput(this, w, config),
})
}
}
if (toInput.length) {
options.push(...toInput, null)
}
if (toWidget.length) {
options.push(...toWidget, null)
}
}
return r
}
}
//- Extending Python Nodes
switch (nodeData.name) {
case 'Psd Save (mtb)': {
const onConnectionsChange = nodeType.prototype.onConnectionsChange
nodeType.prototype.onConnectionsChange = function (
type,
index,
connected,
link_info
) {
const r = onConnectionsChange
? onConnectionsChange.apply(this, arguments)
: undefined
shared.dynamic_connection(this, index, connected)
return r
}
break
}
//TODO: remove this non sense
case 'Get Batch From History (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
const internal_count = this.widgets.find(
(w) => w.name === 'internal_count'
)
shared.hideWidgetForGood(this, internal_count)
internal_count.afterQueued = function () {
this.value++
}
return r
}
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (message) {
const r = onExecuted ? onExecuted.apply(this, message) : undefined
return r
}
break
}
case 'Save Gif (mtb)':
case 'Save Animated Image (mtb)': {
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (message) {
const prefix = 'anything_'
const r = onExecuted ? onExecuted.apply(this, message) : undefined
if (this.widgets) {
const pos = this.widgets.findIndex((w) => w.name === `${prefix}_0`)
if (pos !== -1) {
for (let i = pos; i < this.widgets.length; i++) {
this.widgets[i].onRemoved?.()
}
this.widgets.length = pos
}
let imgURLs = []
if (message) {
if (message.gif) {
imgURLs = imgURLs.concat(
message.gif.map((params) => {
return api.apiURL(
'/view?' + new URLSearchParams(params).toString()
)
})
)
}
if (message.apng) {
imgURLs = imgURLs.concat(
message.apng.map((params) => {
return api.apiURL(
'/view?' + new URLSearchParams(params).toString()
)
})
)
}
let i = 0
for (const img of imgURLs) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_IMG(`${prefix}_${i}`, img)
)
w.parent = this
i++
}
}
this.setSize?.(this.computeSize())
return r
}
const onRemoved = nodeType.prototype.onRemoved
nodeType.prototype.onRemoved = function (message) {
const r = onRemoved ? onRemoved.apply(this, message) : undefined
if (!this.widgets) return r
for (const w of this.widgets) {
if (w.canvas) {
w.canvas.remove()
}
w.onRemoved?.()
}
return r
}
}
break
}
case 'Animation Builder (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: 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')
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 loop_preview = this.addCustomWidget(
MtbWidgets['DEBUG_STRING']('loop_preview', 'Iteration: Idle')
)
loop_preview.parent = this
const onReset = () => {
raw_iteration.value = 0
raw_loop.value = 0
value_preview.value = 'Idle'
loop_preview.value = 'Iteration: Idle'
app.canvas.setDirty(true)
}
const reset_button = this.addWidget(
'button',
`Reset`,
'reset',
onReset
)
const 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?.(
`Started a queue of ${total_frames.value} frames (for ${
loop_count.value
} loop, so ${total_frames.value * loop_count.value})`,
5000
)
})
this.onRemoved = () => {
for (const w of this.widgets) {
if (w.canvas) {
w.canvas.remove()
}
w.onRemoved?.()
}
app.canvas.setDirty(true)
}
raw_iteration.afterQueued = function () {
this.value++
raw_loop.value = Math.floor(this.value / total_frames.value)
value_preview.value = `frame: ${
raw_iteration.value % total_frames.value
} / ${total_frames.value - 1}`
if (raw_loop.value + 1 > loop_count.value) {
loop_preview.value = 'Done 😎!'
} else {
loop_preview.value = `current loop: ${raw_loop.value + 1}/${
loop_count.value
}`
}
}
return r
}
break
}
case 'Text Encore Frames (mtb)': {
const onConnectionsChange = nodeType.prototype.onConnectionsChange
nodeType.prototype.onConnectionsChange = function (
type,
index,
connected,
link_info
) {
const r = onConnectionsChange
? onConnectionsChange.apply(this, arguments)
: undefined
shared.dynamic_connection(this, index, connected)
return r
}
break
}
case 'Interpolate Clip Sequential (mtb)': {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
const addReplacement = () => {
const input = this.addInput(
`replacement_${this.widgets.length}`,
'STRING',
''
)
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)
addReplacement()
})
//- remove
this.addWidget(
'button',
'-',
'remove',
function (value, widget, node) {
console.log(`Button clicked: ${value}`, widget, node)
}
)
return r
}
break
}
case 'Styles Loader (mtb)': {
const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions
nodeType.prototype.getExtraMenuOptions = function (_, options) {
const r = origGetExtraMenuOptions
? origGetExtraMenuOptions.apply(this, arguments)
: undefined
const getStyle = async (node) => {
try {
const getStyles = await api.fetchApi('/mtb/actions', {
method: 'POST',
body: JSON.stringify({
name: 'getStyles',
args:
node.widgets && node.widgets[0].value
? node.widgets[0].value
: '',
}),
})
const output = await getStyles.json()
return output?.result
} catch (e) {
console.error(e)
}
}
const extracters = [
{
content: 'Extract Positive to Text node',
callback: async () => {
const style = await getStyle(this)
if (style && style.length >= 1) {
if (style[0]) {
window.MTB?.notify?.(
`Extracted positive from ${this.widgets[0].value}`
)
const tn = LiteGraph.createNode('Text box')
app.graph.add(tn)
tn.title = `${this.widgets[0].value} (Positive)`
tn.widgets[0].value = style[0]
} else {
window.MTB?.notify?.(
`No positive to extract for ${this.widgets[0].value}`
)
}
}
},
},
{
content: 'Extract Negative to Text node',
callback: async () => {
const style = await getStyle(this)
if (style && style.length >= 2) {
if (style[1]) {
window.MTB?.notify?.(
`Extracted negative from ${this.widgets[0].value}`
)
const tn = LiteGraph.createNode('Text box')
app.graph.add(tn)
tn.title = `${this.widgets[0].value} (Negative)`
tn.widgets[0].value = style[1]
} else {
window.MTB.notify(
`No negative to extract for ${this.widgets[0].value}`
)
}
}
},
},
]
options.push(...extracters)
}
break
}
case 'Save Tensors (mtb)': {
const onDrawBackground = nodeType.prototype.onDrawBackground
nodeType.prototype.onDrawBackground = function (ctx, canvas) {
const r = onDrawBackground
? onDrawBackground.apply(this, arguments)
: undefined
// // draw a circle on the top right of the node, with text inside
// ctx.fillStyle = "#fff";
// ctx.beginPath();
// ctx.arc(this.size[0] - this.node_width * 0.5, this.size[1] - this.node_height * 0.5, this.node_width * 0.5, 0, Math.PI * 2);
// ctx.fill();
// ctx.fillStyle = "#000";
// ctx.textAlign = "center";
// ctx.font = "bold 12px Arial";
// ctx.fillText("Save Tensors", this.size[0] - this.node_width * 0.5, this.size[1] - this.node_height * 0.5);
return r
}
break
}
default: {
break
}
}
},
}
app.registerExtension(mtb_widgets)
+115
View File
@@ -0,0 +1,115 @@
/**
* File: notify.js
* Project: comfy_mtb
* Author: Mel Massadian
*
* Copyright (c) 2023 Mel Massadian
*
*/
import { app } from '/scripts/app.js'
const log = (...args) => {
if (window.MTB?.TRACE) {
console.debug(...args)
}
}
let transition_time = 300
const containerStyle = `
position: fixed;
top: 20px;
left: 20px;
font-family: monospace;
z-index: 99999;
height: 0;
overflow: hidden;
transition: height ${transition_time}ms ease-in-out;
`
const toastStyle = `
background-color: #333;
color: #fff;
padding: 10px;
border-radius: 5px;
opacity: 0;
overflow:hidden;
height:20px;
transition-property: opacity, height, padding;
transition-duration: ${transition_time}ms;
`
function notify(message, timeout = 3000) {
log('Creating toast')
const container = document.getElementById('mtb-notify-container')
const toast = document.createElement('div')
toast.style.cssText = toastStyle
toast.innerText = message
container.appendChild(toast)
toast.addEventListener('transitionend', (e) => {
// Only on out
if (
e.target === toast &&
e.propertyName === 'height' &&
e.elapsedTime > transition_time / 1000 - Number.EPSILON
) {
log('Transition out')
const totalHeight = Array.from(container.children).reduce(
(acc, child) => acc + child.offsetHeight + 10, // Add spacing of 10px between toasts
0
)
container.style.height = `${totalHeight}px`
// If there are no toasts left, set the container's height to 0
if (container.children.length === 0) {
container.style.height = '0'
}
setTimeout(() => {
container.removeChild(toast)
log('Removed toast from DOM')
}, transition_time)
} else {
log('Transition')
}
})
// Fading in the toast
toast.style.opacity = '1'
// Update container's height to fit new toast
const totalHeight = Array.from(container.children).reduce(
(acc, child) => acc + child.offsetHeight + 10, // Add spacing of 10px between toasts
0
)
container.style.height = `${totalHeight}px`
// remove the toast after the specified timeout
setTimeout(() => {
// trigger the transitions
toast.style.opacity = '0'
toast.style.height = '0'
toast.style.paddingTop = '0'
toast.style.paddingBottom = '0'
}, timeout - transition_time)
}
app.registerExtension({
name: 'mtb.Notify',
setup() {
if (!window.MTB) {
window.MTB = {}
}
const container = document.createElement('div')
container.id = 'mtb-notify-container'
container.style.cssText = containerStyle
document.body.appendChild(container)
window.MTB.notify = notify
// window.MTB.notify('Hello world!')
},
})