Compare commits

...
85 Commits
Author SHA1 Message Date
Mel Massadian 821a031bfc feat: ✨ yet another repl node for comfy
Still unsure how to expose it
2025-08-02 02:59:33 +02:00
Mel Massadian 3d12bd29a8 chore: 🧹 add back convex helper 2025-08-02 02:57:46 +02:00
Mel Massadian 3494a4767e chore(TEMP): 🧹 2025-08-02 02:29:41 +02:00
Mel Massadian 41d444ae70 release: 📦 bump version to 0.6.0 2025-08-02 02:29:40 +02:00
Mel Massadian 41d79d4677 chore: 🧹 remove bumpversion 2025-08-02 02:29:40 +02:00
Mel Massadian 54f4963a7b chore: 🧹 remove pyright config 2025-08-02 02:27:44 +02:00
Mel Massadian d585b16ee7 feat: ✨ batch apply text template if inputs are lists
same as previous commit
2025-08-02 02:27:44 +02:00
Mel Massadian 499cd218aa feat: ✨ batch text to image if inputs are lists
this rely on fakingly declaring list[str] as STRING for now...
2025-08-02 02:27:44 +02:00
Mel Massadian fd00e12724 feat: ✨ use a single widget for Debug
also rely on dynamic_connection setup directly
2025-08-02 02:27:43 +02:00
Mel Massadian e37e4648e5 feat: ✨ simplify dynamic widget logic
mostly by relying on properties
this allow renaming inputs at will
2025-08-02 02:27:43 +02:00
Mel Massadian 06685a5418 feat: ✨ improve loop drawing
recurse all LoopStart outputs
2025-08-02 02:27:43 +02:00
Mel Massadian 40145ddf40 fix: 🐛 ensure links are links
It used to return LLink now it returns the link ID
2025-08-02 02:27:42 +02:00
Mel Massadian c1d74c0d69 feat: ✨ add clear outputs context menu for debug node 2025-08-02 02:27:42 +02:00
Mel Massadian eca2ea5da9 chore: 🧹 move save_tensors to new file 2025-08-02 02:27:42 +02:00
Mel Massadian c6d1f73cfc feat: ✨ add rich_mode on Debug node
WIP for now
2025-08-02 02:27:41 +02:00
Mel Massadian 4ea7c0b67f feat: ✨ add ProxyTensor node
would avoid the need for:
https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite/pull/517
2025-07-27 02:11:20 +02:00
Mel Massadian 8316914f02 feat: ✨ add LazyProxyTensor
utility extended from an idea by @AustinMroz
2025-07-27 02:11:19 +02:00
Mel Massadian 5c0e020c73 fix: 🐛 use gpu for uncrop if available
image tensors are often offloaded to cpu which makes
the gaussian blur dead slow
2025-07-18 15:26:58 +02:00
Mel Massadian d00722e9ea fix: 🐛 remove numpy from bbox crop/uncrop 2025-07-17 20:54:44 +02:00
Mel Massadian 0106c13250 fix: 🐛 typo in clock 2025-07-07 21:05:04 +02:00
Mel Massadian 55226058d4 feat: ✨ add a simple clock system
StartClock and EndClock
2025-07-05 18:18:10 +02:00
Mel Massadian 50e0f7b357 wip: 🚧 generic GetItem node
For now pretty bare bones
2025-07-04 12:02:29 +02:00
Mel Massadian 71f601094a feat: ✨ simple not boolean node
requested and contributed by vallestutz
2025-06-28 13:49:54 +02:00
Mel Massadian ea750b5e8b fix: 🐛 use core toast
I made this long before it was a thing in comfy.
It now wraps the builtin toat system unless specificaly requested.

(notify css broke in recent ComfyUI updates anyway)
2025-06-26 17:33:38 +02:00
Mel Massadian ff2e99f73e fix(web): 🐛 allow cancelling queue of animation builder
fixes #246
2025-06-26 17:23:42 +02:00
Mel Massadian efc6855073 chore: 🧹 apply biome on missed files 2025-06-26 15:42:31 +02:00
Mel Massadian 0853b7fb6a chore: 🧹 update biome 2025-06-26 15:42:31 +02:00
Mel Massadian 10aa493dd8 docs(web): 📚 add markdown notice for sidebar settings 2025-06-26 15:42:31 +02:00
Mel Massadian f038d76748 fix(web): 🐛 make main settings appear first 2025-06-26 15:42:31 +02:00
Mel Massadian 940a781f29 feat: ✨ implement ipaq ideas for the I/O sidebar 2025-06-26 15:42:31 +02:00
Jared J c7248344cc Clarify mtb.io-sidebar.img-size name and tooltip 2025-06-26 15:42:31 +02:00
Mel Massadian fab33a40a2 chore: 🧹 add debug after esm load 2025-06-26 12:59:03 +02:00
Mel Massadian 8f83e8d4d7 chore(web): 🧹 remove API stuff
this is being rewritten in typescript
2025-06-26 12:52:44 +02:00
Mel Massadian 6c59d5c32d chore: 🧹 support hot reloading 2025-06-26 12:52:44 +02:00
Mel Massadian e98f3f626f fix: 🐛 add rgb/rgba toggle to stack images
now defaulting to rgb (too many nodes don't properly support rgba)
2025-06-24 17:02:41 +02:00
Mel Massadian 7e89e96e9d feat(web): ✨ use comfy text area fontsize for editors 2025-06-08 19:58:05 +02:00
Mel Massadian 177b6eeef3 fix(web): 🐛 don't break note+ on undo
Issuing undo will both undo the last note edit and the last graph
edit...
I asked upstream about it:
https://github.com/Comfy-Org/ComfyUI_frontend/issues/4108

this also fixes height calculation
2025-06-08 16:52:06 +02:00
Mel Massadian 502a583409 fix(web): 🐛 properly init after ace load 2025-06-07 17:17:05 +02:00
Mel Massadian a7966355c1 fix(web): 🐛 use natural widget/properties de/serialization 2025-06-07 16:39:19 +02:00
Mel Massadian 321abea51a fix(web): 🐛 use the new settings api 2025-06-07 15:00:05 +02:00
Mel Massadian 63be3f26fd fix(web): 🐛 note+
- reworked the internal logic to be simpler and more robust
- removed the dedicated HTML editing mode
  markdown is a superset of HTML in this context
- fixed layout of the css editor
- introduces a quick edit mode: double-clicking the note's preview area
now opens an inline Ace editor
2025-06-07 14:34:39 +02:00
Mel Massadian c4f40e299f fix(web): 🐛 always bind the load event 2025-06-07 12:20:51 +02:00
Mel Massadian b541670a5b fix: 🐛 improve startup times 2025-06-05 16:37:27 +02:00
Mel Massadian 4574c6451c ci: 🤖 disable ci 2025-05-23 02:11:22 +02:00
Mel Massadian 7fb27804e1 chore!: 🧹 bump version 2025-05-23 01:34:56 +02:00
Mel Massadian 9a7e022df1 chore!: 🧹 bump version 2025-05-22 23:00:01 +02:00
Mel Massadian 2c483fd1d2 ci: 🤖 finally fix the registry issue
The upstream action was overwritting the checkout: https://github.com/Comfy-Org/publish-node-action/blob/d2366e7abb6ab16f3bb03e3520ae25c8cf749bc9/action.yml#L16
2025-05-22 22:58:10 +02:00
Mel Massadian 0967d439f5 chore!: 🧹 bump version
closes #230
2025-05-22 22:02:39 +02:00
Mel Massadian 319c02d658 fix: 🐛 ascii encoding only for whisper chunks
fixes #251
2025-05-22 21:52:44 +02:00
Mel Massadian 265cb953ec feat: ✨ rework extract points
Make use of both inputs if provided, more efficient point drawing
2025-05-18 20:56:41 +02:00
Mel Massadian 7e36007933 docs: 📚 add contribution 2025-05-07 10:56:29 +02:00
Mel Massadian bc5b613490 chore: 🧹 bump version 2025-04-17 01:25:02 +02:00
Mel Massadian 01107c45f8 chore: 🧹 small adjustments 2025-04-17 01:17:52 +02:00
Mel Massadian 96185132b8 feat: ⚡ add BatchFromFolder 2025-04-17 01:05:47 +02:00
Mel Massadian d4a31bf19c feat: ⚡ add use_normalized to TransformBatch2D 2025-04-17 01:02:07 +02:00
Mel Massadian fc7ba084f6 feat!: ⚡ add support for masks in BatchFLoatMath 2025-04-17 01:00:07 +02:00
Mel Massadian 4516aa9cb4 feat: ✨ add use_normalized to TransformImage
this makes working with various input dimensions much easier
2025-04-16 22:38:54 +02:00
0e48aaa3e4 ci: 🤖 update publish action workflow with permissions and version constraints (#237)
Co-authored-by: snomiao <snomiao+comfy-pr@gmail.com>
Co-authored-by: Mel Massadian <mel@melmassadian.com>
2025-04-01 00:48:32 +02:00
诗无尽头iandMel Massadian 78946b0fa3 feat: ✨ add regex support for String Replace (#233)
---------

Co-authored-by: Mel Massadian <mel@melmassadian.com>
2025-04-01 00:45:52 +02:00
NumZ c30408f96d feat: ✨ update diarization to 3.1
And fix MTB_AudioIsolateSpeaker

Migrated from #241
2025-04-01 00:35:08 +02:00
Mel Massadian eb7cf89f17 feat: ✨ add "workflow" query to /mtb/view endpoint 2025-04-01 00:20:59 +02:00
Mel Massadian af42134028 fix: 🐛 note+ breaking wfs
Note+ itself still doesn't work (see #238) but this should at least
avoid issues like #239...
2025-03-22 19:33:35 +01:00
Mel Massadian a85e57b18c fix: 🐛 ColorCorrect clamp issue
Closes: #192
2025-03-10 12:15:16 +01:00
Mel Massadian 22fce6fdda feat: ✨ add stretch_x and stretch_y to TransformImage 2025-03-09 18:39:56 +01:00
Mel Massadian 147edcfcbc refactor: 📦 add model autodownload 2025-03-07 22:28:24 +01:00
Mel Massadian 8bf3545fec fix: 🐛 Whisper chunks processing
also add support for whisper chunks in TextToImage
2025-03-04 02:10:37 +01:00
Mel Massadian f47149746a feat: ✨ add AudioDuration node 2025-02-20 00:59:22 +01:00
Mel Massadian 83cfc5c723 feat: ✨ basic whisper nodes 2025-02-20 00:58:06 +01:00
Mel Massadian d87e52ea2c fix: 🐛 stackImages move to device 2025-02-16 02:52:26 +01:00
Mel Massadian 9405784764 feat: ✨ add BboxForDimensions
Useful for doing Crop/Uncrop with video models
2025-02-16 02:36:10 +01:00
Mel Massadian 55261bda7c fix: 🐛 bbox upscale from center 2025-02-16 02:01:41 +01:00
Mel Massadian cf7a9c41e8 feat: ✨ improve the debug node
- preserve input order
- new "as_detailed_type" option
- support mask preview
- improved styling a bit for readibility
2025-02-15 23:44:34 +01:00
Mel Massadian 3a25526e81 chore: 🧹 basic standalone detection 2025-02-14 23:53:01 +01:00
Mel Massadian 00173fa3fb feat: ✨ add BatchImageToSublist and counterpart
Basically like ImpactPack's BatchImageToList but you can specify the batch
count per item
2025-02-14 23:51:37 +01:00
Mel Massadian 0d264b90a7 fix: 🐛 add MASK support for PickFromBatch 2025-02-14 23:48:43 +01:00
Mel Massadian a8cf4650ff feat: ✨ add TensorOps
pretty rough for now, inspired by blender math nodes
2025-02-14 23:47:48 +01:00
Mel Massadian edcb3da08b chore: 🧹 rename type 2025-02-14 23:46:51 +01:00
christian-byrne 7f7a62f832 feat: ✨ live update outputs grid 2025-02-01 14:40:43 +01:00
Mel Massadian fc908ba0a5 chore: 🧹 update env file 2025-02-01 14:35:54 +01:00
Mel Massadian ead4b34e6d wip: 🚧 loop drawing 2025-01-01 05:10:45 +01:00
Mel Massadian 46af6027d6 fix: 🐛 use addDOMWidget for Debug node 2025-01-01 01:58:13 +01:00
Mel Massadian b7ca8ed1c6 fix: 🐛 use "modern" notation in toDevice 2024-12-30 21:36:35 +01:00
Mel Massadian 4aad5c3b9d ⬆️ Bump version: 0.2.0 → 0.2.1 2024-12-30 18:49:43 +01:00
Mel Massadian d61da30409 fix: 🐛 handle missing submodules
the nodes should never fail to load completely.
I still need to remove the few remaining side effects like this one.
2024-12-30 18:49:43 +01:00
Robin Huang 6851da6638 Checkout submodules before publishing. 2024-12-30 18:49:43 +01:00
42 changed files with 6721 additions and 1657 deletions
+7
View File
@@ -0,0 +1,7 @@
**/GFPGAN/inputs/**
**/GFPGAN/tests/**
**/frame_interpolation/photos/*
moment.gif
node.zip
.DS_Store
+9 -5
View File
@@ -1,18 +1,22 @@
name: 📦 Publish to Comfy registry
on:
workflow_dispatch:
push:
tags:
- '*'
permissions:
issues: write
jobs:
publish-node:
name: Publish Custom Node to registry
runs-on: ubuntu-latest
if: ${{ github.repository_owner == 'melMass' }}
steps:
- name: ♻️ Check out code
uses: actions/checkout@v4
- name: 📦 Publish Custom Node
uses: Comfy-Org/publish-node-action@main
with:
submodules: true
- name: 📦 Publish Custom Node
uses: Comfy-Org/publish-node-action@v1
with:
skip_checkout: 'true'
personal_access_token: ${{ secrets.COMFY_REGISTRY_TOKEN }}
+5
View File
@@ -1,11 +1,16 @@
__pycache__
*.py[cod]
*.onnx
wheels/
node_modules/
compose.yaml
comfy_mtb.wsb
Dockerfile
.DS_Store
node.zip
# I store the gh-pages worktrees (src & build) there
.worktrees
comfy.lock
+238 -2
View File
@@ -3,10 +3,193 @@
This is an automated changelog based on the commits in this repository.
Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases) for more information.
## [main] - 2024-03-07
## [main] - 2025-04-16
### Bug Fixes
- 🐛 note+ breaking wfs ([af42134](https://github.com/melMass/comfy_mtb/commit/af421340286b234e4c0cfcd4143a9d8726ebf3d1))
- 🐛 ColorCorrect clamp issue ([a85e57b](https://github.com/melMass/comfy_mtb/commit/a85e57b18c7d3c765131873ffff523244ca9be73))
- 🐛 Whisper chunks processing ([8bf3545](https://github.com/melMass/comfy_mtb/commit/8bf3545fec5b2a180607d40394b025a1e09c14b6))
- 🐛 stackImages move to device ([d87e52e](https://github.com/melMass/comfy_mtb/commit/d87e52ea2c112fd95f257dcd6a54a5db77a34fc3))
- 🐛 bbox upscale from center ([55261bd](https://github.com/melMass/comfy_mtb/commit/55261bda7c33d088b62c5483e4483201e5a9ce77))
- 🐛 add MASK support for PickFromBatch ([0d264b9](https://github.com/melMass/comfy_mtb/commit/0d264b90a78d5a6719fb3ce71f4e9a642db4c950))
- 🐛 use addDOMWidget for Debug node ([46af602](https://github.com/melMass/comfy_mtb/commit/46af6027d6c87d0c29b8bb0fd1cc1dbdae993629))
- 🐛 use "modern" notation in toDevice ([b7ca8ed](https://github.com/melMass/comfy_mtb/commit/b7ca8ed1c6e117b71afd7696f55dcc3dbd5bad08))
- 🐛 handle missing submodules ([d61da30](https://github.com/melMass/comfy_mtb/commit/d61da304099ff5e4528e4beb1ecc2eb83cabaaa1))
- 🐛 add warnings about what each IO mode can do ([6608c0b](https://github.com/melMass/comfy_mtb/commit/6608c0b6d1cf8f7a9901214096f8c78bfe17056f))
- 🐛 soft deprecate compression h264 ([a757e1c](https://github.com/melMass/comfy_mtb/commit/a757e1c98b2abbd2221a15b77e89d772e02d1d82))
- 🐛 limit packages allowed to be installed from API ([d6e004c](https://github.com/melMass/comfy_mtb/commit/d6e004cce2c32f8e48b868e66b89f82da4887dc3))
- 🐛 ensure default settings (io sidebar) ([ed17fa2](https://github.com/melMass/comfy_mtb/commit/ed17fa2ef4688aadf305a6d51b32c13a0efd22d6))
- 🐛 spawn colour picker at pointer location ([e5482ae](https://github.com/melMass/comfy_mtb/commit/e5482aee5e3de07e8f055b3edc0fccc0e0f75c14)) by [@webfiltered](https://github.com/webfiltered) in [#223](https://github.com/melMass/comfy_mtb/pull/223)
- 🐛 i/o sidebar for custom paths ([62469a4](https://github.com/melMass/comfy_mtb/commit/62469a4dd96e32509171aad74fcae8d2bb0ec593))
### Features
- ⚡ add BatchFromFolder ([9618513](https://github.com/melMass/comfy_mtb/commit/96185132b83c182032e9f6e822561eb5699af517))
- ⚡ add use_normalized to TransformBatch2D ([d4a31bf](https://github.com/melMass/comfy_mtb/commit/d4a31bf19c2863df8dfc4cb9a3cd6683304949e4))
- [**breaking**] ⚡ add support for masks in BatchFLoatMath ([fc7ba08](https://github.com/melMass/comfy_mtb/commit/fc7ba084f6ed7880e88e28eb448ab0bd7d796824))
- ✨ add use_normalized to TransformImage ([4516aa9](https://github.com/melMass/comfy_mtb/commit/4516aa9cb4fcb12c946999d6dcc1501cc09011a3))
- ✨ add regex support for String Replace ([78946b0](https://github.com/melMass/comfy_mtb/commit/78946b0fa3c3cf5dfcee8c7c4c0921b722d09d1e)) by [@poetryiii](https://github.com/poetryiii) in [#233](https://github.com/melMass/comfy_mtb/pull/233)
- ✨ update diarization to 3.1 ([c30408f](https://github.com/melMass/comfy_mtb/commit/c30408f96d4df9c7d35545654401162090a74305)) by [@numz](https://github.com/numz)
- ✨ add "workflow" query to /mtb/view endpoint ([eb7cf89](https://github.com/melMass/comfy_mtb/commit/eb7cf89f173b2342b04e7b61dca3d12cfaf65bdb))
- ✨ add stretch_x and stretch_y to TransformImage ([22fce6f](https://github.com/melMass/comfy_mtb/commit/22fce6fdda135cbb1f1aad42c86aae166cba81b5))
- ✨ add AudioDuration node ([f471497](https://github.com/melMass/comfy_mtb/commit/f47149746ac1e418cda2007c38aafbb03946ce22))
- ✨ basic whisper nodes ([83cfc5c](https://github.com/melMass/comfy_mtb/commit/83cfc5c723d1a572af67ad14b52be4f8371a3c5f))
- ✨ add BboxForDimensions ([9405784](https://github.com/melMass/comfy_mtb/commit/940578476438eaa6a42e0056f1b7b319ee585334))
- ✨ improve the debug node ([cf7a9c4](https://github.com/melMass/comfy_mtb/commit/cf7a9c41e81e8dd461ab9dfa3c05bb8e2cdf2a67))
- ✨ add BatchImageToSublist and counterpart ([00173fa](https://github.com/melMass/comfy_mtb/commit/00173fa3fbca4c5b1ff3016cc5139705ce61ec20))
- ✨ add TensorOps ([a8cf465](https://github.com/melMass/comfy_mtb/commit/a8cf4650ff5cbd4975ef954b5829c772ee53250c))
- ✨ live update outputs grid ([7f7a62f](https://github.com/melMass/comfy_mtb/commit/7f7a62f832c865a13b9181daee79d3cfc21581e2)) by [@christian-byrne](https://github.com/christian-byrne) in [#229](https://github.com/melMass/comfy_mtb/pull/229)
- ✨ add SaveImage passthrough ([0eeb707](https://github.com/melMass/comfy_mtb/commit/0eeb707f34f51142def8e0ef7d351ee5028cb5e0))
- ✨ add filtering to TransformImage ([bae26a0](https://github.com/melMass/comfy_mtb/commit/bae26a07fb02dd518c621eba28986a51c5d086bc))
- ✨ add support for video in I/O sidebar ([c92d99a](https://github.com/melMass/comfy_mtb/commit/c92d99a8a37a64cfc285296f21452c4927a22774))
- ✨ add an extra static input to Stack Images ([3f6d082](https://github.com/melMass/comfy_mtb/commit/3f6d08294096918d50101a19083f9134305cc8c9)) in [#222](https://github.com/melMass/comfy_mtb/pull/222)
- ✨ add support for subdirs (i/o sidebar) ([52bd76e](https://github.com/melMass/comfy_mtb/commit/52bd76e19c8bd7e72986900e5dbfade0457ef7e0))
- ✨ add Batch Sequence Nodes ([827c64c](https://github.com/melMass/comfy_mtb/commit/827c64c43d52ebfb8acd2e5c4491c4b66e6b8f40))
- ✨ add support for more formats (I/O sidebar) ([8c629be](https://github.com/melMass/comfy_mtb/commit/8c629bee186b5ac991058018a788e4a836eef630))
### Miscellaneous Tasks
- 🧹 bump version ([d093d76](https://github.com/melMass/comfy_mtb/commit/d093d76efd87474a3ca82858147255038060ab17))
- 🧹 small adjustments ([01107c4](https://github.com/melMass/comfy_mtb/commit/01107c45f8539ff7c579e08e2a9075d93781b9a2))
- 🤖 update publish action workflow with permissions and version constraints ([0e48aaa](https://github.com/melMass/comfy_mtb/commit/0e48aaa3e4f1e440a5d7ab42df56b728ced03aca)) by [@robinjhuang](https://github.com/robinjhuang) in [#237](https://github.com/melMass/comfy_mtb/pull/237)
- 🧹 basic standalone detection ([3a25526](https://github.com/melMass/comfy_mtb/commit/3a25526e818a1af8f886d2ad5c27101c4a0caa8b))
- 🧹 rename type ([edcb3da](https://github.com/melMass/comfy_mtb/commit/edcb3da08bff66f9adcef8dcd37c3925e64d0135))
- 🧹 update env file ([fc908ba](https://github.com/melMass/comfy_mtb/commit/fc908ba0a528523b7c1e37e34fb32f430746de0d))
- 🧹 dev ([9a94371](https://github.com/melMass/comfy_mtb/commit/9a943714aada107bfd236e00fa1063872db7a834))
- 🧹 apply formatting ([58ae89f](https://github.com/melMass/comfy_mtb/commit/58ae89f8e0f0f8b42825722a6aebc04da39847b1))
### Refactor
- 📦 add model autodownload ([147edcf](https://github.com/melMass/comfy_mtb/commit/147edcfcbc09dd27a0c787f9da568fb850c3308a))
### Wip
- 🚧 loop drawing ([ead4b34](https://github.com/melMass/comfy_mtb/commit/ead4b34e6dd03ea4ed309b246ef31c995325aa08))
## New Contributors
* [@poetryiii](https://github.com/poetryiii) made their first contribution in [#233](https://github.com/melMass/comfy_mtb/pull/233)
* [@numz](https://github.com/numz) made their first contribution in [#](https://github.com/melMass/comfy_mtb/pull/)
* [@webfiltered](https://github.com/webfiltered) made their first contribution in [#223](https://github.com/melMass/comfy_mtb/pull/223)
## [0.2.0] - 2024-12-08
### Bug Fixes
- 🐛 remove mtb sidebar ([b0d52f7](https://github.com/melMass/comfy_mtb/commit/b0d52f73051368df6de2d1e10ad28ca56df72803))
- 🐛 always enable the I/O sidebar ([ec1cb1a](https://github.com/melMass/comfy_mtb/commit/ec1cb1ac17d14670aa756dfb1ae7542397b12559))
- 🐛 ui shifts on animation builder ([ecbb220](https://github.com/melMass/comfy_mtb/commit/ecbb220de6a05f2e506ec43f2b786be983166157))
- 🐛 category for settings ([b6fa571](https://github.com/melMass/comfy_mtb/commit/b6fa571fd2096ace60d03cab42dba9ca37d0cb27)) in [#211](https://github.com/melMass/comfy_mtb/pull/211)
- 🐛 new UI issues ([f272526](https://github.com/melMass/comfy_mtb/commit/f272526bfc5da95e95d42cb4c613a0b9585b2577))
- 🐛 disable old BOOL widget (legacy) ([8596b81](https://github.com/melMass/comfy_mtb/commit/8596b8184edb484c907475a77ac1dc9e4a5c92af))
- 🐛 pass ONNX providers explicitely ([43092e4](https://github.com/melMass/comfy_mtb/commit/43092e44a4ea17f90fcfb12372da634fe4b79557))
- 🐛 typo in mtb_widgets error catch ([80b5a0c](https://github.com/melMass/comfy_mtb/commit/80b5a0ca7459763e7662421bccd8636976eefddd)) by [@christian-byrne](https://github.com/christian-byrne) in [#197](https://github.com/melMass/comfy_mtb/pull/197)
- 🐛 doc widget sidebar offset in the new ui ([81b3bc1](https://github.com/melMass/comfy_mtb/commit/81b3bc1651f06ad2fa7938f810d3f406f5e7c41c))
- 🐛 don't fallback to eval ([997d2fb](https://github.com/melMass/comfy_mtb/commit/997d2fb13af6aadf36873ea2ea3317e56f405aef))
- 🐛 rework main utils ([c99b081](https://github.com/melMass/comfy_mtb/commit/c99b0812ab4a4183ef9298fb8a7c954bc7c858b2))
- 🐛 MaskToImage ([821a0ef](https://github.com/melMass/comfy_mtb/commit/821a0ef42735a0a97ab82be22a4fdc67c9cfc80e))
### Documentation
- 📚 update wiki ([e17c6e2](https://github.com/melMass/comfy_mtb/commit/e17c6e29f5111bf5085b1fe6f764cfd1aae709f2))
- 📚 remove link ([5bc125d](https://github.com/melMass/comfy_mtb/commit/5bc125d2f08470c8900dfd89deca721835848917))
- 📚 clean readme ([333f646](https://github.com/melMass/comfy_mtb/commit/333f646ab1959d2c944fb046275cc93a545d557c))
### Features
- ✨ add h264 compression node ([e32d1e0](https://github.com/melMass/comfy_mtb/commit/e32d1e02df5e3a9351f829513f7ee3ffb2934be4))
- ✨ add postshot nodes ([27e03fa](https://github.com/melMass/comfy_mtb/commit/27e03fa23efffda461c6975b15fe3964de476cb3))
- ✨ improve the I/O sidebar ([cd9e614](https://github.com/melMass/comfy_mtb/commit/cd9e614b1a385d6b06eacfaad62def1d69f09808)) in [#193](https://github.com/melMass/comfy_mtb/pull/193)
- ✨ add UpscaleBBoxBy ([74af5c6](https://github.com/melMass/comfy_mtb/commit/74af5c6499ef5dd73ce66c4c21b8c3507d69b037))
- ✨ simplified sidebar and backend ([22f7c30](https://github.com/melMass/comfy_mtb/commit/22f7c3037345a866c9ff0b06f6689748021cee63))
- ✨ add Interpolate Condition ([0133fb9](https://github.com/melMass/comfy_mtb/commit/0133fb93bc944d0dd7593b89b36e5b2676d9397a))
- ✨ dump of wip things... ([cf7d305](https://github.com/melMass/comfy_mtb/commit/cf7d30507e7e449c4489e6a1ca159d3d0486bc55))
- ✨ use the new parser for documentations ([4e593bb](https://github.com/melMass/comfy_mtb/commit/4e593bb30be561e39f1790e3514f60bb39e5a261))
- ✨ add @mtb/markdown-parser bundles ([097ca33](https://github.com/melMass/comfy_mtb/commit/097ca33b8e7b27148e183e91712dc34d98d1a69b))
- ✨ add VitMatte nodes ([896a025](https://github.com/melMass/comfy_mtb/commit/896a025006f9c7809c5e0776393a28f908be8950))
- ✨ add ColorCorrectGPU ([9651a70](https://github.com/melMass/comfy_mtb/commit/9651a7034120589b059329b21688708e42772453))
- ✨ add Swap FG/BG colors to MaskToImage ([57683c3](https://github.com/melMass/comfy_mtb/commit/57683c3c7d299a117a26526d52de4c26f2ec0f69))
- ✨ add Extract coordinates ([f99f92e](https://github.com/melMass/comfy_mtb/commit/f99f92e8f7b2d6fac56f7f40049715910e15cfee))
- ✨ add AudioCut ([5681b46](https://github.com/melMass/comfy_mtb/commit/5681b464adce395086712b61159b2694150b8027))
- ✨ add AudioStack ([8d0fcee](https://github.com/melMass/comfy_mtb/commit/8d0fcee2f3decc1cbbf3b850332e6b2a022e1377))
- ✨ add AudioSequence node ([1078fc6](https://github.com/melMass/comfy_mtb/commit/1078fc6f0fb225b52536f25ec6a9fa0456a90595))
- ✨ add Split Bbox node ([9007a70](https://github.com/melMass/comfy_mtb/commit/9007a70aa0d6b2ead0f68f7aff8ae8e3c4f3624f))
- ✨ update lerp example ([1a0ebd5](https://github.com/melMass/comfy_mtb/commit/1a0ebd5173687784f279a9c2184c89fb3be01dc5))
### Miscellaneous Tasks
- 🧹 bump minor ([50cb6f5](https://github.com/melMass/comfy_mtb/commit/50cb6f5ed6e5d9fecb9733ef3f7852b8500005e9))
- 🧹 add worktree to gitignores ([9ccf572](https://github.com/melMass/comfy_mtb/commit/9ccf572a158caeab9bff53853e8f6fb85b76776d))
- 🧹 remove dupe code ([e099d58](https://github.com/melMass/comfy_mtb/commit/e099d581a7627c3a66d2e3e6df3a701b0e5f31b7))
- 🧹 update externs ([784fb01](https://github.com/melMass/comfy_mtb/commit/784fb0145b7421e2730b52237ce6a8b63b189191))
- 🧹 add pathlibed inputs to utils ([a825504](https://github.com/melMass/comfy_mtb/commit/a825504bdd67e3461be8118119e0becc35f8af40))
- 🧹 disable Constant ([22190cd](https://github.com/melMass/comfy_mtb/commit/22190cd25ee590595f8f19e75a9a6c539699622b))
- 🧹 new ui is default, flag for old ui ([a976adb](https://github.com/melMass/comfy_mtb/commit/a976adbb39a13b4cd76f224ebba40c604900c862))
- 🧹 add methods to shared ([f8829fc](https://github.com/melMass/comfy_mtb/commit/f8829fcb373e0f9bc4f0ad36c939f372349943bf))
- 🧹 add an old_ui flag to my launcher ([dbdf276](https://github.com/melMass/comfy_mtb/commit/dbdf27664cd207dbbc69b8d635adcd59ed8d269a))
- 🧹 move qrcode to his own file ([7d5569e](https://github.com/melMass/comfy_mtb/commit/7d5569e5c1e0f0b6ccb505a02f74640139d6aaf9))
## [0.1.6] - 2024-07-03
### Bug Fixes
- 🐛 menu callback issue ([d64fac4](https://github.com/melMass/comfy_mtb/commit/d64fac4b74e0590acde5e3b8edd4a2f715448cf5))
### Documentation
- 📚 Update requirements file in INSTALL.md ([f25f6bd](https://github.com/melMass/comfy_mtb/commit/f25f6bdcd13d50f9d383065321320b0ce6a03214)) by [@elthariel](https://github.com/elthariel) in [#186](https://github.com/melMass/comfy_mtb/pull/186)
### Features
- ✨ add alpha channel support for faceswap/restore ([d6343e1](https://github.com/melMass/comfy_mtb/commit/d6343e1860f46947e93758f8bba03857c9326b38))
### Miscellaneous Tasks
- 🧹 better classname extraction ([d687497](https://github.com/melMass/comfy_mtb/commit/d687497d8041ab5d77bd31909592def6e4d0e7f6))
- 🤖 limit release only to tags ([4eebdd8](https://github.com/melMass/comfy_mtb/commit/4eebdd8b8bff73c3db4f0248da8dac7d67cb310b))
- 🧹 runner ([fb34671](https://github.com/melMass/comfy_mtb/commit/fb34671ee6fe80b965fe576c279ed1ff77a358f2))
- 🤖 only publish on tag ([f1b4846](https://github.com/melMass/comfy_mtb/commit/f1b484617a917d38d9b3658d8920aa7dec672a79))
- 🧹 small fixes ([4507842](https://github.com/melMass/comfy_mtb/commit/4507842a706141977a6a68945c36e977c358d91a))
## New Contributors
* [@elthariel](https://github.com/elthariel) made their first contribution in [#186](https://github.com/melMass/comfy_mtb/pull/186)
## [0.1.5] - 2024-06-21
### Bug Fixes
- 🐛 keep the last model match instead of first ([1edc2cd](https://github.com/melMass/comfy_mtb/commit/1edc2cd10de81297e7a895009d358813e79b70ba))
- 🐛 properly initialize the curve value ([35622e3](https://github.com/melMass/comfy_mtb/commit/35622e3a5e58103a8f5b150556b85e97e31555e1))
- 🐛 ImageCompare improvements ([acc2d68](https://github.com/melMass/comfy_mtb/commit/acc2d687d596bf82c2075f9a24003eacf18adfe7)) by [@christian-byrne](https://github.com/christian-byrne) in [#176](https://github.com/melMass/comfy_mtb/pull/176)
- 🐛 repetitive warning ([780c52f](https://github.com/melMass/comfy_mtb/commit/780c52f03aca3079a1b695510341486720004bec)) by [@vxkj1211](https://github.com/vxkj1211) in [#177](https://github.com/melMass/comfy_mtb/pull/177)
- 🐛 add back was conversion node ([349a852](https://github.com/melMass/comfy_mtb/commit/349a8524c6f7fcab4a124cacb60bfbef1463cf1b))
- 🐛 drag lag on documentation resize handle ([15330ea](https://github.com/melMass/comfy_mtb/commit/15330eab655f66214d3c25fd237679f090175c32))
- 🐛 kwarg typo ([1571782](https://github.com/melMass/comfy_mtb/commit/1571782d012b83bce32a065e700f9a587db234d2))
- 🐛 seed of PlotBatchFloat ([5b40302](https://github.com/melMass/comfy_mtb/commit/5b4030288d43c79859c9706a12aa0f8b7dea190f))
- 🐛 forceInput for FLOAT <-> FLOATS converters ([5a0ef0d](https://github.com/melMass/comfy_mtb/commit/5a0ef0dadd01fd5937ed0715d829d6a456f96318))
- 🐛 FLOAT always need options to be set ([967e72f](https://github.com/melMass/comfy_mtb/commit/967e72fc66780685f8192cb8fe13ba66b9326f63))
- 🐛 remove doc if opened on node delete ([bee3f47](https://github.com/melMass/comfy_mtb/commit/bee3f47a14ddb92b3760098666bf75dc7d37f1e4))
- 🐛 for documentation on HiDPI ([b11346a](https://github.com/melMass/comfy_mtb/commit/b11346aba88d9f1dac3b6b42c691979cc0978b6f))
- 🐛 never remove input 0 of dynamic inputs ([30982fa](https://github.com/melMass/comfy_mtb/commit/30982fa48829c3fc2a6745ce5a07537a3d94b2f9))
- 🐛 use the same fix as dynamicInputs for debug ([92b7990](https://github.com/melMass/comfy_mtb/commit/92b79906cd2ee1b4ca3ff25378d7786b5a47cb75))
- 🐛 missing numberInput ([76f365b](https://github.com/melMass/comfy_mtb/commit/76f365b5eee165c76f3da7d2e3950786685bc08b))
- 🐛 better curve ([da67e76](https://github.com/melMass/comfy_mtb/commit/da67e766c2f700dd9e2f51a5bafe07c612904f5d))
- 🐛 prepend MTB_ to all classes ([b1d74ad](https://github.com/melMass/comfy_mtb/commit/b1d74adb15166e3e5eb9cf92d6148e4644bed346))
- 🐛 dynamic connections ([652ac3f](https://github.com/melMass/comfy_mtb/commit/652ac3f3b971582b02115177fd6f7a9d3d7295df))
- 🐛 remaining issue before merge ([100067a](https://github.com/melMass/comfy_mtb/commit/100067a645194366426f29b085bf25d0623f4fac))
- 🐛 debug issues ([7807449](https://github.com/melMass/comfy_mtb/commit/7807449e6dcc01cfdb7f0eb818569184c8b41af2))
- 🐛 errors when insightface's folder missing ([e838c04](https://github.com/melMass/comfy_mtb/commit/e838c04758402250fd3464d6cd6a6f872e8cef29))
- 🐛 typo ([e40ad7a](https://github.com/melMass/comfy_mtb/commit/e40ad7a574f961ebe1f338b97214da5cbadcc529))
- 🐛 better defaults (cont) ([1da483a](https://github.com/melMass/comfy_mtb/commit/1da483a8baa6a893f1adb05ef79b90c4412c3834))
- 🐛 better defaults for Autopan ([5eff38b](https://github.com/melMass/comfy_mtb/commit/5eff38b387d22206d39c08e435806f9d03992feb))
- 🐛 dynamic inputs ([9ab20a0](https://github.com/melMass/comfy_mtb/commit/9ab20a0ab50b1656ded9a84c13769fd2d547f2d2))
- 🐛 bundle ace editor ([7c35582](https://github.com/melMass/comfy_mtb/commit/7c3558273bebc0754c802720e705232f220a0da4))
- 🐛 image to mask ([f16d576](https://github.com/melMass/comfy_mtb/commit/f16d576f6f0e83fc2fafd2d1f29b2edeb00d3197))
- 🐛 prepend MTB to classnames ([e56508c](https://github.com/melMass/comfy_mtb/commit/e56508c2078155f053e7f11d538a048df6a5b18b))
- 🐛 allow smaller values in BatchTransform ([9a4b27d](https://github.com/melMass/comfy_mtb/commit/9a4b27d2e05e8ebe31f58a21db94bd3a54ed23d9))
- 🐛 add category for virtual note+ ([eeac8c0](https://github.com/melMass/comfy_mtb/commit/eeac8c002ad1f9e461418fb66b9338e969259e58))
- 🐛 make image feed of by default ([df0a98b](https://github.com/melMass/comfy_mtb/commit/df0a98b94a4a9388811bc8786e820ec892919c1a))
- 🐛 support batch masks (colored image node) ([2465ffb](https://github.com/melMass/comfy_mtb/commit/2465ffb0d3b052fb78559394dbb550bba59b97a3))
- 🐛 support pillow < 10 ([48f91b7](https://github.com/melMass/comfy_mtb/commit/48f91b74e2c7ef6d31c094eafa5332784a275a8b))
- 🐛 image rotation bug ([54ff658](https://github.com/melMass/comfy_mtb/commit/54ff6583ded0ed4054f8e5d7fadf0b2350259dce)) by [@hongminpark](https://github.com/hongminpark) in [#154](https://github.com/melMass/comfy_mtb/pull/154)
- 🐛 font fallback ([9fccdee](https://github.com/melMass/comfy_mtb/commit/9fccdee82d721e88c64d2292c209fec869524dd2))
- ✨ optional inputs of colored image ([cd32f26](https://github.com/melMass/comfy_mtb/commit/cd32f26b167088d6b489e43b260c187ea5e4d223)) by [@ScottNealon](https://github.com/ScottNealon) in [#147](https://github.com/melMass/comfy_mtb/pull/147)
- 📝 adds a way to not load the imagefeed ([501c330](https://github.com/melMass/comfy_mtb/commit/501c3301056b2851555cccd75ab3ff15b1ab8e0c))
@@ -47,6 +230,13 @@ Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases)
### Documentation
- 📚 update the wiki ([fa3199b](https://github.com/melMass/comfy_mtb/commit/fa3199be2b87bf3cb7484a0fee32a8ac099adc65))
- 📚 update wiki submodule ([49cea8d](https://github.com/melMass/comfy_mtb/commit/49cea8d94508b27781506e3b5509c65e1d84e80f))
- 📚 add the wiki as a submodule ([5998924](https://github.com/melMass/comfy_mtb/commit/59989249260a9c579ec851c50534b58f3f02cd61))
- 📚 missing doc ([c9836a8](https://github.com/melMass/comfy_mtb/commit/c9836a87f6823db1d53e56997417f3cbe8cc4727))
- 📚 use flat icon ([991af4f](https://github.com/melMass/comfy_mtb/commit/991af4f45ff8c660b2c45466bb219186699170ed))
- 📚 add banodoco channel link ([9ce34b4](https://github.com/melMass/comfy_mtb/commit/9ce34b47fd99b18db7997ccce44e6063f00b6801))
- 📚 udpate changelog ([8221c49](https://github.com/melMass/comfy_mtb/commit/8221c49942bd87c14d5063066315a449a1fee86e))
- 📝 add changelog ([0d817bf](https://github.com/melMass/comfy_mtb/commit/0d817bf326b4a22e2221264a414af50c3b7048b9))
- 📄 add note+ screenshot ([90d9636](https://github.com/melMass/comfy_mtb/commit/90d96366c8b7637b55d1b4f88cb9aca217c1414b))
- 📝 add cover image ([6b993b8](https://github.com/melMass/comfy_mtb/commit/6b993b84071bbb80ba1b8bd63576f31e35d05590))
@@ -60,6 +250,28 @@ Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases)
### Features
- ✨ add ModelPruner (wip) ([43d65ae](https://github.com/melMass/comfy_mtb/commit/43d65ae68c97e077117b17b7c9d1936583f965eb))
- ✨ Use dynamic contrast in Color Correct ([6abac2e](https://github.com/melMass/comfy_mtb/commit/6abac2e4706a3d937420213e01468bae10cc2017)) by [@christian-byrne](https://github.com/christian-byrne) in [#180](https://github.com/melMass/comfy_mtb/pull/180)
- ✨ StackImages add support for batch mismatch ([5060c56](https://github.com/melMass/comfy_mtb/commit/5060c561353e43624ec164cb73fce7d1d422f765))
- ✨ add BatchFloatMath ([f9d2ebf](https://github.com/melMass/comfy_mtb/commit/f9d2ebf91d09fc214fecf7501a5490b33c30aca2))
- ✨ add FLOATS to INTS ([1b7ae27](https://github.com/melMass/comfy_mtb/commit/1b7ae27cc1907bfba3c5166ec2c61547babd2e0a))
- ✨ debug dict ([63ee25d](https://github.com/melMass/comfy_mtb/commit/63ee25d001d4c94aa95dc8b39008f5d943f2ab45))
- ✨ add Swap BG/FG color menu item ([1caf7c1](https://github.com/melMass/comfy_mtb/commit/1caf7c18c372651b2be7227eb77e2251d963693d))
- ✨ BatchFloatFit the batch version of FitNumber ([ab58c36](https://github.com/melMass/comfy_mtb/commit/ab58c362124f0f4b3178534ca78cb924fb881534))
- ✨ add FloatToFloats (the counterpart) ([78a86da](https://github.com/melMass/comfy_mtb/commit/78a86daaf71dab5be34b90b13491460854718485))
- ✨ add some FLOATS batch nodes ([2159395](https://github.com/melMass/comfy_mtb/commit/2159395389429c5f7012e660b41fad48d376b39f))
- ✨ poc of the doc widget idea ([fac7529](https://github.com/melMass/comfy_mtb/commit/fac7529d1f7b6fc4b3b2e7f6022ebb23ec71169d))
- ✨ add the backend node for Constant ([dff5b22](https://github.com/melMass/comfy_mtb/commit/dff5b2201d73c1a91d4b5864e3b974e68846a011))
- ✨ add Constant node ([cbb5dd2](https://github.com/melMass/comfy_mtb/commit/cbb5dd2cf810d5648a64eae370dba610336b99d5))
- ✨ add FloatsToFloat ([6ebecfd](https://github.com/melMass/comfy_mtb/commit/6ebecfd8cf1dc3779384e565a65baa9dceb43660))
- ✨ add AutoPanEquilateral ([3513937](https://github.com/melMass/comfy_mtb/commit/35139371e84d715423015e05d1b4a6c1d88b0eb5))
- ✨ add MatchDimensions ([5db3ebe](https://github.com/melMass/comfy_mtb/commit/5db3ebedb9d38470c82544e45970775193add05c))
- ✨ add equilateral example ([8d65556](https://github.com/melMass/comfy_mtb/commit/8d65556c37f33d1c496504db92574805916dd613))
- ✨ enhance tiling tools ([ba73fc6](https://github.com/melMass/comfy_mtb/commit/ba73fc6af7039a4629a73cdc36a8c8736dc27c9d))
- ✨ add FLOATS support to blur ([92c810c](https://github.com/melMass/comfy_mtb/commit/92c810c5036f7a2b3f84a3fde8c81e6a2b046b07))
- ✨ add "tube" to Batch Shape ([f658fc3](https://github.com/melMass/comfy_mtb/commit/f658fc31e040141209384d98dfe84b766fe4ae11))
- ✨ note+ editor themes ([133da70](https://github.com/melMass/comfy_mtb/commit/133da705c94af2dfb3d2f38c0d9c2723c72cacf7))
- ✨ add ffmpeg gif export ([1b29aad](https://github.com/melMass/comfy_mtb/commit/1b29aad360116e631b7b4d34e98a5a631f134977)) by [@huanggou666](https://github.com/huanggou666) in [#159](https://github.com/melMass/comfy_mtb/pull/159)
- ✨ add "To Device" ([c28181f](https://github.com/melMass/comfy_mtb/commit/c28181f1615d2e183767aa76cc2350934330e546))
- ✨ add note+ example ([90f3bc2](https://github.com/melMass/comfy_mtb/commit/90f3bc2d953b299ea34e9e3a925f1a824b488855))
- 💄 node+ improvements ([4b29395](https://github.com/melMass/comfy_mtb/commit/4b29395000254382882c0d1be115b2ed80cd7c99))
@@ -82,6 +294,19 @@ Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases)
### Miscellaneous Tasks
- 🧹 add fields for the registry ([bb5682a](https://github.com/melMass/comfy_mtb/commit/bb5682aa6da923859db33830c2e46f24b19199a1))
- 🧹 add pre-commit ([59612fd](https://github.com/melMass/comfy_mtb/commit/59612fd8110a888f0081433242a2b5a5f7e46da6))
- 🧹 migrate from poetry to setuptools ([dfd17f6](https://github.com/melMass/comfy_mtb/commit/dfd17f6d783e784df7dab38d185c747b4c04d1d0))
- 🧹 remove logs ([1070edd](https://github.com/melMass/comfy_mtb/commit/1070edd0245fb235183d5f38cd1bebf6e0405f97))
- 🧹 add more pyproject meta ([644371e](https://github.com/melMass/comfy_mtb/commit/644371e5b5a2b8260fc5c6f699465b0bc1c81d57))
- 🤖 move at the proper location ([f3d468c](https://github.com/melMass/comfy_mtb/commit/f3d468cfc238f13905a13a7b2225e3711129c64d))
- 🤖 add CI to publish to ComfyUI Registry ([6cd448b](https://github.com/melMass/comfy_mtb/commit/6cd448b026956cdf3f1b81e93724b295316fbf09)) by [@haohaocreates](https://github.com/haohaocreates) in [#182](https://github.com/melMass/comfy_mtb/pull/182)
- 🧹 add ComfyUI registry to pyproject.toml ([5951c90](https://github.com/melMass/comfy_mtb/commit/5951c90b10f9b77b2b617e83efe0112f43c8daef)) by [@haohaocreates](https://github.com/haohaocreates) in [#181](https://github.com/melMass/comfy_mtb/pull/181)
- 🧹 update types ([96a0da9](https://github.com/melMass/comfy_mtb/commit/96a0da9dbd051d1fcf8b332c54ed2d307d8ae0dd))
- 🧹 use a gettattr fallback ([a344cdc](https://github.com/melMass/comfy_mtb/commit/a344cdcba9823ca1fb0762795068039b1e1cf0ab))
- 🧹 cleanup js ([64cc4e9](https://github.com/melMass/comfy_mtb/commit/64cc4e9649853023d645245bea1e1ceb11073f01))
- 🧹 add savedatabundle js part ([edd7c3f](https://github.com/melMass/comfy_mtb/commit/edd7c3f5d075b640e9cdb067ebfe51c42ff61791))
- 🧹 wip dynamic multitype ([71bfdd6](https://github.com/melMass/comfy_mtb/commit/71bfdd61d731ce15f9bd0bb19d65b5af208d5dcf))
- 🧹 applied some linting ([fe49312](https://github.com/melMass/comfy_mtb/commit/fe49312cbef03c6540304448fa88aa7a88391efa))
- 📝 header links not parsed ([514c0d2](https://github.com/melMass/comfy_mtb/commit/514c0d2eda9990435eb18258d4bbd1aa137feb3d))
- 📝 hardcode links in changelog ([915b744](https://github.com/melMass/comfy_mtb/commit/915b7444a9db83f349d83b636304af0d276f529f))
@@ -104,9 +329,17 @@ Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases)
### Wip
- 🚧 curve widget logic fixed ([e312b02](https://github.com/melMass/comfy_mtb/commit/e312b02ad2f8334e87654a20b0114837df229371))
- 🚧 dump3 ([eedbb4b](https://github.com/melMass/comfy_mtb/commit/eedbb4bc6581bef85c746307fe9d53360ea45bcf))
- 🚧 dump ([fa23975](https://github.com/melMass/comfy_mtb/commit/fa2397585fff4f54bcf17f0b0e0083c427b34fa8))
- 🚧 dump ([0d0fb8e](https://github.com/melMass/comfy_mtb/commit/0d0fb8e13a5da54a44a96a04607f7a349f8fdb03))
- 🚧 add text template node ([af2175a](https://github.com/melMass/comfy_mtb/commit/af2175a1fc0c2fb29ef3493f242fe45ec6fcabac))
## New Contributors
* [@haohaocreates](https://github.com/haohaocreates) made their first contribution in [#182](https://github.com/melMass/comfy_mtb/pull/182)
* [@vxkj1211](https://github.com/vxkj1211) made their first contribution in [#177](https://github.com/melMass/comfy_mtb/pull/177)
* [@huanggou666](https://github.com/huanggou666) made their first contribution in [#159](https://github.com/melMass/comfy_mtb/pull/159)
* [@hongminpark](https://github.com/hongminpark) made their first contribution in [#154](https://github.com/melMass/comfy_mtb/pull/154)
* [@ScottNealon](https://github.com/ScottNealon) made their first contribution in [#147](https://github.com/melMass/comfy_mtb/pull/147)
* [@Yurchikian](https://github.com/Yurchikian) made their first contribution in [#124](https://github.com/melMass/comfy_mtb/pull/124)
* [@M1kep](https://github.com/M1kep) made their first contribution in [#91](https://github.com/melMass/comfy_mtb/pull/91)
@@ -393,7 +626,10 @@ Check the notes in the [releases](https://github.com/melMass/comfy_mtb/releases)
- 🚀 add gh action ([572b4d5](https://github.com/melMass/comfy_mtb/commit/572b4d52bce1398660d4d7ca0c5c48c11e0128e3)) in [#4](https://github.com/melMass/comfy_mtb/pull/4)
[main]: https://github.com/melMass/comfy_mtb/compare/v0.1.4..main
[main]: https://github.com/melMass/comfy_mtb/compare/v0.2.0..main
[0.2.0]: https://github.com/melMass/comfy_mtb/compare/v0.1.6..v0.2.0
[0.1.6]: https://github.com/melMass/comfy_mtb/compare/v0.1.5..v0.1.6
[0.1.5]: https://github.com/melMass/comfy_mtb/compare/v0.1.4..v0.1.5
[0.1.4]: https://github.com/melMass/comfy_mtb/compare/v0.1.3..v0.1.4
[0.1.3]: https://github.com/melMass/comfy_mtb/compare/v0.1.2..v0.1.3
[0.1.2]: https://github.com/melMass/comfy_mtb/compare/v0.1.1..v0.1.2
+52
View File
@@ -0,0 +1,52 @@
# Code of Conduct
## Our Commitment
We are committed to creating a welcoming and inclusive community for everyone. We believe that a diverse and respectful community is essential for fostering creativity and innovation. We expect all members of our community to adhere to this Code of Conduct.
## Our Expectations
This Code of Conduct applies to all interactions within the mtb community, including:
* Public communication channels (e.g., GitHub issues, pull requests, discussions, social media)
* Private communication channels (e.g., direct messages, email)
* In-person events (if any)
We expect all members to:
* **Be respectful and considerate:** Treat others with kindness and empathy.
* **Be inclusive:** Welcome and respect people of all backgrounds, identities, and experiences.
* **Be constructive:** Focus on providing helpful and positive feedback.
* **Be mindful of your language:** Avoid using offensive, discriminatory, or harassing language.
* **Respect privacy:** Do not share personal information without consent.
## Unacceptable Behavior
The following behaviors are not tolerated:
* Offensive, discriminatory, or harassing language or conduct
* Personal attacks or insults
* Spamming or trolling
* Sharing of malicious or inappropriate content
* Disrupting the community or hindering collaboration
* Violating the privacy of others
## Reporting Violations
If you experience or witness a violation of this Code of Conduct, please report it to @melmass. All reports will be treated confidentially and investigated promptly.
## Enforcement
Violations of this Code of Conduct may result in the following actions:
* Warning
* Removal from the community
* Ban from the community
## License
[![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.1-4baaaa.svg)](code_of_conduct.md)
## Contact
If you have any questions or concerns about this Code of Conduct, please contact @melmass.
+62
View File
@@ -0,0 +1,62 @@
# Contributing to mtb
Thank you for your interest in contributing to mtb! We appreciate your help in making this project better. This document outlines how you can contribute to the project.
## Project Overview
This project is a collection of custom nodes for ComfyUI, tailored specifically for animation workflows. It aims to provide a streamlined and user-friendly experience for creating animations within the ComfyUI environment.
## Ways to Contribute
We welcome all kinds of contributions! Here's how you can get involved:
* **Bug Reports:** If you encounter any issues, please create a new issue on GitHub. Please include clear steps to reproduce the bug, along with any relevant error messages, workflows or screenshots.
* **Feature Requests:** Have an idea for a new node or feature? Create a new issue to discuss it! Please describe the feature in detail, and explain how it would benefit the project.
* **Documentation Improvements:** Help us improve the documentation by fixing errors, adding examples, or clarifying explanations.
* **Code Contributions:** We welcome contributions to the codebase! Please see the "Development Setup" and "File Structure" sections below for more information.
* **Testing:** Help us ensure the stability and reliability of the project by testing new features and bug fixes.
* **Refactoring:** Help us improve the codebase by refactoring existing code to improve readability, maintainability, and performance.
## Development Setup
```sh
git clone --recursive https://github.com/melmass/comfy_mtb
```
## File Structure
Understanding the project structure is crucial for making effective contributions.
* **`./nodes/*.py`:** This directory contains the definitions for all custom nodes. Nodes are automatically registered when a file defines an array named `__nodes__` containing the node classes. Make sure your node follows the ComfyUI node definition structure.
* **`./web/*.js`:** This directory contains all the frontend JavaScript code for the extension's user interface.
* **`./wiki`:** This directory is a Git submodule that contains the project's Wiki documentation, written in Markdown. Node documentation should be created or updated in the corresponding Markdown files within this submodule. This is then referenced by the UI for in-GUI help
## Coding Style
We use **Ruff** for code formatting to ensure consistency. Please run Ruff on your code before submitting a pull request. No specific configuration is required, so the default Ruff settings will be used.
## Contribution Workflow
1. **Create a Branch:** Create a new branch for your feature or fix. Use a descriptive branch name (e.g., `feature/new-node`, `fix/bug-in-ui`). **Do not fork the main branch directly.**
2. **Make Changes:** Implement your changes in your branch.
3. **Run Tests:** (Add instructions on how to run tests if available.)
4. **Format Code:** Run Ruff on your code to ensure it is properly formatted.
5. **Create a Pull Request:** Submit a pull request to the `main` branch. Please provide a clear and concise description of your changes.
## Code of Conduct
We are committed to creating a welcoming and inclusive community. We expect all contributors to adhere to a respectful and professional code of conduct. (Consider adding a link to a CODE_OF_CONDUCT.md file or a standard code of conduct.)
## Tools and Libraries
* **Python:** The primary programming language for this project.
* **ComfyUI:** The underlying framework for the custom nodes.
## Current Focus
We are currently focused on a major refactor to clean up the project's codebase. Contributions related to this effort are particularly welcome!
## Thank You!
Thank you for considering contributing to mtb! Your contributions are greatly appreciated. We look forward to reviewing your pull requests!
+63 -12
View File
@@ -3,11 +3,11 @@
# File: __init__.py
# Project: comfy_mtb
# Author: Mel Massadian
# Copyright (c) 2023 Mel Massadian
# Copyright (c) 2023-2025 Mel Massadian
#
###
__version__ = "0.2.0"
__version__ = "0.6.0"
import os
@@ -31,7 +31,18 @@ from importlib import reload
from pathlib import Path
from aiohttp import web
from server import PromptServer
IN_COMFY = False
PromptServer = None
try:
from server import PromptServer
IN_COMFY = True
except ModuleNotFoundError:
IN_COMFY = False
from .endpoint import endlog
from .install import get_node_dependencies
@@ -66,7 +77,7 @@ def extract_nodes_from_source(filename: Path):
)
break
except SyntaxError:
log.error("Failed to parse")
log.error(f"Failed to parse ast from: {filename}")
return nodes
@@ -231,10 +242,33 @@ if failed:
# - ENDPOINT
if hasattr(PromptServer, "instance"):
# TODO: move that away and simplify existing endpoints
def register_routes():
if not PromptServer:
log.error("No prompt server, are you inside comfy?")
if PromptServer.instance.app.frozen:
log.warning(
"The router is frozen and cannot be further edited."
"If you are hot reloading mtb this is expected."
)
return
img_cache = None
prompt_cache = None
import asyncio
import os
from io import BytesIO
from PIL import Image
from .repl import setup_custom_web_routes
setup_custom_web_routes(PromptServer.instance.app)
with contextlib.suppress(ImportError):
from cachetools import TTLCache
@@ -351,13 +385,6 @@ if hasattr(PromptServer, "instance"):
# Return JSON for other requests
return web.json_response({"message": "Welcome to MTB!"})
import asyncio
import os
from io import BytesIO
from aiohttp import web
from PIL import Image
def get_cached_image(file_path: str, preview_params=None, channel=None):
cache_key = (file_path, preview_params, channel)
if img_cache and (cache_key in img_cache):
@@ -464,6 +491,26 @@ if hasattr(PromptServer, "instance"):
if not os.path.isfile(file):
return web.Response(status=404)
ret_workflow = request.rel_url.query.get("workflow")
if ret_workflow:
image = Image.open(file)
prompt = image.info.get("prompt", "")
workflow = image.info.get("workflow", "")
if workflow:
workflow = json.loads(workflow)
if prompt:
prompt = json.loads(prompt)
return web.json_response(
{
"prompt": prompt,
"workflow": workflow,
}
)
preview_info = None
if "preview" in request.rel_url.query:
preview_params = request.rel_url.query["preview"].split(";")
@@ -542,6 +589,10 @@ if hasattr(PromptServer, "instance"):
return await endpoint.do_action(request)
if IN_COMFY and hasattr(PromptServer, "instance"):
register_routes()
# - WAS Dictionary
MANIFEST = {
"name": "MTB Nodes", # The title that will be displayed on Node Class menu,. and Node Class view
+13 -6
View File
@@ -1,19 +1,26 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
"organizeImports": {
"enabled": true
},
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
"assist": { "actions": { "source": { "organizeImports": "on" } } },
"linter": {
"enabled": true,
"rules": {
"recommended": true,
"suspicious": {
"noConsoleLog": "warn"
"noConsole": { "level": "warn", "options": { "allow": ["log"] } }
},
"style": {
"noParameterAssign": "off",
"noShoutyConstants": "warn",
"useNamingConvention": "off"
"useNamingConvention": "off",
"useAsConstAssertion": "error",
"useDefaultParameterLast": "error",
"useEnumInitializers": "error",
"useSelfClosingElements": "error",
"useSingleVarDeclarator": "error",
"noUnusedTemplateLiteral": "error",
"useNumberNamespace": "error",
"noInferrableTypes": "error",
"noUselessElse": "error"
}
}
},
+10 -7
View File
@@ -15,7 +15,6 @@ from .utils import (
backup_file,
build_glob_patterns,
glob_multiple,
import_install,
reqs_map,
run_command,
styles_dir,
@@ -24,7 +23,6 @@ from .utils import (
endlog = mklog("mtb endpoint")
# - ACTIONS
import_install("requirements")
def ACTIONS_installDependency(dependency_names: list[str] | None = None):
@@ -112,11 +110,15 @@ def ACTIONS_getUserVideos(
def ACTIONS_getUserImages(
mode: Literal["input", "output"],
target_width: int | str | None = None,
count=1000,
offset=0,
sort: str | None = None,
include_subfolders: bool = False,
subfolder=None,
subfolder: str | None = None,
# IIRC I copied this from Comfy base
# just keeping it until I properly checked implications
salt_urls=False,
):
# enabled = "MTB_EXPOSE" in os.environ
# if not enabled:
@@ -124,11 +126,12 @@ def ACTIONS_getUserImages(
imgs = {}
count = count or 1000
target_width = int(target_width) if target_width else None
input_dir = Path(folder_paths.get_input_directory())
output_dir = Path(folder_paths.get_output_directory())
entry_dir = input_dir if mode == "input" else output_dir
entry_dir: Path = input_dir if mode == "input" else output_dir
if subfolder:
entry_dir = entry_dir / subfolder
@@ -157,9 +160,9 @@ def ACTIONS_getUserImages(
imgs = {
img.name: (
f"/mtb/view?filename={img.name}&width=512&type={mode}&subfolder={subfolder or ''}"
f"/mtb/view?filename={img.name}{f'&width={target_width}' if target_width and target_width > 0 else ''}&type={mode}&subfolder={subfolder or ''}"
f"{img.parent.relative_to(entry_dir) if include_subfolders else ''}"
f"&preview=&rand={secrets.randbelow(424242)}"
f"&preview={f'&rand={secrets.randbelow(424242)}' if salt_urls else ''}"
)
for i, img in enumerate(entries)
if offset <= i < offset + count
@@ -403,7 +406,7 @@ def render_table(table_dict: dict[str, Any], sort=True, title=None):
if "dependencies" in item:
table_rows += f"<tr><td>{name}</td><td>"
table_rows += (
f"{dependencies_button(name,item['dependencies'])}"
f"{dependencies_button(name, item['dependencies'])}"
)
table_rows += "</td></tr>"
+289 -117
View File
@@ -1,173 +1,345 @@
# NOTE: This file is only use for development you can ignore it
def get_root [--clean] {
if $clean {
$env.COMFY_CLEAN_ROOT
} else {
$env.COMFY_ROOT
use log.nu
use nssm.nu *
use nutils.nu [ make-id upsert-all fwd-slash backup-file ]
use os.nu [ link ]
# --- utilities ---
def get_root [ --clean] {
if $clean {
$env.COMFY.ROOTS.clean
} else {
$env.COMFY.ROOTS.main
}
}
def --env path-add [pth] {
$env.PATH = ($env.PATH | append ($pth | path expand))
}
def short-date [] {
format date "%Y-%m-%d"
}
export def spawn-for [timeout: duration task: closure] {
let input = $in
let parent_id = job id
let task_id = job spawn {
$input | do $task | job send --tag (job id) $parent_id
}
try {
job recv --tag $task_id --timeout $timeout
} catch {
job kill $task_id
error make {
msg: "Task timed out."
label: {
text: "timed out"
span: (metadata $task).span
}
}
}
}
# --- exports --
export def "comfy profile" [timeout = 60sec] {
let to_match = "To see the GUI go to"
pyinstrument -r html main.py ...($env.COMFY.ARGS)
| tee -e {
each {
let stde = $in
print -ne $stde
if $to_match in $stde {
print $"(ansi gb)Profiling Done!(ansi reset)"
let process = (ps -l | where name =~ python | where command =~ pyinstrument | last)
kill -f $process.pid
}
}
}
| complete
| get stdout
| save $"profiled_(date now | format date '%s').html"
}
export def "comfy profile-plus" [] {
let timestamp = (date now | format date "%s")
let log_name = $"cprofile_run_($timestamp)"
let profiled = (python -m cProfile main.py --port 3000 --preview-method auto | tee -e { print -ne } | complete)
let out = (
$profiled.stdout
| lines
# skip summary
| skip 4
| str join "\n"
)
# save result
$out | save $"raw_($log_name).txt"
# process
$out
| from ssv
| upsert-all { into float } tottime percall cumtime
| save $"($log_name).nuon"
}
export def restart-server [] {
nssm restart -c comfy
}
# build the web components of mtb
export def "comfy build-web" [] {
cd $env.COMFY_MTB
cd web_source
npm run build
cp dist/*.js ../web/dist
cd $env.COMFY.ROOTS.mtb
if ("./web/dist" | path exists) {
rm -rt ./web/dist
}
cd web_source
^$env.NPM_BINARY run build
cp -r dist ../web/dist
}
# start the dev server for web components
export def "comfy dev-web" [] {
cd $env.COMFY_MTB
cd web_source
npm run dev
cd $env.COMFY.ROOTS.mtb
cd web_source
^$env.NPM_BINARY run dev
}
# daily check / update
export def "daily run" [] {
let res = (comfy update --rebase)
comfy update --clean
comfy update_extensions
daily commit $res.from_commit $res.to_commit
}
# was daily run today?
export def "daily was-run" [] {
let daily = ($env.COMFY.ROOTS.mtb | path join daily.nuon)
if ($daily | path exists) {
let last = (open $daily | sort-by date | get date | last | short-date)
let today = (date now | short-date)
return ($last == $today)
}
return false
}
export def "daily commit" [from_commit: string to_commit: string] {
let daily = ($env.COMFY.ROOTS.mtb | path join daily.nuon)
let commit = [{date: (date now) from_commit: $from_commit to_commit: $to_commit}]
let dailies = (
if ($daily | path exists) {
open $daily | append $commit
} else {
$commit
}
)
$dailies | save -f $daily
log success "Commited daily check"
}
# start the comfy server
export def "comfy start" [--clean,--old-ui, --listen] {
export def "comfy start" [
--clean
--old-ui
--listen
--skip-daily (-s)
] {
if not (daily was-run) and not $skip_daily {
log info "Running daily checks"
daily run
}
let root = (get_root --clean=$clean)
cd $root
let root = get_root --clean=($clean)
cd $root
MTB_DEBUG=true python main.py --port 3000 ...(if $old_ui { ["--front-end-version", "Comfy-Org/ComfyUI_legacy_frontend@latest"]} else {[ --front-end-version Comfy-Org/ComfyUI_frontend@latest]}) --preview-method auto ...(if $listen {["--listen"]} else {[]})
log info "Running Server"
MTB_DEBUG=true python main.py --port 3000 ...(if $old_ui { ["--front-end-version" "Comfy-Org/ComfyUI_legacy_frontend@latest"] } else { [--front-end-version Comfy-Org/ComfyUI_frontend@latest] }) --preview-method auto ...(if $listen { ["--listen"] } else { [] })
}
# update comfy itself and merge master in current branch
export def "comfy update" [
--clean # ??
--rebase # Rebase instead of merge
--clean # comfy clean instance
--rebase # Rebase instead of merge
] {
let root = get_root --clean=($clean)
let models = $"($root)/models"
let inputs = $"($root)/input"
cd $root
let branch_name = (git rev-parse --abbrev-ref HEAD | str trim)
print $"(ansi yellow_italic)Backing up and removing models symlinks(ansi reset)"
let root = get_root --clean=$clean
if not $clean {
cd $models
# find all symlinks
let links = (ls -la |
where not ($it.target | is-empty) |
select name target |
sort-by name)
let models = $"($root)/models"
let inputs = $"($root)/input"
cd $root
if not ($links | is-empty) {
$links | save -f links.nuon
# remove them
open links.nuon | each {|p| rm $p.name }
}
} else {
rm $models
rm $inputs
let branch_name = (git rev-parse --abbrev-ref HEAD | str trim)
let current_commit = (git rev-parse HEAD | str trim)
log info "Backing up and removing models symlinks"
# preparing root for pull
let pyproject = if not $clean {
log info "Backing up the pyproject.toml..."
let proj = (backup-file --root pyproject.toml)
log info "Restoring the original pyproject"
git checkout pyproject.toml
cd $models
# find and store all symlinks
log info "Checking for links in models..."
let links = (
ls -la | where not ($it.target | is-empty) | select name target | sort-by name
)
log info $"Found links: ($links)"
if not ($links | is-empty) {
log info "Backing up the symlinks..."
backup-file --root links.nuon
$links | save -f links.nuon
# remove them
open links.nuon | each {|p| rm $p.name }
}
$proj
} else {
# just remove symlinks
rm $models
rm $inputs
}
cd $root
cd $root
print $"(ansi yellow_italic)Checking out to master(ansi reset)"
git checkout master
log info $"Checking out to master"
git checkout master
print $"(ansi yellow_italic)Fetching and pulling remote updates(ansi reset)"
if ($clean) {
git fetch local master
git pull local master
} else {
git fetch
git pull
}
log info "Fetching and pulling remote updates"
if ($clean) {
# from the local base repo master
git fetch local master # $branch_name # master
git pull local master # $branch_name # master
} else {
git fetch
git pull
}
let new_commit = (git rev-parse HEAD | str trim)
print $"(ansi yellow_italic)Back to our branch \(($branch_name)\)(ansi reset)"
git checkout -
log info $"Back to our branch \(($branch_name)\)"
git checkout -
if $current_commit == $new_commit {
log warn "No changes upstream"
} else {
if $rebase {
print $"(ansi yellow_italic)Rebasing changes(ansi reset)"
git rebase master
log info "Rebasing changes"
git rebase master
} else {
print $"(ansi yellow_italic)Merging changes(ansi reset)"
git merge master
log info "Merging changes"
git merge master
}
}
print $"(ansi yellow_italic)Linking back the models(ansi reset)"
log info "Linking back the models"
if not $clean {
cd $models
# resymlink them
open links.nuon | each {|p| link -a $p.target $p.name }
} else {
let master = (get_root)
link ($master | path join models) $models
link ($master | path join input) $inputs
}
if not $clean {
rm pyproject.toml
log info "Using our own pyproject..."
cp $pyproject pyproject.toml
cd $models
log info "Relinking models..."
# resymlink them
open links.nuon | each {|p| link -a $p.target $p.name }
} else {
let master = (get_root)
link ($master | path join models) $models
link ($master | path join input) $inputs
}
let commit_count = (git rev-list --count $branch_name $"^origin/($branch_name)")
print $"(ansi green_bold)Update successful \(($commit_count) new commits\)(ansi reset)"
let commit_count = (git rev-list --count $branch_name $"^origin/($branch_name)")
log success $"Update successful \(($commit_count) new commits\)"
return {from_commit: $current_commit to_commit: $new_commit}
}
export def "comfy toggle_extensions" [--clean] {
let root = get_root --clean=($clean)
cd $root
cd custom_nodes
let exts = (ls | where type in ["dir","symlink"] | get name)
let choices = ($exts | input list -m "choose extension to toggle")
if ($choices | is-empty) {
return
}
export def "comfy toggle_extensions" [
--clean
] {
let root = get_root --clean=$clean
cd $root
cd custom_nodes
let exts = (ls | where type in ["dir" "symlink"] | get name)
let choices = ($exts | input list -m "choose extension to toggle")
if ($choices | is-empty) {
return
}
print $choices
log info "Choices" $choices
let filtered = $choices | wrap name | upsert enabled {|p| not ($p.name | str ends-with ".disabled")}
let filtered = $choices | wrap name | upsert enabled {|p| not ($p.name | str ends-with ".disabled") }
print $filtered
$filtered | each {|f|
let new_name = ($f.name | str replace ".disabled" "")
log info "Filtered" $filtered
$filtered | each {|f|
let new_name = ($f.name | str replace ".disabled" "")
let new_name = if $f.enabled {
$"($new_name).disabled"
} else {
$new_name
}
print $"Moving ($f.name) to ($new_name)"
mv $f.name $new_name
let new_name = if $f.enabled {
$"($new_name).disabled"
} else {
$new_name
}
log info $"Moving ($f.name) to ($new_name)"
mv $f.name $new_name
}
}
# git pull all extensions
export def "comfy update_extensions" [--clean] {
let root = get_root --clean=($clean)
cd $root
cd custom_nodes
git multipull . -s -q
export def "comfy update_extensions" [ --clean] {
let root = get_root --clean=$clean
cd $root
cd custom_nodes
git multipull . -s -q
}
def --env path-add [pth] {
$env.PATH = ($env.PATH | append ($pth | path expand))
# manual set version of mtb
export def "comfy-mtb set-version" [version: string] {
# let pyproject = open pyproject.toml
# let current_version = $pyproject.project.version
# $pyproject | upsert project.version $version | save -f pyproject.toml
# taplo format pyproject.toml
sd "(__version__ = )\"(.*)\"" $"${1}\"($version)\"" __init__.py
sd "(version = )(.*)" $"${1}\"($version)\"" pyproject.toml
# log info $"⬆️ Bump version: ($current_version) → ($version)"
}
# -- env
export-env {
$env.COMFY_MTB = ("." | path expand)
# $env.CUDA_ROOT = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\'
$env.CUDA_HOME = $env.CUDA_ROOT
$env.COMFY_ROOT = ("../.." | path expand)
$env.COMFY_CLEAN_ROOT = ($env.COMFY_ROOT | path dirname | path join ComfyClean)
path-add 'C:/Portable/TensorRT-8.6.0.12/lib'
if $nu.os-info.family == 'windows' {
path-add 'G:\BIN\TensorRT-10.7.0.23\lib'
path-add 'G:\BIN\cudnn-windows-x86_64-9.6.0.74_cuda12-archive\bin'
$env.PYTHONUTF8 = 1
$env.COMFY = {
base_url : "https://mel-pc.tail3c8eb.ts.net"
ARGS: [--port 3000 --preview-method auto]
ROOTS: {
mtb: ("." | path expand | fwd-slash)
main: ("../.." | path expand | fwd-slash)
clean: ($env.COMFY_ROOT | path dirname | path join ComfyClean | fwd-slash)
}
}
$env.NPM_BINARY = "bun"
$env.CUDA_HOME = $env.CUDA_ROOT
#
path-add 'C:/Portable/TensorRT-8.6.0.12/lib'
#
if $nu.os-info.family == 'windows' {
path-add "G:/BIN/TensorRT-10.7.0.23/lib"
path-add "G:/BIN/cudnn-windows-x86_64-9.6.0.74_cuda12-archive/bin"
}
#
path-add ($env.CUDA_ROOT | path join bin)
overlay use ../../.venv/Scripts/activate.nu
overlay use "../../.venv/Scripts/activate.nu"
}
+3
View File
@@ -0,0 +1,3 @@
{
"use_repl": false
}
+1 -2
View File
@@ -43,7 +43,6 @@ pip_map = {
"tb-nightly": "tensorboard",
"protobuf": "google.protobuf",
"qrcode[pil]": "qrcode",
"requirements-parser": "requirements",
# Add more mappings as needed
}
@@ -409,7 +408,7 @@ def main():
args = parser.parse_args()
print_formatted(f"Detected environment: {apply_color(mode,'cyan')}")
print_formatted(f"Detected environment: {apply_color(mode, 'cyan')}")
if args.path:
clone_dir = Path(args.path)
+703 -15
View File
@@ -1,17 +1,38 @@
from typing import TypedDict
from typing import TYPE_CHECKING, Any, TypedDict
import torch
import torchaudio
from comfy.model_management import get_torch_device
from huggingface_hub import snapshot_download
if TYPE_CHECKING:
from transformers import (
WhisperForConditionalGeneration,
WhisperProcessor,
)
from ..log import log
from ..utils import get_model_path
WHISPER_SAMPLE_RATE = 16000
class AudioDict(TypedDict):
class AudioTensor(TypedDict):
"""Comfy's representation of AUDIO data."""
sample_rate: int
waveform: torch.Tensor
AudioData = AudioDict | list[AudioDict]
class WhisperData(TypedDict):
"""Whisper transcription data with timestamps and speaker info."""
text: str
chunks: list[dict[str, Any]]
language: str
AudioData = AudioTensor | list[AudioTensor]
class MtbAudio:
@@ -28,10 +49,14 @@ class MtbAudio:
return audios["waveform"].shape[1] == 2
@staticmethod
def resample(audio: AudioDict, common_sample_rate: int) -> AudioDict:
if audio["sample_rate"] != common_sample_rate:
def resample(audio: AudioTensor, common_sample_rate: int) -> AudioTensor:
current_rate = audio["sample_rate"]
if current_rate != common_sample_rate:
log.debug(
f"Resampling audio from {current_rate} to {common_sample_rate}"
)
resampler = torchaudio.transforms.Resample(
orig_freq=audio["sample_rate"], new_freq=common_sample_rate
orig_freq=current_rate, new_freq=common_sample_rate
)
return {
"sample_rate": common_sample_rate,
@@ -41,7 +66,7 @@ class MtbAudio:
return audio
@staticmethod
def to_stereo(audio: AudioDict) -> AudioDict:
def to_stereo(audio: AudioTensor) -> AudioTensor:
if audio["waveform"].shape[1] == 1:
return {
"sample_rate": audio["sample_rate"],
@@ -54,8 +79,8 @@ class MtbAudio:
@classmethod
def preprocess_audios(
cls, audios: list[AudioDict]
) -> tuple[list[AudioDict], bool, int]:
cls, audios: list[AudioTensor]
) -> tuple[list[AudioTensor], bool, int]:
max_sample_rate = max([audio["sample_rate"] for audio in audios])
resampled_audios = [
@@ -69,6 +94,388 @@ class MtbAudio:
return (audios, is_stereo, max_sample_rate)
class WhisperPipeline(TypedDict):
"""Whisper model pipeline."""
processor: "WhisperProcessor"
model: "WhisperForConditionalGeneration"
class MTB_LoadWhisper:
"""Load Whisper model and processor."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model_size": (
[
"tiny",
"small",
"medium",
"medium.en",
"base",
"large",
"large-v2",
"large-v3",
"large-v3-turbo",
],
{"default": "tiny"},
),
},
"optional": {
"download_missing": (
"BOOLEAN",
{
"default": False,
"tooltip": (
"Download missing models if missing,"
"otherwise they must be in ComfyUI/models/whisper"
),
},
),
},
}
RETURN_TYPES = ("WHISPER_PIPELINE",)
RETURN_NAMES = ("pipeline",)
CATEGORY = "mtb/audio"
FUNCTION = "load"
def load(self, model_size="tiny", download_missing=False):
"""Load Whisper model and processor."""
from transformers import (
WhisperForConditionalGeneration,
WhisperProcessor,
)
whisper_dir = get_model_path("whisper")
tag = f"whisper-{model_size}"
model_dir = whisper_dir / tag
if not (whisper_dir.exists() or model_dir.exists()):
if not download_missing:
raise RuntimeError(
"Models not found and download_missing=False"
)
else:
whisper_dir.mkdir(exist_ok=True)
model_dir.mkdir(exist_ok=True)
snapshot_download(
repo_id=f"openai/{tag}",
resume_download=True,
ignore_patterns=["*.msgpack", "*.bin", "*.h5"],
local_dir=model_dir.as_posix(),
local_dir_use_symlinks=False,
)
device = get_torch_device()
log.debug(
f"Loading Whisper model {model_size} on {device} from {model_dir}"
)
processor = WhisperProcessor.from_pretrained(model_dir.as_posix())
model = WhisperForConditionalGeneration.from_pretrained(
model_dir.as_posix()
).to(device)
model.eval()
model.requires_grad_(False)
return ({"processor": processor, "model": model},)
class MTB_AudioToText(MtbAudio):
"""Transcribe audio to text using Whisper."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"pipeline": ("WHISPER_PIPELINE",),
"audio": ("AUDIO",),
"language": (
["auto"]
+ sorted(
[
"en",
"fr",
"es",
"de",
"it",
"pt",
"nl",
"ru",
"zh",
"ja",
"ko",
]
),
{"default": "auto"},
),
"return_timestamps": ("BOOLEAN", {"default": True}),
},
}
RETURN_TYPES = ("STRING", "WHISPER_OUTPUT")
FUNCTION = "transcribe"
CATEGORY = "mtb/audio"
def transcribe(
self,
pipeline: WhisperPipeline,
audio: AudioTensor,
language="auto",
return_timestamps=True,
):
"""Transcribe audio to text using Whisper."""
processor = pipeline["processor"]
model = pipeline["model"]
device = model.device
audio = self.resample(audio, WHISPER_SAMPLE_RATE)
waveform = audio["waveform"]
log.debug(f"Processed waveform shape: {waveform.shape}")
# - Mono: [1, 1, samples] or [1, samples] or [samples]
# - Stereo: [1, 2, samples] or [2, samples] or [samples, 2]
if len(waveform.shape) == 3:
waveform = waveform.squeeze(0)
if len(waveform.shape) == 2:
if waveform.shape[0] == 2: # [channels, samples]
waveform = waveform.mean(dim=0)
elif waveform.shape[1] == 2: # [samples, channels]
waveform = waveform.mean(dim=1)
else: # mono
waveform = waveform.squeeze(0)
sample_rate = audio["sample_rate"]
chunk_duration = 30
chunk_samples = chunk_duration * sample_rate
total_samples = waveform.shape[-1]
total_duration = total_samples / sample_rate
log.debug(f"Audio duration: {total_duration:.2f}s")
all_tokens = []
all_text = []
chunk_offsets = []
last_time = 0.0
accumulated_offset = 0.0
for chunk_start in range(0, total_samples, chunk_samples):
chunk_end = min(chunk_start + chunk_samples, total_samples)
chunk_waveform = waveform[chunk_start:chunk_end]
chunk_offset = chunk_start / sample_rate
chunk_offsets.append(chunk_offset)
log.debug(
f"Processing chunk {chunk_offset:.1f}s - {chunk_end / sample_rate:.1f}s"
)
max_length = model.config.max_length or 448
attention_mask = torch.ones((1, max_length))
input_features = processor(
chunk_waveform,
sampling_rate=sample_rate,
return_tensors="pt",
).input_features.to(device)
with torch.no_grad():
predicted_ids = model.generate(
input_features,
attention_mask=attention_mask.to(device),
task="transcribe",
language=None if language == "auto" else language,
return_timestamps=return_timestamps,
no_repeat_ngram_size=3,
num_beams=5,
length_penalty=1.0,
max_length=max_length,
)
chunk_tokens = processor.tokenizer.convert_ids_to_tokens(
predicted_ids[0]
)
adjusted_tokens = []
for token in chunk_tokens:
if token.startswith("<|") and token.endswith("|>"):
try:
time_str = token[2:-2]
if time_str.replace(".", "").isdigit():
time_val = float(time_str)
# If this timestamp is less than the last one, we've started a new sequence
if time_val < last_time:
accumulated_offset += last_time
adjusted_time = time_val + accumulated_offset
adjusted_tokens.append(f"<|{adjusted_time:.2f}|>")
last_time = time_val
else:
adjusted_tokens.append(token)
except ValueError:
adjusted_tokens.append(token)
else:
adjusted_tokens.append(token)
all_tokens.extend(adjusted_tokens)
chunk_text = processor.batch_decode(
predicted_ids, skip_special_tokens=True
)[0]
all_text.append(chunk_text)
detected_language = "en"
if language == "auto":
try:
log.debug("Detecting language")
with torch.no_grad():
first_chunk_features = processor(
waveform[:chunk_samples],
sampling_rate=sample_rate,
return_tensors="pt",
).input_features.to(device)
predicted_probs = model.detect_language(
first_chunk_features
)[0]
language_token = processor.tokenizer.convert_ids_to_tokens(
predicted_probs.argmax(-1).item()
)
detected_language = (
language_token[2:-2]
if language_token.startswith("<|")
else "en"
)
log.debug(f"Detected language: {detected_language}")
except Exception as e:
log.warning(f"Language detection failed: {e}")
full_transcription = " ".join(all_text)
whisper_output = {
"text": full_transcription,
"language": detected_language,
"tokens": all_tokens,
"audio": audio,
"chunk_offsets": chunk_offsets,
}
return full_transcription, whisper_output
class MTB_ProcessWhisperOutput:
"""Process Whisper output into timestamped chunks."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"whisper_output": ("WHISPER_OUTPUT",),
"min_chunk_length": (
"FLOAT",
{"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.1},
),
},
}
RETURN_TYPES = ("STRING", "WHISPER_CHUNKS")
FUNCTION = "process"
CATEGORY = "mtb/audio"
def process(self, whisper_output, min_chunk_length=0.0):
"""Process Whisper output into timestamped chunks."""
tokens = whisper_output["tokens"]
audio = whisper_output["audio"]
timestamp_tokens = []
audio_duration = audio["waveform"].shape[-1] / audio["sample_rate"]
log.debug(f"Audio duration: {audio_duration:.2f}s")
for i, token in enumerate(tokens):
if token.startswith("<|") and token.endswith("|>"):
try:
time_str = token[2:-2]
if time_str.replace(".", "").isdigit():
time_val = float(time_str)
if 0 <= time_val <= audio_duration:
timestamp_tokens.append((i, time_val))
log.debug(f"Token {i}: {time_val}")
except ValueError:
continue
chunks = []
if len(timestamp_tokens) > 1:
for i in range(len(timestamp_tokens) - 1):
start_pos, start_time = timestamp_tokens[i]
end_pos, end_time = timestamp_tokens[i + 1]
if end_time - start_time < min_chunk_length:
continue
chunk_tokens = tokens[start_pos + 1 : end_pos]
text = " ".join(
t
for t in chunk_tokens
if not (t.startswith("<|") and t.endswith("|>"))
)
if text.strip():
chunks.append(
{
"text": text.strip(),
"timestamp": [start_time, end_time],
}
)
if timestamp_tokens:
start_pos, start_time = timestamp_tokens[-1]
if start_pos < len(tokens) - 1:
text = " ".join(
t
for t in tokens[start_pos + 1 :]
if not (t.startswith("<|") and t.endswith("|>"))
)
if text.strip():
if chunks:
prev_chunk = chunks[-1]
prev_duration = (
prev_chunk["timestamp"][1]
- prev_chunk["timestamp"][0]
)
end_time = min(
start_time + prev_duration, audio_duration
)
else:
end_time = audio_duration
if (
end_time > start_time
and end_time - start_time >= min_chunk_length
):
chunks.append(
{
"text": text.strip(),
"timestamp": [start_time, end_time],
}
)
result = {
"text": whisper_output["text"],
"chunks": chunks,
"language": whisper_output["language"],
}
return whisper_output["text"], result
class MTB_AudioCut(MtbAudio):
"""Basic audio cutter, values are in ms."""
@@ -98,7 +505,7 @@ class MTB_AudioCut(MtbAudio):
CATEGORY = "mtb/audio"
FUNCTION = "cut"
def cut(self, audio: AudioDict, length: float, offset: float):
def cut(self, audio: AudioTensor, length: float, offset: float):
sample_rate = audio["sample_rate"]
start_idx = int(offset * sample_rate / 1000)
end_idx = min(
@@ -117,7 +524,6 @@ class MTB_AudioCut(MtbAudio):
class MTB_AudioStack(MtbAudio):
"""Stack/Overlay audio inputs (dynamic inputs).
- pad audios to the longest inputs.
- resample audios to the highest sample rate in the inputs.
- convert them all to stereo if one of the inputs is.
@@ -132,7 +538,7 @@ class MTB_AudioStack(MtbAudio):
CATEGORY = "mtb/audio"
FUNCTION = "stack"
def stack(self, **kwargs: AudioDict) -> tuple[AudioDict]:
def stack(self, **kwargs: AudioTensor) -> tuple[AudioTensor]:
audios, is_stereo, max_rate = self.preprocess_audios(
list(kwargs.values())
)
@@ -163,7 +569,6 @@ class MTB_AudioStack(MtbAudio):
class MTB_AudioSequence(MtbAudio):
"""Sequence audio inputs (dynamic inputs).
- adding silence_duration between each segment
can now also be negative to overlap the clips, safely bound
to the the input length.
@@ -187,7 +592,7 @@ class MTB_AudioSequence(MtbAudio):
CATEGORY = "mtb/audio"
FUNCTION = "sequence"
def sequence(self, silence_duration: float, **kwargs: AudioDict):
def sequence(self, silence_duration: float, **kwargs: AudioTensor):
audios, is_stereo, max_rate = self.preprocess_audios(
list(kwargs.values())
)
@@ -232,4 +637,287 @@ class MTB_AudioSequence(MtbAudio):
)
__nodes__ = [MTB_AudioSequence, MTB_AudioStack, MTB_AudioCut]
class MTB_AudioResample(MtbAudio):
"""Resample audio to a different sample rate."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
"sample_rate": (
"INT",
{
"default": 16000,
"min": 1000,
"max": 192000,
"step": 100,
"tooltip": "Target sample rate in Hz. Whisper requires 16000.",
},
),
}
}
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("resampled_audio",)
CATEGORY = "mtb/audio"
FUNCTION = "resample_audio"
def resample_audio(
self, audio: AudioTensor, sample_rate: int
) -> tuple[AudioTensor]:
resampled = self.resample(audio, sample_rate)
return (resampled,)
class MTB_AudioIsolateSpeaker(MtbAudio):
"""Isolate or mute specific speakers using WhisperData"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
"whisper_data": ("WHISPER_CHUNKS",),
"target_speaker": ("STRING", {"default": "SPEAKER_00"}),
"mode": (["isolate", "mute"], {"default": "isolate"}),
"fade_ms": (
"FLOAT",
{
"default": 100.0,
"min": 0.0,
"max": 1000.0,
"step": 10,
"tooltip": "Fade duration in milliseconds to avoid clicks",
},
),
},
}
RETURN_TYPES = ("AUDIO",)
RETURN_NAMES = ("processed_audio",)
CATEGORY = "mtb/audio"
FUNCTION = "process_audio"
def process_audio(
self,
audio: AudioTensor,
whisper_data: WhisperData,
target_speaker: str,
mode: str = "isolate",
fade_ms: float = 100.0,
) -> tuple[AudioTensor]:
fade_samples = int((fade_ms / 1000.0) * audio["sample_rate"])
mask = (
torch.zeros_like(audio["waveform"])
if mode == "isolate"
else torch.ones_like(audio["waveform"])
)
for chunk in whisper_data["chunks"]:
if not chunk.get("speaker"):
continue
speaker_present = target_speaker in chunk["speaker"]
if (mode == "isolate" and speaker_present) or (
mode == "mute" and not speaker_present
):
start_sample = int(
chunk["timestamp"][0] * audio["sample_rate"]
)
end_sample = int(chunk["timestamp"][1] * audio["sample_rate"])
mask[:, start_sample:end_sample] = 1.0
if fade_samples > 0:
fade = torch.linspace(0, 1, fade_samples)
transitions = torch.where(mask[0, 1:] != mask[0, :-1])[0] + 1
for trans_idx in transitions:
if (
trans_idx >= fade_samples
and trans_idx <= mask.shape[1] - fade_samples
):
if mask[0, trans_idx] == 1:
mask[:, trans_idx : trans_idx + fade_samples] *= fade
else:
mask[:, trans_idx - fade_samples : trans_idx] *= (
fade.flip(0)
)
processed_waveform = audio["waveform"] * mask
return (
{
"sample_rate": audio["sample_rate"],
"waveform": processed_waveform,
},
)
class MTB_ProcessWhisperDiarization:
"""Process Whisper chunks with speaker diarization using either pyannote or NeMo."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"whisper_chunks": ("WHISPER_CHUNKS",),
"audio": ("AUDIO",),
"backend": (["pyannote", "nemo"], {"default": "pyannote"}),
"num_speakers": (
"INT",
{"default": 2, "min": 1, "max": 10, "step": 1},
),
},
"optional": {
"device": (["cuda", "cpu"], {"default": "cuda"}),
},
}
RETURN_TYPES = ("WHISPER_CHUNKS",)
FUNCTION = "process"
CATEGORY = "mtb/audio"
def process_pyannote(self, audio, num_speakers, device):
"""Process audio using pyannote backend."""
try:
from pyannote.audio import Pipeline
from pyannote.audio.pipelines.utils.hook import ProgressHook
except ImportError:
raise ImportError(
"pyannote.audio not found. Install with: pip install pyannote.audio"
)
pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization-3.1", use_auth_token=None
)
pipeline.to(torch.device(device))
with ProgressHook() as hook:
diarization = pipeline(
{
"waveform": audio["waveform"][0],
"sample_rate": audio["sample_rate"],
},
num_speakers=num_speakers,
hook=hook,
)
speaker_segments = []
for turn, _, speaker in diarization.itertracks(yield_label=True):
speaker_segments.append(
{
"start": turn.start,
"end": turn.end,
"speaker": speaker,
}
)
return speaker_segments
def process_nemo(self, audio, num_speakers, device):
"""Process audio using NeMo backend."""
try:
import nemo.collections.asr as nemo_asr
except ImportError:
raise ImportError(
"NeMo not found. Install with: pip install nemo_toolkit[asr]"
)
model = nemo_asr.models.ClusteringDiarizer.from_pretrained(
"nvidia/speakerverification_en_titanet_large"
).to(device)
diarization = model.diarize(
audio=audio["waveform"][0],
sample_rate=audio["sample_rate"],
num_speakers=num_speakers,
)
speaker_segments = []
for segment in diarization:
speaker_segments.append(
{
"start": segment["start"],
"end": segment["end"],
"speaker": f"SPEAKER_{segment['speaker']}",
}
)
return speaker_segments
def process(
self,
whisper_chunks,
audio,
backend="pyannote",
num_speakers=2,
device="cuda",
):
if backend == "pyannote":
speaker_segments = self.process_pyannote(
audio, num_speakers, device
)
else: # nemo
speaker_segments = self.process_nemo(audio, num_speakers, device)
for chunk in whisper_chunks["chunks"]:
chunk_start, chunk_end = chunk["timestamp"]
chunk_speakers = set()
for segment in speaker_segments:
if (
segment["start"] <= chunk_end
and segment["end"] >= chunk_start
):
chunk_speakers.add(segment["speaker"])
if chunk_speakers:
chunk["speaker"] = list(chunk_speakers)[0]
else:
chunk["speaker"] = "unknown"
return (whisper_chunks,)
class MTB_AudioDuration:
"""Get audio duration in milliseconds."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"audio": ("AUDIO",),
},
}
RETURN_TYPES = ("INT",)
RETURN_NAMES = ("duration_ms",)
FUNCTION = "get_duration"
CATEGORY = "mtb/audio"
def get_duration(self, audio):
waveform = audio["waveform"]
sample_rate = audio["sample_rate"]
duration_ms = int((waveform.shape[-1] / sample_rate) * 1000)
log.debug(
f"Audio duration: {duration_ms}ms ({duration_ms / 1000:.2f}s)"
)
return (duration_ms,)
__nodes__ = [
MTB_AudioSequence,
MTB_AudioStack,
MTB_AudioCut,
MTB_AudioResample,
MTB_AudioIsolateSpeaker,
MTB_LoadWhisper,
MTB_AudioToText,
MTB_ProcessWhisperOutput,
MTB_ProcessWhisperDiarization,
MTB_AudioDuration,
]
+292 -7
View File
@@ -1,13 +1,18 @@
import os
import random
from io import BytesIO
from pathlib import Path
from typing import Literal
import comfy.utils
import cv2
import folder_paths
import numpy as np
import torch
from PIL import Image
from ..log import log
from ..utils import EASINGS, apply_easing, pil2tensor
from ..utils import EASINGS, apply_easing, glob_multiple, pil2tensor
from .transform import MTB_TransformImage
@@ -47,7 +52,7 @@ class MTB_BatchFloatMath:
for v in vals:
if len(v) != ref_count:
raise ValueError(
f"All values must have the same length (current: {len(v)}, ref: {ref_count}"
f"All values must have the same length (current: {len(v)}, ref: {ref_count})"
)
match operation:
@@ -170,6 +175,124 @@ class MTB_BatchTimeWrap:
return (warped_tensor, interpolated_curve)
class MTB_ImageBatchToSublist:
"""
# Image Batch To Sublist 🔄
Splits a large batched tensor into smaller sub-batches for memory-efficient processing.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"sub_batch_size": (
"INT",
{"default": 1, "min": 1, "max": 1000, "step": 1},
),
},
"optional": {
"image": ("IMAGE",),
"mask": ("MASK",),
},
}
RETURN_TYPES = ("IMAGE", "MASK", "INT")
RETURN_NAMES = ("image_list", "mask_list", "item_count")
OUTPUT_IS_LIST = (True, True)
FUNCTION = "split_batch"
CATEGORY = "batch_processing"
def split_batch(
self,
sub_batch_size: int,
image: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
):
if image is None and mask is None:
raise ValueError(
"You must either pass mask or image, none received"
)
image_count = 0
if image is not None:
image_count = image.size(0)
mask_count = 0
if mask is not None:
mask_count = mask.size(0)
if image_count > 0 and mask_count > 0 and mask_count != image_count:
raise ValueError(
f"When providing image and mask, batch size must match (got {mask.size(0)} mask and {image.size(0)} images)"
)
batch_size = max(image_count, mask_count)
num_full_batches = batch_size // sub_batch_size
im_batches = []
mask_batches = []
for i in range(num_full_batches):
start_idx = i * sub_batch_size
end_idx = start_idx + sub_batch_size
if image_count > 0:
im_batches.append(image[start_idx:end_idx, ...])
if mask_count > 0:
mask_batches.append(mask[start_idx:end_idx, ...])
if batch_size % sub_batch_size != 0:
remaining_start = num_full_batches * sub_batch_size
if image_count > 0:
im_batches.append(image[remaining_start:, ...])
if mask_count > 0:
mask_batches.append(mask[remaining_start:, ...])
return (im_batches, mask_batches, len(im_batches))
class MTB_SublistToImageBatch:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"tensors": ("IMAGE",),
}
}
INPUT_IS_LIST = True
RETURN_TYPES = ("IMAGE",)
FUNCTION = "merge_batches"
CATEGORY = "batch_processing"
DOCUMENTATION = """# Sublist to Image Batch 🔄
Merges a list of sub-batched tensors back into a single large batch.
"""
def merge_batches(self, tensors: list[torch.Tensor]):
if len(tensors) <= 1:
return (tensors[0],)
result = tensors[0]
for next_tensor in tensors[1:]:
if result.shape[1:] != next_tensor.shape[1:]:
next_tensor = comfy.utils.common_upscale(
next_tensor.movedim(-1, 1),
result.shape[2],
result.shape[1],
"lanczos",
"center",
).movedim(1, -1)
result = torch.cat((result, next_tensor), dim=0)
return (result,)
class MTB_BatchMake:
"""Simply duplicates the input frame as a batch"""
@@ -179,18 +302,22 @@ class MTB_BatchMake:
"required": {
"image": ("IMAGE",),
"count": ("INT", {"default": 1}),
}
},
"optional": {"mask": ("MASK",)},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "generate_batch"
CATEGORY = "mtb/batch"
def generate_batch(self, image: torch.Tensor, count):
def generate_batch(self, image: torch.Tensor, count, mask=None):
if len(image.shape) == 3:
image = image.unsqueeze(0)
return (image.repeat(count, 1, 1, 1),)
return (
image.repeat(count, 1, 1, 1),
mask.repeat(count, 1, 1) if mask else mask,
)
class MTB_BatchShape:
@@ -375,8 +502,14 @@ class MTB_BatchFloat:
{"default": "Steps"},
),
"count": ("INT", {"default": 2}),
"min": ("FLOAT", {"default": 0.0, "step": 0.001}),
"max": ("FLOAT", {"default": 1.0, "step": 0.001}),
"min": (
"FLOAT",
{"default": 0.0, "min": -1e4, "max": 1e4, "step": 0.001},
),
"max": (
"FLOAT",
{"default": 1.0, "min": -1e4, "max": 1e4, "step": 0.001},
),
"easing": (
[
"Linear",
@@ -717,6 +850,13 @@ class MTB_Batch2dTransform:
"zoom": ("FLOATS",),
"angle": ("FLOATS",),
"shear": ("FLOATS",),
"use_normalized": (
"BOOLEAN",
{
"default": False,
"tooltip": "If true, transform values will be scaled to image dimensions.",
},
),
},
}
@@ -745,6 +885,7 @@ class MTB_Batch2dTransform:
zoom: list[float] | None = None,
angle: list[float] | None = None,
shear: list[float] | None = None,
use_normalized: bool = False,
):
if all(
self.get_num_elements(param) <= 0
@@ -796,6 +937,7 @@ class MTB_Batch2dTransform:
keyframes["shear"][i],
border_handling,
constant_color,
use_normalized=use_normalized,
)[0]
for i in range(image.shape[0])
]
@@ -1239,6 +1381,146 @@ class MTB_BatchShake:
return (shaken_images, x_translations, y_translations, rotations)
class MTB_BatchFromFolder:
"""Load images from a folder with options for latest, oldest, or random selection."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"enable": (
"BOOLEAN",
{
"default": True,
"tooltip": "Enable or disable the node. If disabled, returns passthrough_image or an empty tensor.",
},
),
"folder_path": (
"STRING",
{
"default": "",
"tooltip": "Path to the folder containing images. Relative paths are resolved to the ComfyUI output directory.",
},
),
"mode": (
["latest", "oldest", "random"],
{
"default": "latest",
"tooltip": "How to select images: latest, oldest, or random.",
},
),
"count": (
"INT",
{
"default": 10,
"min": 1,
"max": 1000,
"tooltip": "Number of images to load from the folder.",
},
),
"filter": (
"STRING",
{
"default": "*",
"tooltip": "Glob filter for image filenames (e.g. *.png).",
},
),
},
"optional": {
"passthrough_image": (
"IMAGE",
{
"tooltip": "If provided and node is disabled, this image is passed through instead of returning an empty tensor."
},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("images",)
CATEGORY = "mtb/batch"
FUNCTION = "load_from_folder"
def load_from_folder(
self,
enable: bool,
folder_path: str,
mode: str,
count: int,
filter: str,
passthrough_image=None,
):
"""Load images from a folder with the specified selection mode."""
if not enable:
if passthrough_image is not None:
log.debug(
"MTB_BatchFromFolder: Using passthrough image (disabled)"
)
return (passthrough_image,)
log.debug(
"MTB_BatchFromFolder: Disabled and no passthrough_image provided, returning empty tensor"
)
return (torch.zeros(0, 0, 0, 3),)
path_obj = Path(folder_path)
if not path_obj.is_absolute():
output_dir = Path(folder_paths.get_output_directory())
path_obj = output_dir / folder_path
path_obj = path_obj.resolve()
if not path_obj.exists():
log.error(f"Folder path does not exist: {path_obj}")
return (torch.zeros(0, 0, 0, 3),)
if not path_obj.is_dir():
log.error(f"Path is not a directory: {path_obj}")
return (torch.zeros(0, 0, 0, 3),)
patterns = [filter] if filter else ["*"]
files = glob_multiple(path_obj, patterns)
image_extensions = [".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tiff"]
image_files = [
f for f in files if f.suffix.lower() in image_extensions
]
if not image_files:
log.warning(
f"No image files found in {path_obj} with filter {filter}"
)
return (torch.zeros(0, 0, 0, 3),)
if mode == "latest":
image_files.sort(key=lambda x: os.path.getmtime(x), reverse=True)
elif mode == "oldest":
image_files.sort(key=lambda x: os.path.getmtime(x))
elif mode == "random":
random.shuffle(image_files)
selected_files = image_files[:count]
if len(selected_files) < count:
log.warning(
f"Requested {count} images but only found {len(selected_files)}"
)
loaded_images = []
for file_path in selected_files:
try:
img = Image.open(file_path)
if img.mode != "RGB":
img = img.convert("RGB")
loaded_images.append(img)
except Exception as e:
log.error(f"Error loading image {file_path}: {e}")
if not loaded_images:
log.error("Failed to load any images")
return (torch.zeros(0, 0, 0, 3),)
return (pil2tensor(loaded_images),)
__nodes__ = [
MTB_Batch2dTransform,
MTB_BatchFloat,
@@ -1247,6 +1529,7 @@ __nodes__ = [
MTB_BatchFloatFit,
MTB_BatchFloatMath,
MTB_BatchFloatNormalize,
MTB_BatchFromFolder,
MTB_BatchMake,
MTB_BatchMerge,
MTB_BatchSequence,
@@ -1255,4 +1538,6 @@ __nodes__ = [
MTB_BatchShape,
MTB_BatchTimeWrap,
MTB_PlotBatchFloat,
MTB_SublistToImageBatch,
MTB_ImageBatchToSublist,
]
+190
View File
@@ -0,0 +1,190 @@
import time
import uuid
from collections import OrderedDict
from typing import Any, TypedDict
from comfy.comfy_types.node_typing import IO as CIO
from server import PromptServer
from ..log import log
class Clock(TypedDict):
name: str
start: float
end: float | None
active_timers: OrderedDict[str, Clock] = OrderedDict()
# TODO: lower this
MAX_CLOCKS = 50
class MTB_StartClock:
"""
Starts a profiling clock with a given name.
Outputs a unique ID that must be passed to EndClock.
"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"name": ("STRING", {"default": "Clock A"}),
"cache": (
"BOOLEAN",
{
"default": False,
"tooltip": "Cache the clock ID, this means the node will follow Comfy's default invalidation system. If False it will always invalidate / mark the node as 'dirty'",
},
),
},
"optional": {
"passthrough": (CIO.ANY,),
},
}
RETURN_TYPES = (
CIO.ANY,
"STRING",
)
RETURN_NAMES = (
"passthrough",
"clock_id",
)
FUNCTION = "start_timer"
CATEGORY = "mtb/utils"
def start_timer(
self, *, name: str, passthrough: Any | None = None, **kwargs
):
global active_timers
if len(active_timers) >= MAX_CLOCKS:
# get oldest clock
removed_key = None
for key, clock_data in active_timers.items():
if clock_data["end"] is not None:
removed_key = key
break
if removed_key:
removed_clock = active_timers.pop(removed_key)
log.info(
f"[Profiling] Evicted finished clock '{removed_clock['name']}' (ID: {removed_key}) due to limit ({MAX_CLOCKS})."
)
else:
removed_key, removed_clock = active_timers.popitem(last=False)
log.warning(
f"[Profiling] Evicted running clock '{removed_clock['name']}' (ID: {removed_key}) due to limit ({MAX_CLOCKS})."
)
clock_id = str(uuid.uuid4())
start_time = time.perf_counter()
active_timers[clock_id] = {
"start": start_time,
"name": name,
"end": None,
}
active_timers.move_to_end(clock_id)
log.debug(f"[Profiling] Clock '{name}' (ID: {clock_id}) started.")
return (
passthrough,
clock_id,
)
@classmethod
def IS_CHANGED(
cls, *, name: str, cache: bool = False, passthrough: Any | None = None
):
if not cache:
return float("Nan")
return {"name": name, "cache": cache, "passthrough": passthrough}
class MTB_EndClock:
"""
Stops a profiling clock identified by its ID and returns the elapsed time in milliseconds.
Errors if the clock ID is not found or already stopped.
"""
def __init__(self):
pass
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"clock_id": (
"STRING",
{"forceInput": True},
),
},
"optional": {
"passthrough": (CIO.ANY,),
},
"hidden": {
"unique_id": "UNIQUE_ID",
},
}
RETURN_TYPES = (
CIO.ANY,
"STRING",
"FLOAT",
"INT",
)
RETURN_NAMES = (
"passthrough",
"name",
"seconds",
"milliseconds",
)
FUNCTION = "end_timer"
CATEGORY = "mtb/utils"
def end_timer(self, clock_id: str, passthrough, unique_id=None):
global active_timers
if clock_id not in active_timers:
raise ValueError(
f"Error: Clock with ID '{clock_id}' not found. "
"Ensure StartClock was executed for this ID and proper passthrough chaining."
)
clock = active_timers[clock_id]
if clock.get("end") is not None:
return (passthrough, clock["name"], clock["end"])
start_time = clock["start"]
end_time = time.perf_counter()
duration_seconds = end_time - start_time
duration_ms = int(duration_seconds * 1000)
clock["end"] = duration_ms
active_timers.move_to_end(clock_id)
log.debug(
f"[Profiling] Clock '{clock['name']}' (ID: {clock_id}) stopped. Elapsed: {duration_ms}ms"
)
if unique_id:
PromptServer.instance.send_progress_text(
f"Clock '{clock['name']}' took {duration_seconds:.4f} seconds",
unique_id,
)
return (passthrough, clock["name"], duration_seconds, duration_ms)
__nodes__ = [MTB_StartClock, MTB_EndClock]
+236 -163
View File
@@ -1,13 +1,22 @@
import numpy as np
from typing import NamedTuple
import torch
from PIL import Image, ImageDraw, ImageFilter
import torchvision.transforms.functional as TF
from ..log import log
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
class BoundingBox(NamedTuple):
"""The bounding box tuple."""
x: int
y: int
width: int
height: int
class MTB_Bbox:
"""The bounding box (BBOX) custom type used by other nodes"""
"""A literal bounding box."""
@classmethod
def INPUT_TYPES(cls):
@@ -37,12 +46,14 @@ class MTB_Bbox:
FUNCTION = "do_crop"
CATEGORY = "mtb/crop"
def do_crop(self, x: int, y: int, width: int, height: int): # bbox
return ((x, y, width, height),)
def do_crop(
self, x: int, y: int, width: int, height: int
) -> tuple[BoundingBox]: # bbox
return (BoundingBox(x, y, width, height),)
class MTB_SplitBbox:
"""Split the components of a bbox"""
"""Split the components of a bbox."""
@classmethod
def INPUT_TYPES(cls):
@@ -55,8 +66,8 @@ class MTB_SplitBbox:
RETURN_TYPES = ("INT", "INT", "INT", "INT")
RETURN_NAMES = ("x", "y", "width", "height")
def split_bbox(self, bbox):
return (bbox[0], bbox[1], bbox[2], bbox[3])
def split_bbox(self, bbox: BoundingBox) -> BoundingBox:
return bbox
class MTB_UpscaleBboxBy:
@@ -74,23 +85,23 @@ class MTB_UpscaleBboxBy:
FUNCTION = "upscale"
def upscale(
self, bbox: tuple[int, int, int, int], scale: float
) -> tuple[tuple[int, int, int, int]]:
def upscale(self, bbox: BoundingBox, scale: float) -> tuple[BoundingBox]:
x, y, width, height = bbox
# scaled = (x * scale, y * scale, width * scale, height * scale)
scaled = (
int(x * scale),
int(y * scale),
int(width * scale),
int(height * scale),
)
return (scaled,)
center_x = x + width / 2
center_y = y + height / 2
new_width = int(width * scale)
new_height = int(height * scale)
new_x = int(center_x - new_width / 2)
new_y = int(center_y - new_height / 2)
return (BoundingBox(new_x, new_y, new_width, new_height),)
class MTB_BboxFromMask:
"""From a mask extract the bounding box"""
"""From a mask extract the bounding box."""
@classmethod
def INPUT_TYPES(cls):
@@ -100,7 +111,7 @@ class MTB_BboxFromMask:
"invert": ("BOOLEAN", {"default": False}),
},
"optional": {
"image": ("IMAGE",),
"image": ("IMAGE", {"tooltip": "Optional image"}),
},
}
@@ -116,52 +127,44 @@ class MTB_BboxFromMask:
CATEGORY = "mtb/crop"
def extract_bounding_box(
self, mask: torch.Tensor, invert: bool, 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})"
# )
self,
mask: torch.Tensor,
*,
invert: bool = False,
image: torch.Tensor | None = None,
) -> tuple[BoundingBox, torch.Tensor | None]:
mask = 1 - mask if invert else mask
non_zero_indices = torch.nonzero(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})"
# )
if non_zero_indices.numel() == 0:
log.warning(
"BboxFromMask: Mask is empty. Returning a (0,0,0,0) bbox."
)
return (BoundingBox(0, 0, 0, 0), image)
# we invert it
_mask = tensor2pil(1.0 - mask)[0] if invert else tensor2pil(mask)[0]
alpha_channel = np.array(_mask)
min_coords = torch.min(non_zero_indices, dim=0).values
max_coords = torch.max(non_zero_indices, dim=0).values
non_zero_indices = np.nonzero(alpha_channel)
min_y, min_x = min_coords[1].item(), min_coords[2].item()
max_y, max_x = max_coords[1].item(), max_coords[2].item()
min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0])
width = max_x - min_x + 1
height = max_y - min_y + 1
# Create a bounding box tuple
if image != None:
# Convert the image to a NumPy array
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,
image,
bounding_box = BoundingBox(
int(min_x), int(min_y), int(width), int(height)
)
cropped_image = None
if image is not None:
cropped_image = image[:, min_y : max_y + 1, min_x : max_x + 1, :]
return (bounding_box, cropped_image)
class MTB_Crop:
"""Crops an image and an optional mask to a given bounding box
"""Crop an image and an optional mask to a given bounding box.
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
The BBOX input takes precedence over the tuple input
"""
@@ -201,35 +204,38 @@ class MTB_Crop:
def do_crop(
self,
image: torch.Tensor,
mask=None,
x=0,
y=0,
width=256,
height=256,
bbox=None,
*,
mask: torch.Tensor | None = None,
x: int = 0,
y: int = 0,
width: int = 256,
height: int = 256,
bbox: BoundingBox | None = None,
):
image = image.numpy()
if mask is not None:
mask = mask.numpy()
if bbox is not None:
x, y, width, height = bbox
cropped_image = image[:, y : y + height, x : x + width, :]
cropped_mask = None
if mask is not None:
cropped_mask = (
mask[:, y : y + height, x : x + width]
if mask is not None
else None
if width <= 0 or height <= 0:
log.error(
"Crop dimensions must be positive. Check the BBOX or widget inputs."
)
crop_data = (x, y, width, height)
return (
torch.zeros_like(image),
torch.zeros_like(mask) if mask is not None else None,
(x, y, width, height),
)
cropped_image = image[:, y : y + height, x : x + width, :]
cropped_mask = (
mask[:, y : y + height, x : x + width]
if mask is not None
else None
)
crop_data = BoundingBox(x, y, width, height)
return (
torch.from_numpy(cropped_image),
torch.from_numpy(cropped_mask)
if cropped_mask is not None
else None,
cropped_image,
cropped_mask if cropped_mask is not None else None,
crop_data,
)
@@ -243,35 +249,33 @@ class MTB_Crop:
# return (x_left, y_top, x_right, y_bottom)
def bbox_check(bbox, target_size=None):
def bbox_check(bbox: BoundingBox, target_size: tuple[int, int] | None = 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]),
new_bbox = BoundingBox(
bbox.x,
bbox.y,
min(target_size[0] - bbox.x, bbox.width),
min(target_size[1] - bbox.y, bbox.height),
)
if new_bbox != bbox:
log.warn(f"BBox too big, constrained to {new_bbox}")
log.warning(f"BBox too big, constrained to {new_bbox}")
return new_bbox
def bbox_to_region(bbox, target_size=None):
def bbox_to_region(
bbox: BoundingBox, target_size: tuple[int, int] | None = None
):
bbox = bbox_check(bbox, target_size)
# to region
return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
return (bbox.x, bbox.y, bbox.x + bbox.width, bbox.y + bbox.height)
class MTB_Uncrop:
"""Uncrops an image to a given bounding box
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
The BBOX input takes precedence over the tuple input
"""
"""Uncrop an image to a given bounding box."""
@classmethod
def INPUT_TYPES(cls):
@@ -288,88 +292,156 @@ class MTB_Uncrop:
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "do_crop"
FUNCTION = "do_uncrop"
CATEGORY = "mtb/crop"
def do_crop(self, image, crop_image, bbox, border_blending):
def inset_border(image, border_width=20, border_color=(0)):
width, height = image.size
bordered_image = Image.new(
image.mode, (width, height), border_color
def do_uncrop(
self,
image: torch.Tensor,
crop_image: torch.Tensor,
bbox: BoundingBox,
border_blending: float = 0.25,
):
if len(image) > 1 and len(image) != len(crop_image):
raise ValueError(
"Uncrop: Batch size of background 'image' must be 1 or match the 'crop_image' batch size."
)
bordered_image.paste(image, (0, 0))
draw = ImageDraw.Draw(bordered_image)
draw.rectangle(
(0, 0, width - 1, height - 1),
outline=border_color,
width=border_width,
)
return bordered_image
import comfy.utils
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"
)
pbar = comfy.utils.ProgressBar(4)
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]
device = image.device
# uncrop the image based on the bounding box
bb_x, bb_y, bb_width, bb_height = bbox
log.debug(f"Working on device: {device}")
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
crop_image = crop_image.to(device)
crop_img = crop.convert("RGB")
if len(image) == 1 and len(crop_image) > 1:
image = image.repeat(len(crop_image), 1, 1, 1)
log.debug(f"Crop image size: {crop_img.size}")
log.debug(f"Image size: {img.size}")
batch_size, bg_h, bg_w, _ = image.shape
_, fg_h, fg_w, _ = crop_image.shape
x, y, width, height = bbox
if border_blending > 1.0:
border_blending = 1.0
elif border_blending < 0.0:
border_blending = 0.0
blend_ratio = (max(crop_img.size) / 2) * float(border_blending)
blend = img.convert("RGBA")
mask = Image.new("L", img.size, 0)
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)
if (width, height) != (fg_w, fg_h):
log.warning(
f"Uncrop: crop_image size {(fg_w, fg_h)} "
"differs from bbox {(width, height)}. Resizing to fit bbox."
)
blend.putalpha(mask)
img = Image.alpha_composite(img.convert("RGBA"), blend)
out_images.append(img.convert("RGB"))
resized_crop = crop_image.permute(0, 3, 1, 2)
resized_crop = torch.nn.functional.interpolate(
resized_crop,
size=(height, width),
mode="bicubic",
align_corners=False,
)
resized_crop = resized_crop.permute(0, 2, 3, 1)
return (pil2tensor(out_images),)
pbar.update(1)
# paste coords
paste_x1 = max(x, 0)
paste_y1 = max(y, 0)
paste_x2 = min(x + width, bg_w)
paste_y2 = min(y + height, bg_h)
# region from crop (bound)
crop_x1 = max(0, -x)
crop_y1 = max(0, -y)
crop_x2 = crop_x1 + (paste_x2 - paste_x1)
crop_y2 = crop_y1 + (paste_y2 - paste_y1)
if paste_x1 >= paste_x2 or paste_y1 >= paste_y2:
log.warning(
"Uncrop: BBOX is entirely outside the image boundaries. Returning original image."
)
return (image,)
pbar.update(1)
source_slice = resized_crop[:, crop_y1:crop_y2, crop_x1:crop_x2, :]
final_image = image.clone()
final_image[:, paste_y1:paste_y2, paste_x1:paste_x2, :] = source_slice
pbar.update(1)
blend_radius = int(max(width, height) * border_blending * 0.5)
if blend_radius > 0:
_device = device
if torch.cuda.is_available():
_device = torch.device("cuda")
log.debug("Processing blending")
alpha_mask = torch.zeros((batch_size, bg_h, bg_w), device=_device)
alpha_mask[:, paste_y1:paste_y2, paste_x1:paste_x2] = 1.0
kernel_size = 2 * blend_radius + 1
log.debug("Gaussian blur...")
alpha_mask = TF.gaussian_blur(
alpha_mask.unsqueeze(1), kernel_size=[kernel_size, kernel_size]
).squeeze(1)
alpha_mask = alpha_mask.unsqueeze(-1)
log.debug("Applying blending")
final_image = final_image.to(_device) * alpha_mask + image.to(
_device
) * (1.0 - alpha_mask)
pbar.update(1)
return (final_image.to(device),)
class MTB_BBoxForceDimensions:
"""
Resize a BBOX to new dimensions while keeping its center.
Optionally constrains the BBOX to stay within image boundaries.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"bbox": ("BBOX",),
"width": ("INT", {"default": 512, "min": 1, "max": 8192}),
"height": ("INT", {"default": 512, "min": 1, "max": 8192}),
"constrain_to_image": ("BOOLEAN", {"default": True}),
},
"optional": {
"image": ("IMAGE",),
},
}
CATEGORY = "mtb/crop"
RETURN_TYPES = ("BBOX",)
FUNCTION = "force_dimensions"
def force_dimensions(
self,
*,
bbox: tuple[int, int, int, int],
width: int,
height: int,
constrain_to_image: bool = True,
image: torch.Tensor | None = None,
) -> tuple[tuple[int, int, int, int]]:
x, y, curr_width, curr_height = bbox
center_x = x + curr_width // 2
center_y = y + curr_height // 2
new_x = center_x - width // 2
new_y = center_y - height // 2
if constrain_to_image and image is not None:
img_height, img_width = image.shape[1:3]
new_x = max(0, min(new_x, img_width - width))
new_y = max(0, min(new_y, img_height - height))
width = min(width, img_width)
height = min(height, img_height)
return ((new_x, new_y, width, height),)
__nodes__ = [
@@ -379,4 +451,5 @@ __nodes__ = [
MTB_Uncrop,
MTB_SplitBbox,
MTB_UpscaleBboxBy,
MTB_BBoxForceDimensions,
]
+641 -138
View File
@@ -1,94 +1,267 @@
import base64
import io
import json
from pathlib import Path
from typing import Optional
import textwrap
from collections.abc import Callable
from functools import wraps
from typing import Any, Literal, Protocol, TypedDict, runtime_checkable
import folder_paths
import torch
from rich import inspect
from rich.console import Console
from ..log import log
from ..utils import tensor2pil
from ..utils import LazyProxyTensor, get_torch_tensor_info, tensor2pil
try:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("dark_background")
MATPLOTLIB_AVAILABLE = True
except ImportError:
MATPLOTLIB_AVAILABLE = False
# region Decorator
def metadata(**meta_kwargs: Any) -> Callable[[Any], Any]:
"""Add metadata to method (`__meta__` dict)."""
def decorator(func: Callable[[Any], Any]) -> Callable[[Any], Any]:
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
wrapper.__meta__ = meta_kwargs
return wrapper
return decorator
# endregion
class UIResult(TypedDict):
kind: Literal["text", "b64_images"]
data: str
def indent_results(results: list[UIResult], by: str = " "):
for res in results:
if res["kind"] == "text":
log.debug(f"Indenting: {res['data']}")
res["data"] = textwrap.indent(res["data"], by)
return results
ProcessorResult = list[UIResult]
def _get_detailed_type_info(obj) -> str:
type_info: list[str] = []
type_name = type(obj).__name__
type_info.append(f"Type: {type_name}")
if isinstance(obj, torch.Tensor):
return get_torch_tensor_info(obj)
elif isinstance(obj, list | tuple):
type_info.extend(
[
f"Length: {len(obj)}",
f"Container type: {type_name}",
]
)
if obj:
type_info.append(f"Element type: {type(obj[0]).__name__}")
elif isinstance(obj, dict):
type_info.extend(
[
f"Length: {len(obj)}",
f"Keys: {list(obj.keys())}",
]
)
elif hasattr(obj, "__dict__"):
attributes = [attr for attr in dir(obj) if not attr.startswith("_")]
type_info.append(f"Attributes: {attributes}")
return "\n".join(type_info)
def _apply_rich_results(processed, mode="none", title=""):
processing_text = False
acc = ""
reshaped: list[UIResult] = []
for i in range(len(processed)):
if processed[i]["kind"] == "text":
if not processing_text:
processing_text = True
acc += processed[i]["data"] + "\n"
if len(processed) == (i + 1):
reshaped.append(
UIResult(
kind="text", data=_apply_rich(acc, mode, title=title)
)
)
else:
if processing_text:
processing_text = False
reshaped.append(
UIResult(
kind="text", data=_apply_rich(acc, mode, title=title)
)
)
acc = ""
reshaped.append(processed[i])
return reshaped
# for item in processed:
# region processors
def process_tensor(tensor):
log.debug(f"Tensor: {tensor.shape}")
image = tensor2pil(tensor)
b64_imgs = []
for im in image:
buffered = io.BytesIO()
im.save(buffered, format="PNG")
b64_imgs.append(
"data:image/png;base64,"
+ base64.b64encode(buffered.getvalue()).decode("utf-8")
def _apply_rich(
formatted: str | list[str], rich_mode: str | None = None, *, title=""
) -> str:
if rich_mode is None:
return (
formatted if isinstance(formatted, str) else "\n".join(formatted)
)
return {"b64_images": b64_imgs}
from rich.console import Console
console = Console(record=True)
def process_list(anything):
text = []
if not anything:
return {"text": []}
first_element = anything[0]
if (
isinstance(first_element, list)
and first_element
and isinstance(first_element[0], torch.Tensor)
):
text.append(
"List of List of Tensors: "
f"{first_element[0].shape} (x{len(anything)})"
)
elif isinstance(first_element, torch.Tensor):
text.append(
f"List of Tensors: {first_element.shape} (x{len(anything)})"
)
if isinstance(formatted, list):
for line in formatted:
console.print(line)
else:
text.append(f"Array ({len(anything)}): {anything}")
console.print(formatted)
return {"text": text}
CSV_CODE_FORMAT = """
<svg class="rich-terminal" viewBox="0 0 {width} {height}" xmlns="http://www.w3.org/2000/svg">
<!-- Generated with Rich https://www.textualize.io -->
<style>
@font-face {{
font-family: "Fira Code";
src: local("FiraCode-Regular"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
font-style: normal;
font-weight: 400;
}}
@font-face {{
font-family: "Fira Code";
src: local("FiraCode-Bold"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
font-style: bold;
font-weight: 700;
}}
def process_dict(anything):
text = []
if "samples" in anything:
is_empty = (
"(empty)" if torch.count_nonzero(anything["samples"]) == 0 else ""
.{unique_id}-matrix {{
font-family: Fira Code, monospace;
font-size: {char_height}px;
line-height: {line_height}px;
font-variant-east-asian: full-width;
}}
.{unique_id}-title {{
font-size: 18px;
font-weight: bold;
font-family: arial;
}}
{styles}
</style>
<defs>
<clipPath id="{unique_id}-clip-terminal">
<rect x="0" y="0" width="{terminal_width}" height="{terminal_height}" />
</clipPath>
{lines}
</defs>
{chrome}
<g clip-path="url(#{unique_id}-clip-terminal)">
{backgrounds}
<g class="{unique_id}-matrix">
{matrix}
</g>
</g>
</svg>
"""
if rich_mode == "svg-window":
return console.export_svg(title=title, code_format=CSV_CODE_FORMAT)
elif rich_mode == "svg":
return console.export_svg(
title=title,
code_format=CSV_CODE_FORMAT.replace("{chrome}", ""),
)
text.append(f"Latent Samples: {anything['samples'].shape} {is_empty}")
else:
text.append(json.dumps(anything, indent=2))
elif rich_mode == "html":
CONSOLE_HTML_FORMAT = textwrap.dedent("""
<div style="color:{foreground};">
<code style="font-family:inherit">{code}</code>
</div>
""").strip()
return {"text": text}
import rich.terminal_theme
return console.export_html(
inline_styles=True,
code_format=CONSOLE_HTML_FORMAT,
theme=rich.terminal_theme.MONOKAI,
)
def process_bool(anything):
return {"text": ["True" if anything else "False"]}
def process_text(anything):
return {"text": [str(anything)]}
log.error(f"Unknown rich mode: {rich_mode}")
return formatted if isinstance(formatted, str) else "\n".join(formatted)
# endregion
class MTB_Debug:
"""Experimental node to debug any Comfy values.
# region conditions
support for more types and widgets is planned.
"""
# those are pretty dumb there is now probably a better way..
def is_condition(item):
return (
isinstance(item, list)
and all(isinstance(i, list) for i in item)
and isinstance(item[0][0], torch.Tensor)
)
# endregion
RICH_MODE = Literal["none", "html", "svg", "svg-window"]
@runtime_checkable
class Processor(Protocol):
"""Generic protocol for processor functions."""
def __call__(
self, item: Any, *, as_type: bool = False, deep: bool = False
) -> ProcessorResult: ...
class MTB_Debug:
"""A debug node."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {"output_to_console": ("BOOLEAN", {"default": False})},
"optional": {
"as_detailed_types": ("BOOLEAN", {"default": False}),
"deep_inspect": ("BOOLEAN", {"default": False}),
"rich_mode": (
("none", "html", "svg", "svg-window"),
{"default": "none"},
),
},
}
RETURN_TYPES = ()
@@ -96,96 +269,426 @@ class MTB_Debug:
CATEGORY = "mtb/debug"
OUTPUT_NODE = True
def do_debug(self, output_to_console: bool, **kwargs):
output = {
"ui": {"b64_images": [], "text": []},
# "result": ("A"),
}
processors = {
torch.Tensor: process_tensor,
list: process_list,
dict: process_dict,
bool: process_bool,
}
if output_to_console:
for k, v in kwargs.items():
log.info(f"{k}: {v}")
for anything in kwargs.values():
processor = processors.get(type(anything), process_text)
processed_data = processor(anything)
for ui_key, ui_value in processed_data.items():
output["ui"][ui_key].extend(ui_value)
return output
class MTB_SaveTensors:
"""Save torch tensors (image, mask or latent) to disk.
useful to debug things outside comfy.
"""
_processors: dict[type, Processor]
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",),
},
self._condition_processors = {is_condition: self._process_condition}
self._class_name_processors = {
"CLIP": self._process_clip,
"VAE": self._process_vae,
}
self._processors = {
torch.nn.Module: self._process_module,
torch.Tensor: self._process_tensor,
LazyProxyTensor: self._process_repr,
list: self._process_container,
tuple: self._process_container,
dict: self._process_dict,
bool: self._process_bool,
str: self._process_primitive,
int: self._process_primitive,
float: self._process_primitive,
type(None): self._process_primitive,
}
FUNCTION = "save"
OUTPUT_NODE = True
RETURN_TYPES = ()
CATEGORY = "mtb/debug"
# - Dispatchers ------------------------------------------------------------
def _dispatch_processor(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
"""Find and calls the appropriate processor for the given item."""
# first conditions
for c, process in self._condition_processors.items():
if c(item):
return process(item, as_type=as_type, deep=deep)
def save(
# named class
class_name = type(item).__name__
if class_name in self._class_name_processors:
return self._class_name_processors[class_name](
item, as_type=as_type, deep=deep
)
# type based or unknown
processor = self._processors.get(type(item), self._process_unknown)
res = processor(item, as_type=as_type, deep=deep)
return res
def do_debug(
self,
filename_prefix,
image: Optional[torch.Tensor] = None,
mask: Optional[torch.Tensor] = None,
latent: Optional[torch.Tensor] = None,
**kwargs,
):
(
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())
output = {"ui": {"items": []}}
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())
settings = {k: kwargs.pop(k) for k in self.INPUT_TYPES()["optional"]}
output_to_console = kwargs.pop("output_to_console")
as_type = settings.get("as_detailed_types", False)
deep = settings.get("deep_inspect", False)
rich_mode = settings.get("rich_mode", "none")
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"))
for input_name, item in kwargs.items():
processed = self._dispatch_processor(
item, as_type=as_type, deep=deep
)
if processed is None:
continue
# np.save(full_output_folder / latent_file,
# latent[""].cpu().numpy())
if rich_mode != "none":
title = f"{input_name} ({type(item).__name__})"
processed = _apply_rich_results(processed, rich_mode, title)
return f"{filename_prefix}_{counter:05}"
if output_to_console:
log.info(f"- Input '{input_name}':")
for p in processed:
if p["kind"] == "text":
log.info(f" {p['data']}")
if p["kind"] == "b64_image":
log.info(f" (contains {len(p['data'])} images)")
output["ui"]["items"].append(
{"input": input_name, "items": processed}
)
return output
def _process_unknown(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
console = Console(
record=True,
width=120,
)
console.print(f"Generic {type(item).__name__}", emoji=True)
if as_type:
inspect(item, console=console, all=deep, methods=deep, docs=deep)
else:
console.print(item, emoji=True)
text_output = console.export_text(clear=True)
return [UIResult(kind="text", data=text_output.strip())]
def _process_repr(
self, item: Any, as_type=False, deep=False
) -> ProcessorResult:
return [{"kind": "text", "data": item.__repr__()}]
def _process_primitive(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
if as_type:
return self._process_unknown(item, as_type=as_type, deep=deep)
return [UIResult(kind="text", data=str(item))]
def _process_bool(
self, item: bool, *, as_type=False, deep=False
) -> ProcessorResult: # noqa: FBT001
return [{"kind": "text", "data": "True" if item else "False"}]
def _process_clip(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
try:
clip_model = getattr(item, "cond_stage_model", None)
tokenizer = getattr(item, "tokenizer", None)
text = [UIResult(kind="text", data="CLIP")]
if clip_model:
text.append(UIResult(kind="text", data="CLIP Model:"))
model_summary = self._process_module(
clip_model, as_type=as_type
)
if model_summary:
text.extend(indent_results(model_summary, " "))
else:
text.append(
UIResult(
kind="text",
data="[error] failed to get informations about clip model",
)
)
if tokenizer:
text.append(UIResult(kind="text", data="Tokenizer:"))
vocab_size = getattr(tokenizer, "vocab_size", "N/A")
text.append(
UIResult(
kind="text",
data=f" Class: {type(tokenizer).__name__}\n Vocab Size: {vocab_size}",
)
)
return text
except Exception as e:
log.error(f"Failed to process CLIP object: {e}")
return self._process_unknown(item, as_type=as_type, deep=deep)
def _process_condition(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
count = len(item)
result = [UIResult(kind="text", data=f"Conditions: {count}")]
for cond in item:
result.extend(self._preview_conditioning_tensor(cond[0]))
return result
def _process_vae(
self, item: Any, *, as_type=False, deep=False
) -> ProcessorResult:
try:
vae_model = getattr(
item, "first_stage_model", getattr(item, "vae", item)
)
text = [
UIResult(kind="text", data="VAE"),
UIResult(kind="text", data="Internal Model:"),
]
model_summary = self._process_module(
vae_model, as_type=as_type, deep=deep
)
text.extend(indent_results(model_summary, " "))
return text
except Exception as e:
log.error(f"Failed to process VAE object: {e}")
return self._process_unknown(item, as_type=as_type, deep=deep)
def _process_module(
self, item: torch.nn.Module, *, as_type=False, deep=False
) -> ProcessorResult:
if as_type and deep:
return self._process_unknown(item, as_type=as_type, deep=deep)
total_params = sum(p.numel() for p in item.parameters())
trainable_params = sum(
p.numel() for p in item.parameters() if p.requires_grad
)
try:
device = next(item.parameters()).device
except StopIteration:
device = "cpu (no parameters)"
train_percent = (
f"{trainable_params / total_params:.2%}"
if total_params > 0
else "0.00%"
)
text = [
f"Model: {type(item).__name__} on {device}",
textwrap.dedent(f"""
- Parameters: {total_params:,}
- Trainable: {trainable_params:,} ({train_percent})
""").strip(),
]
return [{"kind": "text", "data": d} for d in text]
def _process_tensor(
self, item: torch.Tensor, *, as_type=False, deep=False
) -> ProcessorResult:
is_latent = item.ndim == 4 and item.shape[1] == 4
is_image = (
not is_latent and item.ndim == 4 and item.shape[3] in [1, 3, 4]
)
is_conditioning = item.ndim == 3 and item.shape[2] in [
768,
1024,
1152,
1280,
2048,
4096,
]
is_mask = (item.ndim == 2) or (item.ndim == 3 and not is_conditioning)
if as_type:
type_name = "Unknown Tensor"
if is_latent:
type_name = "Latent Tensor"
elif is_image:
type_name = "Image Tensor"
elif is_conditioning:
type_name = "CLIP Conditioning Tensor"
elif is_mask:
type_name = "Mask Tensor"
return [
{
"kind": "text",
"data": get_torch_tensor_info(item, name=type_name),
}
]
if is_image or is_mask:
return self._render_image_tensor(item)
if is_latent:
return self._preview_latent_tensor(item)
if is_conditioning:
return self._preview_conditioning_tensor(item)
return self._process_unknown(item, as_type=as_type, deep=deep)
def _visualize_tensor_heatmap(
self, tensor_2d: torch.Tensor, title: str
) -> str | None:
if not MATPLOTLIB_AVAILABLE:
log.warning("Matplotlib not found. Skipping tensor visualization.")
return None
if tensor_2d.ndim != 2:
log.warning(
f"Cannot visualize tensor with {tensor_2d.ndim} dimensions. Requires 2."
)
return None
fig, ax = plt.subplots(figsize=(6, 4), dpi=100)
im = ax.imshow(tensor_2d.cpu().numpy(), cmap="viridis", aspect="auto")
fig.colorbar(im, ax=ax)
ax.set_title(title)
fig.tight_layout()
buf = io.BytesIO()
fig.savefig(buf, format="png", bbox_inches="tight", pad_inches=0.1)
plt.close(fig)
buf.seek(0)
return "data:image/png;base64," + base64.b64encode(buf.read()).decode(
"utf-8"
)
def _render_image_tensor(self, item: torch.Tensor) -> ProcessorResult:
is_mask = (item.ndim == 2) or (item.ndim == 3 and item.shape[-1] != 3)
img_tensor = (
item.unsqueeze(0) if item.ndim == 3 and not is_mask else item
)
img_tensor = item.unsqueeze(0) if item.ndim == 2 else img_tensor
images = tensor2pil(img_tensor)
b64_imgs = []
for im in images:
if is_mask:
im = im.convert("L")
buffered = io.BytesIO()
im.save(buffered, format="PNG")
b64_imgs.append(
"data:image/png;base64,"
+ base64.b64encode(buffered.getvalue()).decode("utf-8")
)
return [UIResult(kind="b64_images", data=b64_imgs)]
def _preview_latent_tensor(self, item: torch.Tensor) -> ProcessorResult:
is_empty = "(empty)" if torch.count_nonzero(item) == 0 else ""
stats = [
f"Min: {item.min():.4f}",
f"Max: {item.max():.4f}",
f"Mean: {item.mean():.4f}",
]
text = [
get_torch_tensor_info(item, name="Latent Tensor"),
is_empty,
] + stats
result = [UIResult(kind="text", data=t) for t in text]
vis_tensor = item[0].mean(dim=0)
heatmap_b64 = self._visualize_tensor_heatmap(
vis_tensor, "Latent Energy (Channel Mean)"
)
if heatmap_b64:
result.append(UIResult(kind="b64_images", data=[heatmap_b64]))
return result
def _preview_conditioning_tensor(
self, item: torch.Tensor
) -> ProcessorResult:
_batch, tokens, embed_dim = item.shape
text = [
get_torch_tensor_info(item, name="CLIP Conditioning Tensor"),
f"Token Count: {tokens}",
f"Embedding Dim: {embed_dim}",
]
result = [UIResult(kind="text", data=d) for d in text]
heatmap_b64 = self._visualize_tensor_heatmap(
item[0], "Token Embeddings (approx)"
)
if heatmap_b64:
result.append(UIResult(kind="b64_images", data=[heatmap_b64]))
return result
def _process_container(
self, item: list | tuple, *, as_type=False, deep=False
) -> ProcessorResult:
if not item:
return [UIResult(kind="text", data=f"Empty {type(item).__name__}")]
container_type = type(item).__name__
element_type = type(item[0]).__name__
all_match = all(type(i) is type(item[0]) for i in item)
result = [
UIResult(
kind="text",
data=f"{container_type} of {len(item)} x {element_type}",
),
UIResult(kind="text", data=f"(mixed types: {not all_match})"),
]
if not as_type or (as_type and deep):
for i, sub_item in enumerate(item):
res = self._dispatch_processor(
sub_item, as_type=as_type, deep=deep
)
if res:
text = res[0].get("data", "Unknown")
res[0]["data"] = f"[{i}]: {text}"
result.extend(res)
return result
first_item_result = self._dispatch_processor(
item[0], as_type=as_type, deep=deep
)
if not first_item_result:
return result
return (
result
+ [UIResult(kind="text", data="Preview of first element:")]
+ indent_results(first_item_result, " - ")
)
def _process_dict(
self, item: dict, *, as_type=False, deep=False
) -> ProcessorResult:
if "pooled_output" in item and isinstance(
item["pooled_output"], torch.Tensor
):
return self._dispatch_processor(
item["pooled_output"], as_type=as_type, deep=deep
)
if "samples" in item and isinstance(item.get("samples"), torch.Tensor):
return self._dispatch_processor(
item["samples"], as_type=as_type, deep=deep
)
if "waveform" in item and isinstance(
item.get("waveform"), torch.Tensor
):
waveform = item["waveform"]
is_empty = "(empty) " if torch.count_nonzero(waveform) == 0 else ""
text = textwrap.dedent(f"""
Audio Waveform: {waveform.shape}{is_empty}
Sample Rate: {item.get("sample_rate", "N/A")}
""").strip()
return [{"kind": "text", "data": text}]
log.debug(
f"Processing generic dict with rich inspector: {item.keys()}"
)
return self._process_unknown(item, as_type=as_type, deep=deep)
__nodes__ = [MTB_Debug, MTB_SaveTensors]
__nodes__ = [MTB_Debug]
+25 -4
View File
@@ -2,13 +2,16 @@ import tempfile
from pathlib import Path
import numpy as np
# torch must be imported prior to onnx for the CUDAProvider.
import torch # isort:skip
import onnxruntime as ort
import torch
from PIL import Image
from ..errors import ModelNotFound
from ..log import mklog
from ..utils import (
download_model,
get_model_path,
tensor2pil,
tiles_infer,
@@ -23,7 +26,12 @@ log = mklog(__name__)
# - COLOR to NORMALS
def color_to_normals(
color_img, overlap, progress_callback, *, save_temp=False
color_img,
overlap,
progress_callback,
*,
save_temp=False,
auto_download=False,
):
"""Compute a normal map from the given color map.
@@ -67,7 +75,13 @@ def color_to_normals(
log.debug("DeepBump Color → Normals : loading model")
model = get_model_path("deepbump", "deepbump256.onnx")
if not model or not model.exists():
raise ModelNotFound(f"deepbump ({model})")
if not auto_download:
raise ModelNotFound(f"deepbump ({model})")
log.debug("Downloading models...")
download_model(
"https://github.com/HugoTini/DeepBump/raw/master/deepbump256.onnx",
"deepbump",
)
providers = [
"TensorrtExecutionProvider",
@@ -351,6 +365,9 @@ class MTB_DeepBump:
),
"normals_to_height_seamless": ("BOOLEAN", {"default": True}),
},
"optional": {
"auto_download": ("BOOLEAN", {"default": True}),
},
}
RETURN_TYPES = ("IMAGE",)
@@ -366,6 +383,7 @@ class MTB_DeepBump:
color_to_normals_overlap="SMALL",
normals_to_curvature_blur_radius="SMALL",
normals_to_height_seamless=True,
auto_download=False,
):
images = tensor2pil(image)
out_images = []
@@ -380,7 +398,10 @@ class MTB_DeepBump:
# Apply processing
if mode == "Color to Normals":
out_img = color_to_normals(
in_img, color_to_normals_overlap, None
in_img,
color_to_normals_overlap,
None,
auto_download=auto_download,
)
if mode == "Normals to Curvature":
out_img = normals_to_curvature(
+70
View File
@@ -0,0 +1,70 @@
import folder_paths
import torch
class MTB_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: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
latent: torch.Tensor | None = 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__ = [MTB_SaveTensors]
+7 -4
View File
@@ -4,12 +4,8 @@ import sys
from pathlib import Path
import comfy.model_management as model_management
import cv2
import insightface
import numpy as np
import onnxruntime
import torch
from insightface.model_zoo.inswapper import INSwapper
from PIL import Image
from ..errors import ModelNotFound
@@ -43,6 +39,8 @@ class MTB_LoadFaceAnalysisModel:
DEPRECATED = True
def load_model(self, faceswap_model: str):
import insightface
if faceswap_model == "antelopev2":
download_antelopev2()
@@ -81,6 +79,9 @@ class MTB_LoadFaceSwapModel:
DEPRECATED = True
def load_model(self, faceswap_model: str):
import onnxruntime
from insightface.model_zoo.inswapper import INSwapper
model_path = get_model_path("insightface", faceswap_model)
if not model_path or not model_path.exists():
raise ModelNotFound(f"{faceswap_model} ({model_path})")
@@ -212,6 +213,8 @@ def swap_face(
face_swapper_model,
faces_index: set[int] | None = None,
) -> Image.Image:
import cv2
if faces_index is None:
faces_index = {0}
log.debug(f"Swapping faces: {faces_index}")
+200 -47
View File
@@ -1,8 +1,19 @@
from PIL import Image
import io
import requests
import torch
from PIL import Image, ImageDraw, ImageFont
from ..log import log
from ..utils import comfy_dir, font_path, pil2tensor
# try:
# from cairosvg import svg2png
# HAS_CAIRO = True
# except ImportError:
# HAS_CAIRO = False
# class MtbExamples:
# """MTB Example Images"""
@@ -81,10 +92,6 @@ class MTB_UnsplashImage:
CATEGORY = "mtb/generate"
def do_unsplash_image(self, width, height, random_seed, keyword=None):
import io
import requests
base_url = "https://source.unsplash.com/random/"
if width and height:
@@ -213,17 +220,93 @@ by default it fallsback to a default font.
"INT",
{"default": 100, "min": 1, "max": 100, "step": 1},
),
}
},
"optional": {
"whisper_chunks": ("WHISPER_CHUNKS",),
"fps": (
"INT",
{"default": 24, "min": 1, "max": 60, "step": 1},
),
"fade_duration": (
"FLOAT",
{"default": 0.5, "min": 0.0, "max": 5.0, "step": 0.1},
),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "text_to_image"
CATEGORY = "mtb/generate"
def create_animation_frames(
self,
chunks,
base_image,
font,
font_size,
color,
width,
height,
fps,
fade_duration,
):
"""Create animation frames from Whisper chunks."""
if not chunks or not chunks.get("chunks"):
return [base_image]
frames = []
total_duration = chunks["chunks"][-1]["timestamp"][1]
frame_count = int(total_duration * fps)
fade_frames = int(fade_duration * fps)
for frame_idx in range(frame_count):
time = frame_idx / fps
frame = base_image.copy()
draw = ImageDraw.Draw(frame)
active_chunks = []
for chunk in chunks["chunks"]:
start, end = chunk["timestamp"]
if start <= time <= end:
fade_in_alpha = min(
1.0, (time - start) * fps / fade_frames
)
fade_out_alpha = min(1.0, (end - time) * fps / fade_frames)
alpha = min(fade_in_alpha, fade_out_alpha)
active_chunks.append((chunk["text"], alpha))
y = height // 4
for text, alpha in active_chunks:
# Create a temporary image for the text with alpha
text_img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
text_draw = ImageDraw.Draw(text_img)
text_draw.text(
(width // 2, y),
text,
font=font,
fill=color,
anchor="mm",
)
text_img.putalpha(
Image.fromarray(
(torch.ones((height, width)) * (alpha * 255))
.byte()
.numpy()
)
)
frame = Image.alpha_composite(frame, text_img)
y += font_size * 1.5
frames.append(frame)
return frames
def text_to_image(
self,
text: str,
text: str | list[str],
font,
wrap,
trim,
@@ -238,58 +321,128 @@ by default it fallsback to a default font.
h_offset=0,
v_offset=0,
h_coverage=100,
whisper_chunks=None,
fps=24,
fade_duration=0.5,
):
"""Convert text to image, with optional animation support."""
import textwrap
from PIL import Image, ImageDraw, ImageFont
from PIL import ImageColor
font_path = self.fonts[font]
text = (
text.encode("ascii", "ignore").decode().strip() if trim else text
)
# Handle word wrapping
if wrap:
wrap_width = (((width / 100) * h_coverage) / font_size) * 2
lines = textwrap.wrap(text, width=wrap_width)
else:
lines = [text]
font = ImageFont.truetype(font_path, size=font_size)
log.debug(f"Lines: {lines}")
img = Image.new("RGBA", (width, height), background)
draw = ImageDraw.Draw(img)
line_height_px = line_height * font_size
try:
if isinstance(color, str):
color = ImageColor.getrgb(color)
if isinstance(background, str):
background = ImageColor.getrgb(background)
# Vertical alignment
if v_align == "top":
y_text = v_offset
elif v_align == "center":
y_text = ((height - (line_height_px * len(lines))) // 2) + v_offset
else: # bottom
y_text = (height - (line_height_px * len(lines))) - v_offset
if len(color) == 3:
color = color + (255,)
if len(background) == 3:
background = background + (255,)
except ValueError as e:
log.error(f"Color parsing error: {e}")
color = (255, 255, 255, 255)
background = (0, 0, 0, 255)
def get_width(line):
if hasattr(font, "getsize"):
return font.getsize(line)[0]
def render_text(text_to_render: str, alpha=None) -> Image.Image:
if trim:
text_to_render = text_to_render.strip()
if wrap:
wrap_width = (((width / 100) * h_coverage) / font_size) * 2
lines = textwrap.wrap(text_to_render, width=wrap_width)
else:
return font.getlength(line)
lines = [text_to_render]
# Draw each line of text
for line in lines:
line_width = get_width(line)
# Horizontal alignment
if h_align == "left":
x_text = h_offset
elif h_align == "center":
x_text = ((width - line_width) // 2) + h_offset
else: # right
x_text = (width - line_width) - h_offset
img = Image.new("RGBA", (width, height), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
draw.text((x_text, y_text), line, fill=color, font=font)
y_text += line_height_px
line_height_px = line_height * font_size
return (pil2tensor(img),)
if v_align == "top":
y_text = v_offset
elif v_align == "center":
y_text = (
(height - (line_height_px * len(lines))) // 2
) + v_offset
else:
y_text = (height - (line_height_px * len(lines))) - v_offset
def get_width(line):
if hasattr(font, "getsize"):
return font.getsize(line)[0]
else:
return font.getlength(line)
for line in lines:
line_width = get_width(line)
if h_align == "left":
x_text = h_offset
elif h_align == "center":
x_text = ((width - line_width) // 2) + h_offset
else:
x_text = (width - line_width) - h_offset
text_color = color
if alpha is not None:
text_color = tuple(
list(color[:3]) + [int(alpha * color[3])]
)
draw.text((x_text, y_text), line, fill=text_color, font=font)
y_text += line_height_px
return img
base_img = Image.new("RGBA", (width, height), background)
if whisper_chunks and whisper_chunks.get("chunks"):
frames = []
total_duration = whisper_chunks["chunks"][-1]["timestamp"][1]
frame_count = int(total_duration * fps)
fade_frames = int(fade_duration * fps)
for frame_idx in range(frame_count):
time = frame_idx / fps
frame = base_img.copy()
active_chunks = []
for chunk in whisper_chunks["chunks"]:
start, end = chunk["timestamp"]
if start <= time <= end:
fade_in_alpha = min(
1.0, (time - start) * fps / fade_frames
)
fade_out_alpha = min(
1.0, (end - time) * fps / fade_frames
)
alpha = min(fade_in_alpha, fade_out_alpha)
active_chunks.append((chunk["text"], alpha))
for chunk_text, alpha in active_chunks:
chunk_img = render_text(
chunk_text.encode("ascii", "ignore").decode(), alpha
)
frame = Image.alpha_composite(frame, chunk_img)
frames.append(frame)
frame_tensors = [pil2tensor(frame) for frame in frames]
return (torch.cat(frame_tensors, dim=0),)
else:
results = []
if not isinstance(text, list):
text = [text]
for t in text:
text_img = render_text(t)
result = Image.alpha_composite(base_img, text_img)
results.append(result)
return (pil2tensor(results),)
__nodes__ = [
+396 -20
View File
@@ -1,20 +1,25 @@
import io
import json
import re
import urllib.parse
import urllib.request
from math import pi
from typing import Any
import comfy.model_management as model_management
import comfy.model_management as mm
import comfy.utils
import numpy as np
import torch
from comfy.comfy_types.node_typing import IO as CIO
from PIL import Image
from ..log import log
from ..utils import (
EASINGS,
LazyProxyTensor,
apply_easing,
get_server_info,
get_torch_tensor_info,
numpy_NFOV,
pil2tensor,
tensor2np,
@@ -44,14 +49,22 @@ class MTB_ToDevice:
if torch.backends.mps.is_available():
devices.append("mps")
if torch.cuda.is_available():
devices.append("cuda:0")
for i in range(1, torch.cuda.device_count()):
devices.append(f"cuda:{i}")
devices.append("cuda")
for i in range(torch.cuda.device_count()):
devices.append(f"cuda{i}")
return {
"required": {
"ignore_errors": ("BOOLEAN", {"default": False}),
"device": (devices, {"default": "cpu"}),
"device": (
devices,
{
"default": "cuda"
if torch.cuda.is_available()
else "cpu"
},
),
},
"optional": {
"image": ("IMAGE",),
@@ -67,20 +80,36 @@ class MTB_ToDevice:
def to_device(
self,
*,
ignore_errors=False,
device="cuda",
ignore_errors: bool = False,
device: str = "cuda",
image: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
):
if not ignore_errors and image is None and mask is None:
raise ValueError(
"You must either provide an image or a mask,"
" use ignore_error to passthrough"
+ " use ignore_error to passthrough"
)
if (
device.startswith("cuda")
and ":" not in device
and device != "cuda"
):
device = f"cuda:{device[4:]}"
try:
if image is not None:
image = image.to(device)
if mask is not None:
mask = mask.to(device)
except RuntimeError as e:
if not ignore_errors:
raise RuntimeError(
f"Failed to move tensor to device {device}: {str(e)}"
) from e
log.warning(
f"Failed to move tensor to device {device}, ignoring: {str(e)}"
)
if image is not None:
image = image.to(device)
if mask is not None:
mask = mask.to(device)
return (image, mask)
@@ -107,12 +136,64 @@ class MTB_ApplyTextTemplate:
CATEGORY = "mtb/utils"
FUNCTION = "execute"
def execute(self, *, template: str, **kwargs):
res = f"{template}"
for k, v in kwargs.items():
res = res.replace(f"{{{k}}}", f"{v}")
def execute(self, *, template: str, **kwargs) -> tuple[str | list[str]]:
keys = list(kwargs.keys())
values = list(kwargs.values())
return (res,)
has_list = any(isinstance(v, list) for v in values)
target_length = -1
if has_list:
first_list = next(x for x in values if isinstance(x, list))
# all_list = all(isinstance(x, list) for x in kwargs.values())
# if not all_list:
# raise ValueError(
# "Text template supports either str or list[str] but not a mix of the two (yet?)"
# )
target_length = len(first_list)
same_length = all(
len(v) == target_length for v in values if isinstance(v, list)
)
if not same_length:
raise ValueError(
"Text template received multiple list[str] but their size is varying, they should match..."
)
if has_list:
results = []
# do a padded loop, not the most efficient but easy
# to handle for now
for it in range(target_length):
res = f"{template}"
for k, v in kwargs.items():
if isinstance(v, list):
res = self.apply_res(res, k, v[it])
else:
res = self.apply_res(res, k, v)
results.append(res)
return (results,)
else:
res = f"{template}"
for k, v in kwargs.items():
res = self.apply_res(res, k, v)
return (res,)
def apply_res(self, res, key, value):
if isinstance(value, float):
value = f"{value:.3f}"
elif isinstance(value, torch.Tensor):
value = get_torch_tensor_info(value)
else:
log.debug(
f"Falling back to default string conversion for {key} of type {type(value).__name__}"
)
return res.replace(f"{{{key}}}", f"{value}")
class MTB_MatchDimensions:
@@ -316,7 +397,7 @@ class MTB_AutoPanEquilateral:
frames.append(frame)
model_management.throw_exception_if_processing_interrupted()
mm.throw_exception_if_processing_interrupted()
pbar.update(1)
return (pil2tensor(frames),)
@@ -447,7 +528,7 @@ class MTB_AnyToString:
class MTB_StringReplace:
"""Basic string replacement."""
"""Basic string replacement with regex support."""
@classmethod
def INPUT_TYPES(cls):
@@ -456,6 +537,7 @@ class MTB_StringReplace:
"string": ("STRING", {"forceInput": True}),
"old": ("STRING", {"default": ""}),
"new": ("STRING", {"default": ""}),
"use_regex": ("BOOLEAN", {"default": False}),
}
}
@@ -463,12 +545,19 @@ class MTB_StringReplace:
RETURN_TYPES = ("STRING",)
CATEGORY = "mtb/string"
def replace_str(self, string: str, old: str, new: str):
def replace_str(self, string: str, old: str, new: str, use_regex: bool):
log.debug(f"Current string: {string}")
log.debug(f"Find string: {old}")
log.debug(f"Replace string: {new}")
log.debug(f"Use regex: {use_regex}")
string = string.replace(old, new)
if use_regex:
try:
string = re.sub(old, new, string)
except re.error as e:
raise ValueError(f"Regex error: {e}") from e
else:
string = string.replace(old, new)
log.debug(f"New string: {string}")
@@ -653,6 +742,289 @@ class MTB_ConcatImages:
return (concatenated,)
class MTB_TensorOps:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"tensor": ("IMAGE",),
"operation": (
[
"multiply",
"divide",
"add",
"subtract",
"power",
"clamp",
"abs",
"log",
"exp",
"convert_dtype",
"normalize_range",
"normalize_per_channel",
],
{"default": "multiply"},
),
"value": (
"FLOAT",
{
"default": 1.0,
"min": -1000000.0,
"max": 1000000.0,
"step": 0.01,
},
),
"source_min": (
"FLOAT",
{
"default": 0.0,
"min": -1000000.0,
"max": 1000000.0,
"step": 0.01,
},
),
"source_max": (
"FLOAT",
{
"default": 1.0,
"min": -1000000.0,
"max": 1000000.0,
"step": 0.01,
},
),
"target_min": (
"FLOAT",
{
"default": 0.0,
"min": -1000000.0,
"max": 1000000.0,
"step": 0.01,
},
),
"target_max": (
"FLOAT",
{
"default": 16.0,
"min": -1000000.0,
"max": 1000000.0,
"step": 0.01,
},
),
"dtype": (
["uint8", "float32", "float16", "bfloat16"],
{"default": "float32"},
),
"use_mean": ("BOOLEAN", {"default": False}),
},
"optional": {
"target_tensor": ("IMAGE",),
},
}
RETURN_TYPES = ("IMAGE",)
FUNCTION = "apply"
CATEGORY = "mtb/tensor_ops"
def apply(
self,
tensor,
operation="multiply",
value=1.0,
source_min=0.0,
source_max=1.0,
target_min=0.0,
target_max=1.0,
dtype="float32",
use_mean=False,
target_tensor=None,
):
log.debug(
f"Input tensor stats: shape={tensor.shape}, dtype={tensor.dtype}, range=[{tensor.min().item():.6f}, {tensor.max().item():.6f}]"
)
if operation == "normalize_per_channel":
if target_tensor is None:
raise ValueError(
"Target tensor required for per-channel normalization"
)
result = tensor.clone()
for c in range(tensor.shape[-1]):
if use_mean:
source_mean = tensor[..., c].mean()
target_mean = target_tensor[..., c].mean()
scale = target_mean / source_mean
result[..., c] = tensor[..., c] * scale
else:
source_min = tensor[..., c].min()
source_max = tensor[..., c].max()
target_min = target_tensor[..., c].min()
target_max = target_tensor[..., c].max()
normalized = (tensor[..., c] - source_min) / (
source_max - source_min
)
result[..., c] = (
normalized * (target_max - target_min) + target_min
)
log.debug(
f"Channel {c} - Scale: source=[{source_min:.6f}, {source_max:.6f}], target=[{target_min:.6f}, {target_max:.6f}]"
)
elif operation == "normalize_range":
if target_tensor is not None:
target_min = target_tensor.min().item()
target_max = target_tensor.max().item()
log.debug(
f"Using target tensor range: [{target_min:.6f}, {target_max:.6f}]"
)
normalized = (tensor - source_min) / (source_max - source_min)
result = normalized * (target_max - target_min) + target_min
elif operation == "convert_dtype":
if dtype == "float32":
result = tensor.float()
elif dtype == "float16":
result = tensor.half()
elif dtype == "bfloat16":
result = tensor.bfloat16()
else:
result = tensor
if operation == "multiply":
result = tensor * value
elif operation == "divide":
result = tensor / value if value != 0 else tensor
elif operation == "add":
result = tensor + value
elif operation == "subtract":
result = tensor - value
elif operation == "power":
result = torch.pow(tensor, value)
elif operation == "clamp":
if target_tensor is not None:
result = torch.clamp(
tensor,
target_tensor.min().item(),
target_tensor.max().item(),
)
else:
result = torch.clamp(tensor, source_min, source_max)
elif operation == "abs":
result = torch.abs(tensor)
elif operation == "log":
result = torch.log(tensor.clamp(min=1e-10))
elif operation == "exp":
result = torch.exp(tensor)
log.debug(
f"Output tensor stats: shape={result.shape}, dtype={result.dtype}, range=[{result.min().item():.6f}, {result.max().item():.6f}]"
)
return (result,)
class MTB_GetItem:
"""Generic index based getter for common types"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"container": (CIO.ANY,),
"index": ("INT", {"default": 0}),
}
}
RETURN_TYPES = (CIO.ANY,)
RETURN_NAMES = ("item",)
FUNCTION = "get_item"
CATEGORY = "mtb/utils"
def get_item(self, container: Any, index: int):
if "__getitem__" in dir(container):
log.debug(f"Container is {type(container)}")
res = container[index]
if type(res) is torch.Tensor:
res = res.unsqueeze(0)
return (res,)
class MTB_BooleanNot:
"""Inverts a boolean."""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"bool_in": ("BOOLEAN", {"default": False}),
},
}
RETURN_TYPES = ("BOOLEAN",)
RETURN_NAMES = ("inverted_bool",)
FUNCTION = "invert"
CATEGORY = "mtb/utils"
def invert(self, bool_in: bool):
return (not bool_in,)
class MTB_ProxyTensor:
"""Wraps an input tensor into a LazyProxyTensor.
builds upon an idea by @AustinMroz
"""
NODE_NAME = "ProxyTensor"
NODE_DISPLAY_NAME = "Proxy Tensor"
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"tensor": ("IMAGE",),
"target_dtype": (
["float32", "float16", "bfloat16"],
{"default": "float32"},
),
"target_device": (
["keep", "cpu", "gpu"],
{
"default": "keep",
"tooltip": "CAUTION: This isn't compatible with most nodes for now",
},
),
}
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("proxy_tensor",)
FUNCTION = "execute"
CATEGORY = "mtb/utils"
def execute(
self,
tensor: torch.Tensor,
target_dtype: str = "float32",
target_device: str = "keep",
):
torch_dtype: torch.dtype = getattr(torch, target_dtype)
if target_device == "gpu":
torch_device = mm.get_torch_device()
elif target_device == "cpu":
torch_device = torch.device("cpu")
else:
torch_device = tensor.device
proxy = LazyProxyTensor(tensor, torch_dtype, torch_device)
log.info(f"Created Proxy Tensor: \n{proxy}")
return (proxy,)
__nodes__ = [
MTB_StringReplace,
MTB_FitNumber,
@@ -667,4 +1039,8 @@ __nodes__ = [
MTB_FloatsToFloat,
MTB_FloatToFloats,
MTB_FloatsToInts,
MTB_TensorOps,
MTB_BooleanNot,
MTB_GetItem,
MTB_ProxyTensor,
]
+104 -48
View File
@@ -3,11 +3,12 @@ import json
import math
import os
import comfy.model_management as model_management
import comfy.utils
import folder_paths
import numpy as np
import torch
import torch.nn.functional as F
from comfy import model_management
from PIL import Image, ImageOps
from PIL.PngImagePlugin import PngInfo
from skimage.filters import gaussian
@@ -74,7 +75,10 @@ class MTB_ExtractCoordinatesFromImage:
def INPUT_TYPES(cls):
return {
"required": {
"threshold": ("FLOAT",),
"threshold": (
"FLOAT",
{"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01},
),
"max_points": ("INT", {"default": 50, "min": 0}),
},
"optional": {"image": ("IMAGE",), "mask": ("MASK",)},
@@ -87,72 +91,124 @@ class MTB_ExtractCoordinatesFromImage:
image: torch.Tensor | None = None,
mask: torch.Tensor | None = None,
) -> tuple[list[list[tuple[int, int]]], torch.Tensor]:
if image is not None:
batch_count, height, width, channel_count = image.shape
imgs = image
else:
if mask is None:
raise ValueError("Must provide either image or mask")
batch_count, height, width = mask.shape
channel_count = 1
imgs = mask
if image is None and mask is None:
raise ValueError("Must provide either image or mask")
if channel_count not in [1, 2, 3, 4]:
raise ValueError(f"Incorrect channel count: {channel_count}")
if image is not None:
batch_count, height, width, _channel_count = image.shape
input_device = image.device
if mask is not None:
if mask.ndim == 2:
mask = mask.unsqueeze(0)
if mask.ndim != 3:
raise ValueError(
f"Mask has unexpected ndim: {mask.ndim}. Expected 2 or 3."
)
b_mask, h_mask, w_mask = mask.shape
if not (h_mask == height and w_mask == width):
raise ValueError(
f"Image dimensions ({height}x{width}) and mask dimensions ({h_mask}x{w_mask}) are spatially incompatible."
)
if b_mask == 1 and batch_count > 1:
mask = mask.expand(batch_count, height, width)
elif b_mask != batch_count:
raise ValueError(
f"Image batch size ({batch_count}) and mask batch size ({b_mask}) are incompatible and mask cannot be broadcast."
)
else:
if mask.ndim == 2:
mask = mask.unsqueeze(0)
if mask.ndim != 3:
raise ValueError(
f"Mask has unexpected ndim: {mask.ndim} when image is not provided. Expected 2 or 3."
)
batch_count, height, width = mask.shape
input_device = mask.device
all_points: list[list[tuple[int, int]]] = []
debug_images = torch.zeros(
(batch_count, height, width, 3),
dtype=torch.uint8,
device=imgs.device,
device=input_device,
)
for i, img in enumerate(imgs):
if channel_count == 1:
alpha_channel = img if len(img.shape) == 2 else img[:, :, 0]
elif channel_count == 2:
alpha_channel = img[:, :, 1]
elif channel_count == 4:
alpha_channel = img[:, :, 3]
points_tensor = torch.tensor(
[255, 255, 255], dtype=torch.uint8, device=input_device
)
for i in range(batch_count):
value_threshold: torch.Tensor
if image is not None:
img_slice = image[i]
img_channels = img_slice.shape[2]
if img_channels == 1 or img_channels == 2:
value_threshold = img_slice[:, :, 0]
elif img_channels == 3 or img_channels == 4:
value_threshold = img_slice[:, :, :3].max(dim=2)[0]
else:
raise ValueError(
f"Unsupported image channel count: {img_channels} for image at batch index {i}"
)
else:
# get intensity
alpha_channel = img[:, :, :3].max(dim=2)[0]
mask_slice = mask[i]
value_threshold = mask_slice
points = (alpha_channel > threshold).nonzero(as_tuple=False)
condition = value_threshold > threshold
if image is not None and mask is not None:
mask_slice = mask[i]
mask_active_condition = mask_slice > 0.0
condition = condition & mask_active_condition
if len(points) > max_points:
indices = torch.randperm(points.size(0), device=img.device)[
:max_points
]
points = points[indices]
points_yx = condition.nonzero(as_tuple=False)
points = [(int(y.item()), int(x.item())) for x, y in points]
all_points.append(points)
if points_yx.size(0) > max_points:
# shuffle and pick max_points randomly
indices = torch.randperm(
points_yx.size(0), device=input_device
)[:max_points]
points_yx = points_yx[indices]
elif max_points == 0:
points_yx = torch.empty(
(0, 2), dtype=torch.long, device=input_device
)
for x, y in points:
self._draw_circle(debug_images[i], (x, y), 5)
current_points = [
(int(p[1].item()), int(p[0].item())) for p in points_yx
]
all_points.append(current_points)
for x_coord, y_coord in current_points:
self._draw_circle(
debug_images[i],
(x_coord, y_coord),
radius=5,
color_tensor=points_tensor,
)
return (all_points, debug_images)
@staticmethod
def _draw_circle(
image: torch.Tensor, center: tuple[int, int], radius: int
image: torch.Tensor,
center: tuple[int, int],
radius: int,
color_tensor: torch.Tensor,
):
"""Draw a 5px circle on the image."""
x0, y0 = center
for x in range(-radius, radius + 1):
for y in range(-radius, radius + 1):
in_radius = x**2 + y**2 <= radius**2
in_bounds = (
0 <= x0 + x < image.shape[1]
and 0 <= y0 + y < image.shape[0]
)
if in_radius and in_bounds:
image[y0 + y, x0 + x] = torch.tensor(
[255, 255, 255],
dtype=torch.uint8,
device=image.device,
)
h, w, _ = image.shape
min_x_bbox = max(0, x0 - radius)
max_x_bbox = min(w - 1, x0 + radius)
min_y_bbox = max(0, y0 - radius)
max_y_bbox = min(h - 1, y0 + radius)
for py in range(min_y_bbox, max_y_bbox + 1):
for px in range(min_x_bbox, max_x_bbox + 1):
if (px - x0) ** 2 + (py - y0) ** 2 <= radius**2:
image[py, px] = color_tensor
class MTB_ColorCorrectGPU:
@@ -543,7 +599,7 @@ class MTB_ColorCorrect:
adjusted = self.hsv_adjustment(adjusted, hue, saturation, value)
if clamp:
adjusted = torch.clamp(image, 0.0, 1.0)
adjusted = torch.clamp(adjusted, 0.0, 1.0)
result = (
adjusted
+27 -7
View File
@@ -21,7 +21,11 @@ class MTB_StackImages:
"match_method": (
["error", "smallest", "largest"],
{"default": "error"},
)
),
"output_rgb": (
"BOOLEAN",
{"default": True, "tooltip": "Output RGB instead of RGBA"},
),
},
}
@@ -29,7 +33,7 @@ class MTB_StackImages:
FUNCTION = "stack"
CATEGORY = "mtb/image utils"
def stack(self, vertical, match_method="error", **kwargs):
def stack(self, vertical, match_method="error", output_rgb=True, **kwargs):
if not kwargs:
raise ValueError("At least one tensor must be provided.")
@@ -39,9 +43,13 @@ class MTB_StackImages:
f"{'vertically' if vertical else 'horizontally'}"
)
target_device = tensors[0].device
normalized_tensors = [
self.normalize_to_rgba(tensor) for tensor in tensors
self.normalize_to_rgba(tensor.to(target_device))
for tensor in tensors
]
max_batch_size = max(tensor.shape[0] for tensor in normalized_tensors)
normalized_tensors = [
self.duplicate_frames(tensor, max_batch_size)
@@ -94,6 +102,9 @@ class MTB_StackImages:
stacked_tensor = torch.cat(normalized_tensors, dim=dim)
if output_rgb:
stacked_tensor = stacked_tensor[:, :, :, :3]
return (stacked_tensor,)
def normalize_to_rgba(self, tensor):
@@ -167,25 +178,34 @@ class MTB_PickFromBatch:
"image": ("IMAGE",),
"from_direction": (["end", "start"], {"default": "start"}),
"count": ("INT", {"default": 1}),
}
},
"optional": {
"mask": ("MASK",),
},
}
RETURN_TYPES = ("IMAGE",)
RETURN_TYPES = ("IMAGE", "MASK")
FUNCTION = "pick_from_batch"
CATEGORY = "mtb/image utils"
def pick_from_batch(self, image, from_direction, count):
def pick_from_batch(self, image, from_direction, count, mask=None):
batch_size = image.size(0)
# Limit count to the available number of images in the batch
count = min(count, batch_size)
selected_masks = None
if from_direction == "end":
selected_tensors = image[-count:]
if mask is not None:
selected_masks = mask[-count:]
else:
selected_tensors = image[:count]
if mask is not None:
selected_masks = mask[:count]
return (selected_tensors,)
return (selected_tensors, selected_masks)
import folder_paths
+67 -16
View File
@@ -57,6 +57,21 @@ class MTB_TransformImage:
],
{"default": "bilinear"},
),
"stretch_x": (
"FLOAT",
{"default": 1.0, "min": 0.001, "max": 10.0, "step": 0.01},
),
"stretch_y": (
"FLOAT",
{"default": 1.0, "min": 0.001, "max": 10.0, "step": 0.01},
),
"use_normalized": (
"BOOLEAN",
{
"default": False,
"tooltip": "If true, transform values are scaled to image dimensions.",
},
),
},
}
@@ -75,6 +90,9 @@ class MTB_TransformImage:
border_handling="edge",
constant_color=None,
filter_type="nearest",
stretch_x=1.0,
stretch_y=1.0,
use_normalized: bool = False,
):
filter_map = {
"nearest": Image.NEAREST,
@@ -86,20 +104,21 @@ class MTB_TransformImage:
}
resampling_filter = filter_map[filter_type]
_, frame_height, frame_width, _ = image.size()
if use_normalized:
x = float(x) * frame_width
y = float(y) * frame_height
x = int(x)
y = int(y)
angle = int(angle)
log.debug(
f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}"
f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear} | stretch_x: {stretch_x}, stretch_y: {stretch_y}"
)
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),
@@ -130,23 +149,55 @@ class MTB_TransformImage:
for img in tensor2pil(image):
img = TF.pad(
img, # transformed_frame,
img,
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,
interpolation=resampling_filter,
),
)
if stretch_x != 1.0 or stretch_y != 1.0:
img = cast(
Image.Image,
TF.affine(
img,
angle=angle,
scale=zoom,
translate=[x, y],
shear=shear,
interpolation=resampling_filter,
),
)
width, height = img.size
center = (width // 2, height // 2)
stretch_x_factor = 1.0 / stretch_x
stretch_y_factor = 1.0 / stretch_y
matrix = [
stretch_x_factor,
0,
center[0] - center[0] * stretch_x_factor,
0,
stretch_y_factor,
center[1] - center[1] * stretch_y_factor,
]
img = img.transform(
img.size, Image.AFFINE, matrix, resampling_filter
)
else:
img = cast(
Image.Image,
TF.affine(
img,
angle=angle,
scale=zoom,
translate=[x, y],
shear=shear,
interpolation=resampling_filter,
),
)
left = abs(padding[0])
upper = abs(padding[1])
+11 -43
View File
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
[project]
name = "comfy-mtb"
version = "0.2.0"
version = "0.6.0"
description = "Animation oriented nodes pack for ComfyUI."
license = "MIT"
license = { text = "MIT" }
readme = "README.md"
# repository = ""
# url = "https://github.com/melMass/comfy_mtb"
@@ -62,39 +62,6 @@ PublisherId = "mel"
DisplayName = "comfy-mtb"
Icon = "https://avatars.githubusercontent.com/u/7041726?v=4"
[tool.bumpversion]
current_version = "0.2.0"
parse = "(?P<major>\\d+)\\.(?P<minor>\\d+)\\.(?P<patch>\\d+)"
serialize = ["{major}.{minor}.{patch}"]
search = "{current_version}"
replace = "{new_version}"
regex = false
ignore_missing_version = false
ignore_missing_files = false
tag = true
sign_tags = true
tag_name = "v{new_version}"
tag_message = "⬆️ Bump version: {current_version} → {new_version}"
allow_dirty = true
commit = true
message = "⬆️ Bump version: {current_version} → {new_version}"
commit_args = ""
[[tool.bumpversion.files]]
filename = "__init__.py"
search = "__version__ = \"{current_version}\""
replace = "__version__ = \"{new_version}\""
[[tool.bumpversion.files]]
filename = "pyproject.toml"
search = "version = \"{current_version}\""
replace = "version = \"{new_version}\""
# [[tool.bumpversion.files]]
# filename = "your_package/__init__.py"
# search = "__version__ = '{current_version}'"
# replace = "__version__ = '{new_version}'"
# INFO: All those remaining keys are meant for local dev
[tool.pyright]
include = ["."]
@@ -111,18 +78,18 @@ stubPath = "src/stubs"
reportMissingImports = true
reportMissingTypeStubs = false
reportExplicitAny = false
typeCheckingMode = "basic"
pythonVersion = "3.10"
pythonVersion = "3.11"
pythonPlatform = "Windows"
[tool.pytest.ini_options]
log_level = "DEBUG"
log_cli = true
markers = [
"wip: tests that aren't fully finished yet",
"heavy: marks tests as heavy (deselect with '-m \"not heavy\"')",
'''heavy: marks tests as heavy (deselect with '-m "not heavy"')''',
]
filterwarnings = ["ignore::UserWarning", 'ignore::DeprecationWarning']
@@ -150,6 +117,9 @@ show_contexts = true
[tool.ruff]
line-length = 79
extend-exclude = ["./docs/conf.py", "notebooks", "stubs"]
[tool.ruff.lint]
select = ["A", "B", "C", "D", "E", "F", "FBT", "I", "N", "S", "SIM", "UP", "W"]
# NOTE:
# D102 - undocumented-public-method (noisy)
@@ -157,16 +127,14 @@ select = ["A", "B", "C", "D", "E", "F", "FBT", "I", "N", "S", "SIM", "UP", "W"]
# D100 - undocumented-public-module (noisy)
# N802 - invalid-function-name (forced by comfy's arch)
ignore = ["D103", "D102", "D100", "N802"]
# exclude auto generated file
extend-exclude = ["./docs/conf.py"]
[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
# imported but unused
"__init__.py" = ["F401"]
# use of assert detected
"tests/*" = ["S101"]
[tool.ruff.pydocstyle]
[tool.ruff.lint.pydocstyle]
convention = "numpy"
[tool.mypy]
-18
View File
@@ -1,18 +0,0 @@
{
"exclude": [
"**/node_modules",
"**/__pycache__",
],
"ignore": [
"extern"
],
"defineConstant": {
"DEBUG": true
},
"venvPath": "../../../.venv/",
"reportMissingImports": true,
"reportMissingTypeStubs": false,
"pythonVersion": "3.10",
"pythonPlatform": "All",
"reportOptionalMemberAccess": "none"
}
+637
View File
@@ -0,0 +1,637 @@
import base64
import code
import io
import re
import sys
from contextlib import redirect_stderr, redirect_stdout
# import matplotlib.pyplot as plt
import numpy as np
import torch
from aiohttp import web
from PIL import Image
from rich.console import Console
from rich.traceback import Traceback
from .log import log
try:
import pyflakes.api
import pyflakes.reporter
_HAS_LINT = True
except ImportError:
print(
"ComfyREPL: pyflakes not found. Linting will be disabled. Install with 'pip install pyflakes'."
)
_HAS_LINT = False
# --- Linting Library ---
# try:
# import ruff
# import ruff.lint
# import ruff.lint.linter
# import ruff.settings
#
# _HAS_LINT = True
# except ImportError:
# print(
# "ComfyREPL: ruff not found. Linting will be disabled. Install with 'pip install ruff'."
# )
# _HAS_LINT = False
# --- Audio/Video Libraries ---
try:
import scipy.io.wavfile
_HAS_SCIPY = True
except ImportError:
print(
"ComfyREPL: SciPy not found. Audio display will be disabled. Install with 'pip install scipy'."
)
_HAS_SCIPY = False
try:
import imageio
import imageio.plugins.ffmpeg # Ensure ffmpeg plugin is available
_HAS_IMAGEIO = True
except ImportError:
print(
"ComfyREPL: Imageio or imageio-ffmpeg not found. Video display will be disabled. Install with 'pip install imageio imageio-ffmpeg'."
)
_HAS_IMAGEIO = False
# --- Audio Display ---
class AudioDisplay:
def __init__(self, samples, sample_rate):
if not _HAS_SCIPY:
raise ImportError("Audio display requires scipy and numpy.")
if not isinstance(samples, (np.ndarray, torch.Tensor)):
raise TypeError(
"Audio samples must be a numpy array or torch tensor."
)
if isinstance(samples, torch.Tensor):
samples = samples.detach().cpu().numpy()
# Ensure samples are in a format scipy.io.wavfile can handle (e.g., int16, float32)
if samples.dtype == np.float64:
samples = samples.astype(np.float32)
elif samples.dtype == np.int64:
# Or scale to int32 if range requires
samples = samples.astype(np.int16)
self.samples = samples
self.sample_rate = sample_rate
def _to_wav_base64(self):
buffer = io.BytesIO()
try:
scipy.io.wavfile.write(buffer, self.sample_rate, self.samples)
audio_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
return audio_base64
except Exception as e:
return f"<div style='color: red;'>Error encoding audio: {e}</div>"
def _repr_html_(self):
base64_data = self._to_wav_base64()
if base64_data.startswith("<div"):
return base64_data
return f'<audio controls src="data:audio/wav;base64,{base64_data}" style="margin: 5px 0;"/>'
def render_audio(samples, sample_rate):
"""
Render audio samples as an HTML audio player.
Args:
samples (np.ndarray or torch.Tensor): Audio samples.
sample_rate (int): Sample rate in Hz.
Returns
-------
AudioDisplay: An object that will render as an HTML audio player.
"""
return AudioDisplay(samples, sample_rate)
# --- Display Classes ---
class VideoDisplay:
def __init__(self, frames, fps=24, options=None):
if not _HAS_IMAGEIO: # numpy/PIL/torch needed for frames
raise ImportError(
"Video display requires imageio, imageio-ffmpeg, and image libraries (numpy, Pillow, torch)."
)
self.frames = []
for frame in frames:
if isinstance(frame, Image.Image):
self.frames.append(np.array(frame))
elif isinstance(frame, np.ndarray):
# Ensure HWC and uint8
if frame.ndim == 3 and frame.shape[0] in [1, 3, 4]: # CHW
frame = np.transpose(frame, (1, 2, 0))
if frame.dtype != np.uint8:
frame = (
(frame * 255).astype(np.uint8)
if frame.max() <= 1.0
else frame.astype(np.uint8)
)
self.frames.append(frame)
elif isinstance(frame, torch.Tensor):
np_frame = frame.detach().cpu().numpy()
if np_frame.ndim == 3 and np_frame.shape[0] in [
1,
3,
4,
]: # CHW
np_frame = np.transpose(np_frame, (1, 2, 0))
if np_frame.dtype != np.uint8:
np_frame = (
(np_frame * 255).astype(np.uint8)
if np_frame.max() <= 1.0
else np_frame.astype(np.uint8)
)
self.frames.append(np_frame)
else:
raise TypeError(
f"Unsupported frame type: {type(frame)}. Must be PIL.Image, numpy.ndarray, or torch.Tensor."
)
self.fps = fps
self.options = options if options is not None else {}
def _to_mp4_base64(self):
buffer = io.BytesIO()
try:
# Use imageio to write frames to an in-memory MP4 file
imageio.mimwrite(
buffer,
self.frames,
format="mp4",
fps=self.fps,
codec="libx264",
quality=8,
) # quality 1-10
video_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
return video_base64
except Exception as e:
return f"<div style='color: red;'>Error encoding video: {e}</div>"
def _repr_html_(self):
base64_data = self._to_mp4_base64()
if base64_data.startswith("<div"): # Check if it's an error message
return base64_data
# Build HTML options string
option_str = ""
for key, value in self.options.items():
if isinstance(value, bool) and value:
option_str += f" {key}"
elif isinstance(value, str):
option_str += f' {key}="{value}"'
else:
option_str += f' {key}="{value}"' # Fallback for numbers etc.
return f'<video controls src="data:video/mp4;base64,{base64_data}" style="max-width: 100%; height: auto; border: 1px solid #555; margin: 5px 0;"{option_str}/>'
def render_video(batch_tensor_or_array_of_pil_images, fps=24, options=None):
"""
Render video frames as an HTML video player.
Args:
batch_tensor_or_array_of_pil_images (list of PIL.Image, np.ndarray, or torch.Tensor):
A list of frames, or a single batch tensor/array (B, H, W, C) or (B, C, H, W).
fps (int): Frames per second.
options (dict): Dictionary of HTML <video> tag attributes (e.g., {"loop": True, "autoplay": True}).
Returns
-------
VideoDisplay: An object that will render as an HTML video player.
"""
frames_list = []
if isinstance(
batch_tensor_or_array_of_pil_images, (np.ndarray, torch.Tensor)
):
# Assume it's a batch tensor/array
for i in range(batch_tensor_or_array_of_pil_images.shape[0]):
frames_list.append(batch_tensor_or_array_of_pil_images[i])
elif isinstance(batch_tensor_or_array_of_pil_images, list):
frames_list = batch_tensor_or_array_of_pil_images
else:
raise TypeError(
"Input for render_video must be a list of frames or a batch tensor/array."
)
return VideoDisplay(frames_list, fps, options)
class ComfyREPLBackend:
def __init__(self):
self.repl_consoles: dict[str, code.InteractiveConsole] = {}
# self.repl_console = None
self.image_outputs = []
self.audio_outputs = []
self.video_outputs = []
self._original_displayhook = sys.displayhook
# self._init_repl_console()
@staticmethod
def _init_repl_console():
"""Define the globals that will be available in the REPL session."""
repl_globals = {"__builtins__": __builtins__}
# repl_globals["plt"] = plt
repl_globals["np"] = np
repl_globals["Image"] = Image
repl_globals["torch"] = torch
repl_globals["repl_display"] = _repl_display_image
if _HAS_SCIPY:
repl_globals["render_audio"] = render_audio
if _HAS_IMAGEIO:
repl_globals["render_video"] = render_video
return code.InteractiveConsole(locals=repl_globals)
def _custom_displayhook(self, value):
"""
Displayhook that capture and process image, audio, video objects.
For other objects, it fallsback to the original displayhook.
"""
if value is None:
return
# Attempt to handle as an image
if (
isinstance(value, (Image.Image, np.ndarray, torch.Tensor))
# or (
# hasattr(value, "figure")
# and isinstance(value.figure, plt.Figure)
# )
# or isinstance(value, plt.Figure)
):
img_html = _repl_display_image(value)
self.image_outputs.append(img_html)
return
# Attempt to handle as audio
elif isinstance(value, AudioDisplay):
audio_html = value._repr_html_()
self.audio_outputs.append(audio_html)
return
# Attempt to handle as video
elif isinstance(value, VideoDisplay):
video_html = value._repr_html_()
self.video_outputs.append(video_html)
return
else:
# If not a special media type, let the original displayhook handle it.
self._original_displayhook(value)
def _console_to_html(
self, stream: io.StringIO | Traceback, width: int = 120
) -> str:
if isinstance(stream, io.StringIO):
captured_text_output = stream.getvalue()
else:
captured_text_output = Traceback
html_console = Console(
file=io.StringIO(), record=True, force_terminal=True, width=width
)
html_console.print(captured_text_output)
return html_console.export_html(inline_styles=True)
def get_console(self, node_name: str):
console = self.repl_consoles.get(node_name)
if console:
return console
console = self._init_repl_console()
self.repl_consoles[node_name] = console
return self.repl_consoles[node_name]
def execute_code(self, node_name: str, code: str):
# Clear outputs from previous execution
self.image_outputs = []
self.audio_outputs = []
self.video_outputs = []
output_html = ""
error_message = None
repl_console = self.get_console(node_name)
string_io = io.StringIO()
# Temporarily patch sys.displayhook
sys.displayhook = self._custom_displayhook
try:
with redirect_stdout(string_io), redirect_stderr(string_io):
for line in code.splitlines():
repl_console.push(line)
full_rich_html = self._console_to_html(string_io)
match = re.search(
r"<body.*?>(.*?)</body>", full_rich_html, re.DOTALL
)
if match:
output_html = match.group(1)
else:
output_html = full_rich_html
# Append any captured media HTML *after* the rich text output
for img_html in self.image_outputs:
output_html += img_html
for audio_html in self.audio_outputs:
output_html += audio_html
for video_html in self.video_outputs:
output_html += video_html
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
rich_traceback = Traceback.from_exception(
exc_type,
exc_value,
exc_traceback,
show_locals=True,
suppress=[__file__],
)
# error_console = Console(
# file=io.StringIO(), record=True, force_terminal=True, width=120
# )
# error_console.print(rich_traceback)
# full_error_html = error_console.export_html(inline_styles=True)
full_error_html = self._console_to_html(rich_traceback)
match = re.search(
r"<body.*?>(.*?)</body>", full_error_html, re.DOTALL
)
output_html = match.group(1) if match else full_error_html
error_message = str(e)
finally:
sys.displayhook = (
self._original_displayhook
) # Always restore original displayhook
return {"output_html": output_html, "error": error_message}
def lint_code(self, node_name: str, code: str):
diagnostics = []
if not _HAS_LINT:
diagnostics.append(
{
"row": 0,
"column": 0,
"text": "Pyflakes not installed. Linting disabled. Install with 'uv add pyflakes'.",
"type": "warning",
}
)
return web.json_response({"diagnostics": diagnostics})
# Use a custom reporter to capture messages
class PyflakesReporter(pyflakes.reporter.Reporter):
def __init__(self):
self.messages = []
# Suppress stdout/stderr from pyflakes itself
self._stdout = io.StringIO()
self._stderr = io.StringIO()
super().__init__(self._stdout, self._stderr)
def flake(self, message):
# Ace editor expects 0-indexed row, pyflakes gives 1-indexed lineno
self.messages.append(
{
"row": message.lineno - 1,
"column": message.col,
"text": str(message),
"type": "warning", # pyflakes usually gives warnings
}
)
def unexpectedError(self, filename, msg):
self.messages.append(
{
"row": 0,
"column": 0,
"text": f"Pyflakes internal error: {msg}",
"type": "error",
}
)
def syntaxError(self, filename, msg, lineno, offset, text):
log.info(f"Received {text} to syntax error")
self.messages.append(
{
"row": lineno - 1, # Ace is 0-indexed
"column": offset,
"text": f"Syntax Error: {msg}",
"type": "error",
}
)
reporter = PyflakesReporter()
pyflakes.api.check(code, node_name, reporter)
return {"diagnostics": reporter.messages}
def lint_code_ruff(self, code: str):
diagnostics = []
if not _HAS_LINT:
diagnostics.append(
{
"row": 0,
"column": 0,
"text": "Ruff not installed. Linting disabled. Install with 'pip install ruff'.",
"type": "warning",
}
)
return {"diagnostics": diagnostics}
# Define the builtins/globals that Ruff should recognize
# These are the names we inject into the REPL's scope
repl_builtins = [
"repl_display",
"render_audio",
"render_video",
# "plt",
"np",
"Image",
"torch",
]
try:
# Lint the code using Ruff's programmatic API
result = ruff.lint.linter.lint_stdin(
code.encode("utf-8"),
path="<stdin>",
builtins=repl_builtins,
)
for diagnostic in result.diagnostics:
diag_type = "warning" # Default
# Ruff's error codes: F (Pyflakes), E (Pycodestyle), W (Pycodestyle warning), I (isort), N (naming), etc.
# F821: Undefined name (often an error)
if (
diagnostic.kind.code.startswith("E")
or diagnostic.kind.code == "F821"
):
diag_type = "error"
elif diagnostic.kind.code.startswith("W"):
diag_type = "warning"
diagnostics.append(
{
"row": diagnostic.location.row - 1, # Ace is 0-indexed
"column": diagnostic.location.column
- 1, # Ace is 0-indexed
"text": diagnostic.message,
"type": diag_type,
}
)
except Exception as e:
diagnostics.append(
{
"row": 0,
"column": 0,
"text": f"Ruff internal error: {e}",
"type": "error",
}
)
return {"diagnostics": diagnostics}
def _repl_display_image(img_data):
"""
Internal function to convert image data (PIL, numpy, torch, matplotlib) to base64 HTML.
"""
pil_img = None
# fig = None
if isinstance(img_data, Image.Image):
pil_img = img_data
elif isinstance(img_data, np.ndarray):
# Handle different numpy array shapes (HWC, CHW)
if img_data.ndim == 3:
if img_data.shape[0] in [1, 3, 4]: # Likely CHW
if img_data.shape[0] == 1: # Grayscale
img_data = img_data.squeeze(0)
else: # Color
img_data = np.transpose(img_data, (1, 2, 0)) # CHW to HWC
# Ensure it's uint8 for PIL, assuming float [0,1] or int [0,255]
if img_data.dtype != np.uint8:
img_data = (
(img_data * 255).astype(np.uint8)
if img_data.max() <= 1.0
else img_data.astype(np.uint8)
)
pil_img = Image.fromarray(img_data)
elif isinstance(img_data, torch.Tensor):
# Move to CPU, convert to numpy
np_img = img_data.detach().cpu().numpy()
# Handle different tensor shapes (CHW, HWC)
if np_img.ndim == 3:
if np_img.shape[0] in [1, 3, 4]: # Likely CHW
if np_img.shape[0] == 1: # Grayscale
np_img = np_img.squeeze(0)
else: # Color
np_img = np.transpose(np_img, (1, 2, 0)) # CHW to HWC
# Ensure it's uint8 for PIL, assuming float [0,1] or int [0,255]
if np_img.dtype != np.uint8:
np_img = (
(np_img * 255).astype(np.uint8)
if np_img.max() <= 1.0
else np_img.astype(np.uint8)
)
pil_img = Image.fromarray(np_img)
# elif hasattr(img_data, "figure") and isinstance(
# img_data.figure, plt.Figure
# ):
# # If it's a matplotlib Axes object, get its figure
# fig = img_data.figure
# elif isinstance(img_data, plt.Figure):
# fig = img_data
else:
return f"<div style='color: red;'>Unsupported image type for display: {type(img_data)}</div>"
buffer = io.BytesIO()
try:
if pil_img:
pil_img.save(buffer, format="PNG")
# elif fig:
# fig.savefig(
# buffer, format="PNG", bbox_inches="tight", pad_inches=0.1
# )
# plt.close(
# fig
# ) # Close the figure to prevent it from showing up in other contexts
else:
return (
"<div style='color: red;'>Could not process image data.</div>"
)
except Exception as e:
return f"<div style='color: red;'>Error saving image: {e}</div>"
img_base64 = base64.b64encode(buffer.getvalue()).decode("utf-8")
return f'<img src="data:image/png;base64,{img_base64}" style="max-width: 100%; height: auto; border: 1px solid #555; margin: 5px 0;"/>'
# Instantiate the backend class globally
_comfy_repl_backend = ComfyREPLBackend()
# Update aiohttp handlers to use the backend instance
async def repl_execute_code_handler(request):
data = await request.json()
name = data.get("name")
if name is None: # we send an error
return web.Response(
status=417, reason="Expectation Failed", text="Missing name key"
)
code = data.get("code", "")
result = _comfy_repl_backend.execute_code(name, code)
return web.json_response(result)
async def repl_lint_code_handler(request):
data = await request.json()
name = data.get("name")
if name is None: # we send an error
return web.Response(
status=417, reason="Expectation Failed", text="Missing name key"
)
# raise web.HTTPExpectationFailed(
# reason="Missing name key (reason)", text="Missing name key (text)"
# )
code = data.get("code", "")
result = _comfy_repl_backend.lint_code(name, code)
return web.json_response(result)
def setup_custom_web_routes(app: web.Application):
"""
Function to register our custom web routes with the ComfyUI server.
"""
log.info("ComfyREPL: Registering /mtb/execute route...")
app.router.add_post("/mtb/execute", repl_execute_code_handler)
app.router.add_post("/mtb/lint", repl_lint_code_handler)
# You can add more routes here if needed, e.g., for clearing state.
+1
View File
@@ -9,3 +9,4 @@ rich_argparse
matplotlib
pillow
cachetools
transformers
+47
View File
@@ -16,3 +16,50 @@
* @typedef {import("./shared.d.ts").INodeOutputSlot} INodeOutputSlot
*/
/**
* @typedef {Object} ResultItem
* @property {string} [filename] - The filename of the item.
* @property {string} [subfolder] - The subfolder of the item.
* @property {string} [type] - The type of the item.
*/
/**
* @typedef {Object} Outputs
* @property {ResultItem[]} [audio] - Audio result items.
* @property {ResultItem[]} [images] - Image result items.
* @property {ResultItem[]} [animated] - Animated result items.
*/
/**
* @typedef {Record<string, Outputs>} TaskOutput
* - A record mapping Node IDs to their Outputs.
*/
/**
* @typedef {Array} TaskPrompt
* @property {QueueIndex} [0] - The queue index.
* @property {PromptId} [1] - The unique prompt ID.
* @property {PromptInputs} [2] - The prompt inputs.
* @property {ExtraData} [3] - Extra data.
* @property {OutputsToExecute} [4] - The outputs to execute.
*/
/**
* @typedef {Object} HistoryTaskItem
* @property {'History'} taskType - The type of task.
* @property {TaskPrompt} prompt - The task prompt.
* @property {Status} [status] - The status of the task.
* @property {TaskOutput} outputs - The task outputs.
* @property {TaskMeta} [meta] - Optional task metadata.
*/
/**
* @typedef {Object} ExecInfo
* @property {number} queue_remaining - The number of items remaining in the queue.
*/
/**
* @typedef {Object} StatusWsMessageStatus
* @property {ExecInfo} exec_info - Execution information.
*/
+258 -28
View File
@@ -1,6 +1,5 @@
import contextlib
import functools
import importlib
import math
import operator
import os
@@ -9,13 +8,18 @@ import shutil
import socket
import subprocess
import sys
import textwrap
import uuid
import warnings
from collections.abc import Callable, Sequence
from enum import Enum
from functools import reduce
from pathlib import Path
from types import EllipsisType
from typing import TypeVar
from urllib.parse import urlparse
import comfy.utils
import folder_paths
import numpy as np
import numpy.typing as npt
@@ -460,25 +464,6 @@ def _run_command(shell_cmd, ignored_lines_start):
print("Command executed successfully!")
def import_install(package_name):
package_spec = reqs_map.get(package_name, package_name)
try:
importlib.import_module(package_name)
except Exception: # (ImportError, ModuleNotFoundError):
run_command(
[
Path(sys.executable).as_posix(),
"-m",
"pip",
"install",
package_spec,
]
)
importlib.import_module(package_name)
# endregion
@@ -513,9 +498,10 @@ font_path = here / "data" / "font.ttf"
extern_root = here / "extern"
add_path(extern_root)
for pth in extern_root.iterdir():
if pth.is_dir():
add_path(pth)
if extern_root.exists():
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_path(comfy_dir)
@@ -541,11 +527,199 @@ PIL_FILTER_MAP = {
# region TENSOR Utilities
class LazyProxyTensor:
"""Memory-efficient proxy that wrap a tensor but presents itself as a different dtype (e.g., float32).
It mimics a torch.Tensor's read-only attributes and methods. Data conversion
and normalization happen lazily on access (e.g., via slicing), avoiding
the high memory cost of a full conversion.
Supported source dtypes:
- torch.uint8 (normalized from [0, 255])
- torch.uint16 (normalized from [0, 65535])
- All float types (passed through, assumed to be in [0, 1] range)"
"""
_source_tensor: torch.Tensor
_target_dtype: torch.dtype
_target_element_size: int
_scale_divisor: float
_warned_inefficient_access: bool
def __init__(
self, source_tensor, target_dtype=torch.float32, target_device=None
):
if not isinstance(source_tensor, torch.Tensor):
raise ValueError("Input must be a torch.Tensor.")
self._source_tensor = source_tensor
self._target_dtype = target_dtype
self._target_device = (
target_device
if target_device is not None
else source_tensor.device
)
# Determine the normalization divisor based on source dtype
# fmt: off
if source_tensor.dtype == torch.uint8: self._scale_divisor = 255.0
elif source_tensor.dtype == torch.uint16: self._scale_divisor = 65535.0
elif torch.is_floating_point(source_tensor): self._scale_divisor = 1.0
else: raise ValueError(f"Unsupported source dtype for LazyProxyTensor: {source_tensor.dtype}")
# fmt: on
self._target_element_size = torch.empty(
(), dtype=self._target_dtype
).element_size()
self._warned_inefficient_access = False
def is_contiguous(self, *args, **kwargs):
return self._source_tensor.is_contiguous(*args, **kwargs)
def stride(self, *args, **kwargs):
return self._source_tensor.stride(*args, **kwargs)
@property
def shape(self):
return self._source_tensor.shape
@property
def requires_grad(self):
return False
def nelement(self):
"""Return the total number of elements in the (pretend) tensor."""
return self._source_tensor.nelement()
def element_size(self):
"""Return the size in bytes of an individual (pretend) float element."""
return self._target_element_size
@property
def dtype(self):
return self._target_dtype
@property
def device(self):
return self._target_device
def __len__(self):
return self._source_tensor.shape[0]
def __getitem__(self, key):
if (
self._source_tensor.device != self._target_device
and not self._warned_inefficient_access
):
warnings.warn(
"Inefficient access pattern detected for LazyProxyTensor. "
"You are slicing a device-proxied tensor, which causes slow, "
"repeated data transfers. For performance, use the .iter_chunks() method."
)
self._warned_inefficient_access = True
subset = self._source_tensor[key]
return (
subset.to(self._target_device).to(self._target_dtype)
/ self._scale_divisor
)
# def __iter__(self):
# for i in range(len(self)):
# yield self[i]
def iter_chunks(self, chunk_size=16):
for i in range(0, len(self), chunk_size):
chunk = self._source_tensor[i : i + chunk_size]
yield (
chunk.to(self._target_device, non_blocking=True).to(
self._target_dtype
)
/ self._scale_divisor
)
def squeeze(self, dim: str | EllipsisType | None = None):
squeezed = self._source_tensor.squeeze(dim)
return LazyProxyTensor(squeezed, self._target_dtype)
def unsqueeze(self, dim: int = 0):
unsqueezed = self._source_tensor.unsqueeze(dim)
return LazyProxyTensor(unsqueezed, self._target_dtype)
def repeat(self, *sizes):
repeated = self._source_tensor.repeat(*sizes)
return LazyProxyTensor(repeated, self._target_dtype)
def _format_mem_size(self, mem_bytes):
if mem_bytes > 1e9:
return f"{mem_bytes / 1e9:.2f} GB"
if mem_bytes > 1e6:
return f"{mem_bytes / 1e6:.2f} MB"
if mem_bytes > 1e3:
return f"{mem_bytes / 1e3:.2f} KB"
return f"{mem_bytes} B"
def __repr__(self):
actual_info = get_torch_tensor_info(self._source_tensor, name="Source")
target_info = get_torch_tensor_info(self, name="Target")
info = f"""
{target_info}
{actual_info}
"""
return textwrap.dedent(info).strip()
def get_torch_tensor_info(
tensor: torch.Tensor | LazyProxyTensor | np.ndarray,
*,
name: str | None = None,
):
mem_str = "N/A"
is_tensor = isinstance(tensor, torch.Tensor | LazyProxyTensor)
if is_tensor:
mem_bytes = tensor.element_size() * tensor.nelement()
else:
mem_bytes = tensor.itemsize * tensor.size
if mem_bytes > 1e9:
mem_str = f"{mem_bytes / 1e9:.2f} GB"
elif mem_bytes > 1e6:
mem_str = f"{mem_bytes / 1e6:.2f} MB"
elif mem_bytes > 1e3:
mem_str = f"{mem_bytes / 1e3:.2f} KB"
else:
mem_str = f"{mem_bytes} B"
device = "N/A"
grad = "False"
type_name = name or "Tensor" if is_tensor else "Numpy Array"
if is_tensor:
device = tensor.device
grad = str(tensor.requires_grad)
text = f"""
{type_name}
shape: {tensor.shape}
dtype: {str(tensor.dtype).replace("torch.", "")}
device: {device}
requires grad: {grad}
memory: {mem_str}
"""
return textwrap.dedent(text).strip()
def to_numpy(image: torch.Tensor) -> npt.NDArray[np.uint8]:
"""Converts a tensor to a ndarray with proper scaling and type conversion."""
log.debug(f"Converting tensor to numpy array with shape {image.shape}")
np_array = np.clip(255.0 * image.cpu().numpy(), 0, 255).astype(np.uint8)
log.debug(f"Numpy array shape after conversion: {np_array.shape}")
return np_array
@@ -553,12 +727,12 @@ def handle_batch(
tensor: torch.Tensor,
func: Callable[[torch.Tensor], Image.Image | npt.NDArray[np.uint8]],
) -> list[Image.Image] | list[npt.NDArray[np.uint8]]:
"""Handles batch processing for a given tensor and conversion function."""
"""Handle batch processing for a given tensor and conversion function."""
return [func(tensor[i]) for i in range(tensor.shape[0])]
def tensor2pil(tensor: torch.Tensor) -> list[Image.Image]:
"""Converts a batch of tensors to a list of PIL Images."""
"""Convert a batch of tensors to a list of PIL Images."""
def single_tensor2pil(t: torch.Tensor) -> Image.Image:
np_array = to_numpy(t)
@@ -575,7 +749,7 @@ def tensor2pil(tensor: torch.Tensor) -> list[Image.Image]:
def pil2tensor(images: Image.Image | list[Image.Image]) -> torch.Tensor:
"""Converts a PIL Image or a list of PIL Images to a tensor."""
"""Convert a PIL Image or a list of PIL Images to a tensor."""
def single_pil2tensor(image: Image.Image) -> torch.Tensor:
np_image = np.array(image).astype(np.float32) / 255.0
@@ -857,6 +1031,62 @@ def tiles_split(img, tile_size, stride_size):
# region MODEL Utilities
def download_model(model_url: str, destination: str):
if isinstance(model_url, list):
for url in model_url:
download_model(url, destination)
return
filename = Path(urlparse(model_url).path).name
if "drive.google.com" in model_url:
try:
import gdown
except ImportError:
log.info("Installing gdown")
subprocess.check_call(
[
sys.executable,
"-m",
"pip",
"install",
"gdown",
]
)
import gdown
if "/folders/" in model_url:
# download folder
try:
gdown.download_folder(
model_url, output=destination, resume=True
)
except TypeError:
gdown.download_folder(model_url, output=destination)
return
# download from google drive
gdown.download(model_url, destination, quiet=False, resume=True)
return True
response = requests.get(model_url, stream=True)
total_size = int(response.headers.get("content-length", 0))
destination_path = get_model_path(destination, filename)
destination_path.parent.mkdir(exist_ok=True)
pbar = comfy.utils.ProgressBar(total_size)
with open(destination_path, "wb") as file:
for data in response.iter_content(chunk_size=4096):
file.write(data)
pbar.update(len(data))
log.info(
f"Downloaded model from {model_url} to {destination_path}",
)
def download_antelopev2():
antelopev2_url = (
"https://drive.google.com/uc?id=18wEUfMNohBJ4K3Ly5wpTejPfDzp-8fI8"
+236 -90
View File
@@ -14,6 +14,51 @@ import { api } from '../../scripts/api.js'
// #region base utils
/**
* Computes the convex hull of a set of points using the Monotone Chain algorithm.
*
* @param {Array<Array<number>>} points An array of points, where each point is an array of two numbers [x, y].
* @returns {Array<Array<number>>} The points forming the convex hull, in counter-clockwise order.
*/
export const getConvexHull = (points) => {
if (points.length <= 3) {
return points
}
points.sort((a, b) => a[0] - b[0] || a[1] - b[1])
const lower = []
for (const p of points) {
while (
lower.length >= 2 &&
cross_product(lower[lower.length - 2], lower[lower.length - 1], p) <= 0
) {
lower.pop()
}
lower.push(p)
}
const upper = []
for (let i = points.length - 1; i >= 0; i--) {
const p = points[i]
while (
upper.length >= 2 &&
cross_product(upper[upper.length - 2], upper[upper.length - 1], p) <= 0
) {
upper.pop()
}
upper.push(p)
}
function cross_product(o, a, b) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
}
return lower
.slice(0, lower.length - 1)
.concat(upper.slice(0, upper.length - 1))
}
// - crude uuid
export function makeUUID() {
let dt = new Date().getTime()
@@ -25,6 +70,19 @@ export function makeUUID() {
return uuid
}
// - basic debounce decorator
export function debounce(func, delay) {
let timeout
let debounced = function (...args) {
clearTimeout(timeout)
timeout = setTimeout(() => func.apply(this, args), delay)
}
debounced.cancel = () => {
clearTimeout(timeout)
}
return debounced
}
//- local storage manager
export class LocalStorageManager {
constructor(namespace) {
@@ -195,6 +253,7 @@ export function hideWidgetForGood(node, widget, suffix = '') {
widget.origComputeSize = widget.computeSize
widget.origSerializeValue = widget.serializeValue
widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
widget.hidden = true
widget.type = CONVERTED_TYPE + suffix
// widget.serializeValue = () => {
// // Prevent serializing the widget if we have no input linked
@@ -276,6 +335,10 @@ export const getNamedWidget = (node, ...names) => {
* @returns {{to:LGraphNode, from:LGraphNode, type:'error' | 'incoming' | 'outgoing'}}
*/
export const nodesFromLink = (node, link) => {
if (typeof link === 'number') {
link = app.graph.getLink(link)
}
const fromNode = app.graph.getNodeById(link.origin_id)
const toNode = app.graph.getNodeById(link.target_id)
@@ -366,12 +429,54 @@ export function getWidgetType(config) {
// #endregion
// function to test if input is a dynamic one
const isDynamicInput = (input) => {
infoLogger('Checking if input dynamic', { input })
// return input.name.startsWith(connectionPrefix)
return input._isDynamic === true
}
// Add a dynamic input, update node properties and slot colors!
const addDynamicInput = (node, name, kind) => {
const input = node.addInput(name, kind)
input._isDynamic = true
update_dynamic_properties(node)
set_slot_colors(node, ['cyan', undefined], isDynamicInput)
return input
}
const set_slot_colors = (node, colors, condition) => {
if (!condition) {
condition = (_s) => true
}
for (const slot of node.slots) {
infoLogger('Candidate', { slot, accepted: condition(slot) })
if (condition(slot)) {
slot.color_off = colors[0]
slot.color_on = colors[1]
}
}
}
const update_dynamic_properties = (node) => {
const dyn = []
for (const input of node.inputs) {
if (isDynamicInput(input)) {
dyn.push(input.name)
}
}
node.setProperty('dynamic_connections', dyn)
}
// #region dynamic connections
/**
* @param {NodeType} nodeType The nodetype to attach the documentation to
* @param {str} prefix A prefix added to each dynamic inputs
* @param {str | [str]} inputType The datatype(s) of those dynamic inputs
* @param {{separator?:string, start_index?:number, link?:LLink, ioSlot?:INodeInputSlot | INodeOutputSlot}?} [opts] Extra options
* @param {{separator?:string,rename_menu?:'label'|'name', start_index?:number, link?:LLink, ioSlot?:INodeInputSlot | INodeOutputSlot}?} [opts] Extra options
* @returns
*/
export const setupDynamicConnections = (
@@ -385,20 +490,115 @@ export const setupDynamicConnections = (
Object.getOwnPropertyDescriptors(nodeType).title.value,
)
/** @type {{separator:string, start_index:number, link?:LLink, ioSlot?:INodeInputSlot | INodeOutputSlot}?} */
/** @type {{separator:string,rename_menu?:"label"|"name" start_index:number, link?:LLink, ioSlot?:INodeInputSlot | INodeOutputSlot}?} */
const options = Object.assign(
{
separator: '_',
start_index: 1,
rename_menu: 'label',
},
opts || {},
)
const is_valid_name = (node, val) => {
return true
}
nodeType.prototype.getSlotMenuOptions = (slot) => {
if (!slot.input) {
return
}
infoLogger('Slot Menu', { slot })
return [
{
content: `Rename Input (${options.rename_menu})`,
callback: () => {
const dialog = app.canvas.createDialog(
"<span class='name'>Name</span><input autofocus type='text'/><button>OK</button>",
{},
)
const dialogInput = dialog.querySelector('input')
if (dialogInput) {
if (options.rename_menu === 'label') {
dialogInput.value = slot.input.label || slot.input.name || ''
} else if (options.rename_menu === 'name') {
dialogInput.value = slot.input.name || ''
}
}
const inner = () => {
// TODO: check if name exists or other guards
const val = dialogInput.value
if (!is_valid_name(slot.node, val)) {
dialog.close()
return
}
app.graph.beforeChange()
if (options.rename_menu === 'label') {
slot.input.label = val
} else if (options.rename_menu === 'name') {
slot.input.name = val
slot.input.label = val
}
app.graph.afterChange()
dialog.close()
}
dialog.querySelector('button').addEventListener('click', inner)
dialogInput.addEventListener('keydown', (e) => {
dialog.is_modified = true
if (e.keyCode === 27) {
dialog.close()
} else if (e.keyCode === 13) {
inner()
} else if (e.keyCode !== 13 && e.target?.localName !== 'textarea') {
return
}
e.preventDefault()
e.stopPropagation()
})
dialogInput.focus()
},
},
]
}
const onConfigure = nodeType.prototype.onConfigure
nodeType.prototype.onConfigure = function (data) {
const r = onConfigure ? onConfigure.apply(this, data) : undefined
// Set or restore serialized properties, lt seems to auto serialize/deserialize to/from string
if (!('dynamic_connections' in this.properties)) {
// this.addProperty('dynamic_connections', [], 'string')
this.setProperty('dynamic_connections', [])
} else {
const dynamic_connections = this.properties.dynamic_connections
if (typeof dynamic_connections !== 'object') {
return r
}
for (const name of dynamic_connections) {
infoLogger(`Would dynamize: ${name}`)
const input = this.inputs.find((i) => i.name === name)
if (input) {
infoLogger('Input found', { input })
input._isDynamic = true
}
}
}
// set color
set_slot_colors(this, ['cyan', undefined], isDynamicInput)
return r
}
const onNodeCreated = nodeType.prototype.onNodeCreated
const inputList = typeof inputType === 'object'
nodeType.prototype.onNodeCreated = function () {
const r = onNodeCreated ? onNodeCreated.apply(this, []) : undefined
this.addInput(
const input = addDynamicInput(
this,
`${prefix}${options.separator}${options.start_index}`,
inputList ? '*' : inputType,
)
@@ -470,10 +670,7 @@ export const dynamic_connection = (
opts || {},
)
// function to test if input is a dynamic one
const isDynamicInput = (inputName) => inputName.startsWith(connectionPrefix)
if (node.inputs.length > 0 && !isDynamicInput(node.inputs[index].name)) {
if (node.inputs.length > 0 && !isDynamicInput(node.inputs[index])) {
return
}
@@ -483,6 +680,7 @@ export const dynamic_connection = (
const nameArray = options.nameArray || []
const clean_inputs = () => {
if (node.id < 0) return // being duplicated
if (node.inputs.length === 0) return
let w_count = node.widgets?.length || 0
@@ -492,7 +690,7 @@ export const dynamic_connection = (
const to_remove = []
for (let n = 1; n < node.inputs.length; n++) {
const element = node.inputs[n]
if (!element.link && isDynamicInput(element.name)) {
if (!element.link && isDynamicInput(element)) {
if (node.widgets) {
const w = node.widgets.find((w) => w.name === element.name)
if (w) {
@@ -506,9 +704,12 @@ export const dynamic_connection = (
}
for (let i = 0; i < to_remove.length; i++) {
const id = to_remove[i]
node.removeInput(id)
i_count -= 1
try {
node.removeInput(id)
i_count -= 1
} catch (err) {
errorLogger('Cannot remove input', err)
}
}
node.inputs.length = i_count
@@ -522,7 +723,7 @@ export const dynamic_connection = (
for (let i = 0; i < node.inputs.length; i++) {
let name = ''
// rename only prefixed inputs
if (isDynamicInput(node.inputs[i].name)) {
if (node.inputs[i].name.startsWith(connectionPrefix)) {
// prefixed => rename and increase index
name = `${connectionPrefix}${prefixed_idx}`
prefixed_idx += 1
@@ -576,9 +777,8 @@ export const dynamic_connection = (
if (node.inputs.length === 0) return
// add an extra input
if (node.inputs[node.inputs.length - 1].link !== null) {
// count only the prefixed inputs
const nextIndex = node.inputs.reduce(
(acc, cur) => (isDynamicInput(cur.name) ? ++acc : acc),
(acc, cur) => (isDynamicInput(cur) ? ++acc : acc),
0,
)
@@ -588,7 +788,7 @@ export const dynamic_connection = (
: `${connectionPrefix}${nextIndex + options.start_index}`
infoLogger(`Adding input ${nextIndex + 1} (${name})`)
node.addInput(name, conType)
addDynamicInput(node, name, conType)
}
}
}
@@ -621,21 +821,21 @@ function getBrightness(rgbObj) {
export function calculateTotalChildrenHeight(parentElement) {
let totalHeight = 0
if (!parentElement || !parentElement.children) {
return 0
}
for (const child of parentElement.children) {
const style = window.getComputedStyle(child)
// Get height as an integer (without 'px')
const height = Number.parseInt(style.height, 10)
const height = Number.parseFloat(style.height)
const marginTop = Number.parseFloat(style.marginTop)
const marginBottom = Number.parseFloat(style.marginBottom)
// Get vertical margin as integers
const marginTop = Number.parseInt(style.marginTop, 10)
const marginBottom = Number.parseInt(style.marginBottom, 10)
// Sum up height and vertical margins
totalHeight += height + marginTop + marginBottom
}
return totalHeight
return Math.ceil(totalHeight)
}
export const loadScript = (
@@ -646,13 +846,15 @@ export const loadScript = (
return new Promise((resolve, reject) => {
try {
// Check if the script already exists
const existingScript = document.querySelector(`script[src="${FILE_URL}"]`)
if (existingScript) {
resolve({ status: true, message: 'Script already loaded' })
let scriptEle = document.querySelector(`script[src="${FILE_URL}"]`)
if (scriptEle) {
scriptEle.addEventListener('load', (_ev) => {
resolve({ status: true })
})
return
}
const scriptEle = document.createElement('script')
scriptEle = document.createElement('script')
scriptEle.type = type
scriptEle.async = async
scriptEle.src = FILE_URL
@@ -671,6 +873,8 @@ export const loadScript = (
document.body.appendChild(scriptEle)
} catch (error) {
reject(error)
} finally {
infoLogger(`Finally loaded script: ${FILE_URL}`)
}
})
}
@@ -784,12 +988,10 @@ function loadParser(shiki) {
export const ensureMarkdownParser = async (callback) => {
infoLogger('Ensuring md parser')
let use_shiki = false
try {
use_shiki = await api.getSetting('mtb.Use Shiki')
} catch (e) {
console.warn('Option not available yet', e)
}
const use_shiki = app.extensionManager.setting.get(
'mtb.noteplus.use-shiki',
false,
)
if (window.MTB?.mdParser) {
infoLogger('Markdown parser found')
@@ -814,8 +1016,7 @@ export const ensureMarkdownParser = async (callback) => {
callbackQueue.push(callback)
}
await parserPromise
await parserPromise
await await parserPromise
return window.MTB.mdParser
}
@@ -1154,58 +1355,3 @@ export const setServerInfo = async (opts) => {
}
// #endregion
// #region Authoring API / graph utilities
export const getAPIInputs = () => {
const inputs = {}
let counter = 1
for (const node of getNodes(true)) {
const widgets = node.widgets
if (node.properties.mtb_api && node.properties.useAPI) {
if (node.properties.mtb_api.inputs) {
for (const currentName in node.properties.mtb_api.inputs) {
const current = node.properties.mtb_api.inputs[currentName]
if (current.enabled) {
const inputName = current.name || currentName
const widget = widgets.find((w) => w.name === currentName)
if (!widget) continue
if (!(inputName in inputs)) {
inputs[inputName] = {
...current,
id: counter,
name: inputName,
type: current.type,
node_id: node.id,
widgets: [],
}
}
inputs[inputName].widgets.push(widget)
counter = counter + 1
}
}
}
}
}
return inputs
}
export const getNodes = (skip_unused) => {
const nodes = []
for (const outerNode of app.graph.computeExecutionOrder(false)) {
const skipNode =
(outerNode.mode === 2 || outerNode.mode === 4) && skip_unused
const innerNodes =
!skipNode && outerNode.getInnerNodes
? outerNode.getInnerNodes()
: [outerNode]
for (const node of innerNodes) {
if ((node.mode === 2 || node.mode === 4) && skip_unused) {
continue
}
nodes.push(node)
}
}
return nodes
}
// #endregion
+132 -82
View File
@@ -12,10 +12,12 @@
import { app } from '../../scripts/app.js'
import * as shared from './comfy_shared.js'
import { MtbWidgets } from './mtb_widgets.js'
// TODO: respect inputs order...
import {
setupDynamicConnections,
cleanupNode,
infoLogger,
} from './comfy_shared.js'
import * as mtb_ui from './mtb_ui.js'
function escapeHtml(unsafe) {
return unsafe
@@ -25,6 +27,54 @@ function escapeHtml(unsafe) {
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;')
}
function createDebugSection(title) {
const section = mtb_ui.makeElement('div', {
margin: '8px 0',
padding: '8px',
borderRadius: '4px',
backgroundColor: 'rgba(0,0,0,0.2)',
})
const header = mtb_ui.makeElement('h3', {
margin: '0 0 8px 0',
padding: '4px 0',
borderBottom: '1px solid rgba(255,255,255,0.1)',
fontSize: '14px',
fontWeight: 'bold',
color: '#9f9',
})
header.textContent = title
section.appendChild(header)
return section
}
function createDebugContent(item) {
const wrapper = mtb_ui.makeElement('div', {
margin: '4px 0',
})
if (item.kind === 'text') {
const text = mtb_ui.makeElement('div', {
margin: '2px 0',
fontFamily: 'monospace',
whiteSpace: 'pre-wrap',
})
text.innerHTML = item.data
wrapper.appendChild(text)
} else if (item.kind === 'b64_images') {
const img = mtb_ui.makeElement('img', {
width: '100%',
borderRadius: '2px',
})
img.src = item.data
wrapper.appendChild(img)
}
return wrapper
}
app.registerExtension({
name: 'mtb.Debug',
@@ -35,98 +85,98 @@ app.registerExtension({
*/
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === 'Debug (mtb)') {
const onNodeCreated = nodeType.prototype.onNodeCreated
nodeType.prototype.onNodeCreated = function () {
this.options = {}
const r = onNodeCreated
? onNodeCreated.apply(this, arguments)
: undefined
this.addInput(`anything_1`, '*')
return r
const clear_widgets = (target) => {
if (target.widgets) {
let tgt_len = target.widgets.length
for (let i = 0; i < target.widgets.length; i++) {
if (
![
'output_to_console',
'deep_inspect',
'as_detailed_types',
'rich_mode',
].includes(target.widgets[i].name)
) {
target.widgets[i].onRemove?.()
target.widgets[i].onRemoved?.()
tgt_len -= 1
}
}
target.widgets.length = tgt_len
}
}
const onConnectionsChange = nodeType.prototype.onConnectionsChange
/**
* @param {OnConnectionsChangeParams} args
*/
nodeType.prototype.onConnectionsChange = function (...args) {
const [_type, index, connected, link_info, ioSlot] = args
const r = onConnectionsChange
? onConnectionsChange.apply(this, args)
: undefined
// TODO: remove all widgets on disconnect once computed
shared.dynamic_connection(this, index, connected, 'anything_', '*', {
link: link_info,
ioSlot: ioSlot,
const original_getExtraMenuOptions =
nodeType.prototype.getExtraMenuOptions
nodeType.prototype.getExtraMenuOptions = function (_, options) {
original_getExtraMenuOptions?.apply(this, arguments)
options.push({
content: '🐛 Clear Outputs',
callback: async () => {
clear_widgets(this)
},
})
//- infer type
if (link_info) {
// const fromNode = this.graph._nodes.find(
// (otherNode) => otherNode.id === link_info.origin_id,
// )
// const fromNode = app.graph.getNodeById(link_info.origin_id)
const { from } = shared.nodesFromLink(this, link_info)
if (!from || this.inputs.length === 0) return
const type = from.outputs[link_info.origin_slot].type
this.inputs[index].type = type
// this.inputs[index].label = type.toLowerCase()
}
//- restore dynamic input
if (!connected) {
this.inputs[index].type = '*'
this.inputs[index].label = `anything_${index + 1}`
}
return r
}
setupDynamicConnections(nodeType, 'var', '*')
const onExecuted = nodeType.prototype.onExecuted
nodeType.prototype.onExecuted = function (data) {
onExecuted?.apply(this, arguments)
nodeType.prototype.onExecuted = function (...args) {
onExecuted?.apply(this, args)
const [data, ..._rest] = args
const prefix = 'anything_'
clear_widgets(this)
if (this.widgets) {
for (let i = 0; i < this.widgets.length; i++) {
if (this.widgets[i].name !== 'output_to_console') {
this.widgets[i].onRemoved?.()
}
}
this.widgets.length = 1
}
let widgetI = 1
// console.log(message)
if (data.text) {
for (const txt of data.text) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_STRING(`${prefix}_${widgetI}`, escapeHtml(txt)),
)
w.parent = this
widgetI++
}
}
if (data.b64_images) {
for (const img of data.b64_images) {
const w = this.addCustomWidget(
MtbWidgets.DEBUG_IMG(`${prefix}_${widgetI}`, img),
)
w.parent = this
widgetI++
}
}
const inputData = {}
// this.setSize(this.computeSize())
const uiData = data.ui || data
const name_to_label = this.inputs.reduce((acc, input) => {
acc[input.name] = input.label || input.name
return acc
}, {})
if (uiData.items) {
uiData.items.forEach((item) => {
const inputName = item.input
inputData[inputName] = item.items
})
}
const mainDebugContainer = mtb_ui.makeElement('div', {
width: '100%',
})
let hasContent = false
for (const [inputName, content] of Object.entries(inputData)) {
if (!content || content?.length === 0) {
continue
}
hasContent = true
const section = createDebugSection(name_to_label[inputName])
for (const item of content) {
section.appendChild(createDebugContent(item))
}
mainDebugContainer.appendChild(section)
}
if (hasContent) {
this.addDOMWidget('debug_output', 'CUSTOM', mainDebugContainer, {
hideOnZoom: false,
})
}
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()
for (const widget of this.widgets) {
if (widget.canvas) {
widget.canvas.remove()
}
shared.cleanupNode(this)
this.widgets[y].onRemoved?.()
widget.onRemoved?.()
widget.onRemove?.()
}
cleanupNode(this)
}
this.setDirtyCanvas(true, true)
}
}
},
+296 -296
View File
@@ -13,40 +13,40 @@ import { api } from '../../scripts/api.js'
import { app } from '../../scripts/app.js'
import { LocalStorageManager } from './comfy_shared.js'
const styles = {
lighbox: {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
background: 'rgba(0,0,0,0.5)',
display: 'none',
justifyContent: 'center',
alignItems: 'center',
zIndex: 999,
},
lightboxBtn: (extra) => ({
position: 'absolute',
top: '50%',
background: 'none',
border: 'none',
color: '#fff',
zIndex: 1000,
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'auto',
...extra,
}),
img_list: {
minHeight: '30px',
maxHeight: '300px',
width: '100vw',
position: 'absolute',
bottom: 0,
zIndex: 10,
background: '#333',
overflow: 'auto',
},
lighbox: {
position: 'fixed',
top: 0,
left: 0,
width: '100vw',
height: '100vh',
background: 'rgba(0,0,0,0.5)',
display: 'none',
justifyContent: 'center',
alignItems: 'center',
zIndex: 999,
},
lightboxBtn: (extra) => ({
position: 'absolute',
top: '50%',
background: 'none',
border: 'none',
color: '#fff',
zIndex: 1000,
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'auto',
...extra,
}),
img_list: {
minHeight: '30px',
maxHeight: '300px',
width: '100vw',
position: 'absolute',
bottom: 0,
zIndex: 10,
background: '#333',
overflow: 'auto',
},
}
let currentImageIndex = 0
@@ -58,299 +58,299 @@ const storage = new LocalStorageManager('mtb')
let activated = storage.get('image_feed', false)
app.registerExtension({
name: 'mtb.ImageFeed',
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.Main.image-feed-enabled',
category: ['mtb', 'Main', 'image-feed-enabled'],
name: 'Enable Image Feed',
type: 'boolean',
defaultValue: false,
attrs: {
style: {
fontFamily: 'monospace',
},
},
async onChange(value) {
storage.set('image_feed', value)
activated = value
},
})
},
init: async () => {
if (!activated) {
return
}
const pythongossFeed = app.extensions.find(
(e) => e.name === 'pysssss.ImageFeed',
)
if (pythongossFeed) {
console.warn(
"[mtb] - Aborting the loading of mtb's imageFeed in favor of pysssss.ImageFeed",
)
activated = false // just in case other methods are added later on
return
}
// - HTML & CSS
//- lightbox
const lightboxContainer = document.createElement('div')
Object.assign(lightboxContainer.style, styles.lighbox)
name: 'mtb.ImageFeed',
setup: () => {
app.ui.settings.addSetting({
id: 'mtb.Main.image-feed-enabled',
category: ['mtb', ' Main', 'image-feed-enabled'],
name: 'Enable Image Feed',
type: 'boolean',
defaultValue: false,
attrs: {
style: {
fontFamily: 'monospace',
},
},
async onChange(value) {
storage.set('image_feed', value)
activated = value
},
})
},
init: async () => {
if (!activated) {
return
}
const pythongossFeed = app.extensions.find(
(e) => e.name === 'pysssss.ImageFeed',
)
if (pythongossFeed) {
console.warn(
"[mtb] - Aborting the loading of mtb's imageFeed in favor of pysssss.ImageFeed",
)
activated = false // just in case other methods are added later on
return
}
// - HTML & CSS
//- lightbox
const lightboxContainer = document.createElement('div')
Object.assign(lightboxContainer.style, styles.lighbox)
const lightboxImage = document.createElement('img')
Object.assign(lightboxImage.style, {
maxHeight: '100%',
maxWidth: '100%',
borderRadius: '5px',
})
const lightboxImage = document.createElement('img')
Object.assign(lightboxImage.style, {
maxHeight: '100%',
maxWidth: '100%',
borderRadius: '5px',
})
// previous and next buttons
const lightboxPrevBtn = document.createElement('button')
const lightboxNextBtn = document.createElement('button')
// previous and next buttons
const lightboxPrevBtn = document.createElement('button')
const lightboxNextBtn = document.createElement('button')
lightboxPrevBtn.textContent = '❮'
lightboxNextBtn.textContent = '❯'
lightboxPrevBtn.textContent = '❮'
lightboxNextBtn.textContent = '❯'
Object.assign(lightboxPrevBtn.style, styles.lightboxBtn({ left: '0%' }))
Object.assign(lightboxNextBtn.style, styles.lightboxBtn({ right: '0%' }))
Object.assign(lightboxPrevBtn.style, styles.lightboxBtn({ left: '0%' }))
Object.assign(lightboxNextBtn.style, styles.lightboxBtn({ right: '0%' }))
// close button
const lightboxCloseBtn = document.createElement('button')
Object.assign(
lightboxCloseBtn.style,
styles.lightboxBtn({ right: '0', top: '0' }),
)
lightboxCloseBtn.textContent = '❌'
// close button
const lightboxCloseBtn = document.createElement('button')
Object.assign(
lightboxCloseBtn.style,
styles.lightboxBtn({ right: '0', top: '0' }),
)
lightboxCloseBtn.textContent = '❌'
const lightboxButtons = document.createElement('div')
Object.assign(lightboxButtons.style, {
position: 'absolute',
top: '0%',
right: '0%',
// transform: "translate(50%, -50%)",
height: '100%',
width: '100%',
background: 'none',
border: 'none',
color: '#fff',
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'none',
})
const lightboxButtons = document.createElement('div')
Object.assign(lightboxButtons.style, {
position: 'absolute',
top: '0%',
right: '0%',
// transform: "translate(50%, -50%)",
height: '100%',
width: '100%',
background: 'none',
border: 'none',
color: '#fff',
fontSize: '30px',
cursor: 'pointer',
pointerEvents: 'none',
})
lightboxButtons.append(lightboxPrevBtn, lightboxNextBtn, lightboxCloseBtn)
lightboxContainer.append(lightboxButtons, lightboxImage)
lightboxButtons.append(lightboxPrevBtn, lightboxNextBtn, lightboxCloseBtn)
lightboxContainer.append(lightboxButtons, lightboxImage)
//- image list
const imageListContainer = document.createElement('div')
Object.assign(imageListContainer.style, styles.img_list)
//- image list
const imageListContainer = document.createElement('div')
Object.assign(imageListContainer.style, styles.img_list)
const createImgListBtn = (text, style) => {
const btn = document.createElement('button')
btn.type = 'button'
btn.textContent = text
Object.assign(btn.style, {
...style,
border: 'none',
color: '#fff',
background: 'none',
height: '20px',
cursor: 'pointer',
position: 'absolute',
top: '5px',
fontSize: '12px',
lineHeight: '12px',
})
imageListContainer.append(btn)
return btn
}
const showBtn = document.createElement('button')
const closeBtn = createImgListBtn('❌', {
width: '20px',
textIndent: '-4px',
right: '5px',
})
const loadButton = createImgListBtn('Load Session History', {
right: '90px',
})
const clearButton = createImgListBtn('Clear', {
right: '30px',
})
const createImgListBtn = (text, style) => {
const btn = document.createElement('button')
btn.type = 'button'
btn.textContent = text
Object.assign(btn.style, {
...style,
border: 'none',
color: '#fff',
background: 'none',
height: '20px',
cursor: 'pointer',
position: 'absolute',
top: '5px',
fontSize: '12px',
lineHeight: '12px',
})
imageListContainer.append(btn)
return btn
}
const showBtn = document.createElement('button')
const closeBtn = createImgListBtn('❌', {
width: '20px',
textIndent: '-4px',
right: '5px',
})
const loadButton = createImgListBtn('Load Session History', {
right: '90px',
})
const clearButton = createImgListBtn('Clear', {
right: '30px',
})
//- tools popup button
showBtn.classList.add('comfy-settings-btn')
Object.assign(showBtn.style, {
right: '16px',
cursor: 'pointer',
display: 'none',
})
//- tools popup button
showBtn.classList.add('comfy-settings-btn')
Object.assign(showBtn.style, {
right: '16px',
cursor: 'pointer',
display: 'none',
})
//- append to DOM
document.body.append(imageListContainer)
//- append to DOM
document.body.append(imageListContainer)
showBtn.textContent = '🖼'
showBtn.onclick = () => {
imageListContainer.style.display = 'block'
showBtn.style.display = 'none'
}
document.querySelector('.comfy-settings-btn').after(showBtn)
document.querySelector('.comfy-settings-btn').after(lightboxContainer)
showBtn.textContent = '🖼'
showBtn.onclick = () => {
imageListContainer.style.display = 'block'
showBtn.style.display = 'none'
}
document.querySelector('.comfy-settings-btn').after(showBtn)
document.querySelector('.comfy-settings-btn').after(lightboxContainer)
// for (const { output } of history) {
// if (output?.images) {
// for (const src of output.images) {
// const img = document.createElement("img");
// const but = document.createElement("button");
// for (const { output } of history) {
// if (output?.images) {
// for (const src of output.images) {
// const img = document.createElement("img");
// const but = document.createElement("button");
//- callbacks
closeBtn.onclick = () => {
imageListContainer.style.display = 'none'
showBtn.style.display = 'unset'
}
//- callbacks
closeBtn.onclick = () => {
imageListContainer.style.display = 'none'
showBtn.style.display = 'unset'
}
clearButton.onclick = () => {
imageListContainer.replaceChildren(closeBtn, clearButton, loadButton)
}
clearButton.onclick = () => {
imageListContainer.replaceChildren(closeBtn, clearButton, loadButton)
}
lightboxNextBtn.onclick = () => {
currentImageIndex = (currentImageIndex + 1) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
lightboxNextBtn.onclick = () => {
currentImageIndex = (currentImageIndex + 1) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
// Modify the lightboxPrevBtn onclick callback
lightboxPrevBtn.onclick = () => {
currentImageIndex =
(currentImageIndex - 1 + imageUrls.length) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
// Modify the lightboxPrevBtn onclick callback
lightboxPrevBtn.onclick = () => {
currentImageIndex =
(currentImageIndex - 1 + imageUrls.length) % imageUrls.length
const imageUrl = imageUrls[currentImageIndex]
lightboxImage.src = imageUrl
}
lightboxCloseBtn.onclick = () => {
lightboxContainer.style.display = 'none'
}
lightboxImage.onclick = lightboxNextBtn.onclick
/**
* This is the function that creates the image buttons for the image list
* They are wrapped in a button so that they can be clicked and open
* the image in the lightbox.
* @param {*} src
*/
const createImageBtn = (src) => {
console.debug(`making image ${src.filename}`)
const img = document.createElement('img')
const but = document.createElement('button')
lightboxCloseBtn.onclick = () => {
lightboxContainer.style.display = 'none'
}
lightboxImage.onclick = lightboxNextBtn.onclick
/**
* This is the function that creates the image buttons for the image list
* They are wrapped in a button so that they can be clicked and open
* the image in the lightbox.
* @param {*} src
*/
const createImageBtn = (src) => {
console.debug(`making image ${src.filename}`)
const img = document.createElement('img')
const but = document.createElement('button')
Object.assign(but.style, {
height: '120px',
width: '120px',
border: 'none',
padding: 0,
margin: 0,
})
Object.assign(img.style, {
width: '100%',
height: '100%',
objectFit: 'cover',
})
Object.assign(but.style, {
height: '120px',
width: '120px',
border: 'none',
padding: 0,
margin: 0,
})
Object.assign(img.style, {
width: '100%',
height: '100%',
objectFit: 'cover',
})
img.src = `/view?filename=${encodeURIComponent(src.filename)}&type=${
src.type
}&subfolder=${encodeURIComponent(src.subfolder)}`
img.src = `/view?filename=${encodeURIComponent(src.filename)}&type=${
src.type
}&subfolder=${encodeURIComponent(src.subfolder)}`
imageUrls.push(img.src)
imageUrls.push(img.src)
console.debug(img.src)
console.debug(img.src)
img.onload = () => {
but.style.width = `${120 * (img.naturalWidth / img.naturalHeight)}px`
}
img.onload = () => {
but.style.width = `${120 * (img.naturalWidth / img.naturalHeight)}px`
}
but.onclick = () => {
lightboxContainer.style.display = 'flex'
// add the same image to the lightbox
lightboxImage.src = img.src
// lighboxContainer.replaceChildren(lightboxButtons, img);
}
but.onclick = () => {
lightboxContainer.style.display = 'flex'
// add the same image to the lightbox
lightboxImage.src = img.src
// lighboxContainer.replaceChildren(lightboxButtons, img);
}
// add right click menu
but.addEventListener('contextmenu', (e) => {
e.preventDefault()
// add right click menu
but.addEventListener('contextmenu', (e) => {
e.preventDefault()
if (image_menu) {
image_menu.remove()
}
if (image_menu) {
image_menu.remove()
}
image_menu = document.createElement('div')
Object.assign(image_menu.style, {
position: 'absolute',
top: `${e.clientY}px`,
left: `${e.clientX}px`,
background: '#333',
color: '#fff',
padding: '5px',
borderRadius: '5px',
zIndex: 999,
})
const load_img = document.createElement('button')
load_img.textContent = 'Load'
load_img.onclick = () => {
app.handleFile(img.src)
}
image_menu = document.createElement('div')
Object.assign(image_menu.style, {
position: 'absolute',
top: `${e.clientY}px`,
left: `${e.clientX}px`,
background: '#333',
color: '#fff',
padding: '5px',
borderRadius: '5px',
zIndex: 999,
})
const load_img = document.createElement('button')
load_img.textContent = 'Load'
load_img.onclick = () => {
app.handleFile(img.src)
}
image_menu.appendChild(load_img)
document.body.appendChild(image_menu)
})
image_menu.appendChild(load_img)
document.body.appendChild(image_menu)
})
but.append(img)
imageListContainer.prepend(but)
}
but.append(img)
imageListContainer.prepend(but)
}
loadButton.onclick = async () => {
const all_history = await api.getHistory()
for (const history of all_history.History) {
if (history.outputs) {
for (const key of Object.keys(history.outputs)) {
console.debug(key)
if (history.outputs[key].images) {
for (const im of history.outputs[key].images) {
console.debug(im)
createImageBtn(im)
}
}
}
// for (const src of outputs.outputs.images) {
// console.debug(src)
// makeImage(`${src.subfolder}/${src.filename}`)
// }
}
}
}
loadButton.onclick = async () => {
const all_history = await api.getHistory()
for (const history of all_history.History) {
if (history.outputs) {
for (const key of Object.keys(history.outputs)) {
console.debug(key)
if (history.outputs[key].images) {
for (const im of history.outputs[key].images) {
console.debug(im)
createImageBtn(im)
}
}
}
// for (const src of outputs.outputs.images) {
// console.debug(src)
// makeImage(`${src.subfolder}/${src.filename}`)
// }
}
}
}
///////-------
///////-------
// const all_history = await api.getHistory()
// for (const history of all_history.History) {
// if (history.outputs) {
// for (const key of Object.keys(history.outputs)) {
// for (const im of history.outputs[key].images) {
// makeImage(im)
// }
// }
// // for (const src of outputs.outputs.images) {
// // console.debug(src)
// // makeImage(`${src.subfolder}/${src.filename}`)
// // }
// }
// }
// const all_history = await api.getHistory()
// for (const history of all_history.History) {
// if (history.outputs) {
// for (const key of Object.keys(history.outputs)) {
// for (const im of history.outputs[key].images) {
// makeImage(im)
// }
// }
// // for (const src of outputs.outputs.images) {
// // console.debug(src)
// // makeImage(`${src.subfolder}/${src.filename}`)
// // }
// }
// }
//- Hook into the API
api.addEventListener('executed', ({ detail }) => {
if (detail?.output?.images) {
for (const src of detail.output.images) {
console.debug(`Adding ${src} to image feed`)
createImageBtn(src)
}
}
})
},
//- Hook into the API
api.addEventListener('executed', ({ detail }) => {
if (detail?.output?.images) {
for (const src of detail.output.images) {
console.debug(`Adding ${src} to image feed`)
createImageBtn(src)
}
}
})
},
})
+215 -39
View File
@@ -1,6 +1,9 @@
/// <reference path="../types/typedefs.js" />
import { app } from '../../scripts/app.js'
import { api } from '../../scripts/api.js'
import * as mtb_ui from './mtb_ui.js'
import * as shared from './comfy_shared.js'
import {
@@ -13,13 +16,20 @@ import {
} from './mtb_ui.js'
const offset = 0
// These are "global" variables mostly meant to sync user settings.
let currentWidth = 200
let saltUrls =
app.extensionManager.setting.get('mtb.io-sidebar.salt_urls') || false
let targetWidth =
app.extensionManager.setting.get('mtb.io-sidebar.img-size') || 512
let currentMode = 'input'
let subfolder = ''
let currentSort = 'None'
const IMAGE_NODES = ['LoadImage', 'VHS_LoadImagePath']
const VIDEO_NODES = ['VHS_LoadVideo']
const PROCESSED_PROMPT_IDS = new Set()
const updateImage = (node, image) => {
if (IMAGE_NODES.includes(node.type)) {
@@ -38,7 +48,78 @@ const updateImage = (node, image) => {
}
}
const getImgsFromUrls = (urls, target) => {
/**
* Converts a result item to a request url.
* @param {ResultItem} resultItem
* @returns {string} - The request URL.
*/
const resultItemToQuery = (resultItem) => {
const res = [
`/mtb/view?filename=${resultItem.filename}`,
`type=${resultItem.type}`,
`subfolder=${resultItem.subfolder}`,
'preview=',
]
if (targetWidth > 0) {
res.splice(1, 0, `width=${targetWidth}`)
}
return res.join('&')
}
/**
* Retrieves the unique prompt ID from a history task item.
* @param {HistoryTaskItem} historyTaskItem
* @returns {string} - The prompt ID.
*/
const getPromptId = (historyTaskItem) => `${historyTaskItem.prompt[1]}`
/**
* Process and return any new/unseen outputs from the most recent history item.
* @param {HistoryTaskItem} mostRecentTask - The most recent history task item.
* @returns {Object<string, string>} - A map of task outputs URLs.
*/
const getNewOutputUrls = (mostRecentTask) => {
if (!mostRecentTask) return
const promptId = getPromptId(mostRecentTask)
if (PROCESSED_PROMPT_IDS.has(promptId)) return
const urls = {}
for (const nodeOutputs of Object.values(mostRecentTask.outputs)) {
const { images, audio, animated } = nodeOutputs
if (images) {
const imageOutputs = Object.values(nodeOutputs.images)
imageOutputs.forEach(
(resultItem) =>
(urls[resultItem.filename] = resultItemToQuery(resultItem)),
)
}
// Can process `animated` and `audio` outputs here.
}
const foundNewOutputs = Object.keys(urls).length > 0
if (!foundNewOutputs) return null
PROCESSED_PROMPT_IDS.add(promptId)
return urls
}
/** Fetch history and update the grid with any new ouput images. */
const updateOutputsGrid = async () => {
try {
const history = await api.getHistory(/** maxSize: */ 1)
const mostRcentTask = history.History[0]
const newUrls = getNewOutputUrls(mostRcentTask)
if (newUrls) {
const imgGrid = document.querySelector('.mtb_img_grid')
getImgsFromUrls(newUrls, imgGrid, { prepend: true })
}
} catch (error) {
console.error('Error fetching history:', error)
}
}
const getImgsFromUrls = (urls, target, options = { prepend: false }) => {
const imgs = []
if (urls === undefined) {
return imgs
@@ -123,7 +204,8 @@ const getImgsFromUrls = (urls, target) => {
imgs.push(a)
}
if (target !== undefined) {
target.append(...imgs)
if (options.prepend) target.prepend(...imgs)
else target.append(...imgs)
}
return imgs
}
@@ -138,7 +220,7 @@ const getUrls = async (subfolder) => {
if (currentMode === 'video') {
const output = await shared.runAction(
'getUserVideos',
256,
targetWidth,
count,
offset,
currentSort,
@@ -148,11 +230,13 @@ const getUrls = async (subfolder) => {
const output = await shared.runAction(
'getUserImages',
currentMode,
targetWidth,
count,
offset,
currentSort,
false,
subfolder,
saltUrls,
)
return output || {}
}
@@ -165,55 +249,110 @@ if (window?.__COMFYUI_FRONTEND_VERSION__) {
const sidebar_extension = {
name: 'mtb.io-sidebar',
// init: async () => {
// try {
// const res = await api.fetchApi('/mtb/server-info')
// const msg = await res.json()
// exposed = msg.exposed
// } catch (e) {
// console.error('Error:', e)
// }
// },
init: () => {
let handle
const version = window?.__COMFYUI_FRONTEND_VERSION__
console.log(`%c ${version}`, 'background: orange; color: white;')
ensureMTBStyles()
app.ui.settings.addSetting({
settings: [
{
id: 'mtb.io-sidebar.count',
category: ['mtb', 'Input & Output Sidebar', 'count'],
name: 'Number of images to fetch',
type: 'number',
defaultValue: 1000,
tooltip:
"This setting affects the input/output sidebar to determine how many images to fetch per pagination (pagination is not yet supported so for now it's the static total)",
attrs: {
style: {
// fontFamily: 'monospace',
},
},
{
id: 'mtb.io-sidebar.salt_urls',
category: ['mtb', 'Input & Output Sidebar', 'salt_urls'],
name: 'Salt URLs',
type: 'boolean',
defaultValue: false,
onChange: (n, o) => {
saltUrls = n
},
})
app.ui.settings.addSetting({
tooltip:
'Adds a random query parameter to every urls to always invalidate caching.',
},
{
id: 'mtb.io-sidebar.img-size',
category: ['mtb', 'Input & Output Sidebar', 'img-size'],
name: 'Resolution of the images',
type: 'number',
name: 'Resize width of shown images',
defaultValue: 512,
type: (name, setter, value, attrs) => {
targetWidth = value
const container = mtb_ui.makeElement('div', {
display: 'flex',
alignItems: 'center',
gap: '8px',
})
tooltip: "It's recommended to keep it at 512px",
attrs: {
style: {
// fontFamily: 'monospace',
},
console.log({ name, setter, value, attrs })
const baseId = name.replace(/[^a-zA-Z0-9]/g, '-').toLowerCase()
const checkboxId = `${baseId}-checkbox`
const numberInputId = `${baseId}-number`
const isCheckedInitially = value !== -1
// TODO: better way to get defaultValue?
const defaultValue = 512
const initialNumberValue = isCheckedInitially ? value : defaultValue
console.log('recreate')
const checkbox = mtb_ui.makeElement(
// harder to match styles (.p-toggleswitch-input)
// since it uses a div synced to the input...
'input',
{},
container,
)
checkbox.type = 'checkbox'
checkbox.id = checkboxId
checkbox.checked = isCheckedInitially
const numberInput = mtb_ui.makeElement(
'input.p-inputtext',
{},
container,
)
numberInput.type = 'number'
numberInput.id = numberInputId
numberInput.value = initialNumberValue
numberInput.disabled = !isCheckedInitially
numberInput.min = 128
checkbox.addEventListener('change', () => {
let valToSet = -1
if (checkbox.checked) {
numberInput.disabled = false
valToSet = Number.parseInt(numberInput.value, 10)
if (Number.isNaN(valToSet) || valToSet < numberInput.min) {
valToSet = defaultValue
numberInput.value = valToSet
}
} else {
numberInput.disabled = true
}
setter(valToSet)
})
numberInput.addEventListener('input', () => {
if (checkbox.checked) {
const numValue = Number.parseInt(numberInput.value, 10)
if (!Number.isNaN(numValue) && numberInput.value !== '') {
setter(numValue)
}
}
})
return container
},
})
app.ui.settings.addSetting({
tooltip:
"If browsing large folders it's recommended to use this to avoid overflow/crash of the webpage. Image will get resized to this target width on the server before being sent to the client.",
},
{
id: 'mtb.io-sidebar.sort',
category: ['mtb', 'Input & Output Sidebar', 'sort'],
name: 'Default sort mode',
@@ -233,7 +372,39 @@ if (window?.__COMFYUI_FRONTEND_VERSION__) {
'Name',
'Name-Reverse',
],
})
},
{
id: 'mtb.io-sidebar.notice',
category: ['mtb', 'Input & Output Sidebar', 'sort'],
name: ' ',
type: (name, setter, value, attrs) => {
const container = mtb_ui.makeElement('div')
const notice =
'## Important\nIf you make **any** edits here you need to toggle off and back on the sidebar for it to take effect.'
if (window.MTB?.mdParser) {
MTB.mdParser.parse(notice).then((e) => {
container.innerHTML = e
})
} else {
shared.ensureMarkdownParser((p) => {
p.parse(notice).then((e) => {
container.innerHTML = e
})
})
}
return container
},
},
],
init: () => {
let handle
const version = window?.__COMFYUI_FRONTEND_VERSION__
console.log(`%c ${version}`, 'background: orange; color: white;')
ensureMTBStyles()
app.extensionManager.registerSidebarTab({
id: 'mtb-inputs-outputs',
@@ -324,11 +495,16 @@ if (window?.__COMFYUI_FRONTEND_VERSION__) {
}
})
handle = renderSidebar(el, cont, [selector, imgGrid, imgTools])
app.api.addEventListener('status', async () => {
if (currentMode !== 'output') return
updateOutputsGrid()
})
},
destroy: () => {
if (handle) {
handle.unregister()
handle = undefined
app.api.removeEventListener('status')
}
},
})
+529
View File
@@ -0,0 +1,529 @@
/** Python REPL for the frontend (uses rich)*/
import { app } from '../../scripts/app.js'
import * as shared from './comfy_shared.js'
import * as mtb_ui from './mtb_ui.js'
class ComfyREPL extends LiteGraph.LGraphNode {
constructor() {
super()
this.shape = LiteGraph.BOX_SHAPE
this.isVirtualNode = true
this.category = 'mtb/repl'
this.title = '🐍 REPL (mtb)'
this.uuid = shared.makeUUID()
this.size = [600, 400]
// Create a container for our custom widgets
this.widget = this.addDOMWidget('HTML', 'html', this.createREPLWidget())
this.loadAceEditor()
// Store input and output for persistence
this.properties = {
inputCode: '',
outputHistory: '',
}
this.outputArea.innerHTML = this.properties.outputHistory
this.outputArea.scrollTop = this.outputArea.scrollHeight
// Debounced linting function
this.debouncedLint = shared.debounce(this.lintCode.bind(this), 500)
// Resizing state variables
this.isResizing = false
this.initialMouseY = 0
this.initialInputHeight = 0
this.initialOutputHeight = 0
}
loadAceEditor() {
if (window.MTB?.ace_loaded) {
return
}
let NEED_PATCH = false
if (window.ace) {
shared.infoLogger(
'A global ace was found in scope, to avoid issues with it we will patch it',
)
NEED_PATCH = true
// window._backupAce = window.ace
// window.ace = null
}
shared
.loadScript('/mtb_async/ace/ace.js')
.then((m) => {
shared.infoLogger('ACE was loaded', m)
// window.MTB_ACE = window.ace
window.MTB.ace_loaded = true
this.initAceEditor()
this.aceEditor.setValue(this.properties.inputCode, -1)
})
.catch((e) => {
shared.errorLogger(e)
})
.finally(() => {
if (NEED_PATCH) {
console.log('Patching back window object')
window.ace = window._backupAce
}
})
}
initAceEditor() {
if (!window.MTB.ace_loaded) {
console.error('ACE editor not loaded. Cannot set up editors.')
return
}
if (!this.inputDiv) {
console.error('Input div not found for Ace editor initialization.')
return
}
this.aceEditor = ace.edit(this.inputDiv)
this.aceEditor.setTheme('ace/theme/monokai') //"ace/theme/dracula", "ace/theme/github"
this.aceEditor.session.setMode('ace/mode/python')
this.aceEditor.setOptions({
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
fontSize: '14px',
fontFamily: 'monospace',
showPrintMargin: false,
wrap: true,
tabSize: 4,
useSoftTabs: true,
highlightActiveLine: true,
highlightSelectedWord: true,
cursorStyle: 'ace', // "ace" | "slim" | "smooth" | "wide"
behavioursEnabled: true,
displayIndentGuides: true,
fixedWidthGutter: true,
scrollPastEnd: 0.5,
})
// Custom keybinding for Ctrl+Enter
this.aceEditor.commands.addCommand({
name: 'runCode',
bindKey: { win: 'Ctrl-Enter', mac: 'Command-Enter' },
exec: () => this.executeCode(),
})
// Listen for changes to trigger linting
let lintDisabled = false
this.aceEditor.session.on('change', () => {
if (!lintDisabled) {
this.debouncedLint()
}
})
this.outputArea.scrollTop = this.outputArea.scrollHeight
}
addOutput(html) {
this.outputArea.innerHTML += html
this.properties.outputHistory += html
this.outputArea.scrollTop = this.outputArea.scrollHeight
}
createREPLWidget() {
const container = mtb_ui.makeElement('div', {
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
boxSizing: 'border-box',
padding: '5px',
})
this.inputDiv = mtb_ui.makeElement(
'div',
{
width: 'calc(100% - 10px)',
height: '100px',
backgroundColor: '#333',
color: '#eee',
border: '1px solid #555',
borderRadius: '4px',
marginBottom: '5px',
boxSizing: 'border-box',
overflow: 'hidden',
},
container,
)
// Resizable Handle
this.handleDiv = mtb_ui.makeElement(
'div',
{
width: '100%',
height: '5px',
backgroundColor: '#666',
cursor: 'ns-resize',
marginBottom: '5px',
borderRadius: '2px',
},
container,
)
this.handleDiv.addEventListener('mousedown', this.startResizing.bind(this))
// Run Button
this.runButton = mtb_ui.makeElement(
'button',
{
width: '100%',
padding: '8px',
backgroundColor: '#555',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
marginBottom: '5px',
fontSize: '14px',
},
container,
)
this.runButton.textContent = 'Run Code (Ctrl+Enter)'
this.runButton.onclick = () => this.executeCode()
// Clear Button
this.clearButton = mtb_ui.makeElement(
'button',
{
width: '100%',
padding: '8px',
backgroundColor: '#555',
color: '#fff',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
marginBottom: '5px',
fontSize: '14px',
},
container,
)
this.clearButton.textContent = 'Clear Output'
this.clearButton.onclick = () => {
this.outputArea.innerHTML = ''
this.properties.outputHistory = ''
}
// Output Area
this.outputArea = mtb_ui.makeElement(
'div',
{
flexGrow: '1',
width: 'calc(100% - 10px)',
backgroundColor: '#222',
color: '#ddd',
border: '1px solid #555',
borderRadius: '4px',
padding: '5px',
fontFamily: 'monospace',
fontSize: '14px',
overflowY: 'auto',
whiteSpace: 'pre-wrap',
boxSizing: 'border-box',
},
container,
)
return container
}
// --- Resizing Logic ---
startResizing(e) {
if (!this.inputDiv) {
shared.infoLogger("The input div isn't ready", this)
shared.errorLogger("The input div isn't ready")
return
}
this.isResizing = true
this.initialMouseY = e.clientY
this.initialInputHeight = this.inputDiv.offsetHeight
this.initialOutputHeight = this.outputArea.offsetHeight
document.addEventListener('mousemove', this.doResize.bind(this))
document.addEventListener('mouseup', this.stopResizing.bind(this))
document.body.style.cursor = 'ns-resize' // Change cursor globally
}
doResize(e) {
if (!this.isResizing) return
const deltaY = e.clientY - this.initialMouseY
let new_input_height = this.initialInputHeight + deltaY
let new_output_height = this.initialOutputHeight - deltaY
const minInputHeight = 50 // Minimum height for Ace editor
const minOutputHeight = 50 // Minimum height for output area
// Clamp heights to minimums
if (new_input_height < minInputHeight) {
new_input_height = minInputHeight
new_output_height =
this.initialInputHeight + this.initialOutputHeight - minInputHeight
}
if (new_output_height < minOutputHeight) {
new_output_height = minOutputHeight
new_input_height =
this.initialInputHeight + this.initialOutputHeight - minOutputHeight
}
this.inputDiv.style.height = `${new_input_height}px`
this.outputArea.style.height = `${new_output_height}px`
// Update the stored ratio for persistence
const totalDynamicHeight =
this.inputDiv.offsetHeight + this.outputArea.offsetHeight
if (totalDynamicHeight > 0) {
this.properties.inputHeightRatio = new_input_height / totalDynamicHeight
}
this.aceEditor.resize() // Important for Ace to redraw
}
stopResizing() {
this.isResizing = false
document.removeEventListener('mousemove', this.doResize)
document.removeEventListener('mouseup', this.stopResizing)
document.body.style.cursor = '' // Restore default cursor
}
// --- End Resizing Logic ---
async executeCode() {
const code = this.aceEditor.getValue()
if (!code.trim()) {
return
}
const inputPrompt = `<div style="color:#888; margin-top: 10px;">>>> ${code}</div>`
this.addOutput(inputPrompt)
try {
const response = await fetch('/mtb/execute', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: code, name: this.uuid }),
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const result = await response.json()
console.debug('Received from backend', result)
const outputHtml = result.output_html || ''
const error = result.error
if (error) {
this.addOutput(
`<div style="color: #f00; font-weight: bold;">Error:</div>${outputHtml}`,
)
} else {
this.addOutput(outputHtml)
}
} catch (e) {
const errorMessage = `<div style="color: #f00;">Frontend Error: ${e.message}</div>`
this.addOutput(errorMessage)
console.error('ComfyREPL Frontend Error:', e)
} finally {
// Not clearing
// this.inputArea.value = '' // Clear input after execution
// this.properties.inputCode = '' // Clear persisted input
}
}
async lintCode() {
if (!this.aceEditor) {
return
}
const code = this.aceEditor.getValue()
if (!code.trim()) {
this.aceEditor.session.setAnnotations([]) // Clear annotations if empty
return
}
try {
const response = await fetch('/mtb/lint', {
// New linting endpoint
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ code: code, name: this.uuid }),
})
if (!response.ok) {
console.log(response)
throw new Error(
`HTTP error! status: ${response.status} ${response.statusText}`,
)
}
const result = await response.json()
// result.diagnostics should be an array of {row, column, text, type}
this.aceEditor.session.setAnnotations(result.diagnostics)
} catch (e) {
console.error('ComfyREPL Linting Error:', e)
this.aceEditor.session.setAnnotations([
{
row: 0,
column: 0,
text: `Linting failed: ${e.message}`,
type: 'error',
},
])
}
}
// Restore properties when loading a graph
onConfigure() {
if (this.properties.inputCode && this.aceEditor) {
this.aceEditor.setValue(this.properties.inputCode, -1)
}
// if (this.properties.inputCode) {
// this.inputArea.value = this.properties.inputCode
// }
if (this.properties.outputHistory) {
this.outputArea.innerHTML = this.properties.outputHistory
this.outputArea.scrollTop = this.outputArea.scrollHeight
}
if (this.properties.uuid) {
this.uuid = this.properties.uuid
}
this.debouncedLint()
this.onResize(this.size)
}
// Save properties when saving a graph
onSerialize(o) {
if (this.aceEditor) {
o.properties.inputCode = this.aceEditor.getValue() //this.inputArea.value
}
o.properties.outputHistory = this.outputArea.innerHTML
o.properties.uuid = this.uuid
o.properties.inputHeightRatio = this.properties.inputHeightRatio
}
onRemoved() {
// Clean up DOM elements when node is removed
if (this.widget?.element?.parentNode) {
this.widget.element.parentNode.removeChild(this.widget.element)
}
// Destroy Ace editor instance to prevent memory leaks
if (this.aceEditor) {
this.aceEditor.destroy()
this.aceEditor.container.remove() // Remove the Ace container div from DOM
}
// Clean up global event listeners if node is removed while resizing
document.removeEventListener('mousemove', this.doResize)
document.removeEventListener('mouseup', this.stopResizing)
document.body.style.cursor = ''
}
// LiteGraph method to handle node resizing
onResize(size) {
// Call parent method if it exists (important for LiteGraph's internal sizing)
if (super.onResize) {
super.onResize(size)
}
// Adjust container size
const container = this.widget.element
container.style.width = `${size[0] - 10}px` // Account for padding
container.style.height = `${size[1] - 10}px`
// Adjust input and output area widths
this.inputDiv.style.width = 'calc(100% - 10px)'
this.outputArea.style.width = 'calc(100% - 10px)'
//
// const old = () => {
// // Calculate remaining height for output area
// // Ace editor manages its own height within this.inputDiv, so we use offsetHeight
// const inputHeight = this.inputDiv.offsetHeight
// const runButtonHeight = this.runButton.offsetHeight
// const clearButtonHeight = this.clearButton.offsetHeight
// const totalFixedHeight =
// inputHeight + runButtonHeight + clearButtonHeight + 15 // 15 for margins/padding
//
// const remainingHeight = size[1] - 10 - totalFixedHeight
// this.outputArea.style.height = `${Math.max(50, remainingHeight)}px` // Min height 50px
// }
// Calculate dynamic heights
const containerHeight = size[1] - 10
const handleHeight = this.handleDiv.offsetHeight
const buttonHeights =
this.runButton.offsetHeight + this.clearButton.offsetHeight + 15 // Sum of button heights + margins
const dynamicContentHeight = containerHeight - buttonHeights - handleHeight
const minInputHeight = 50
const minOutputHeight = 50
let inputHeight = Math.max(
minInputHeight,
dynamicContentHeight * (this.properties.inputHeightRatio || 1.0),
)
let outputHeight = Math.max(
minOutputHeight,
dynamicContentHeight - inputHeight,
)
//
// // Re-distribute if one hits its minimum
// if (
// inputHeight === minInputHeight &&
// dynamicContentHeight - minInputHeight > minOutputHeight
// ) {
// outputHeight = dynamicContentHeight - minInputHeight
// } else if (
// outputHeight === minOutputHeight &&
// dynamicContentHeight - minOutputHeight > minInputHeight
// ) {
// inputHeight = dynamicContentHeight - minOutputHeight
// }
//
// // Final check to ensure total height matches available dynamic space
// const currentTotal = inputHeight + outputHeight
// if (currentTotal !== dynamicContentHeight) {
// // Adjust one of them if there's a small discrepancy due to rounding
// if (inputHeight > minInputHeight) {
// inputHeight += dynamicContentHeight - currentTotal
// } else if (outputHeight > minOutputHeight) {
// outputHeight += dynamicContentHeight - currentTotal
// }
// }
this.inputDiv.style.height = `${inputHeight}px`
this.outputArea.style.height = `${outputHeight}px`
// Update the ratio based on the actual heights set
if (dynamicContentHeight > 0) {
this.properties.inputHeightRatio = inputHeight / dynamicContentHeight
}
// Inform Ace editor about the resize so it can redraw its content
if (this.aceEditor) {
this.aceEditor.resize()
}
}
}
const repl = {
name: 'mtb.repl',
registerCustomNodes() {
LiteGraph.registerNodeType('Python REPL', ComfyREPL)
},
}
app.registerExtension(repl)
-28
View File
@@ -1,28 +0,0 @@
// NOTE: this will be the LT part of mtb API system
// I need to properly publish the source and fix a few things before
// import { app } from '../../scripts/app.js'
// // import { api } from '../../scripts/api.js'
//
// import * as shared from './comfy_shared.js'
// import { createOutliner } from './dist/mtb_inspector.js'
//
// if (window?.__COMFYUI_FRONTEND_VERSION__) {
// const version = window?.__COMFYUI_FRONTEND_VERSION__
// console.log(`%c ${version}`, 'background: orange; color: white;')
//
// const panel = app.extensionManager.registerSidebarTab({
// id: 'mtb-nodes',
// icon: 'pi pi-bolt',
// title: 'MTB',
// tooltip: 'MTB: API outliner',
// type: 'custom',
// // this is run everytime the tab's diplay is toggled on.
// render: (el) => {
// const outliner = createOutliner(el)
// const inputs = shared.getAPIInputs()
// console.log('INPUTS', inputs)
// outliner.$$set({ inputs })
// },
// })
// }
+16 -1
View File
@@ -184,6 +184,18 @@ ${inputs}
)
}
/**
* Wrap an element with a div
*
* @param {Object} [style] - CSS styles to apply to the element.
* @returns {HTMLElement} - The created DOM element.
*/
export const wrapElement = (element, style = {}) => {
const container = makeElement('div', style)
container.appendChild(element)
return container
}
/**
* Creates a DOM element with optional styles, class, and id.
*
@@ -191,7 +203,7 @@ ${inputs}
* @param {Object} [style] - CSS styles to apply to the element.
* @returns {HTMLElement} - The created DOM element.
*/
export const makeElement = (kind, style) => {
export const makeElement = (kind, style, parent) => {
let [real_kind, className] = kind.split('.')
let id
@@ -212,6 +224,9 @@ export const makeElement = (kind, style) => {
if (id) {
el.id = id
}
if (parent) {
parent.appendChild(el)
}
return el
}
+178 -21
View File
@@ -21,7 +21,7 @@ import { infoLogger } from './comfy_shared.js'
import { NumberInputWidget } from './numberInput.js'
// NOTE: new widget types registered by MTB Widgets
const newTypes = [/*'BOOL'*/ , 'COLOR', 'BBOX']
const newTypes = [/*'BOOL'*/ 'COLOR', 'BBOX']
const deprecated_nodes = {
// 'Animation Builder':
@@ -694,7 +694,7 @@ const mtb_widgets = {
app.ui.settings.addSetting({
id: 'mtb.Main.debug-enabled',
category: ['mtb', 'Main', 'debug-enabled'],
category: ['mtb', ' Main', 'debug-enabled'],
name: 'Enable Debug (py and js)',
type: 'boolean',
defaultValue: false,
@@ -1012,12 +1012,15 @@ const mtb_widgets = {
)
loop_preview.value = 'Iteration: Idle'
let cancelQueue = false
const onReset = () => {
raw_iteration.value = 0
raw_loop.value = 0
value_preview.value = 'Idle'
loop_preview.value = 'Iteration: Idle'
cancelQueue = false
app.canvas.setDirty(true)
}
@@ -1026,15 +1029,42 @@ const mtb_widgets = {
this.addWidget('button', 'Reset', 'reset', onReset)
// 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)
const chunkSize = 10
this.addWidget('button', 'Queue', 'queue', async () => {
onReset()
const totalPrompts = 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})`,
`Starting a queue of ${totalPrompts} frames in chunks of ${chunkSize}...`,
5000,
)
for (let i = 0; i < totalPrompts; i += chunkSize) {
console.log({ cancelQueue })
if (cancelQueue) {
window.MTB?.notify?.(
`Queueing cancelled after ${i} frames.`,
3000,
)
break
}
const currentChunkSize = Math.min(chunkSize, totalPrompts - i)
await app.queuePrompt(0, currentChunkSize)
}
if (!cancelQueue) {
window.MTB?.notify?.(
`Finished queuing ${totalPrompts} frames.`,
5000,
)
}
})
this.addWidget('button', 'Cancel', 'cancel', () => {
cancelQueue = true
window.MTB?.notify?.(
'Cancellation requested. Waiting for current chunk to finish...',
3000,
)
})
this.onRemoved = () => {
@@ -1166,7 +1196,9 @@ const mtb_widgets = {
//NOTE: dynamic nodes
case 'Apply Text Template (mtb)': {
shared.setupDynamicConnections(nodeType, 'var', '*')
shared.setupDynamicConnections(nodeType, 'var', '*', {
rename_menu: 'name',
})
break
}
case 'Save Data Bundle (mtb)': {
@@ -1283,23 +1315,148 @@ const mtb_widgets = {
})
break
}
case 'Save Tensors (mtb)': {
case 'Scene Detect (mtb)': {
break
}
case 'Loop Start (mtb)': {
const onDrawBackground = nodeType.prototype.onDrawBackground
nodeType.prototype.onDrawBackground = function (ctx, canvas) {
nodeType.prototype.onDrawBackground = function (...args) {
const r = onDrawBackground
? onDrawBackground.apply(this, arguments)
? onDrawBackground.apply(this, args)
: 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();
const [ctx, /*canvas,*/ ..._rest] = args
if (this.flags.collapsed) return r
if (!this.computed_flow) {
const related = new Set([this.id])
const visited = new Set()
if (this.outputs[0].links) {
for (const linkId of this.outputs[0].links) {
const { to: loopEnd } = shared.nodesFromLink(this, linkId)
const canReachEnd = (node, visited = new Set()) => {
if (node === loopEnd) return true
if (visited.has(node.id)) return false
visited.add(node.id)
for (const output of node.outputs || []) {
if (!output.links) continue
for (const linkId of output.links) {
const { to: nextNode } = shared.nodesFromLink(
node,
linkId,
)
if (!nextNode) continue
if (canReachEnd(nextNode, visited)) {
return true
}
}
}
return false
}
const traverseNodes = (node) => {
if (visited.has(node.id)) return
visited.add(node.id)
// 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);
// can reach the end
if (node !== this && node !== loopEnd && !canReachEnd(node)) {
return
}
related.add(node.id)
for (const output of node.outputs || []) {
if (!output.links) continue
for (const linkId of output.links) {
const { to: nextNode } = shared.nodesFromLink(
node,
linkId,
)
if (!nextNode) continue
traverseNodes(nextNode)
}
}
}
traverseNodes(this)
}
}
this.related_to_flow = Array.from(related)
this.computed_flow = true
}
if (this.related_to_flow) {
ctx.save()
const points = []
const padding = 20
const graph = this.graph
const offset = this._pos
for (const nodeId of this.related_to_flow) {
const node = graph.getNodeById(nodeId)
if (!node) continue
const scale = 1.0
const x = node._pos[0] * scale - offset[0]
const y = node._pos[1] * scale - offset[1]
const width = node.size[0] * scale
const height = node.size[1] * scale
const scaledPadding = padding * scale
// console.log({ main: this, x, y, width, height })
points.push(
[x - scaledPadding, y - scaledPadding],
[x + width + scaledPadding, y - scaledPadding],
[x + width + scaledPadding, y + height + scaledPadding],
[x - scaledPadding, y + height + scaledPadding],
)
}
// console.log({ points })
const hull = shared.getConvexHull(points)
ctx.beginPath()
ctx.moveTo(hull[0][0], hull[0][1])
for (let i = 1; i < hull.length; i++) {
ctx.lineTo(hull[i][0], hull[i][1])
}
ctx.closePath()
ctx.fillStyle = 'rgba(255, 0, 0, 0.1)'
ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)'
ctx.lineWidth = 2
ctx.fill()
ctx.stroke()
ctx.restore()
} else {
ctx.save()
ctx.fillStyle = 'red'
ctx.fillRect(-50, -50, this.size[0] + 100, this.size[1] + 100)
ctx.fillStyle = 'white'
ctx.font = 'bold 12px Arial'
ctx.fillText(
`pos: ${this.x}x${this.y}`,
this.size[0] / 2,
this.size[1],
)
ctx.fillText(
`size:${this._posSize}`,
this.size[0] / 2,
this.size[1] - 30,
)
ctx.fillText(
`dpi: ${window.devicePixelRatio}`,
this.size[0] / 2,
this.size[1] - 60,
)
ctx.fillText(
`next: ${graph.getNodeById(this.related_to_flow[1])._posSize}`,
this.size[0] / 2,
this.size[1] - 90,
)
ctx.restore()
}
return r
}
break
+64 -52
View File
@@ -1,10 +1,13 @@
// web/note_plus.constants.js
export const DEFAULT_CSS = ''
export const DEFAULT_CSS = `/** here you can write css**/
h1 {
color: whitesmoke;
}`
export const DEFAULT_HTML = `<p style='color:red;font-family:monospace'>
Note+
</p>`
export const DEFAULT_MD = '## Note+'
export const DEFAULT_MD = '# 📝 Note+'
export const DEFAULT_MODE = 'markdown'
export const DEFAULT_THEME = 'one_dark'
@@ -55,58 +58,57 @@ We also support github callout:
`
export const THEMES = [
'ambiance',
'chaos',
'chrome',
'cloud9_day',
'cloud9_night',
'cloud9_night_low_color',
'cloud_editor',
'cloud_editor_dark',
'clouds',
'clouds_midnight',
'cobalt',
'crimson_editor',
'dawn',
'dracula',
'dreamweaver',
'eclipse',
'github',
'github_dark',
'gob',
'gruvbox',
'gruvbox_dark_hard',
'gruvbox_light_hard',
'idle_fingers',
'iplastic',
'katzenmilch',
'kr_theme',
'kuroir',
'merbivore',
'merbivore_soft',
'mono_industrial',
'monokai',
'nord_dark',
'one_dark',
'pastel_on_dark',
'solarized_dark',
'solarized_light',
'sqlserver',
'terminal',
'textmate',
'tomorrow',
'tomorrow_night',
'tomorrow_night_blue',
'tomorrow_night_bright',
'tomorrow_night_eighties',
'twilight',
'vibrant_ink',
'vscode',
'ambiance',
'chaos',
'chrome',
'cloud9_day',
'cloud9_night',
'cloud9_night_low_color',
'cloud_editor',
'cloud_editor_dark',
'clouds',
'clouds_midnight',
'cobalt',
'crimson_editor',
'dawn',
'dracula',
'dreamweaver',
'eclipse',
'github',
'github_dark',
'gob',
'gruvbox',
'gruvbox_dark_hard',
'gruvbox_light_hard',
'idle_fingers',
'iplastic',
'katzenmilch',
'kr_theme',
'kuroir',
'merbivore',
'merbivore_soft',
'mono_industrial',
'monokai',
'nord_dark',
'one_dark',
'pastel_on_dark',
'solarized_dark',
'solarized_light',
'sqlserver',
'terminal',
'textmate',
'tomorrow',
'tomorrow_night',
'tomorrow_night_blue',
'tomorrow_night_bright',
'tomorrow_night_eighties',
'twilight',
'vibrant_ink',
'vscode',
]
export const CSS_RESET = `
* {
font-family: monospace;
line-height: 1.25em;
}
.shiki{
@@ -116,6 +118,8 @@ export const CSS_RESET = `
.markdown-callout-title {
.octicon{
fill:white;
width:29px;
height:29px;
}
/* background: var(--current-color); */
color: var(--current-color);
@@ -124,6 +128,8 @@ export const CSS_RESET = `
/* border-start-start-radius: var(--radius); */
padding: 0.5em;
padding-inline-start: 1em;
display: flex;
align-items: center;
}
.markdown-callout-content {
padding: 1em;
@@ -136,7 +142,12 @@ export const CSS_RESET = `
border-left: 3px solid var(--current-color);
margin-bottom: 1em;
margin-top: 1em;
}
.markdown-callout p:nth-child(2) {
padding:1em;
}
.markdown-callout-tip {
--text-color: whitesmoke;
@@ -164,8 +175,9 @@ export const CSS_RESET = `
flex-direction:column;
align-items: flex-start;
width:95%;
margin-left: 20px;
margin-top:20px;
/*margin-left: 20px;*/
/*margin-top:20px;*/
/*background-color: rgba(255,0,0,0.5)!important;*/
}
+379 -336
View File
File diff suppressed because it is too large Load Diff
+12 -3
View File
@@ -41,7 +41,16 @@ const toastStyle = `
transition-duration: ${transition_time}ms;
`
function notify(message, timeout = 3000) {
function notify(message, timeout = 3000, old_mode = false) {
if (!old_mode) {
app.extensionManager.toast.add({
severity: 'info',
summary: 'MTB',
detail: message,
life: timeout,
})
return
}
log('Creating toast')
const container = document.getElementById('mtb-notify-container')
const toast = document.createElement('div')
@@ -59,7 +68,7 @@ function notify(message, timeout = 3000) {
log('Transition out')
const totalHeight = Array.from(container.children).reduce(
(acc, child) => acc + child.offsetHeight + 10, // Add spacing of 10px between toasts
0
0,
)
container.style.height = `${totalHeight}px`
@@ -83,7 +92,7 @@ function notify(message, timeout = 3000) {
// 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
0,
)
container.style.height = `${totalHeight}px`