Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
954b89f4a9 | ||
|
|
42161bcbfc | ||
|
|
3dbcf2cd67 | ||
|
|
21efb000b8 | ||
|
|
9725ed1366 | ||
|
|
77718e9428 | ||
|
|
42229d0d5d | ||
|
|
1accc920ce | ||
|
|
ea6d5d4e59 | ||
|
|
e90a7048fb | ||
|
|
114db05be0 | ||
|
|
d21729659d | ||
|
|
37d6569f68 | ||
|
|
a33af90b6d | ||
|
|
e8fe379c62 | ||
|
|
427506f771 | ||
|
|
9bf8f0f0dd | ||
|
|
668f3dd99d | ||
|
|
ad11af050a | ||
|
|
317aef7632 | ||
|
|
f0fbcfc1b0 | ||
|
|
2ec932da63 | ||
|
|
a9e7331f7d | ||
|
|
951c2dd423 | ||
|
|
fead8afdd3 | ||
|
|
723f0c19e1 | ||
|
|
444e7f816a | ||
|
|
1e3eb522ac | ||
|
|
295e967d88 | ||
|
|
9501b9e459 | ||
|
|
1650ee4769 | ||
|
|
4d8f28c5a2 | ||
|
|
83648284bf | ||
|
|
d711eda249 | ||
|
|
5d43f7d57d | ||
|
|
33ffb630a7 | ||
|
|
117ccde5f8 | ||
|
|
6e48c85602 | ||
|
|
699002b2bc | ||
|
|
b9841d810a | ||
|
|
c85827223f | ||
|
|
e6c241bb4a | ||
|
|
2ab911826a | ||
|
|
045951db79 | ||
|
|
eabe43db79 | ||
|
|
1c99a1c63c | ||
|
|
426cdf5f9f | ||
|
|
5fa3791559 | ||
|
|
5c0e020c73 | ||
|
|
d00722e9ea | ||
|
|
0106c13250 | ||
|
|
55226058d4 | ||
|
|
50e0f7b357 | ||
|
|
71f601094a | ||
|
|
ea750b5e8b | ||
|
|
ff2e99f73e | ||
|
|
efc6855073 | ||
|
|
0853b7fb6a | ||
|
|
10aa493dd8 | ||
|
|
f038d76748 | ||
|
|
940a781f29 | ||
|
|
c7248344cc | ||
|
|
fab33a40a2 | ||
|
|
8f83e8d4d7 | ||
|
|
6c59d5c32d | ||
|
|
e98f3f626f | ||
|
|
7e89e96e9d | ||
|
|
177b6eeef3 | ||
|
|
502a583409 | ||
|
|
a7966355c1 | ||
|
|
321abea51a | ||
|
|
63be3f26fd | ||
|
|
c4f40e299f | ||
|
|
b541670a5b | ||
|
|
4574c6451c | ||
|
|
7fb27804e1 | ||
|
|
9a7e022df1 | ||
|
|
2c483fd1d2 | ||
|
|
0967d439f5 | ||
|
|
319c02d658 | ||
|
|
265cb953ec | ||
|
|
7e36007933 | ||
|
|
bc5b613490 | ||
|
|
01107c45f8 | ||
|
|
96185132b8 | ||
|
|
d4a31bf19c | ||
|
|
fc7ba084f6 | ||
|
|
4516aa9cb4 | ||
|
|
0e48aaa3e4 | ||
|
|
78946b0fa3 | ||
|
|
c30408f96d | ||
|
|
eb7cf89f17 | ||
|
|
af42134028 | ||
|
|
a85e57b18c | ||
|
|
22fce6fdda | ||
|
|
147edcfcbc | ||
|
|
8bf3545fec | ||
|
|
f47149746a | ||
|
|
83cfc5c723 | ||
|
|
d87e52ea2c | ||
|
|
9405784764 | ||
|
|
55261bda7c | ||
|
|
cf7a9c41e8 | ||
|
|
3a25526e81 | ||
|
|
00173fa3fb | ||
|
|
0d264b90a7 | ||
|
|
a8cf4650ff | ||
|
|
edcb3da08b | ||
|
|
7f7a62f832 | ||
|
|
fc908ba0a5 | ||
|
|
ead4b34e6d | ||
|
|
46af6027d6 | ||
|
|
b7ca8ed1c6 | ||
|
|
4aad5c3b9d | ||
|
|
d61da30409 | ||
|
|
6851da6638 | ||
|
|
0eeb707f34 | ||
|
|
9a943714aa | ||
|
|
bae26a07fb | ||
|
|
c92d99a8a3 | ||
|
|
3f6d082940 | ||
|
|
58ae89f8e0 | ||
|
|
c9a26427a8 | ||
|
|
6608c0b6d1 | ||
|
|
a757e1c98b | ||
|
|
52bd76e19c | ||
|
|
d6e004cce2 | ||
|
|
ed17fa2ef4 | ||
|
|
827c64c43d | ||
|
|
e5482aee5e | ||
|
|
62469a4dd9 | ||
|
|
8c629bee18 | ||
|
|
50cb6f5ed6 | ||
|
|
e32d1e02df | ||
|
|
b0d52f7305 | ||
|
|
e17c6e29f5 | ||
|
|
27e03fa23e | ||
|
|
ec1cb1ac17 | ||
|
|
64634104a2 | ||
|
|
ecbb220de6 | ||
|
|
cd9e614b1a | ||
|
|
9ccf572a15 | ||
|
|
74af5c6499 | ||
|
|
caf0b39d8a | ||
|
|
e099d581a7 | ||
|
|
22f7c30373 | ||
|
|
0133fb93bc | ||
|
|
cf7d30507e | ||
|
|
b6fa571fd2 | ||
|
|
f272526bfc | ||
|
|
4e593bb30b | ||
|
|
097ca33b8e | ||
|
|
784fb0145b | ||
|
|
dbcca15a21 | ||
|
|
bc41576fac | ||
|
|
8596b8184e | ||
|
|
896a025006 | ||
|
|
43092e44a4 | ||
|
|
80b5a0ca74 | ||
|
|
81b3bc1651 | ||
|
|
a825504bdd | ||
|
|
22190cd25e | ||
|
|
a976adbb39 | ||
|
|
997d2fb13a | ||
|
|
f8829fcb37 | ||
|
|
9651a70341 | ||
|
|
57683c3c7d | ||
|
|
f99f92e8f7 | ||
|
|
5bc125d2f0 | ||
|
|
c99b0812ab | ||
|
|
333f646ab1 | ||
|
|
dbdf27664c | ||
|
|
7d5569e5c1 | ||
|
|
5681b464ad | ||
|
|
8d0fcee2f3 | ||
|
|
1078fc6f0f | ||
|
|
821a0ef427 | ||
|
|
9007a70aa0 | ||
|
|
1a0ebd5173 | ||
|
|
59608320c8 | ||
|
|
d64fac4b74 | ||
|
|
d687497d80 | ||
|
|
d6343e1860 | ||
|
|
4eebdd8b8b | ||
|
|
372e035686 | ||
|
|
fb34671ee6 | ||
|
|
f25f6bdcd1 | ||
|
|
f1b484617a | ||
|
|
4507842a70 |
@@ -0,0 +1,7 @@
|
||||
**/GFPGAN/inputs/**
|
||||
**/GFPGAN/tests/**
|
||||
**/frame_interpolation/photos/*
|
||||
moment.gif
|
||||
node.zip
|
||||
.DS_Store
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
name: 📦 Publish to Comfy registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "pyproject.toml"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.repository_owner == '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 }}
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
__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
|
||||
web/dist
|
||||
|
||||
+8
-6
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false
|
||||
}
|
||||
{
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"plugins": ["prettier-plugin-svelte"]
|
||||
}
|
||||
|
||||
|
||||
+238
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
[](code_of_conduct.md)
|
||||
|
||||
## Contact
|
||||
|
||||
If you have any questions or concerns about this Code of Conduct, please contact @melmass.
|
||||
|
||||
@@ -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!
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# 安装
|
||||
- [安装](#安装)
|
||||
- [自动安装(推荐)](#自动安装推荐)
|
||||
- [ComfyUI 管理器](#comfyui-管理器)
|
||||
- [虚拟环境](#虚拟环境)
|
||||
- [模型下载](#模型下载)
|
||||
- [网络扩展](#网络扩展)
|
||||
- [旧的安装方法 (MANUAL)](#旧的安装方法-manual)
|
||||
- [依赖关系](#依赖关系)
|
||||
### 自动安装(推荐)
|
||||
|
||||
### ComfyUI 管理器
|
||||
|
||||
从 0.1.0 版开始,该扩展将使用 [ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager) 进行安装,这对处理各种环境下的各种安装问题大有帮助。
|
||||
|
||||
### 虚拟环境
|
||||
还有一种试验性的单行安装方法,即在 ComfyUI 根目录下使用以下命令进行安装。它将下载代码、安装依赖项并运行安装脚本:
|
||||
|
||||
|
||||
```bash
|
||||
curl -sSL "https://raw.githubusercontent.com/username/repo/main/install.py" | python3 -
|
||||
```
|
||||
|
||||
## 模型下载
|
||||
某些节点需要下载额外的模型,您可以使用与上述相同的 python 环境以交互方式完成下载:
|
||||
|
||||
```bash
|
||||
python scripts/download_models.py
|
||||
```
|
||||
|
||||
然后根据提示或直接按回车键下载每个模型。
|
||||
|
||||
> **Note**
|
||||
> 您可以使用以下方法下载所有型号,无需提示:
|
||||
```bash
|
||||
python scripts/download_models.py -y
|
||||
```
|
||||
|
||||
#### 网络扩展
|
||||
|
||||
首次运行时,脚本会尝试将 [网络扩展](https://github.com/melMass/comfy_mtb/tree/main/web)链接到你的 "web/extensions "文件夹,[请参阅](https://github.com/melMass/comfy_mtb/blob/d982b69a58c05ccead9c49370764beaa4549992a/__init__.py#L45-L61)。
|
||||
|
||||
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
|
||||
|
||||
### 旧的安装方法 (MANUAL)
|
||||
### 依赖关系
|
||||
<details><summary><h4>Custom Virtualenv(我主要用这个)</h4></summary
|
||||
|
||||
1. 确保您处于用于 ComfyUI 的 Python 环境中。
|
||||
2. 运行以下命令安装所需的依赖项:
|
||||
```bash
|
||||
pip install -r comfy_mtb/reqs.txt
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary><h4>Comfy 便携式/单机版(来自 ComfyUI 版本)</h4></summary>
|
||||
|
||||
如果您使用 ComfyUI 单机版中的 `python-embeded `,那么当二进制文件没有轮子时,您就无法使用 pip 安装二进制文件的依赖项,在这种情况下,请查看最近的 [发布](https://github.com/melMass/comfy_mtb/releases),那里有一个预编译轮子的 linux 和 windows 捆绑包(只有那些需要从源代码编译的轮子),请查看 [此问题 (#1)](https://github.com/melMass/comfy_mtb/issues/1) 以获取更多信息。
|
||||

|
||||
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary><h4>Google Colab</h4></summary>
|
||||
|
||||
在 **Run ComfyUI with localtunnel (Recommended Way)** 标题之后(代码单元格之前)添加一个新的代码单元格
|
||||
|
||||

|
||||
|
||||
|
||||
```python
|
||||
# download the nodes
|
||||
!git clone --recursive https://github.com/melMass/comfy_mtb.git custom_nodes/comfy_mtb
|
||||
|
||||
# download all models
|
||||
!python custom_nodes/comfy_mtb/scripts/download_models.py -y
|
||||
|
||||
# install the dependencies
|
||||
!pip install -r custom_nodes/comfy_mtb/reqs.txt -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.0/index.html
|
||||
```
|
||||
|
||||
如果运行后 colab 抱怨需要重新启动运行时,请重新启动,然后不要重新运行之前的单元格,只运行运行本地隧道的单元格。(可能需要先添加一个包含 `%cd ComfyUI` 的单元格)
|
||||
|
||||
|
||||
> **Note**:
|
||||
> If you don't need all models, remove the `-y` as collab actually supports user input: 
|
||||
|
||||
> **Preview**
|
||||
> 
|
||||
|
||||
</details>
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# インストール
|
||||
|
||||
- [インストール](#インストール)
|
||||
- [自動インストール (推奨)](#自動インストール-推奨)
|
||||
- [ComfyUI マネージャ](#comfyui-マネージャ)
|
||||
- [仮想環境](#仮想環境)
|
||||
- [モデルのダウンロード](#モデルのダウンロード)
|
||||
- [ウェブ拡張機能](#ウェブ拡張機能)
|
||||
- [旧インストール方法 (MANUAL)](#旧インストール方法-manual)
|
||||
- [依存関係](#依存関係)
|
||||
|
||||
|
||||
## 自動インストール (推奨)
|
||||
|
||||
### ComfyUI マネージャ
|
||||
|
||||
バージョン0.1.0では、この拡張機能は[ComfyUI-Manager](https://github.com/ltdrdata/ComfyUI-Manager)と一緒にインストールすることを想定しています。これは、様々な環境で直面する様々なインストール問題を処理するのに非常に役立ちます。
|
||||
|
||||
### 仮想環境
|
||||
また、ComfyUIのルートから以下のコマンドを使用する実験的なワンライナー・インストールもあります。これはコードをダウンロードし、依存関係をインストールし、インストールスクリプトを実行します:
|
||||
|
||||
```bash
|
||||
curl -sSL "https://raw.githubusercontent.com/username/repo/main/install.py" | python3 -
|
||||
```
|
||||
|
||||
## モデルのダウンロード
|
||||
ノードによっては、追加モデルのダウンロードが必要な場合があるので、上記と同じ python 環境を使って対話的に行うことができる:
|
||||
```bash
|
||||
python scripts/download_models.py
|
||||
```
|
||||
|
||||
プロンプトに従うか、Enterを押すだけで全てのモデルをダウンロードできます。
|
||||
|
||||
|
||||
> **Note**
|
||||
> プロンプトを出さずに全てのモデルをダウンロードするには、以下のようにします:
|
||||
```bash
|
||||
python scripts/download_models.py -y
|
||||
```
|
||||
|
||||
### ウェブ拡張機能
|
||||
|
||||
初回実行時にスクリプトは[web extensions](https://github.com/melMass/comfy_mtb/tree/main/web)をあなたの快適な `web/extensions` フォルダに[シンボリックリンク](https://github.com/melMass/comfy_mtb/blob/d982b69a58c05ccead9c49370764beaa4549992a/__init__.py#L45-L61)しようとします。万が一失敗した場合は、mtbフォルダを手動で`ComfyUI/web/extensions`にコピーしてください:
|
||||
|
||||
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
|
||||
|
||||
## 旧インストール方法 (MANUAL)
|
||||
### 依存関係
|
||||
|
||||
<details><summary><h4>カスタム Virtualenv (私は主にこれを使っています)</h4></summary>
|
||||
|
||||
1. ComfyUIで使用しているPython環境であることを確認してください。
|
||||
2. 以下のコマンドを実行して、必要な依存関係をインストールします:
|
||||
```bash
|
||||
pip install -r comfy_mtb/reqs.txt
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details><summary><h4>Comfy-portable / standalone (ComfyUI リリースより)</h4></summary>。
|
||||
|
||||
もしあなたがComfyUIスタンドアロンから`python-embeded`を使用している場合、バイナリがホイールを持っていない場合、依存関係をpipでインストールすることができません。この場合、最後の[リリース](https://github.com/melMass/comfy_mtb/releases)をチェックしてください。(ソースからのビルドが必要なもののみ)あらかじめビルドされたホイールがあるlinuxとwindows用のバンドルがあります。詳細は[この問題(#1)](https://github.com/melMass/comfy_mtb/issues/1)をチェックしてください。
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
<details><summary><h4>Google Colab</h4></summary>
|
||||
|
||||
ComfyUI with localtunnel (Recommended Way)**ヘッダーのすぐ後(コードセルの前)に、新しいコードセルを追加してください。
|
||||

|
||||
|
||||
```python
|
||||
# download the nodes
|
||||
!git clone --recursive https://github.com/melMass/comfy_mtb.git custom_nodes/comfy_mtb
|
||||
|
||||
# download all models
|
||||
!python custom_nodes/comfy_mtb/scripts/download_models.py -y
|
||||
|
||||
# install the dependencies
|
||||
!pip install -r custom_nodes/comfy_mtb/reqs.txt -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.0/index.html
|
||||
```
|
||||
これを実行した後、colabがランタイムを再起動する必要があると文句を言ったら、それを実行し、それ以前のセルは再実行せず、localtunnelを実行するセルだけを再実行してください。(最初に`%cd ComfyUI`のセルを追加する必要があるかもしれません...)
|
||||
|
||||
|
||||
> **Note**:
|
||||
> すべてのモデルが必要でない場合は、`-y`を削除してください : 
|
||||
|
||||
> **プレビュー**
|
||||
> 
|
||||
|
||||
</details>
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ then follow the prompt or just press enter to download every models.
|
||||
1. Make sure you are in the Python environment you use for ComfyUI.
|
||||
2. Install the required dependencies by running the following command:
|
||||
```bash
|
||||
pip install -r comfy_mtb/reqs.txt
|
||||
pip install -r comfy_mtb/requirements.txt
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
# MTB Nodes
|
||||
|
||||
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
|
||||
|
||||
[** 安装指南**](./INSTALL-CN.md) | [** 示例**](https://github.com/melMass/comfy_mtb/wiki/Examples)
|
||||
|
||||
欢迎使用 MTB Nodes 项目!这个代码库是开放的,您可以自由地探索和利用。它的主要目的是构建用于 [MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs) 中的概念验证(POCs)。该项目中的许多节点都是受到现有社区贡献或内置功能的启发而创建的。
|
||||
|
||||
在继续之前,请注意与此项目中使用的某些库相关的许可证。例如,`deepbump` 库采用 [GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE) 许可证。
|
||||
|
||||
- [节点列表](#节点列表)
|
||||
- [bbox](#bbox)
|
||||
- [colors](#colors)
|
||||
- [人脸检测/交换](#人脸检测交换)
|
||||
- [图像插值(动画)](#图像插值动画)
|
||||
- [图像操作](#图像操作)
|
||||
- [潜在变量工具](#潜在变量工具)
|
||||
- [其他工具](#其他工具)
|
||||
- [纹理](#纹理)
|
||||
- [Comfy 资源](#comfy-资源)
|
||||
|
||||
|
||||
|
||||
|
||||
# 节点列表
|
||||
|
||||
## bbox
|
||||
- `Bounding Box`: BBox 构造函数(自定义类型)
|
||||
- `BBox From Mask`: 从遮罩中提取边界框
|
||||
- `Crop`: 根据边界框裁剪图像
|
||||
- `Uncrop`: 根据边界框还原图像
|
||||
|
||||
## colors
|
||||
- `Colored Image`: 给定尺寸的纯色图像
|
||||
- `RGB to HSV`: -
|
||||
- `HSV to RGB`: -
|
||||
- `Color Correct`: 基本颜色校正工具
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=345/>
|
||||
|
||||
## 人脸检测/交换
|
||||
- `Face Swap`: 使用 deepinsight/insightface 模型进行人脸交换(该节点在早期版本中称为 `Roop`,功能相同,`Roop` 只是使用这些模型的应用程序)
|
||||
> **注意**
|
||||
> 人脸索引允许您选择要替换的人脸,如下所示:
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42" width=320/>
|
||||
- `Load Face Swap Model`: 加载 insightface 模型用于人脸交换
|
||||
- `Restore Face`: 使用 [GFPGan](https://github.com/TencentARC/GFPGAN) 还原人脸,与 `Face Swap` 配合使用效果很好,并支持 `bg_upscaler` 的 Comfy 原生放大器
|
||||
|
||||
## 图像插值(动画)
|
||||
- `Load Film Model`: 加载 [FILM](https://github.com/google-research/frame-interpolation) 模型
|
||||
- `Film Interpolation`: 使用 [FILM](https://github.com/google-research/frame-interpolation) 处理输入帧
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834" width=400/>
|
||||
- `Export to Prores (experimental)`: 将输入帧导出为 ProRes 4444 mov 文件。这使用 ffmpeg stdin 发送原始的 NumPy 数组,与 `Film Interpolation` 一起使用,目前很简单,但可以进一步扩展。
|
||||
|
||||
## 图像操作
|
||||
- `Blur`: 使用高斯滤波器对图像进行模糊处理。
|
||||
- `Deglaze Image`: 从 [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py) 中提取
|
||||
- `Denoise`: 对输入图像进行降噪处理
|
||||
- `Image Compare`: 比较两个图像并返回差异图像
|
||||
- `Image Premultiply`: 使用掩码对图像进行预乘处理
|
||||
- `Image Remove Background Rembg`: 使用 [RemBG](https://github.com/danielgatis/rembg) 进行背景去除
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
|
||||
- `Image Resize Factor`: 大部分提取自 [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui),经过一些编辑(特别是支持多个图像)和较少的功能。
|
||||
- `Mask To Image`: 将遮罩(Alpha)转换为带有颜色和背景的 RGB 图像
|
||||
- `Save Image Grid`: 将输入批次中的所有图像保存为图像网格。
|
||||
|
||||
## 潜在变量工具
|
||||
- `Latent Lerp`: 两个潜在变量之间的线性插值(混合)
|
||||
|
||||
|
||||
## 其他工具
|
||||
- `Concat Images`: 接受两个图像流,并将它们合并为其他 Comfy 管道支持的图像批次。
|
||||
- `Image Resize Factor`: **已弃用**,因为我后来发现了内
|
||||
|
||||
置的图像调整大小功能。
|
||||
- `Text To Image`: 使用字体将文本转换为图像的工具
|
||||
- `Styles Loader`: 加载 csv 文件并从行中填充下拉列表(类似于 A111)
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
|
||||
- `Smart Step`: 一个非常基本的节点,用于获取在 KSampler 高级中使用的步骤百分比
|
||||
- `Qr Code`: 基本的 QR Code 生成器
|
||||
- `Save Tensors`: 调试节点,将来可能会被删除
|
||||
- `Int to Number`: 用于 WASSuite 数字节点的补充
|
||||
- `Smart Step`: 使用百分比来控制 `KAdvancedSampler` 的步骤(开始/停止)
|
||||
|
||||
## 纹理
|
||||
|
||||
- `DeepBump`: 从单张图片生成法线图和高度图
|
||||
|
||||
# Comfy 资源
|
||||
|
||||
**指南**:
|
||||
- [官方示例(英文)](https://comfyanonymous.github.io/ComfyUI_examples/)
|
||||
- @BlenderNeko 的[ComfyUI 社区手册(英文)](https://blenderneko.github.io/ComfyUI-docs/)
|
||||
|
||||
- @tjhayasaka 的[Tomoaki 个人 Wiki(日文)](https://comfyui.creamlab.net/guides/)
|
||||
|
||||
**扩展和自定义节点**:
|
||||
- @WASasquatch 的[Comfy 列表插件(英文)](https://github.com/WASasquatch/comfyui-plugins)
|
||||
|
||||
- [CivitAI 上的 ComfyUI 标签(英文)](https://civitai.com/tag/comfyui)
|
||||
@@ -1,96 +0,0 @@
|
||||
# MTB Nodes
|
||||
|
||||
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
|
||||
|
||||
[**インストールガイド**](./INSTALL-JP.md) | [**サンプル**](https://github.com/melMass/comfy_mtb/wiki/Examples)
|
||||
|
||||
MTB Nodesプロジェクトへようこそ!このコードベースは、自由に探索し、利用することができます。主な目的は、[MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs)の実装のための概念実証(POC)を構築することです。このプロジェクトの多くのノードは、既存のコミュニティの貢献や組み込みの機能に触発されています。
|
||||
|
||||
続行する前に、このプロジェクトで使用されている特定のライブラリに関連するライセンスに注意してください。たとえば、「deepbump」ライブラリは、[GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE)の下でライセンスされています。
|
||||
|
||||
- [ノードリスト](#ノードリスト)
|
||||
- [bbox](#bbox)
|
||||
- [colors](#colors)
|
||||
- [顔検出 / スワッピング](#顔検出--スワッピング)
|
||||
- [画像補間(アニメーション)](#画像補間アニメーション)
|
||||
- [画像操作](#画像操作)
|
||||
- [潜在的なユーティリティ](#潜在的なユーティリティ)
|
||||
- [その他のユーティリティ](#その他のユーティリティ)
|
||||
- [テクスチャ](#テクスチャ)
|
||||
- [Comfyリソース](#comfyリソース)
|
||||
|
||||
|
||||
# ノードリスト
|
||||
|
||||
## bbox
|
||||
- `Bounding Box`: BBoxコンストラクタ(カスタムタイプ)
|
||||
- `BBox From Mask`: マスクからバウンディングボックスを抽出
|
||||
- `Crop`: BBoxから画像を切り抜く
|
||||
- `Uncrop`: BBoxから画像を元に戻す
|
||||
|
||||
## colors
|
||||
- `Colored Image`: 指定されたサイズの一定の色の画像
|
||||
- `RGB to HSV`: -
|
||||
- `HSV to RGB`: -
|
||||
- `Color Correct`: 基本的なカラーコレクションツール
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=345/>
|
||||
|
||||
## 顔検出 / スワッピング
|
||||
- `Face Swap`: deepinsight/insightfaceモデルを使用した顔の入れ替え(このノードは初期バージョンでは「Roop」と呼ばれていましたが、同じ機能を提供します。Roopは単にこれらのモデルを使用するアプリです)
|
||||
> **注意**
|
||||
> 顔のインデックスを使用して置き換える顔を選択できます。以下を参照してください:
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/2e9d6066-c466-4a01-bd6c-315f7f1e8b42" width=320/>
|
||||
- `Load Face Swap Model`: 顔の交換のためのinsightfaceモデルを読み込む
|
||||
- `Restore Face`: [GFPGan](https://github.com/TencentARC/GFPGAN)を使用して顔を復元し、`Face Swap`と組み合わせて使用すると非常に効果的であり、`bg_upscaler`のComfyネイティブアップスケーラーもサポートしています。
|
||||
|
||||
## 画像補間(アニメーション)
|
||||
- `Load Film Model`: [FILM](https://github.com/google-research/frame-interpolation)モデルを読み込む
|
||||
- `Film Interpolation`: [FILM](https://github.com/google-research/frame-interpolation)を使用して入力フレームを処理する
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834" width=400/>
|
||||
- `Export to Prores (experimental)`: 入力フレームをProRes 4444 movファイルにエクスポートします。これは現在は単純なものですが、`Film Interpolation`と組み合わせて使用するためのffmpegのstdinを使用して生のNumPy配列を送信するもので、拡張することもできます。
|
||||
|
||||
## 画像操作
|
||||
- `Blur`: ガウスフィルタを使用して画像をぼかす
|
||||
- `Deglaze Image`: [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py)から取得
|
||||
- `Denoise`: 入力画像のノイズを除去する
|
||||
- `Image Compare`: 2つの画像を比較し、差分画像を返す
|
||||
- `Image Premultiply`: 画像をマスクで乗算
|
||||
- `Image Remove Background Rembg`: [RemBG](https://github.com/danielgatis/rembg)を使用した背景除去
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/704172
|
||||
|
||||
6/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
|
||||
- `Image Resize Factor`: [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui)から抽出され、いくつかの編集(特に複数の画像のサポート)と機能の削減が行われました。
|
||||
- `Mask To Image`: マスク(アルファ)をカラーと背景を持つRGBイメージに変換します。
|
||||
- `Save Image Grid`: 入力バッチのすべての画像を画像グリッドとして保存します。
|
||||
|
||||
## 潜在的なユーティリティ
|
||||
- `Latent Lerp`: 2つの潜在的なベクトルの間の線形補間(ブレンド)
|
||||
|
||||
## その他のユーティリティ
|
||||
- `Concat Images`: 2つの画像ストリームを取り、他のComfyパイプラインでサポートされている画像のバッチとしてマージします。
|
||||
- `Image Resize Factor`: **非推奨**。組み込みの画像リサイズ機能を発見したため、削除される予定です。
|
||||
- `Text To Image`: フォントを使用してテキストを画像に変換するためのユーティリティ
|
||||
- `Styles Loader`: csvファイルをロードし、行からドロップダウンを作成します(A111のようなもの)
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
|
||||
- `Smart Step`: KSamplerの高度な使用に使用するステップパーセントを取得する非常に基本的なノード
|
||||
- `Qr Code`: 基本的なQRコード生成器
|
||||
- `Save Tensors`: 将来的に削除される可能性のあるデバッグノード
|
||||
- `Int to Number`: WASSuiteの数値ノードの補完
|
||||
- `Smart Step`: `KAdvancedSampler`のステップ(開始/停止)を制御するための非常に基本的なツールで、パーセンテージを使用します。
|
||||
|
||||
## テクスチャ
|
||||
|
||||
- `DeepBump`: 1枚の画像から法線マップと高さマップを生成します。
|
||||
|
||||
# Comfyリソース
|
||||
|
||||
**ガイド**:
|
||||
- [公式の例(英語)](https://comfyanonymous.github.io/ComfyUI_examples/)
|
||||
- @BlenderNekoによる[ComfyUIコミュニティマニュアル(英語)](https://blenderneko.github.io/ComfyUI-docs/)
|
||||
|
||||
- @tjhayasakaによる[Tomoakiの個人Wiki(日本語)](https://comfyui.creamlab.net/guides/)
|
||||
|
||||
**拡張機能とカスタムノード**:
|
||||
- @WASasquatchによる[Comfyリスト用のプラグイン(英語)](https://github.com/WASasquatch/comfyui-plugins)
|
||||
|
||||
- [CivitAIのComfyUIタグ(英語)](https://civitai.com/tag/comfyui)
|
||||
@@ -1,180 +1,17 @@
|
||||
# MTB Nodes
|
||||
|
||||
> [!CAUTION]
|
||||
> A lot of recent changes to comfy broke many things in mtb (colors, dynamic inputs and probably more)
|
||||
> [`dev/0.6.0`](https://github.com/melMass/comfy_mtb/tree/dev/0.6.0) partially address these. My time is limited lately so it might take time to finish and merge
|
||||
|
||||
|
||||
[](https://github.com/melMass/comfy_mtb/actions/workflows/test_embedded.yml)
|
||||
|
||||

|
||||
|
||||
<!-- omit in toc -->
|
||||
|
||||
**Translated Readme (using DeepTranslate, PRs are welcome)**:
|
||||

|
||||
[日本語による説明](./README-JP.md)
|
||||

|
||||
[中文说明](./README-CN.md)
|
||||
|
||||
<a href="https://www.buymeacoffee.com/melmass" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: 32px !important;width: 140px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;" ></a>
|
||||
|
||||
[**Install Guide**](./INSTALL.md) | [**Examples**](https://github.com/melMass/comfy_mtb/wiki/Examples)
|
||||
|
||||
There is now a dedicated `#mtb-nodes` channel on the Banodoco discord:
|
||||
[](https://discord.gg/IAXhsabmDhn)
|
||||
|
||||
---
|
||||
|
||||
Welcome to the MTB Nodes project! This codebase is open for you to explore and utilize as you wish. Its primary purpose is to build proof-of-concepts (POCs) for implementation in [MLOPs](https://github.com/Bismuth-Consultancy-BV/MLOPs). Many nodes in this project are inspired by existing community contributions or built-in functionalities.
|
||||
|
||||
Before proceeding, please be aware of the licenses associated with certain libraries used in this project. For example, the `deepbump` library is licensed under [GPLv3](https://github.com/HugoTini/DeepBump/blob/master/LICENSE).
|
||||
|
||||
- [Web Extensions](#web-extensions)
|
||||
- [Node List](#node-list)
|
||||
- [Animation](#animation)
|
||||
- [bbox](#bbox)
|
||||
- [colors](#colors)
|
||||
- [image ops](#image-ops)
|
||||
- [latent utils](#latent-utils)
|
||||
- [textures](#textures)
|
||||
- [misc utils](#misc-utils)
|
||||
- [Optional nodes](#optional-nodes)
|
||||
- [face detection / swapping](#face-detection--swapping)
|
||||
- [image interpolation (animation)](#image-interpolation-animation)
|
||||
- [Comfy Resources](#comfy-resources)
|
||||
|
||||
# Web Extensions
|
||||
mtb add a few widgets like `COLOR`
|
||||
|
||||
<img alt="color widget preview" src="https://github.com/melMass/comfy_mtb/assets/7041726/cff7e66a-4cc4-4866-b35b-10af0bb2d110" width=450>
|
||||
|
||||
A few nodes have the concept of "dynamic" inputs:
|
||||
<img alt="dynamic inputs" width=450 src="https://github.com/melMass/comfy_mtb/assets/7041726/10b3976e-b212-4968-91eb-f34c02bb80c3" />
|
||||
|
||||
<!-- NOTE: Here it should just be some examples and warnings, move the rest to the wiki -->
|
||||
|
||||
# Node List
|
||||
|
||||
## Animation
|
||||
- `Animation Builder`: Convenient way to manage basic animation maths at the core of many of my workflows (both worflows for the following GIFs are in the [examples](https://github.com/melMass/comfy_mtb/wiki/Examples))
|
||||
|
||||
**[Example lerping two conditions (blue car -> yellow car)](https://github.com/melMass/comfy_mtb/blob/main/examples/03-animation_builder-condition-lerp.json)**
|
||||
|
||||
<img width=300 src="https://user-images.githubusercontent.com/7041726/260258970-d6d66d96-fb34-40d0-9038-cbabf0714c5d.gif"/>
|
||||
|
||||
|
||||
**[Example using image transforms a feedback for a fake deforum effect](https://github.com/melMass/comfy_mtb/blob/main/examples/04-animation_builder-deforum.json)**
|
||||
|
||||
<img width=300 src="https://user-images.githubusercontent.com/7041726/260261504-303a1037-60d3-4b31-a589-b15d549752f6.gif"/>
|
||||
|
||||
- `Batch Float`: Generates a batch of float values with interpolation.
|
||||
- `Batch Shape`: Generates a batch of 2D shapes with optional shading (experimental).
|
||||
- `Batch Transform`: Transform a batch of images using a batch of keyframes.
|
||||
<img width=400 src="https://github.com/melMass/comfy_mtb/assets/7041726/3f217de1-79aa-49b0-a66a-35cf29dd8f01"/>
|
||||
- `Export With Ffmpeg`: Export with FFmpeg, it used to be export to Proress and is still tailored for YUV
|
||||
- `Fit Number` : Fit the input float using a source and target range, you can also control the interpolation curve from a list of presets (default to linear)
|
||||
|
||||
## bbox
|
||||
- `Bounding Box`: BBox constructor (custom type),
|
||||
- `BBox From Mask`: From a mask extract the bounding box
|
||||
- `Crop`: Crop image from BBox
|
||||
- `Uncrop`: Uncrop image from BBox
|
||||
|
||||
## colors
|
||||
- `Colored Image`: Constant color image of given size
|
||||
- `RGB to HSV`: -,
|
||||
- `HSV to RGB`: -,
|
||||
- `Color Correct`: Basic color correction tools
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/7c20ac83-31ff-40ea-a1a0-06c2acefb2ef" width=400/>
|
||||
|
||||
## image ops
|
||||
- `Blur`: Blur an image using a Gaussian filter.
|
||||
- `Deglaze Image`: taken from [FN16](https://github.com/Fannovel16/FN16-ComfyUI-nodes/blob/main/DeglazeImage.py),
|
||||
- `Denoise`: Denoise the input image,
|
||||
- `Image Compare`: Compare two images and return a difference image
|
||||
- `Image Premultiply`: Premultiply image with mask
|
||||
- `Image Remove Background Rembg`: [RemBG](https://github.com/danielgatis/rembg) powered background removal.
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/e69253b4-c03c-45e9-92b5-aa46fb887be8" width=320/>
|
||||
- `Image Resize Factor`: Extracted mostly from [WAS Node Suite](https://github.com/WASasquatch/was-node-suite-comfyui), with a few edits (most notably multiple image support) and less features.
|
||||
- `Mask To Image`: Converts a mask (alpha) to an RGB image with a color and background
|
||||
- `Save Image Grid`: Save all the images in the input batch as a grid of images.
|
||||
|
||||
## latent utils
|
||||
- `Latent Lerp`: Linear interpolation (blend) between two latent
|
||||
|
||||
## textures
|
||||
- `Model Patch Seamless`: Use the [seamless diffusion "hack"](https://gitlab.com/-/snippets/2395088) to patch any model to infere seamless images, check the [examples](https://github.com/melMass/comfy_mtb/wiki/Examples) to see how to use all those textures node together
|
||||
<img width=500 src="https://user-images.githubusercontent.com/7041726/272970506-9db516b5-45d2-4389-b904-b3a94660f24c.png"/>
|
||||
- `DeepBump`: Normal & height maps generation from single pictures
|
||||
<img width=500 src="https://user-images.githubusercontent.com/7041726/272970715-7e4477f6-8e18-4839-9864-83d07d6690a1.png"/>
|
||||
- `Image Tile Offset`: Mimics an old photoshop technique to check for seamless textures by offsetting tiles of the image.
|
||||
<img width=600 src="https://github.com/melMass/comfy_mtb/assets/7041726/cbcc51fb-922f-433f-acf1-c6c6c2a7ffc4" />
|
||||
|
||||
## misc utils
|
||||
- `Any To String`: Tries to take any input and convert it to a string.
|
||||
- `Concat Images`: Takes two image stream and merge them as a batch of images supported by other Comfy pipelines.
|
||||
- `Image Resize Factor`: **Deprecated**, I since discovered the builtin image resize.
|
||||
- `Text To Image`: Utils to convert text to image using a font
|
||||
- `Styles Loader`: Load csv files and populate a dropdown from the rows (à la A111)
|
||||
<img src="https://github.com/melMass/comfy_mtb/assets/7041726/02fe3211-18ee-4e54-a029-931388f5fde8" width=320/>
|
||||
- `Smart Step`: A very basic node to get step percent to use in KSampler advanced,
|
||||
- `Qr Code`: Basic QR Code generator
|
||||
- `Save Tensors`: Debug node that will probably be removed in the future
|
||||
- `Int to Number`: Supplement for WASSuite number nodes
|
||||
- `Smart Step`: A very basic tool to control the steps (start/stop) of the `KAdvancedSampler` using percentage
|
||||
- `Load Image From Url`: Load an image from the given URL
|
||||
[**Wiki**](https://github.com/melMass/comfy_mtb/wiki) | [**Install Guide**](./INSTALL.md) | [**Examples**](https://github.com/melMass/comfy_mtb/wiki/Examples)
|
||||
|
||||
|
||||
## Optional nodes
|
||||
|
||||
These nodes are still bundled in mtb, but moving forward (>0.2.0) they won't
|
||||
be setup by the install script and their dependencies won't install either.
|
||||
The reason is mostly that they all have a better alternatives available and tensorflow on windows was not a fun experience and since Python 3.11 not an experience at all.
|
||||
|
||||
For linux and mac users though these nodes didn't cause any issue and I personally still use them, these are the extra requirements needed:
|
||||
|
||||
```console
|
||||
.venv/python -m pip install tensorflow facexlib insightface basicsr
|
||||
```
|
||||
|
||||
### face detection / swapping
|
||||
> **Warning**
|
||||
> Those nodes were among the first to be implemented they do work, but on windows the installation is still not properly handled for everyone
|
||||
> As alternatives you can use [reactor](https://github.com/Gourieff/comfyui-reactor-node) for face swap and [facerestore](https://github.com/Haidra-Org/hordelib/tree/main/hordelib/nodes/facerestore) for restoration
|
||||
> You can check [this video](https://www.youtube.com/watch?v=FShlpMxbU0E) for a tutorial by Ferniclestix using these alternatives
|
||||
|
||||
- `Face Swap`: Face swap using deepinsight/insightface models (this node used to be called `Roop` in early versions, it does the same, roop is *just* an app that uses those model)
|
||||
<img width=320 src="https://user-images.githubusercontent.com/7041726/260261217-54e33446-183f-4dda-88b3-d38a1e6de980.gif"/>
|
||||
- `Load Face Swap Model`: Load an insightface model for face swapping
|
||||
- `Restore Face`: Using [GFPGan](https://github.com/TencentARC/GFPGAN) to restore faces, works great in conjunction with `Face Swap` and supports Comfy native upscalers for the `bg_upscaler`
|
||||
|
||||
### image interpolation (animation)
|
||||
> **Warning**
|
||||
> The FILM nodes will be deprecated at some point after 0.2.0, [Fannovel16](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)'s interpolation nodes implement it and they rely on a pytorch implementation of FILM
|
||||
> which solves the issues related to the ones included in mtb. They will probably remain available if your system meet the requirements and ignored otherwise.
|
||||
|
||||
<details><summary>Why?</summary>
|
||||
|
||||
> **Windows only issue**: This requires tensorflow-gpu that is unfortunately not a thing anymore on Windows since 2.10.1 (unless you use a complex WSL passthrough setup but it's still not "Windows")
|
||||
> Using this old version is quite clunky and require some patching that install.py does automatically, but the main issue is that no wheels are available for python > 3.10
|
||||
> Comfy-nightly is already using Python 11 so installing this old tf version won't work there.
|
||||
> You can in any case install the normal up to date tensorflow but that will run on CPU and is much MUCH slower for FILM inference.
|
||||
</details>
|
||||
|
||||
- `Load Film Model`: Loads a [FILM](https://github.com/google-research/frame-interpolation) model
|
||||
- `Film Interpolation`: Process input frames using [FILM](https://github.com/google-research/frame-interpolation)
|
||||
<img width=400 src="https://github.com/melMass/comfy_mtb/assets/7041726/3afd1647-6634-4b92-a34b-51432e6a9834"/>
|
||||
<img width=400 src="https://user-images.githubusercontent.com/7041726/260259079-c0f04a63-960c-43a7-ba78-a45cd5ac7514.gif"/>
|
||||
- `Export to Prores (experimental)`: Exports the input frames to a ProRes 4444 mov file. This is using ffmpeg stdin to send raw numpy arrays, used with `Film Interpolation` and very simple for now but could be expanded upon.
|
||||
|
||||
# Comfy Resources
|
||||
|
||||
**Misc**
|
||||
|
||||
- [Slick ComfyUI by NoCrypt](https://colab.research.google.com/drive/1ZMvLWEiYITmBJngtqeIQToeNuiydwI0z#scrollTo=1fWMaexXS188): A colab notebook with batteries included!
|
||||
|
||||
**Guides**:
|
||||
- [Official Examples (eng)](https://comfyanonymous.github.io/ComfyUI_examples/)
|
||||
- [ComfyUI Community Manual (eng)](https://blenderneko.github.io/ComfyUI-docs/) by @BlenderNeko
|
||||
|
||||
- [Tomoaki's personal Wiki (jap)](https://comfyui.creamlab.net/guides/) by @tjhayasaka
|
||||
|
||||
**Extensions and Custom Nodes**:
|
||||
- [Plugins for Comfy List (eng)](https://github.com/WASasquatch/comfyui-plugins) by @WASasquatch
|
||||
|
||||
- [ComfyUI tag on CivitAI (eng)](https://civitai.com/tag/comfyui)
|
||||
|
||||
+274
-111
@@ -3,14 +3,16 @@
|
||||
# File: __init__.py
|
||||
# Project: comfy_mtb
|
||||
# Author: Mel Massadian
|
||||
# Copyright (c) 2023 Mel Massadian
|
||||
# Copyright (c) 2023-2025 Mel Massadian
|
||||
#
|
||||
###
|
||||
|
||||
__version__ = "0.1.5"
|
||||
__version__ = "0.6.0"
|
||||
|
||||
import os
|
||||
|
||||
from aiohttp.web_request import Request
|
||||
|
||||
# TODO: don't override this if the user has that setup already
|
||||
if not os.environ.get("TF_FORCE_GPU_ALLOW_GROWTH"):
|
||||
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
|
||||
@@ -29,26 +31,34 @@ from importlib import reload
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
import nodes
|
||||
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
|
||||
from .log import blue_text, cyan_text, get_label, get_summary, log
|
||||
from .utils import comfy_dir, here
|
||||
|
||||
NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
NODE_CLASS_MAPPINGS_DEBUG = {}
|
||||
NODE_CLASS_MAPPINGS: dict[str, type] = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS: dict[str, str] = {}
|
||||
NODE_CLASS_MAPPINGS_DEBUG: dict[str, str | None] = {}
|
||||
WEB_DIRECTORY = "./web"
|
||||
|
||||
|
||||
def extract_nodes_from_source(filename: Path):
|
||||
source_code = ""
|
||||
|
||||
source_code = filename.read_text(encoding="utf-8")
|
||||
|
||||
nodes = []
|
||||
nodes: list[str] = []
|
||||
|
||||
try:
|
||||
parsed = ast.parse(source_code)
|
||||
@@ -57,23 +67,24 @@ def extract_nodes_from_source(filename: Path):
|
||||
target = node.targets[0]
|
||||
if isinstance(target, ast.Name) and target.id == "__nodes__":
|
||||
value = ast.get_source_segment(source_code, node.value)
|
||||
node_value = ast.parse(value).body[0].value
|
||||
if isinstance(node_value, (ast.List, ast.Tuple)):
|
||||
nodes.extend(
|
||||
element.id
|
||||
for element in node_value.elts
|
||||
if isinstance(element, ast.Name)
|
||||
)
|
||||
break
|
||||
if value:
|
||||
node_value = ast.parse(value).body[0].value
|
||||
if isinstance(node_value, ast.List | ast.Tuple):
|
||||
nodes.extend(
|
||||
str(element.id)
|
||||
for element in node_value.elts
|
||||
if isinstance(element, ast.Name)
|
||||
)
|
||||
break
|
||||
except SyntaxError:
|
||||
log.error("Failed to parse")
|
||||
log.error(f"Failed to parse ast from: {filename}")
|
||||
return nodes
|
||||
|
||||
|
||||
def load_nodes():
|
||||
errors: list[str] = []
|
||||
nodes = []
|
||||
nodes_failed = []
|
||||
nodes: list[type] = []
|
||||
nodes_failed: list[str] = []
|
||||
|
||||
for filename in (here / "nodes").iterdir():
|
||||
if filename.suffix == ".py":
|
||||
@@ -124,7 +135,8 @@ def uninstall_old_web_extensions():
|
||||
shutil.rmtree(web_mtb)
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
f"Failed to remove web mtb directory: {e}\nPlease manually remove it from disk ({web_mtb}) and restart the server."
|
||||
f"""Failed to remove web mtb directory: {e}
|
||||
Please manually remove it from disk ({web_mtb}) and restart the server."""
|
||||
)
|
||||
|
||||
|
||||
@@ -132,80 +144,41 @@ def uninstall_old_web_extensions():
|
||||
|
||||
|
||||
# - GATHER WIKI PAGES
|
||||
def wiki_to_classname(s: str):
|
||||
wiki_name = s.replace("nodes-", "", 1)
|
||||
return "MTB_" + "".join(
|
||||
[part.capitalize() for part in wiki_name.split("-")]
|
||||
)
|
||||
|
||||
|
||||
def classname_to_wiki(s: str):
|
||||
classname = s.replace("MTB_", "")
|
||||
parts = []
|
||||
start = 0
|
||||
for i in range(1, len(classname)):
|
||||
if classname[i].isupper():
|
||||
parts.append(classname[start:i].lower())
|
||||
start = i
|
||||
parts.append(classname[start:].lower())
|
||||
return "nodes-" + "-".join(parts)
|
||||
|
||||
from .docs import assign_descriptions, load_wiki_docs
|
||||
|
||||
wiki = here / "wiki"
|
||||
node_docs = {}
|
||||
if wiki.exists() and wiki.is_dir():
|
||||
node_docs = {
|
||||
wiki_to_classname(x.stem): x.read_text(encoding="utf-8")
|
||||
for x in (wiki / "nodes").glob("*.md")
|
||||
}
|
||||
node_docs = load_wiki_docs(wiki)
|
||||
|
||||
|
||||
# - REGISTER NODES
|
||||
|
||||
|
||||
MTB_EXPORT = os.environ.get("MTB_EXPORT")
|
||||
|
||||
nodes, failed = load_nodes()
|
||||
assign_descriptions(nodes, node_docs, wiki, log, export=bool(MTB_EXPORT))
|
||||
|
||||
for node_class in nodes:
|
||||
class_name: str = node_class.__name__
|
||||
linked_doc = node_docs.get(class_name)
|
||||
|
||||
if not hasattr(node_class, "DESCRIPTION"):
|
||||
if linked_doc:
|
||||
log.debug(f"Found linked doc for {class_name}, using it")
|
||||
node_class.DESCRIPTION = linked_doc
|
||||
elif node_class.__doc__:
|
||||
log.debug(f"Using __doc__ as description for {class_name}")
|
||||
node_class.DESCRIPTION = node_class.__doc__
|
||||
if MTB_EXPORT:
|
||||
wiki_name = classname_to_wiki(class_name)
|
||||
(wiki / "nodes" / wiki_name + ".md").write_text(
|
||||
node_class.__doc__, encoding="utf-8"
|
||||
)
|
||||
|
||||
else:
|
||||
log.debug(
|
||||
f"None of the methods could retrieve documentation for {class_name}"
|
||||
)
|
||||
|
||||
node_label = f"{get_label(class_name)} (mtb)"
|
||||
NODE_CLASS_MAPPINGS[node_label] = node_class
|
||||
NODE_DISPLAY_NAME_MAPPINGS[class_name] = node_label
|
||||
NODE_CLASS_MAPPINGS_DEBUG[node_label] = node_class.__doc__
|
||||
# TODO: I removed this, I find it more convenient to write without spaces, but it breaks every of my workflows
|
||||
# TODO (cont): and until I find a way to automate the conversion, I'll leave it like this
|
||||
|
||||
if os.environ.get("MTB_EXPORT"):
|
||||
with open(here / "node_list.json", "w") as f:
|
||||
f.write(
|
||||
json.dumps(
|
||||
{
|
||||
k: NODE_CLASS_MAPPINGS_DEBUG[k]
|
||||
for k in sorted(NODE_CLASS_MAPPINGS_DEBUG.keys())
|
||||
},
|
||||
indent=4,
|
||||
)
|
||||
# TODO: I removed this, I find it more convenient to write without spaces
|
||||
# but it breaks every of my workflows
|
||||
# TODO (cont): and until I find a way to automate the conversion
|
||||
# I'll leave it like this
|
||||
|
||||
if MTB_EXPORT:
|
||||
with open(here / "node_list.json", "w") as f:
|
||||
_ = f.write(
|
||||
json.dumps(
|
||||
{
|
||||
k: NODE_CLASS_MAPPINGS_DEBUG[k]
|
||||
for k in sorted(NODE_CLASS_MAPPINGS_DEBUG.keys())
|
||||
},
|
||||
indent=4,
|
||||
)
|
||||
)
|
||||
|
||||
log.debug(
|
||||
"Loaded the following nodes:\n\t"
|
||||
@@ -215,29 +188,54 @@ log.debug(
|
||||
)
|
||||
)
|
||||
|
||||
log.info(f"loaded {cyan_text(len(nodes))} nodes successfuly")
|
||||
log.info(f"loaded {cyan_text(str(len(nodes)))} nodes successfuly")
|
||||
|
||||
if failed:
|
||||
with contextlib.suppress(Exception):
|
||||
base_url, port = utils.get_server_info()
|
||||
log.info(
|
||||
f"Some nodes ({len(failed)}) could not be loaded. This can be ignored, but go to http://{base_url}:{port}/mtb if you want more information."
|
||||
)
|
||||
log.debug(failed)
|
||||
|
||||
|
||||
# - ENDPOINT
|
||||
|
||||
|
||||
if hasattr(PromptServer, "instance"):
|
||||
restore_deps = ["basicsr"]
|
||||
onnx_deps = ["onnxruntime"]
|
||||
swap_deps = ["insightface"] + onnx_deps
|
||||
node_dependency_mapping = {
|
||||
"QrCode": ["qrcode"],
|
||||
"DeepBump": onnx_deps,
|
||||
"FaceSwap": swap_deps,
|
||||
"LoadFaceSwapModel": swap_deps,
|
||||
"LoadFaceAnalysisModel": restore_deps,
|
||||
}
|
||||
# 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
|
||||
|
||||
img_cache = TTLCache(maxsize=100, ttl=5) # 1 min TTL
|
||||
prompt_cache = TTLCache(maxsize=100, ttl=5) # 1 min TTL
|
||||
|
||||
node_dependency_mapping = get_node_dependencies()
|
||||
|
||||
PromptServer.instance.app.router.add_static(
|
||||
"/mtb-assets/", path=(here / "html").as_posix()
|
||||
@@ -306,10 +304,10 @@ if hasattr(PromptServer, "instance"):
|
||||
}
|
||||
)
|
||||
|
||||
@PromptServer.instance.routes.post("/mtb/debug")
|
||||
async def set_debug(request):
|
||||
json_data = await request.json()
|
||||
enabled = json_data.get("enabled")
|
||||
@PromptServer.instance.routes.post("/mtb/server-info")
|
||||
async def set_server_info(request: Request):
|
||||
json_data: dict[str, bool] = await request.json()
|
||||
enabled = json_data.get("debug")
|
||||
if enabled:
|
||||
os.environ["MTB_DEBUG"] = "true"
|
||||
log.setLevel(logging.DEBUG)
|
||||
@@ -317,7 +315,7 @@ if hasattr(PromptServer, "instance"):
|
||||
|
||||
elif "MTB_DEBUG" in os.environ:
|
||||
# del os.environ["MTB_DEBUG"]
|
||||
os.environ.pop("MTB_DEBUG")
|
||||
_ = os.environ.pop("MTB_DEBUG")
|
||||
log.setLevel(logging.INFO)
|
||||
|
||||
return web.json_response(
|
||||
@@ -325,17 +323,17 @@ if hasattr(PromptServer, "instance"):
|
||||
)
|
||||
|
||||
@PromptServer.instance.routes.get("/mtb")
|
||||
async def get_home(request):
|
||||
async def get_home(request: Request):
|
||||
from . import endpoint
|
||||
|
||||
reload(endpoint)
|
||||
_ = reload(endpoint)
|
||||
# Check if the request prefers HTML content
|
||||
if "text/html" in request.headers.get("Accept", ""):
|
||||
# # Return an HTML page
|
||||
html_response = """
|
||||
<div class="flex-container menu">
|
||||
<a href="/mtb/manage">manage</a>
|
||||
<a href="/mtb/debug">debug</a>
|
||||
<a href="/mtb/server-info">Server Info</a>
|
||||
<a href="/mtb/status">status</a>
|
||||
</div>
|
||||
"""
|
||||
@@ -347,28 +345,189 @@ if hasattr(PromptServer, "instance"):
|
||||
# Return JSON for other requests
|
||||
return web.json_response({"message": "Welcome to MTB!"})
|
||||
|
||||
@PromptServer.instance.routes.get("/mtb/debug")
|
||||
async def get_debug(request):
|
||||
def get_cached_image(file_path: str, preview_params=None, channel=None):
|
||||
cache_key = (file_path, preview_params, channel)
|
||||
if img_cache and (cache_key in img_cache):
|
||||
return img_cache[cache_key]
|
||||
|
||||
with Image.open(file_path) as img:
|
||||
info = img.info
|
||||
if preview_params:
|
||||
img = process_preview(img, preview_params)
|
||||
if channel:
|
||||
img = process_channel(img, channel)
|
||||
if prompt_cache:
|
||||
prompt_cache[cache_key] = info
|
||||
if img_cache:
|
||||
img_cache[cache_key] = img.getvalue()
|
||||
return img_cache[cache_key]
|
||||
|
||||
return img.getvalue()
|
||||
|
||||
def process_preview(img: Image.Image, preview_params):
|
||||
image_format, quality, width = preview_params
|
||||
quality = int(quality)
|
||||
|
||||
if width:
|
||||
width = int(width)
|
||||
img.thumbnail((width, int(width * img.height / img.width)))
|
||||
|
||||
buffer = BytesIO()
|
||||
img.save(
|
||||
buffer, format=image_format, quality=quality, metadata=img.info
|
||||
)
|
||||
buffer.seek(0)
|
||||
return buffer
|
||||
|
||||
def process_channel(img: Image.Image, channel: str):
|
||||
if channel == "rgb":
|
||||
if img.mode == "RGBA":
|
||||
r, g, b, _ = img.split()
|
||||
img = Image.merge("RGB", (r, g, b))
|
||||
else:
|
||||
img = img.convert("RGB")
|
||||
elif channel == "a":
|
||||
if img.mode == "RGBA":
|
||||
_, _, _, a = img.split()
|
||||
else:
|
||||
a = Image.new("L", img.size, 255)
|
||||
img = Image.new("RGBA", img.size)
|
||||
img.putalpha(a)
|
||||
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, format="PNG")
|
||||
_ = buffer.seek(0)
|
||||
return buffer
|
||||
|
||||
async def get_image_response(
|
||||
file, filename: str, preview_info=None, channel=None
|
||||
):
|
||||
img = await asyncio.to_thread(
|
||||
get_cached_image, file, preview_info, channel
|
||||
)
|
||||
return web.Response(
|
||||
body=img,
|
||||
content_type="image/webp" if preview_info else "image/png",
|
||||
headers={"Content-Disposition": f'filename="{filename}"'},
|
||||
)
|
||||
|
||||
# TODO: Embed the metadatas somehow so we can drag and drop
|
||||
# to load workflows in the sidebar
|
||||
@PromptServer.instance.routes.get("/mtb/view")
|
||||
async def view_image(request: Request):
|
||||
import folder_paths
|
||||
|
||||
filename = request.rel_url.query.get("filename")
|
||||
if not filename:
|
||||
return web.Response(status=404)
|
||||
|
||||
filename, output_dir = folder_paths.annotated_filepath(filename)
|
||||
if filename[0] == "/" or ".." in filename:
|
||||
return web.Response(status=400)
|
||||
|
||||
if output_dir is None:
|
||||
rtype = request.rel_url.query.get("type", "output")
|
||||
output_dir = folder_paths.get_directory_by_type(rtype)
|
||||
|
||||
if output_dir is None:
|
||||
return web.Response(status=400)
|
||||
|
||||
if "subfolder" in request.rel_url.query:
|
||||
full_output_dir = os.path.join(
|
||||
output_dir, request.rel_url.query["subfolder"]
|
||||
)
|
||||
if (
|
||||
os.path.commonpath(
|
||||
(os.path.abspath(full_output_dir), output_dir)
|
||||
)
|
||||
!= output_dir
|
||||
):
|
||||
return web.Response(status=403)
|
||||
output_dir = full_output_dir
|
||||
|
||||
filename = os.path.basename(filename)
|
||||
file = os.path.join(output_dir, filename)
|
||||
|
||||
if not os.path.isfile(file):
|
||||
return web.Response(status=404)
|
||||
|
||||
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(";")
|
||||
image_format = (
|
||||
preview_params[0]
|
||||
if preview_params[0] in ["webp", "jpeg"]
|
||||
else "webp"
|
||||
)
|
||||
quality = (
|
||||
int(preview_params[1])
|
||||
if len(preview_params) > 1 and preview_params[1].isdigit()
|
||||
else 90
|
||||
)
|
||||
width = request.rel_url.query.get("width")
|
||||
preview_info = (image_format, quality, width)
|
||||
|
||||
channel = request.rel_url.query.get("channel")
|
||||
|
||||
return await get_image_response(file, filename, preview_info, channel)
|
||||
|
||||
@PromptServer.instance.routes.get("/mtb/server-info")
|
||||
async def get_debug(request: Request):
|
||||
from . import endpoint
|
||||
|
||||
reload(endpoint)
|
||||
enabled = "MTB_DEBUG" in os.environ
|
||||
_ = reload(endpoint)
|
||||
isdebug = "MTB_DEBUG" in os.environ
|
||||
exposed = "MTB_EXPOSE" in os.environ
|
||||
|
||||
def render_property(name: str, val: str):
|
||||
return f"""<strong>{name}:</strong>
|
||||
<p>
|
||||
{val}
|
||||
</p>"""
|
||||
|
||||
# Check if the request prefers HTML content
|
||||
if "text/html" in request.headers.get("Accept", ""):
|
||||
# # Return an HTML page
|
||||
html_response = f"""
|
||||
<h1>MTB Debug Status: {'Enabled' if enabled else 'Disabled'}</h1>
|
||||
"""
|
||||
html_response = ""
|
||||
|
||||
html_response += render_property(
|
||||
"Debug", "Enabled" if isdebug else "Disabled"
|
||||
)
|
||||
|
||||
html_response += render_property("Exposed", str(exposed))
|
||||
|
||||
return web.Response(
|
||||
text=endpoint.render_base_template("Debug", html_response),
|
||||
text=endpoint.render_base_template(
|
||||
"Server Info", html_response
|
||||
),
|
||||
content_type="text/html",
|
||||
)
|
||||
|
||||
# Return JSON for other requests
|
||||
return web.json_response({"enabled": enabled})
|
||||
return web.json_response({"exposed": exposed, "debug": isdebug})
|
||||
|
||||
@PromptServer.instance.routes.get("/mtb/actions")
|
||||
async def no_route(request):
|
||||
async def no_route(request: Request):
|
||||
from . import endpoint
|
||||
|
||||
if "text/html" in request.headers.get("Accept", ""):
|
||||
@@ -382,7 +541,7 @@ if hasattr(PromptServer, "instance"):
|
||||
return web.json_response({"message": "actions has no get for now"})
|
||||
|
||||
@PromptServer.instance.routes.post("/mtb/actions")
|
||||
async def do_action(request):
|
||||
async def do_action(request: Request):
|
||||
from . import endpoint
|
||||
|
||||
reload(endpoint)
|
||||
@@ -390,6 +549,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
|
||||
|
||||
+37
-19
@@ -1,22 +1,40 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"lineEnding": "lf"
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "single",
|
||||
"semicolons": "asNeeded",
|
||||
"indentWidth": 2
|
||||
}
|
||||
"$schema": "https://biomejs.dev/schemas/2.0.5/schema.json",
|
||||
"assist": {
|
||||
"enabled": true,
|
||||
"actions": { "source": { "useSortedKeys": "on", "organizeImports": "on" } }
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"suspicious": {
|
||||
"noConsole": "error"
|
||||
},
|
||||
"style": {
|
||||
"noShoutyConstants": "warn",
|
||||
"useNamingConvention": "off",
|
||||
"useAsConstAssertion": "error",
|
||||
"useDefaultParameterLast": "error",
|
||||
"useEnumInitializers": "error",
|
||||
"useSelfClosingElements": "error",
|
||||
"useSingleVarDeclarator": "error",
|
||||
"noUnusedTemplateLiteral": "error",
|
||||
"useNumberNamespace": "error",
|
||||
"noInferrableTypes": "error",
|
||||
"noUselessElse": "error"
|
||||
}
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2,
|
||||
"lineEnding": "lf"
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "single",
|
||||
"semicolons": "asNeeded"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
###
|
||||
# File: docs.py
|
||||
# Project: comfy_mtb
|
||||
# Author: Mel Massadian
|
||||
# Copyright (c) 2023-2025 Mel Massadian
|
||||
#
|
||||
###
|
||||
"""Documentation handling utilities for MTB nodes."""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def strip_html_tags(text: str) -> str:
|
||||
"""Strip HTML tags from description text, converting images to markdown.
|
||||
|
||||
- Removes <details>...</details> blocks entirely (they contain JSON workflows)
|
||||
- Converts <img src="URL"> to 
|
||||
- Removes all other HTML tags while keeping their content
|
||||
"""
|
||||
# Remove <details>...</details> blocks entirely (contain JSON workflows)
|
||||
text = re.sub(r"<details>.*?</details>", "", text, flags=re.DOTALL)
|
||||
# Convert <img src="URL"> to 
|
||||
text = re.sub(r'<img[^>]+src=["\']([^"\']+)["\'][^>]*/?\s*>', r"", text)
|
||||
# Remove remaining HTML tags, keep content
|
||||
text = re.sub(r"<[^>]+>", "", text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def wiki_to_classname(s: str) -> str:
|
||||
"""Convert wiki filename to class name.
|
||||
|
||||
Example: "nodes-animation-builder" -> "MTB_AnimationBuilder"
|
||||
"""
|
||||
wiki_name = s.replace("nodes-", "", 1)
|
||||
return "MTB_" + "".join([part.capitalize() for part in wiki_name.split("-")])
|
||||
|
||||
|
||||
def classname_to_wiki(s: str) -> str:
|
||||
"""Convert class name to wiki filename.
|
||||
|
||||
Example: "MTB_AnimationBuilder" -> "nodes-animation-builder"
|
||||
"""
|
||||
classname = s.replace("MTB_", "")
|
||||
parts: list[str] = []
|
||||
start = 0
|
||||
for i in range(1, len(classname)):
|
||||
if classname[i].isupper():
|
||||
parts.append(classname[start:i].lower())
|
||||
start = i
|
||||
parts.append(classname[start:].lower())
|
||||
return "nodes-" + "-".join(parts)
|
||||
|
||||
|
||||
def load_wiki_docs(wiki_path: Path) -> dict[str, str]:
|
||||
"""Load wiki documentation files as a dict of classname -> content."""
|
||||
if not wiki_path.exists() or not wiki_path.is_dir():
|
||||
return {}
|
||||
nodes_path = wiki_path / "nodes"
|
||||
if not nodes_path.exists():
|
||||
return {}
|
||||
return {
|
||||
wiki_to_classname(x.stem): x.read_text(encoding="utf-8")
|
||||
for x in nodes_path.glob("*.md")
|
||||
}
|
||||
|
||||
|
||||
def assign_descriptions(
|
||||
nodes: list,
|
||||
node_docs: dict[str, str],
|
||||
wiki_path: Path,
|
||||
log,
|
||||
export: bool = False,
|
||||
) -> None:
|
||||
"""Assign DESCRIPTION to nodes from wiki docs or docstrings.
|
||||
|
||||
Priority:
|
||||
1. Existing DESCRIPTION attribute (not modified)
|
||||
2. Wiki doc file
|
||||
3. __doc__ docstring
|
||||
"""
|
||||
for node_class in nodes:
|
||||
class_name = node_class.__name__
|
||||
linked_doc = node_docs.get(class_name)
|
||||
|
||||
if not hasattr(node_class, "DESCRIPTION"):
|
||||
if linked_doc:
|
||||
log.debug(f"Found linked doc for {class_name}, using it")
|
||||
node_class.DESCRIPTION = linked_doc
|
||||
elif node_class.__doc__:
|
||||
log.debug(f"Using __doc__ as description for {class_name}")
|
||||
node_class.DESCRIPTION = node_class.__doc__
|
||||
if export:
|
||||
wiki_name = classname_to_wiki(class_name)
|
||||
(wiki_path / "nodes" / f"{wiki_name}.md").write_text(
|
||||
node_class.__doc__, encoding="utf-8"
|
||||
)
|
||||
else:
|
||||
log.debug(
|
||||
f"None of the methods could retrieve documentation for {class_name}"
|
||||
)
|
||||
+158
-23
@@ -1,11 +1,20 @@
|
||||
import csv
|
||||
import secrets
|
||||
import sys
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
from typing import Any, Literal
|
||||
|
||||
import folder_paths
|
||||
from aiohttp import web
|
||||
|
||||
from .install import get_node_dependencies
|
||||
from .log import mklog
|
||||
from .utils import (
|
||||
SortMode,
|
||||
backup_file,
|
||||
import_install,
|
||||
build_glob_patterns,
|
||||
glob_multiple,
|
||||
reqs_map,
|
||||
run_command,
|
||||
styles_dir,
|
||||
@@ -14,18 +23,24 @@ from .utils import (
|
||||
endlog = mklog("mtb endpoint")
|
||||
|
||||
# - ACTIONS
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import_install("requirements")
|
||||
|
||||
|
||||
def ACTIONS_installDependency(dependency_names=None):
|
||||
def ACTIONS_installDependency(dependency_names: list[str] | None = None):
|
||||
if dependency_names is None:
|
||||
# return web.Response(text="No dependency name provided", status=400)
|
||||
return {"error": "No dependency name provided"}
|
||||
|
||||
endlog.debug(f"Received Install Dependency request for {dependency_names}")
|
||||
# reqs = []
|
||||
resolved_names = [reqs_map.get(name, name) for name in dependency_names]
|
||||
allowed_deps = list(
|
||||
{d for dep in get_node_dependencies().values() for d in dep}
|
||||
)
|
||||
for dep in dependency_names:
|
||||
if dep not in allowed_deps:
|
||||
return {
|
||||
"error": f"Unknown dependency: {dep}, you can only use this endpoint to install {allowed_deps}"
|
||||
}
|
||||
try:
|
||||
run_command(
|
||||
[Path(sys.executable), "-m", "pip", "install"] + resolved_names
|
||||
@@ -50,6 +65,111 @@ def ACTIONS_installDependency(dependency_names=None):
|
||||
# break
|
||||
|
||||
|
||||
def ACTIONS_getUserImageFolders():
|
||||
input_dir = Path(folder_paths.get_input_directory())
|
||||
output_dir = Path(folder_paths.get_output_directory())
|
||||
|
||||
input_subdirs = [x.name for x in input_dir.iterdir() if x.is_dir()]
|
||||
output_subdirs = [x.name for x in output_dir.iterdir() if x.is_dir()]
|
||||
|
||||
return {"input": input_subdirs, "output": output_subdirs}
|
||||
|
||||
|
||||
def ACTIONS_getUserVideos(
|
||||
size=256, count=200, offset=0, sort: str | None = None
|
||||
):
|
||||
count = count or 1000
|
||||
video_extensions = ["webm", "mp4", "mkv", "mov"]
|
||||
entries = {}
|
||||
patterns = build_glob_patterns(video_extensions)
|
||||
input_dir = Path(folder_paths.get_input_directory())
|
||||
entries = glob_multiple(input_dir, patterns)
|
||||
|
||||
sort_mode = SortMode.from_str(sort)
|
||||
|
||||
if sort_mode:
|
||||
sort_key = {
|
||||
SortMode.MODIFIED: lambda x: x.stat().st_mtime,
|
||||
SortMode.MODIFIED_REVERSE: lambda x: x.stat().st_mtime,
|
||||
SortMode.NAME: lambda x: x.name,
|
||||
SortMode.NAME_REVERSE: lambda x: x.name,
|
||||
}.get(sort_mode)
|
||||
if sort_key:
|
||||
reverse = sort_mode in (SortMode.MODIFIED, SortMode.NAME_REVERSE)
|
||||
entries = sorted(entries, key=sort_key, reverse=reverse)
|
||||
|
||||
videos = {
|
||||
video.name: (
|
||||
f"/view?force_rate=0&frame_load_cap=0&skip_first_frames=0&select_every_nth=1&filename={urllib.parse.quote_plus(video.name)}&type=input&format=video&force_size={size}x?"
|
||||
)
|
||||
for i, video in enumerate(entries)
|
||||
if offset <= i < offset + count
|
||||
}
|
||||
return videos
|
||||
|
||||
|
||||
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: 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:
|
||||
# return {"error": "Session not authorized to getInputs"}
|
||||
|
||||
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: Path = input_dir if mode == "input" else output_dir
|
||||
if subfolder:
|
||||
entry_dir = entry_dir / subfolder
|
||||
|
||||
if not entry_dir.exists():
|
||||
return {
|
||||
"error": f"Subfolder {entry_dir.name} doesn't exists in {entry_dir.parent.as_posix()}"
|
||||
}
|
||||
supported = ["png", "jpg", "jpeg", "webp", "gif"]
|
||||
|
||||
entries = {}
|
||||
patterns = build_glob_patterns(supported, recursive=include_subfolders)
|
||||
entries = glob_multiple(entry_dir, patterns)
|
||||
|
||||
sort_mode = SortMode.from_str(sort)
|
||||
|
||||
if sort_mode:
|
||||
sort_key = {
|
||||
SortMode.MODIFIED: lambda x: x.stat().st_mtime,
|
||||
SortMode.MODIFIED_REVERSE: lambda x: x.stat().st_mtime,
|
||||
SortMode.NAME: lambda x: x.name,
|
||||
SortMode.NAME_REVERSE: lambda x: x.name,
|
||||
}.get(sort_mode)
|
||||
if sort_key:
|
||||
reverse = sort_mode in (SortMode.MODIFIED, SortMode.NAME_REVERSE)
|
||||
entries = sorted(entries, key=sort_key, reverse=reverse)
|
||||
|
||||
imgs = {
|
||||
img.name: (
|
||||
f"/mtb/view?filename={img.name}{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={f'&rand={secrets.randbelow(424242)}' if salt_urls else ''}"
|
||||
)
|
||||
for i, img in enumerate(entries)
|
||||
if offset <= i < offset + count
|
||||
}
|
||||
return imgs
|
||||
|
||||
|
||||
def ACTIONS_getStyles(style_name=None):
|
||||
from .nodes.conditions import MTB_StylesLoader
|
||||
|
||||
@@ -97,7 +217,7 @@ def ACTIONS_saveStyle(data):
|
||||
csv_writer.writerow(row)
|
||||
|
||||
|
||||
async def do_action(request) -> web.Response:
|
||||
async def do_action(request: web.Request) -> web.Response:
|
||||
endlog.debug("Init action request")
|
||||
request_data = await request.json()
|
||||
name = request_data.get("name")
|
||||
@@ -109,7 +229,12 @@ async def do_action(request) -> web.Response:
|
||||
method = globals().get(method_name)
|
||||
|
||||
if callable(method):
|
||||
result = method(args) if args else method()
|
||||
result = None
|
||||
if args:
|
||||
result = method(*args) if isinstance(args, list) else method(args)
|
||||
else:
|
||||
result = method()
|
||||
|
||||
endlog.debug(f"Action result: {result}")
|
||||
return web.json_response({"result": result})
|
||||
|
||||
@@ -130,10 +255,13 @@ async def do_action(request) -> web.Response:
|
||||
# - HTML UTILS
|
||||
|
||||
|
||||
def dependencies_button(name, dependencies):
|
||||
def dependencies_button(name: str, dependencies: list[str]) -> str:
|
||||
deps = ",".join([f"'{x}'" for x in dependencies])
|
||||
return f"""
|
||||
<button class="dependency-button" onclick="window.mtb_action('installDependency',[{deps}])">Install {name} deps</button>
|
||||
<button
|
||||
class="dependency-button"
|
||||
onclick="window.mtb_action('installDependency',[{deps}])"
|
||||
>Install {name} deps</button>
|
||||
"""
|
||||
|
||||
|
||||
@@ -153,7 +281,7 @@ def csv_editor():
|
||||
html_out = """
|
||||
<div id="style-editor">
|
||||
<h1>Style Editor</h1>
|
||||
|
||||
|
||||
"""
|
||||
for current, styles in style_files.items():
|
||||
current_out = f"<h3>{current}</h3>"
|
||||
@@ -215,11 +343,14 @@ def render_tab_view(**kwargs):
|
||||
"""
|
||||
|
||||
|
||||
def add_foldable_region(title, content):
|
||||
def add_foldable_region(title: str, content: str):
|
||||
symbol_id = f"{title}-symbol"
|
||||
return f"""
|
||||
<div class='foldable'>
|
||||
<div class='foldable-title' onclick="toggleFoldable('{title}', '{symbol_id}')">
|
||||
<div
|
||||
class='foldable-title'
|
||||
onclick="toggleFoldable('{title}', '{symbol_id}')"
|
||||
>
|
||||
<span id='{symbol_id}' class='foldable-symbol'>▷</span>
|
||||
{title}
|
||||
</div>
|
||||
@@ -231,7 +362,9 @@ def add_foldable_region(title, content):
|
||||
"""
|
||||
|
||||
|
||||
def add_split_pane(left_content, right_content, vertical=True):
|
||||
def add_split_pane(
|
||||
left_content: str, right_content: str, *, vertical: bool = True
|
||||
):
|
||||
orientation = "vertical" if vertical else "horizontal"
|
||||
return f"""
|
||||
<div class="split-pane {orientation}">
|
||||
@@ -250,7 +383,7 @@ def add_split_pane(left_content, right_content, vertical=True):
|
||||
"""
|
||||
|
||||
|
||||
def add_dropdown(title, options):
|
||||
def add_dropdown(title: str, options: list[str]):
|
||||
option_str = "\n".join(
|
||||
[f"<option value='{opt}'>{opt}</option>" for opt in options]
|
||||
)
|
||||
@@ -262,18 +395,18 @@ def add_dropdown(title, options):
|
||||
"""
|
||||
|
||||
|
||||
def render_table(table_dict, sort=True, title=None):
|
||||
table_dict = sorted(
|
||||
def render_table(table_dict: dict[str, Any], sort=True, title=None):
|
||||
table_list = sorted(
|
||||
table_dict.items(), key=lambda item: item[0]
|
||||
) # Sort the dictionary by keys
|
||||
|
||||
table_rows = ""
|
||||
for name, item in table_dict:
|
||||
for name, item in table_list:
|
||||
if isinstance(item, dict):
|
||||
if "dependencies" in item:
|
||||
table_rows += f"<tr><td>{name}</td><td>"
|
||||
table_rows += (
|
||||
f"{dependencies_button(name,item['dependencies'])}"
|
||||
f"{dependencies_button(name, item['dependencies'])}"
|
||||
)
|
||||
|
||||
table_rows += "</td></tr>"
|
||||
@@ -299,12 +432,12 @@ def render_table(table_dict, sort=True, title=None):
|
||||
<tbody>
|
||||
{table_rows}
|
||||
</tbody>
|
||||
</table>
|
||||
</table>
|
||||
</div>
|
||||
"""
|
||||
|
||||
|
||||
def render_base_template(title, content):
|
||||
def render_base_template(title: str, content: str):
|
||||
github_icon_svg = """<svg xmlns="http://www.w3.org/2000/svg" fill="whitesmoke" height="3em" viewBox="0 0 496 512"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg>"""
|
||||
return f"""
|
||||
<!DOCTYPE html>
|
||||
@@ -340,7 +473,9 @@ def render_base_template(title, content):
|
||||
<header>
|
||||
<a href="/">Back to Comfy</a>
|
||||
<div class="mtb_logo">
|
||||
<img src="https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873" alt="Comfy MTB Logo" height="70" width="128">
|
||||
<img
|
||||
src="https://repository-images.githubusercontent.com/649047066/a3eef9a7-20dd-4ef9-b839-884502d4e873"
|
||||
alt="Comfy MTB Logo" height="70" width="128">
|
||||
<span class="title">Comfy MTB</span></div>
|
||||
<a style="width:128px;text-align:center" href="https://www.github.com/melmass/comfy_mtb">
|
||||
{github_icon_svg}
|
||||
@@ -355,6 +490,6 @@ def render_base_template(title, content):
|
||||
<!-- Shared footer content here -->
|
||||
</footer>
|
||||
</body>
|
||||
|
||||
|
||||
</html>
|
||||
"""
|
||||
|
||||
@@ -1,147 +1,345 @@
|
||||
# NOTE: This file is only use for development you can ignore it
|
||||
|
||||
use path.nu *
|
||||
use log.nu
|
||||
use nssm.nu *
|
||||
use nutils.nu [ make-id upsert-all fwd-slash backup-file ]
|
||||
use os.nu [ link ]
|
||||
|
||||
def get_root [--clean] {
|
||||
if $clean {
|
||||
$env.COMFY_CLEAN_ROOT
|
||||
} else {
|
||||
$env.COMFY_ROOT
|
||||
# --- 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, --listen] {
|
||||
let root = get_root --clean=($clean)
|
||||
cd $root
|
||||
MTB_DEBUG=true python main.py --port 3000 --preview-method auto ...(if $listen {["--listen"]} else {[]})
|
||||
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
|
||||
|
||||
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"
|
||||
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
|
||||
|
||||
let models = $"($root)/models"
|
||||
let inputs = $"($root)/input"
|
||||
|
||||
cd $root
|
||||
|
||||
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)"
|
||||
|
||||
# find all symlinks
|
||||
let links = (ls -la |
|
||||
where not ($it.target | is-empty) |
|
||||
select name target |
|
||||
sort-by name)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
if not ($links | is-empty) {
|
||||
$links | save -f links.nuon
|
||||
# remove them
|
||||
open links.nuon | each {|p| rm $p.name }
|
||||
}
|
||||
cd $root
|
||||
|
||||
cd $root
|
||||
log info $"Checking out to master"
|
||||
git checkout master
|
||||
|
||||
print $"(ansi yellow_italic)Checking out to master(ansi reset)"
|
||||
git checkout master
|
||||
|
||||
print $"(ansi yellow_italic)Fetching and pulling remote updates(ansi reset)"
|
||||
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
|
||||
}
|
||||
|
||||
print $"(ansi yellow_italic)Back to our branch \(($branch_name)\)(ansi reset)"
|
||||
git checkout -
|
||||
let new_commit = (git rev-parse HEAD | str trim)
|
||||
|
||||
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 {
|
||||
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")}
|
||||
|
||||
print $filtered
|
||||
$filtered | each {|f|
|
||||
let new_name = ($f.name | str replace ".disabled" "")
|
||||
|
||||
let new_name = if $f.enabled {
|
||||
$"($new_name).disabled"
|
||||
} else {
|
||||
$new_name
|
||||
}
|
||||
print $"Moving ($f.name) to ($new_name)"
|
||||
mv $f.name $new_name
|
||||
let filtered = $choices | wrap name | upsert enabled {|p| not ($p.name | str ends-with ".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
|
||||
}
|
||||
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 .
|
||||
export def "comfy update_extensions" [ --clean] {
|
||||
let root = get_root --clean=$clean
|
||||
cd $root
|
||||
cd custom_nodes
|
||||
git multipull . -s -q
|
||||
}
|
||||
|
||||
# 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.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
|
||||
|
||||
$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"
|
||||
}
|
||||
#
|
||||
path-add ($env.CUDA_ROOT | path join bin)
|
||||
overlay use ../../.venv/Scripts/activate.nu
|
||||
|
||||
overlay use "../../.venv/Scripts/activate.nu"
|
||||
}
|
||||
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"use_repl": false
|
||||
}
|
||||
+64
-29
@@ -43,10 +43,27 @@ pip_map = {
|
||||
"tb-nightly": "tensorboard",
|
||||
"protobuf": "google.protobuf",
|
||||
"qrcode[pil]": "qrcode",
|
||||
"requirements-parser": "requirements"
|
||||
# Add more mappings as needed
|
||||
}
|
||||
|
||||
|
||||
def get_node_dependencies():
|
||||
restore_deps = ["basicsr"]
|
||||
onnx_deps = ["onnxruntime"]
|
||||
swap_deps = ["insightface"] + onnx_deps
|
||||
quant_deps = ["bitsandbytes"]
|
||||
io_deps = ["av"]
|
||||
return {
|
||||
"QrCode": ["qrcode"],
|
||||
"DeepBump": onnx_deps,
|
||||
"FaceSwap": swap_deps,
|
||||
"LoadFaceSwapModel": swap_deps,
|
||||
"LoadFaceAnalysisModel": restore_deps,
|
||||
"Quantize": quant_deps,
|
||||
"SaveGif": io_deps,
|
||||
}
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
# region ansi
|
||||
@@ -124,12 +141,12 @@ def print_formatted(text, *formats, color=None, background=None, **kwargs):
|
||||
header = "[mtb install] "
|
||||
|
||||
# Handle console encoding for Unicode characters (utf-8)
|
||||
encoded_header = header.encode(sys.stdout.encoding, errors="replace").decode(
|
||||
sys.stdout.encoding
|
||||
)
|
||||
encoded_text = formatted_text.encode(sys.stdout.encoding, errors="replace").decode(
|
||||
sys.stdout.encoding
|
||||
)
|
||||
encoded_header = header.encode(
|
||||
sys.stdout.encoding, errors="replace"
|
||||
).decode(sys.stdout.encoding)
|
||||
encoded_text = formatted_text.encode(
|
||||
sys.stdout.encoding, errors="replace"
|
||||
).decode(sys.stdout.encoding)
|
||||
|
||||
print(
|
||||
" " * len(encoded_header)
|
||||
@@ -163,7 +180,9 @@ def run_command(cmd, ignored_lines_start=None):
|
||||
try:
|
||||
_run_command(shell_cmd, ignored_lines_start)
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"Command failed with return code: {e.returncode}", file=sys.stderr)
|
||||
print(
|
||||
f"Command failed with return code: {e.returncode}", file=sys.stderr
|
||||
)
|
||||
print(e.stderr.strip(), file=sys.stderr)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
@@ -238,7 +257,7 @@ def suppress_std():
|
||||
def get_local_version():
|
||||
init_file = os.path.join(os.path.dirname(__file__), "__init__.py")
|
||||
if os.path.isfile(init_file):
|
||||
with open(init_file, "r") as f:
|
||||
with open(init_file) as f:
|
||||
tree = ast.parse(f.read())
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Assign):
|
||||
@@ -256,13 +275,16 @@ def download_file(url, file_name):
|
||||
with requests.get(url, stream=True) as response:
|
||||
response.raise_for_status()
|
||||
total_size = int(response.headers.get("content-length", 0))
|
||||
with open(file_name, "wb") as file, tqdm(
|
||||
desc=file_name.stem,
|
||||
total=total_size,
|
||||
unit="B",
|
||||
unit_scale=True,
|
||||
unit_divisor=1024,
|
||||
) as progress_bar:
|
||||
with (
|
||||
open(file_name, "wb") as file,
|
||||
tqdm(
|
||||
desc=file_name.stem,
|
||||
total=total_size,
|
||||
unit="B",
|
||||
unit_scale=True,
|
||||
unit_divisor=1024,
|
||||
) as progress_bar,
|
||||
):
|
||||
for chunk in response.iter_content(chunk_size=8192):
|
||||
file.write(chunk)
|
||||
progress_bar.update(len(chunk))
|
||||
@@ -302,7 +324,9 @@ def import_or_install(requirement, dry=False):
|
||||
pip_install_name = pip_name + pip_spec
|
||||
|
||||
if not installed:
|
||||
print_formatted(f"Installing package {pip_name}...", "italic", color="yellow")
|
||||
print_formatted(
|
||||
f"Installing package {pip_name}...", "italic", color="yellow"
|
||||
)
|
||||
if dry:
|
||||
print_formatted(
|
||||
f"Dry-run: Package {pip_install_name} would be installed (import name: '{import_name}').",
|
||||
@@ -310,7 +334,9 @@ def import_or_install(requirement, dry=False):
|
||||
)
|
||||
else:
|
||||
try:
|
||||
run_command([executable, "-m", "pip", "install", pip_install_name])
|
||||
run_command(
|
||||
[executable, "-m", "pip", "install", pip_install_name]
|
||||
)
|
||||
print_formatted(
|
||||
f"Package {pip_install_name} installed successfully using pip package name (import name: '{import_name}')",
|
||||
"bold",
|
||||
@@ -326,13 +352,9 @@ def import_or_install(requirement, dry=False):
|
||||
|
||||
def get_github_assets(tag=None):
|
||||
if tag:
|
||||
tag_url = (
|
||||
f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/tags/{tag}"
|
||||
)
|
||||
tag_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/tags/{tag}"
|
||||
else:
|
||||
tag_url = (
|
||||
f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
|
||||
)
|
||||
tag_url = f"https://api.github.com/repos/{repo_owner}/{repo_name}/releases/latest"
|
||||
response = requests.get(tag_url)
|
||||
if response.status_code == 404:
|
||||
# print_formatted(
|
||||
@@ -361,7 +383,9 @@ except ImportError:
|
||||
def main():
|
||||
if len(sys.argv) == 1:
|
||||
print_formatted(
|
||||
"mtb doesn't need an install script anymore.", "italic", color="yellow"
|
||||
"mtb doesn't need an install script anymore.",
|
||||
"italic",
|
||||
color="yellow",
|
||||
)
|
||||
return
|
||||
if all(arg not in ("-p", "--path") for arg in sys.argv):
|
||||
@@ -384,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)
|
||||
@@ -397,8 +421,12 @@ def main():
|
||||
else:
|
||||
repo_dir = clone_dir / repo_name
|
||||
if not repo_dir.exists():
|
||||
print_formatted(f"Cloning to {repo_dir}...", "italic", color="yellow")
|
||||
run_command(["git", "clone", "--recursive", repo_url, repo_dir])
|
||||
print_formatted(
|
||||
f"Cloning to {repo_dir}...", "italic", color="yellow"
|
||||
)
|
||||
run_command(
|
||||
["git", "clone", "--recursive", repo_url, repo_dir]
|
||||
)
|
||||
else:
|
||||
print_formatted(
|
||||
f"Directory {repo_dir} already exists, we will update it..."
|
||||
@@ -409,7 +437,14 @@ def main():
|
||||
|
||||
print_formatted("Checking environment...", "italic", color="yellow")
|
||||
missing_deps = []
|
||||
install_cmd = [executable, "-m", "pip", "install", "-r", "requirements.txt"]
|
||||
install_cmd = [
|
||||
executable,
|
||||
"-m",
|
||||
"pip",
|
||||
"install",
|
||||
"-r",
|
||||
"requirements.txt",
|
||||
]
|
||||
run_command(install_cmd)
|
||||
|
||||
print_formatted(
|
||||
|
||||
@@ -55,7 +55,7 @@ def mklog(name: str, level: int = base_log_level):
|
||||
|
||||
|
||||
# - The main app logger
|
||||
log = mklog(__package__, base_log_level)
|
||||
log = mklog("comfy-mtb", base_log_level)
|
||||
|
||||
|
||||
def log_user(arg: str):
|
||||
@@ -77,5 +77,11 @@ def cyan_text(text: str):
|
||||
def get_label(label: str):
|
||||
if label.startswith("MTB_"):
|
||||
label = label[4:]
|
||||
words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
|
||||
|
||||
words = re.findall(
|
||||
r"(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z]))",
|
||||
label,
|
||||
)
|
||||
reformatted_label = re.sub(r"([A-Z]+)", r" \1", label).strip()
|
||||
words = reformatted_label.split()
|
||||
return " ".join(words).strip()
|
||||
|
||||
+931
@@ -0,0 +1,931 @@
|
||||
import sys
|
||||
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 AudioTensor(TypedDict):
|
||||
"""Comfy's representation of AUDIO data."""
|
||||
|
||||
sample_rate: int
|
||||
waveform: torch.Tensor
|
||||
|
||||
|
||||
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:
|
||||
"""Base class for audio processing."""
|
||||
|
||||
@classmethod
|
||||
def is_stereo(
|
||||
cls,
|
||||
audios: AudioData,
|
||||
) -> bool:
|
||||
if isinstance(audios, list):
|
||||
return any(cls.is_stereo(audio) for audio in audios)
|
||||
else:
|
||||
return audios["waveform"].shape[1] == 2
|
||||
|
||||
@staticmethod
|
||||
def resample(audio: 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=current_rate, new_freq=common_sample_rate
|
||||
)
|
||||
return {
|
||||
"sample_rate": common_sample_rate,
|
||||
"waveform": resampler(audio["waveform"]),
|
||||
}
|
||||
else:
|
||||
return audio
|
||||
|
||||
@staticmethod
|
||||
def to_stereo(audio: AudioTensor) -> AudioTensor:
|
||||
if audio["waveform"].shape[1] == 1:
|
||||
return {
|
||||
"sample_rate": audio["sample_rate"],
|
||||
"waveform": torch.cat(
|
||||
[audio["waveform"], audio["waveform"]], dim=1
|
||||
),
|
||||
}
|
||||
else:
|
||||
return audio
|
||||
|
||||
@classmethod
|
||||
def preprocess_audios(
|
||||
cls, audios: list[AudioTensor]
|
||||
) -> tuple[list[AudioTensor], bool, int]:
|
||||
max_sample_rate = max([audio["sample_rate"] for audio in audios])
|
||||
|
||||
resampled_audios = [
|
||||
cls.resample(audio, max_sample_rate) for audio in audios
|
||||
]
|
||||
|
||||
is_stereo = cls.is_stereo(audios)
|
||||
if is_stereo:
|
||||
audios = [cls.to_stereo(audio) for audio in resampled_audios]
|
||||
|
||||
return (audios, is_stereo, max_sample_rate)
|
||||
|
||||
|
||||
class 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."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": ("AUDIO",),
|
||||
"length": (
|
||||
("INT"),
|
||||
{
|
||||
"default": 1000,
|
||||
"min": 100,
|
||||
"max": sys.maxsize,
|
||||
"step": 1,
|
||||
"tooltip": "Length in milliseconds",
|
||||
},
|
||||
),
|
||||
"offset": (
|
||||
("INT"),
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": sys.maxsize,
|
||||
"step": 1,
|
||||
"tooltip": "Offset in milliseconds",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("cut_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "cut"
|
||||
|
||||
def cut(self, audio: AudioTensor, length: int, offset: int):
|
||||
sample_rate = audio["sample_rate"]
|
||||
start_idx: int = int(float(offset) * float(sample_rate) / 1000)
|
||||
end_idx = min(
|
||||
start_idx + int(float(length) * float(sample_rate) / 1000),
|
||||
audio["waveform"].shape[-1],
|
||||
)
|
||||
cut_waveform = audio["waveform"][:, :, start_idx:end_idx]
|
||||
|
||||
return (
|
||||
{
|
||||
"sample_rate": sample_rate,
|
||||
"waveform": cut_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class MTB_AudioStack(MtbAudio):
|
||||
"""Stack/Overlay audio inputs (dynamic inputs).
|
||||
- pad audios to the longest inputs.
|
||||
- resample audios to the highest sample rate in the inputs.
|
||||
- convert them all to stereo if one of the inputs is.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {}}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("stacked_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "stack"
|
||||
|
||||
def stack(self, **kwargs: AudioTensor) -> tuple[AudioTensor]:
|
||||
audios, is_stereo, max_rate = self.preprocess_audios(
|
||||
list(kwargs.values())
|
||||
)
|
||||
|
||||
max_length = max([audio["waveform"].shape[-1] for audio in audios])
|
||||
|
||||
padded_audios: list[torch.Tensor] = []
|
||||
for audio in audios:
|
||||
padding = torch.zeros(
|
||||
(
|
||||
1,
|
||||
2 if is_stereo else 1,
|
||||
max_length - audio["waveform"].shape[-1],
|
||||
)
|
||||
)
|
||||
padded_audio = torch.cat([audio["waveform"], padding], dim=-1)
|
||||
padded_audios.append(padded_audio)
|
||||
|
||||
stacked_waveform = torch.stack(padded_audios, dim=0).sum(dim=0)
|
||||
|
||||
return (
|
||||
{
|
||||
"sample_rate": max_rate,
|
||||
"waveform": stacked_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class MTB_AudioSequence(MtbAudio):
|
||||
"""Sequence audio inputs (dynamic inputs).
|
||||
- adding silence_duration between each segment
|
||||
can now also be negative to overlap the clips, safely bound
|
||||
to the the input length.
|
||||
- resample audios to the highest sample rate in the inputs.
|
||||
- convert them all to stereo if one of the inputs is.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"silence_duration": (
|
||||
("FLOAT"),
|
||||
{"default": 0.0, "min": -999.0, "max": 999, "step": 0.01},
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("sequenced_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "sequence"
|
||||
|
||||
def sequence(self, silence_duration: float, **kwargs: AudioTensor):
|
||||
audios, is_stereo, max_rate = self.preprocess_audios(
|
||||
list(kwargs.values())
|
||||
)
|
||||
|
||||
sequence: list[torch.Tensor] = []
|
||||
for i, audio in enumerate(audios):
|
||||
if i > 0:
|
||||
if silence_duration > 0:
|
||||
silence = torch.zeros(
|
||||
(
|
||||
1,
|
||||
2 if is_stereo else 1,
|
||||
int(silence_duration * max_rate),
|
||||
)
|
||||
)
|
||||
sequence.append(silence)
|
||||
elif silence_duration < 0:
|
||||
overlap = int(abs(silence_duration) * max_rate)
|
||||
previous_audio = sequence[-1]
|
||||
overlap = min(
|
||||
overlap,
|
||||
previous_audio.shape[-1],
|
||||
audio["waveform"].shape[-1],
|
||||
)
|
||||
if overlap > 0:
|
||||
overlap_part = (
|
||||
previous_audio[:, :, -overlap:]
|
||||
+ audio["waveform"][:, :, :overlap]
|
||||
)
|
||||
sequence[-1] = previous_audio[:, :, :-overlap]
|
||||
sequence.append(overlap_part)
|
||||
audio["waveform"] = audio["waveform"][:, :, overlap:]
|
||||
|
||||
sequence.append(audio["waveform"])
|
||||
|
||||
sequenced_waveform = torch.cat(sequence, dim=-1)
|
||||
return (
|
||||
{
|
||||
"sample_rate": max_rate,
|
||||
"waveform": sequenced_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
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,
|
||||
]
|
||||
+507
-21
@@ -1,12 +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
|
||||
|
||||
|
||||
@@ -46,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:
|
||||
@@ -169,6 +175,109 @@ 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, False)
|
||||
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 = image.size(0) if image is not None else 0
|
||||
mask_count = mask.size(0) if mask is not None else 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_count} mask and {image_count} images)"
|
||||
)
|
||||
|
||||
batch_size = max(image_count, mask_count)
|
||||
if batch_size == 0:
|
||||
return ([], [], [0])
|
||||
|
||||
im_batches = []
|
||||
mask_batches = []
|
||||
|
||||
for i in range(0, batch_size, sub_batch_size):
|
||||
if image is not None:
|
||||
im_batches.append(image[i : i + sub_batch_size])
|
||||
if mask is not None:
|
||||
mask_batches.append(mask[i : i + sub_batch_size])
|
||||
|
||||
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"""
|
||||
|
||||
@@ -178,18 +287,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:
|
||||
@@ -207,9 +320,9 @@ class MTB_BatchShape:
|
||||
"image_width": ("INT", {"default": 512}),
|
||||
"image_height": ("INT", {"default": 512}),
|
||||
"shape_size": ("INT", {"default": 100}),
|
||||
"color": ("COLOR", {"default": "#ffffff"}),
|
||||
"bg_color": ("COLOR", {"default": "#000000"}),
|
||||
"shade_color": ("COLOR", {"default": "#000000"}),
|
||||
"color": ("COLOR", {"default": "#ffffff","widgetType": "MTB_COLOR"}),
|
||||
"bg_color": ("COLOR", {"default": "#000000","widgetType": "MTB_COLOR"}),
|
||||
"shade_color": ("COLOR", {"default": "#000000","widgetType": "MTB_COLOR"}),
|
||||
"thickness": ("INT", {"default": 5}),
|
||||
"shadex": ("FLOAT", {"default": 0.0}),
|
||||
"shadey": ("FLOAT", {"default": 0.0}),
|
||||
@@ -374,8 +487,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",
|
||||
@@ -410,7 +529,14 @@ class MTB_BatchFloat:
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
CATEGORY = "mtb/batch"
|
||||
|
||||
def set_floats(self, mode, count, min, max, easing):
|
||||
def set_floats(
|
||||
self,
|
||||
mode: Literal["Steps"] | Literal["Single"] = "Steps",
|
||||
count: int = 1,
|
||||
min: float = 0.0, # noqa: A002
|
||||
max: float = 1.0, # noqa: A002
|
||||
easing: str = "Linear",
|
||||
):
|
||||
if mode == "Steps" and count == 1:
|
||||
raise ValueError(
|
||||
"Steps mode requires at least a count of 2 values"
|
||||
@@ -429,6 +555,210 @@ class MTB_BatchFloat:
|
||||
return (keyframes,)
|
||||
|
||||
|
||||
class MTB_BatchSequencePlus:
|
||||
"""Sequences multiple image batches with transition effects."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"transition": (
|
||||
[
|
||||
"none",
|
||||
"crossfade",
|
||||
"slide_left",
|
||||
"slide_right",
|
||||
"slide_up",
|
||||
"slide_down",
|
||||
"wipe_left",
|
||||
"wipe_right",
|
||||
"wipe_up",
|
||||
"wipe_down",
|
||||
"band_wipe_h",
|
||||
"band_wipe_v",
|
||||
],
|
||||
{"default": "none"},
|
||||
),
|
||||
"overlap_frames": (
|
||||
"INT",
|
||||
{"default": 0, "min": 0, "max": 120, "step": 1},
|
||||
),
|
||||
"reverse": ("BOOLEAN", {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "sequence_batches"
|
||||
CATEGORY = "mtb/batch"
|
||||
|
||||
def apply_transition(
|
||||
self,
|
||||
frame1: torch.Tensor,
|
||||
frame2: torch.Tensor,
|
||||
transition: str,
|
||||
progress: float,
|
||||
):
|
||||
"""Apply transition effect between two frames."""
|
||||
if transition == "none":
|
||||
return frame1 if progress < 0.5 else frame2
|
||||
|
||||
elif transition == "crossfade":
|
||||
return frame1 * (1 - progress) + frame2 * progress
|
||||
|
||||
elif transition.startswith("slide_"):
|
||||
h, w = frame1.shape[1:3]
|
||||
if transition == "slide_left":
|
||||
offset = int(w * progress)
|
||||
frame2 = torch.roll(frame2, shifts=-offset, dims=2)
|
||||
elif transition == "slide_right":
|
||||
offset = int(w * progress)
|
||||
frame2 = torch.roll(frame2, shifts=offset, dims=2)
|
||||
elif transition == "slide_up":
|
||||
offset = int(h * progress)
|
||||
frame2 = torch.roll(frame2, shifts=-offset, dims=1)
|
||||
elif transition == "slide_down":
|
||||
offset = int(h * progress)
|
||||
frame2 = torch.roll(frame2, shifts=offset, dims=1)
|
||||
return frame1 * (1 - progress) + frame2 * progress
|
||||
|
||||
elif transition.startswith("wipe_"):
|
||||
h, w = frame1.shape[1:3]
|
||||
mask = torch.zeros_like(frame1)
|
||||
if transition == "wipe_left":
|
||||
edge = int(w * progress)
|
||||
mask[:, :, :edge, :] = 1
|
||||
elif transition == "wipe_right":
|
||||
edge = int(w * (1 - progress))
|
||||
mask[:, :, edge:, :] = 1
|
||||
elif transition == "wipe_up":
|
||||
edge = int(h * progress)
|
||||
mask[:, :edge, :, :] = 1
|
||||
elif transition == "wipe_down":
|
||||
edge = int(h * (1 - progress))
|
||||
mask[:, edge:, :, :] = 1
|
||||
return frame1 * (1 - mask) + frame2 * mask
|
||||
|
||||
elif transition.startswith("band_wipe_"):
|
||||
h, w = frame1.shape[1:3]
|
||||
mask = torch.zeros_like(frame1)
|
||||
num_bands = 10 # Number of bands
|
||||
|
||||
if transition == "band_wipe_h":
|
||||
band_width = w / num_bands
|
||||
for i in range(num_bands):
|
||||
edge = int((w * progress) - (i * band_width))
|
||||
start = int(i * band_width)
|
||||
end = int(min(start + edge, (i + 1) * band_width))
|
||||
if end > start:
|
||||
mask[:, :, start:end, :] = 1
|
||||
else: # band_wipe_v
|
||||
band_height = h / num_bands
|
||||
for i in range(num_bands):
|
||||
edge = int((h * progress) - (i * band_height))
|
||||
start = int(i * band_height)
|
||||
end = int(min(start + edge, (i + 1) * band_height))
|
||||
if end > start:
|
||||
mask[:, start:end, :, :] = 1
|
||||
|
||||
return frame1 * (1 - mask) + frame2 * mask
|
||||
|
||||
return frame1
|
||||
|
||||
def sequence_batches(
|
||||
self, transition: str, overlap_frames: int, reverse: bool, **kwargs
|
||||
):
|
||||
images: list[torch.Tensor] = list(kwargs.values())
|
||||
|
||||
if reverse:
|
||||
images = images[::-1]
|
||||
|
||||
processed_images: list[torch.Tensor] = []
|
||||
for img in images:
|
||||
if len(img.shape) == 3:
|
||||
img = img.unsqueeze(0)
|
||||
processed_images.append(img)
|
||||
|
||||
if overlap_frames == 0 or transition == "none":
|
||||
return (torch.cat(processed_images, dim=0),)
|
||||
|
||||
result_frames: list[torch.Tensor] = []
|
||||
|
||||
if len(processed_images) > 0:
|
||||
result_frames.extend(
|
||||
list(processed_images[0][: -overlap_frames // 2])
|
||||
)
|
||||
|
||||
for i in range(1, len(processed_images)):
|
||||
prev_batch = processed_images[i - 1]
|
||||
curr_batch = processed_images[i]
|
||||
|
||||
prev_frames = min(overlap_frames // 2, len(prev_batch))
|
||||
next_frames = min(overlap_frames // 2, len(curr_batch))
|
||||
total_overlap = prev_frames + next_frames
|
||||
|
||||
if total_overlap < 2:
|
||||
# when not enough frames for transition, just concatenate
|
||||
result_frames.extend(list(prev_batch[-prev_frames:]))
|
||||
result_frames.extend(list(curr_batch[:next_frames]))
|
||||
continue
|
||||
|
||||
for t in range(total_overlap):
|
||||
progress = t / (total_overlap - 1)
|
||||
|
||||
prev_idx = (
|
||||
len(prev_batch) - prev_frames + min(t, prev_frames - 1)
|
||||
)
|
||||
next_idx = max(0, t - prev_frames)
|
||||
|
||||
transition_frame = self.apply_transition(
|
||||
prev_batch[prev_idx : prev_idx + 1],
|
||||
curr_batch[next_idx : next_idx + 1],
|
||||
transition,
|
||||
progress,
|
||||
)
|
||||
result_frames.append(transition_frame[0])
|
||||
|
||||
if i < len(processed_images) - 1:
|
||||
result_frames.extend(
|
||||
list(curr_batch[next_frames : -overlap_frames // 2])
|
||||
)
|
||||
else:
|
||||
result_frames.extend(list(curr_batch[next_frames:]))
|
||||
|
||||
result = torch.stack(result_frames, dim=0)
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
class MTB_BatchSequence:
|
||||
"""Sequences multiple image batches one after another"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"reverse": ("BOOLEAN", {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "sequence_batches"
|
||||
CATEGORY = "mtb/batch"
|
||||
|
||||
def sequence_batches(self, reverse: bool, **kwargs):
|
||||
images = list(kwargs.values())
|
||||
if reverse:
|
||||
images = images[::-1]
|
||||
|
||||
processed = []
|
||||
for img in images:
|
||||
if len(img.shape) == 3:
|
||||
img = img.unsqueeze(0)
|
||||
processed.append(img)
|
||||
|
||||
return (torch.cat(processed, dim=0),)
|
||||
|
||||
|
||||
class MTB_BatchMerge:
|
||||
"""Merges multiple image batches with different frame counts"""
|
||||
|
||||
@@ -497,7 +827,7 @@ class MTB_Batch2dTransform:
|
||||
["edge", "constant", "reflect", "symmetric"],
|
||||
{"default": "edge"},
|
||||
),
|
||||
"constant_color": ("COLOR", {"default": "#000000"}),
|
||||
"constant_color": ("COLOR", {"default": "#000000","widgetType": "MTB_COLOR"}),
|
||||
},
|
||||
"optional": {
|
||||
"x": ("FLOATS",),
|
||||
@@ -505,6 +835,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.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -533,6 +870,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
|
||||
@@ -584,6 +922,7 @@ class MTB_Batch2dTransform:
|
||||
keyframes["shear"][i],
|
||||
border_handling,
|
||||
constant_color,
|
||||
use_normalized=use_normalized,
|
||||
)[0]
|
||||
for i in range(image.shape[0])
|
||||
]
|
||||
@@ -711,7 +1050,9 @@ class MTB_PlotBatchFloat:
|
||||
ax.set_xlim(1, max_length) # Set X-axis limits
|
||||
np.random.seed(seed)
|
||||
colors = np.random.rand(len(kwargs), 3) # Generate random RGB values
|
||||
for color, (label, values) in zip(colors, kwargs.items()):
|
||||
for color, (label, values) in zip(
|
||||
colors, kwargs.items(), strict=False
|
||||
):
|
||||
ax.plot(x_values[: len(values)], values, label=label, color=color)
|
||||
ax.legend(
|
||||
title="Legend",
|
||||
@@ -1025,18 +1366,163 @@ 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_BatchFloat,
|
||||
MTB_Batch2dTransform,
|
||||
MTB_BatchShape,
|
||||
MTB_BatchMake,
|
||||
MTB_BatchFloat,
|
||||
MTB_BatchFloatAssemble,
|
||||
MTB_BatchFloatFill,
|
||||
MTB_BatchFloatNormalize,
|
||||
MTB_BatchMerge,
|
||||
MTB_BatchShake,
|
||||
MTB_PlotBatchFloat,
|
||||
MTB_BatchTimeWrap,
|
||||
MTB_BatchFloatFit,
|
||||
MTB_BatchFloatMath,
|
||||
MTB_BatchFloatNormalize,
|
||||
MTB_BatchFromFolder,
|
||||
MTB_BatchMake,
|
||||
MTB_BatchMerge,
|
||||
MTB_BatchSequence,
|
||||
MTB_BatchSequencePlus,
|
||||
MTB_BatchShake,
|
||||
MTB_BatchShape,
|
||||
MTB_BatchTimeWrap,
|
||||
MTB_PlotBatchFloat,
|
||||
MTB_SublistToImageBatch,
|
||||
MTB_ImageBatchToSublist,
|
||||
]
|
||||
|
||||
+190
@@ -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]
|
||||
+124
-2
@@ -3,10 +3,127 @@ import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import folder_paths
|
||||
import torch
|
||||
|
||||
from ..log import log
|
||||
from ..utils import here
|
||||
|
||||
Conditioning = list[tuple[torch.Tensor, dict[str, torch.Tensor]]]
|
||||
|
||||
|
||||
def check_condition(conditioning: Conditioning):
|
||||
has_cn = False
|
||||
if len(conditioning) > 1:
|
||||
log.warn(
|
||||
"More than one conditioning was provided. Only the first one will be used."
|
||||
)
|
||||
first = conditioning[0]
|
||||
cond, kwargs = first
|
||||
|
||||
log.debug("Conditioning Shape")
|
||||
log.debug(cond.shape)
|
||||
log.debug("Conditioning keys")
|
||||
log.debug([f"\t{k} - {type(kwargs[k])}" for k in kwargs])
|
||||
if "control" in kwargs:
|
||||
log.debug("Conditioning contains a controlnet")
|
||||
has_cn = True
|
||||
if "pooled_output" not in kwargs:
|
||||
raise ValueError(
|
||||
"Conditioning is not valid. Missing 'pooled_output' key."
|
||||
)
|
||||
return has_cn
|
||||
|
||||
|
||||
class MTB_InterpolateCondition:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"blend": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
CATEGORY = "mtb/conditioning"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(
|
||||
self, blend: float, **kwargs: Conditioning
|
||||
) -> tuple[Conditioning]:
|
||||
blend = max(0.0, min(1.0, blend))
|
||||
|
||||
conditions: list[Conditioning] = list(kwargs.values())
|
||||
num_conditions = len(conditions)
|
||||
|
||||
if num_conditions < 2:
|
||||
raise ValueError("At least two conditioning inputs are required.")
|
||||
|
||||
segment_length = 1.0 / (num_conditions - 1)
|
||||
|
||||
segment_index = min(int(blend // segment_length), num_conditions - 2)
|
||||
|
||||
local_blend = (
|
||||
blend - (segment_index * segment_length)
|
||||
) / segment_length
|
||||
|
||||
cond_from = conditions[segment_index]
|
||||
cond_to = conditions[segment_index + 1]
|
||||
|
||||
from_cn = check_condition(cond_from)
|
||||
to_cn = check_condition(cond_to)
|
||||
|
||||
if from_cn and to_cn:
|
||||
raise ValueError(
|
||||
"Interpolating conditions cannot both contain ControlNets"
|
||||
)
|
||||
|
||||
try:
|
||||
interpolated_condition = [
|
||||
(1.0 - local_blend) * c_from + local_blend * c_to
|
||||
for c_from, c_to in zip(
|
||||
cond_from[0][0], cond_to[0][0], strict=False
|
||||
)
|
||||
]
|
||||
except Exception as e:
|
||||
print(f"Error during interpolation: {e}")
|
||||
raise
|
||||
|
||||
pooled_from = cond_from[0][1].get(
|
||||
"pooled_output",
|
||||
torch.zeros_like(
|
||||
next(iter(cond_from[0][1].values()), torch.tensor([]))
|
||||
),
|
||||
)
|
||||
|
||||
pooled_to = cond_to[0][1].get(
|
||||
"pooled_output",
|
||||
torch.zeros_like(
|
||||
next(iter(cond_from[0][1].values()), torch.tensor([]))
|
||||
),
|
||||
)
|
||||
|
||||
interpolated_pooled = (
|
||||
1.0 - local_blend
|
||||
) * pooled_from + local_blend * pooled_to
|
||||
|
||||
res = {"pooled_output": interpolated_pooled}
|
||||
|
||||
if from_cn:
|
||||
res["control"] = cond_from[0][1]["control"]
|
||||
res["control_apply_to_uncond"] = cond_from[0][1][
|
||||
"control_apply_to_uncond"
|
||||
]
|
||||
if to_cn:
|
||||
res["control"] = cond_to[0][1]["control"]
|
||||
res["control_apply_to_uncond"] = cond_to[0][1][
|
||||
"control_apply_to_uncond"
|
||||
]
|
||||
|
||||
return ([(torch.stack(interpolated_condition), res)],)
|
||||
|
||||
|
||||
class MTB_InterpolateClipSequential:
|
||||
@classmethod
|
||||
@@ -177,7 +294,7 @@ class MTB_StylesLoader:
|
||||
with open(file, encoding="utf8") as f:
|
||||
parsed = csv.reader(f)
|
||||
for i, row in enumerate(parsed):
|
||||
log.debug(f"Adding style {row[0]}")
|
||||
# log.debug(f"Adding style {row[0]}")
|
||||
try:
|
||||
name, positive, negative = (row + [None] * 3)[:3]
|
||||
positive = positive or ""
|
||||
@@ -213,4 +330,9 @@ class MTB_StylesLoader:
|
||||
return (self.options[style_name][0], self.options[style_name][1])
|
||||
|
||||
|
||||
__nodes__ = [MTB_SmartStep, MTB_StylesLoader, MTB_InterpolateClipSequential]
|
||||
__nodes__ = [
|
||||
MTB_SmartStep,
|
||||
MTB_StylesLoader,
|
||||
MTB_InterpolateClipSequential,
|
||||
MTB_InterpolateCondition,
|
||||
]
|
||||
|
||||
+1
-1
@@ -24,4 +24,4 @@ class MTB_Constant:
|
||||
return (kwargs.get("Value"),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_Constant]
|
||||
# __nodes__ = [MTB_Constant]
|
||||
|
||||
+278
-150
@@ -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,62 @@ 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."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"bbox": ("BBOX",)},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/crop"
|
||||
FUNCTION = "split_bbox"
|
||||
RETURN_TYPES = ("INT", "INT", "INT", "INT")
|
||||
RETURN_NAMES = ("x", "y", "width", "height")
|
||||
|
||||
def split_bbox(self, bbox: BoundingBox) -> BoundingBox:
|
||||
return bbox
|
||||
|
||||
|
||||
class MTB_UpscaleBboxBy:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"bbox": ("BBOX",),
|
||||
"scale": ("FLOAT", {"default": 1.0}),
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/crop"
|
||||
RETURN_TYPES = ("BBOX",)
|
||||
|
||||
FUNCTION = "upscale"
|
||||
|
||||
def upscale(self, bbox: BoundingBox, scale: float) -> tuple[BoundingBox]:
|
||||
x, y, width, height = bbox
|
||||
|
||||
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):
|
||||
@@ -52,7 +111,7 @@ class MTB_BboxFromMask:
|
||||
"invert": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"image": ("IMAGE",),
|
||||
"image": ("IMAGE", {"tooltip": "Optional image"}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -68,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
|
||||
"""
|
||||
|
||||
@@ -153,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,
|
||||
)
|
||||
|
||||
@@ -195,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):
|
||||
@@ -240,88 +292,164 @@ 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),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_BboxFromMask, MTB_Bbox, MTB_Crop, MTB_Uncrop]
|
||||
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__ = [
|
||||
MTB_BboxFromMask,
|
||||
MTB_Bbox,
|
||||
MTB_Crop,
|
||||
MTB_Uncrop,
|
||||
MTB_SplitBbox,
|
||||
MTB_UpscaleBboxBy,
|
||||
MTB_BBoxForceDimensions,
|
||||
]
|
||||
|
||||
+641
-138
@@ -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]
|
||||
|
||||
+45
-5
@@ -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,9 +75,34 @@ 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",
|
||||
)
|
||||
|
||||
ort_session = ort.InferenceSession(model)
|
||||
providers = [
|
||||
"TensorrtExecutionProvider",
|
||||
"CUDAExecutionProvider",
|
||||
"CoreMLProvider",
|
||||
"CPUExecutionProvider",
|
||||
]
|
||||
available_providers = [
|
||||
provider
|
||||
for provider in providers
|
||||
if provider in ort.get_available_providers()
|
||||
]
|
||||
|
||||
if not available_providers:
|
||||
raise RuntimeError(
|
||||
"No valid ONNX Runtime providers available on this machine."
|
||||
)
|
||||
log.debug(f"Using ONNX providers: {available_providers}")
|
||||
ort_session = ort.InferenceSession(
|
||||
model.as_posix(), providers=available_providers
|
||||
)
|
||||
|
||||
# Predict normal map for each tile
|
||||
log.debug("DeepBump Color → Normals : generating")
|
||||
@@ -332,6 +365,9 @@ class MTB_DeepBump:
|
||||
),
|
||||
"normals_to_height_seamless": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
"optional": {
|
||||
"auto_download": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
@@ -347,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 = []
|
||||
@@ -361,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(
|
||||
|
||||
@@ -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]
|
||||
+25
-5
@@ -78,6 +78,7 @@ class MTB_LoadFaceEnhanceModel:
|
||||
RETURN_NAMES = ("model",)
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "mtb/facetools"
|
||||
DEPRECATED = True
|
||||
|
||||
def load_model(self, model_name, upscale=2, bg_upsampler=None):
|
||||
from gfpgan import GFPGANer
|
||||
@@ -163,6 +164,7 @@ class MTB_RestoreFace:
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "restore"
|
||||
CATEGORY = "mtb/facetools"
|
||||
DEPRECATED = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -177,7 +179,10 @@ class MTB_RestoreFace:
|
||||
# Adjustable weights
|
||||
"weight": ("FLOAT", {"default": 0.5}),
|
||||
"save_tmp_steps": ("BOOLEAN", {"default": True}),
|
||||
}
|
||||
},
|
||||
"optional": {
|
||||
"preserve_alpha": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
def do_restore(
|
||||
@@ -188,11 +193,19 @@ class MTB_RestoreFace:
|
||||
only_center_face,
|
||||
weight,
|
||||
save_tmp_steps,
|
||||
preserve_alpha: bool = False,
|
||||
) -> torch.Tensor:
|
||||
pimage = tensor2np(image)[0]
|
||||
width, height = pimage.shape[1], pimage.shape[0]
|
||||
source_img = cv2.cvtColor(np.array(pimage), cv2.COLOR_RGB2BGR)
|
||||
|
||||
alpha_channel = None
|
||||
if (
|
||||
preserve_alpha and image.size(-1) == 4
|
||||
): # Check if the image has an alpha channel
|
||||
alpha_channel = pimage[:, :, 3]
|
||||
pimage = pimage[:, :, :3] # Remove alpha channel for processing
|
||||
|
||||
sys.stdout = NullWriter()
|
||||
cropped_faces, restored_faces, restored_img = model.enhance(
|
||||
source_img,
|
||||
@@ -211,9 +224,14 @@ class MTB_RestoreFace:
|
||||
)
|
||||
output = None
|
||||
if restored_img is not None:
|
||||
output = Image.fromarray(
|
||||
cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
|
||||
)
|
||||
restored_img = cv2.cvtColor(restored_img, cv2.COLOR_BGR2RGB)
|
||||
output = Image.fromarray(restored_img)
|
||||
|
||||
if alpha_channel is not None:
|
||||
alpha_resized = Image.fromarray(alpha_channel).resize(
|
||||
output.size, Image.LANCZOS
|
||||
)
|
||||
output.putalpha(alpha_resized)
|
||||
# imwrite(restored_img, save_restore_path)
|
||||
|
||||
return pil2tensor(output)
|
||||
@@ -226,6 +244,7 @@ class MTB_RestoreFace:
|
||||
only_center_face=False,
|
||||
weight=0.5,
|
||||
save_tmp_steps=True,
|
||||
preserve_alpha: bool = False,
|
||||
) -> tuple[torch.Tensor]:
|
||||
out = [
|
||||
self.do_restore(
|
||||
@@ -235,6 +254,7 @@ class MTB_RestoreFace:
|
||||
only_center_face,
|
||||
weight,
|
||||
save_tmp_steps,
|
||||
preserve_alpha,
|
||||
)
|
||||
for i in range(image.size(0))
|
||||
]
|
||||
@@ -260,7 +280,7 @@ class MTB_RestoreFace:
|
||||
self, cropped_faces, restored_faces, height, width
|
||||
):
|
||||
for idx, (cropped_face, restored_face) in enumerate(
|
||||
zip(cropped_faces, restored_faces)
|
||||
zip(cropped_faces, restored_faces, strict=False)
|
||||
):
|
||||
face_id = idx + 1
|
||||
file = self.get_step_image_path("cropped_faces", face_id)
|
||||
|
||||
+25
-9
@@ -2,15 +2,10 @@
|
||||
# region imports
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Set, Union
|
||||
|
||||
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
|
||||
@@ -41,8 +36,11 @@ class MTB_LoadFaceAnalysisModel:
|
||||
RETURN_TYPES = ("FACE_ANALYSIS_MODEL",)
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "mtb/facetools"
|
||||
DEPRECATED = True
|
||||
|
||||
def load_model(self, faceswap_model: str):
|
||||
import insightface
|
||||
|
||||
if faceswap_model == "antelopev2":
|
||||
download_antelopev2()
|
||||
|
||||
@@ -78,8 +76,12 @@ class MTB_LoadFaceSwapModel:
|
||||
RETURN_TYPES = ("FACESWAP_MODEL",)
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "mtb/facetools"
|
||||
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})")
|
||||
@@ -119,12 +121,15 @@ class MTB_FaceSwap:
|
||||
),
|
||||
"faceswap_model": ("FACESWAP_MODEL", {"default": "None"}),
|
||||
},
|
||||
"optional": {},
|
||||
"optional": {
|
||||
"preserve_alpha": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "swap"
|
||||
CATEGORY = "mtb/facetools"
|
||||
DEPRECATED = True
|
||||
|
||||
def swap(
|
||||
self,
|
||||
@@ -133,11 +138,18 @@ class MTB_FaceSwap:
|
||||
faces_index: str,
|
||||
faceanalysis_model,
|
||||
faceswap_model,
|
||||
preserve_alpha=False,
|
||||
):
|
||||
def do_swap(img):
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
img = tensor2pil(img)[0]
|
||||
ref = tensor2pil(reference)[0]
|
||||
|
||||
alpha_channel = None
|
||||
if preserve_alpha and img.mode == "RGBA":
|
||||
alpha_channel = img.getchannel("A")
|
||||
img = img.convert("RGB")
|
||||
|
||||
face_ids = {
|
||||
int(x)
|
||||
for x in faces_index.strip(",").split(",")
|
||||
@@ -148,6 +160,8 @@ class MTB_FaceSwap:
|
||||
faceanalysis_model, ref, img, faceswap_model, face_ids
|
||||
)
|
||||
sys.stdout = sys.__stdout__
|
||||
if alpha_channel:
|
||||
swapped.putalpha(alpha_channel)
|
||||
return pil2tensor(swapped)
|
||||
|
||||
batch_count = image.size(0)
|
||||
@@ -194,11 +208,13 @@ def get_face_single(
|
||||
|
||||
def swap_face(
|
||||
face_analyser,
|
||||
source_img: Union[Image.Image, List[Image.Image]],
|
||||
target_img: Union[Image.Image, List[Image.Image]],
|
||||
source_img: Image.Image | list[Image.Image],
|
||||
target_img: Image.Image | list[Image.Image],
|
||||
face_swapper_model,
|
||||
faces_index: Optional[Set[int]] = None,
|
||||
faces_index: set[int] | None = None,
|
||||
) -> Image.Image:
|
||||
import cv2
|
||||
|
||||
if faces_index is None:
|
||||
faces_index = {0}
|
||||
log.debug(f"Swapping faces: {faces_index}")
|
||||
|
||||
+203
-122
@@ -1,9 +1,19 @@
|
||||
import qrcode
|
||||
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"""
|
||||
|
||||
@@ -82,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:
|
||||
@@ -113,76 +119,6 @@ class MTB_UnsplashImage:
|
||||
return (None,)
|
||||
|
||||
|
||||
class MTB_QrCode:
|
||||
"""Basic QR Code generator"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"url": ("STRING", {"default": "https://www.github.com"}),
|
||||
"width": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
|
||||
"box_size": (
|
||||
"INT",
|
||||
{"default": 10, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"border": (
|
||||
"INT",
|
||||
{"default": 4, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"invert": (("BOOLEAN",), {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "do_qr"
|
||||
CATEGORY = "mtb/generate"
|
||||
|
||||
def do_qr(
|
||||
self, url, width, height, error_correct, box_size, border, invert
|
||||
):
|
||||
log.warning(
|
||||
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
|
||||
)
|
||||
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_L
|
||||
elif error_correct == "M":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_M
|
||||
elif error_correct == "Q":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_Q
|
||||
else:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_H
|
||||
|
||||
qr = qrcode.QRCode(
|
||||
version=1,
|
||||
error_correction=error_correct,
|
||||
box_size=box_size,
|
||||
border=border,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
back_color = (255, 255, 255) if invert else (0, 0, 0)
|
||||
fill_color = (0, 0, 0) if invert else (255, 255, 255)
|
||||
|
||||
code = img = qr.make_image(
|
||||
back_color=back_color, fill_color=fill_color
|
||||
)
|
||||
|
||||
# that we now resize without filtering
|
||||
code = code.resize((width, height), Image.NEAREST)
|
||||
|
||||
return (pil2tensor(code),)
|
||||
|
||||
|
||||
def bbox_dim(bbox):
|
||||
left, upper, right, lower = bbox
|
||||
width = right - left
|
||||
@@ -202,7 +138,7 @@ class MTB_TextToImage:
|
||||
fonts = {}
|
||||
DESCRIPTION = """# Text to Image
|
||||
|
||||
This node look for any font files in comfy_dir/fonts.
|
||||
This node look for any font files in comfy_dir/fonts.
|
||||
by default it fallsback to a default font.
|
||||
|
||||

|
||||
@@ -264,11 +200,11 @@ by default it fallsback to a default font.
|
||||
),
|
||||
"color": (
|
||||
"COLOR",
|
||||
{"default": "black"},
|
||||
{"default": "black", "widgetType": "MTB_COLOR"},
|
||||
),
|
||||
"background": (
|
||||
"COLOR",
|
||||
{"default": "white"},
|
||||
{"default": "white", "widgetType": "MTB_COLOR"},
|
||||
),
|
||||
"h_align": (("left", "center", "right"), {"default": "left"}),
|
||||
"v_align": (("top", "center", "bottom"), {"default": "top"}),
|
||||
@@ -284,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,
|
||||
@@ -309,62 +321,131 @@ 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__ = [
|
||||
MTB_QrCode,
|
||||
MTB_UnsplashImage,
|
||||
MTB_TextToImage,
|
||||
# MtbExamples,
|
||||
|
||||
+514
-51
@@ -1,22 +1,25 @@
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from math import pi
|
||||
from typing import Optional
|
||||
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
|
||||
import torchvision.transforms.functional as F
|
||||
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,
|
||||
@@ -46,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",),
|
||||
@@ -69,20 +80,36 @@ class MTB_ToDevice:
|
||||
def to_device(
|
||||
self,
|
||||
*,
|
||||
ignore_errors=False,
|
||||
device="cuda",
|
||||
image: Optional[torch.Tensor] = None,
|
||||
mask: Optional[torch.Tensor] = None,
|
||||
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)
|
||||
|
||||
|
||||
@@ -102,6 +129,9 @@ class MTB_ApplyTextTemplate:
|
||||
"required": {
|
||||
"template": ("STRING", {"default": "", "multiline": True}),
|
||||
},
|
||||
"optional":{
|
||||
"strip": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
@@ -109,12 +139,70 @@ 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, *, strip:bool,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)
|
||||
if strip:
|
||||
results.append(res.strip())
|
||||
else:
|
||||
results.append(res)
|
||||
|
||||
return (results,)
|
||||
|
||||
else:
|
||||
res = f"{template}"
|
||||
for k, v in kwargs.items():
|
||||
res = self.apply_res(res, k, v)
|
||||
|
||||
if strip:
|
||||
return (res.strip(),)
|
||||
else:
|
||||
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:
|
||||
@@ -138,6 +226,8 @@ class MTB_MatchDimensions:
|
||||
def execute(
|
||||
self, source: torch.Tensor, reference: torch.Tensor, match: str
|
||||
):
|
||||
import torchvision.transforms.functional as VF
|
||||
|
||||
_batch_size, height, width, _channels = source.shape
|
||||
_rbatch_size, rheight, rwidth, _rchannels = reference.shape
|
||||
|
||||
@@ -155,7 +245,7 @@ class MTB_MatchDimensions:
|
||||
new_height = int(rwidth / source_aspect_ratio)
|
||||
|
||||
resized_images = [
|
||||
F.resize(
|
||||
VF.resize(
|
||||
source[i],
|
||||
(new_height, new_width),
|
||||
antialias=True,
|
||||
@@ -170,7 +260,10 @@ class MTB_MatchDimensions:
|
||||
|
||||
|
||||
class MTB_FloatToFloats:
|
||||
"""Conversion utility for compatibility with other extensions (AD, IPA, Fitz are using FLOAT to represent list of floats.)"""
|
||||
"""Conversion utility for compatibility with other extensions.
|
||||
|
||||
AD, IPA, Fitz, KJ are using FLOAT to represent list of floats.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -188,6 +281,26 @@ class MTB_FloatToFloats:
|
||||
def convert(self, float: float):
|
||||
return (float,)
|
||||
|
||||
class MTB_FloatsToFloatList:
|
||||
"""Turn a FLOATS type into a list of floats (for loops)."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"floats": ("FLOATS", { "forceInput": True }),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOAT",)
|
||||
RETURN_NAMES = ("float",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
CATEGORY = "mtb/utils"
|
||||
FUNCTION = "convert"
|
||||
|
||||
def convert(self, floats: list[float]):
|
||||
return (floats,)
|
||||
|
||||
class MTB_FloatsToInts:
|
||||
"""Conversion utility for compatibility with frame interpolation."""
|
||||
@@ -316,7 +429,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),)
|
||||
@@ -417,7 +530,7 @@ class MTB_AnyToString:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"input": ("*")},
|
||||
"required": {"input": ("*",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
@@ -447,7 +560,7 @@ class MTB_AnyToString:
|
||||
|
||||
|
||||
class MTB_StringReplace:
|
||||
"""Basic string replacement."""
|
||||
"""Basic string replacement with regex support."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -456,6 +569,7 @@ class MTB_StringReplace:
|
||||
"string": ("STRING", {"forceInput": True}),
|
||||
"old": ("STRING", {"default": ""}),
|
||||
"new": ("STRING", {"default": ""}),
|
||||
"use_regex": ("BOOLEAN", {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,12 +577,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}")
|
||||
|
||||
@@ -491,14 +612,14 @@ class MTB_MathExpression:
|
||||
RETURN_NAMES = ("result (float)", "result (int)")
|
||||
CATEGORY = "mtb/math"
|
||||
DESCRIPTION = (
|
||||
"evaluate a simple math expression string (!! Fallsback to eval)"
|
||||
"evaluate a simple math expression string, only supports literal_eval"
|
||||
)
|
||||
|
||||
def eval_expression(self, expression, **kwargs):
|
||||
def eval_expression(self, expression: str, **kwargs):
|
||||
from ast import literal_eval
|
||||
|
||||
for key, value in kwargs.items():
|
||||
print(f"Replacing placeholder <{key}> with value {value}")
|
||||
log.debug(f"Replacing placeholder <{key}> with value {value}")
|
||||
expression = expression.replace(f"<{key}>", str(value))
|
||||
|
||||
result = -1
|
||||
@@ -509,15 +630,10 @@ class MTB_MathExpression:
|
||||
f"The expression syntax is wrong '{expression}': {e}"
|
||||
) from e
|
||||
|
||||
except ValueError:
|
||||
try:
|
||||
expression = expression.replace("^", "**")
|
||||
result = eval(expression)
|
||||
except Exception as e:
|
||||
# Handle any other exceptions and provide a meaningful error message
|
||||
raise ValueError(
|
||||
f"Error evaluating expression '{expression}': {e}"
|
||||
) from e
|
||||
except Exception as e:
|
||||
raise ValueError(
|
||||
f"Math expression only support literal_eval now: {e}"
|
||||
)
|
||||
|
||||
return (result, int(result))
|
||||
|
||||
@@ -531,10 +647,22 @@ class MTB_FitNumber:
|
||||
"required": {
|
||||
"value": ("FLOAT", {"default": 0, "forceInput": True}),
|
||||
"clamp": ("BOOLEAN", {"default": False}),
|
||||
"source_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"source_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"target_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"target_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"source_min": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"source_max": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"target_min": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"target_max": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"easing": (
|
||||
EASINGS,
|
||||
{"default": "Linear"},
|
||||
@@ -583,22 +711,352 @@ class MTB_ConcatImages:
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"reverse": ("BOOLEAN", {"default": False})},
|
||||
"optional": {
|
||||
"on_mismatch": (
|
||||
["Error", "Smallest", "Largest"],
|
||||
{"default": "Smallest"},
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
def concatenate_tensors(self, reverse, **kwargs):
|
||||
tensors = tuple(kwargs.values())
|
||||
batch_sizes = [tensor.size(0) for tensor in tensors]
|
||||
def concatenate_tensors(
|
||||
self,
|
||||
reverse: bool,
|
||||
on_mismatch: str = "Smallest",
|
||||
**kwargs: torch.Tensor,
|
||||
) -> tuple[torch.Tensor]:
|
||||
tensors = list(kwargs.values())
|
||||
|
||||
if on_mismatch == "Error":
|
||||
shapes = [tensor.shape for tensor in tensors]
|
||||
if not all(shape == shapes[0] for shape in shapes):
|
||||
raise ValueError(
|
||||
"All input tensors must have the same shape when on_mismatch is 'Error'."
|
||||
)
|
||||
|
||||
else:
|
||||
import torch.nn.functional as F
|
||||
|
||||
if on_mismatch == "Smallest":
|
||||
target_shape = min(
|
||||
(tensor.shape for tensor in tensors),
|
||||
key=lambda s: (s[1], s[2]),
|
||||
)
|
||||
else: # on_mismatch == "Largest"
|
||||
target_shape = max(
|
||||
(tensor.shape for tensor in tensors),
|
||||
key=lambda s: (s[1], s[2]),
|
||||
)
|
||||
|
||||
target_height, target_width = target_shape[1], target_shape[2]
|
||||
|
||||
resized_tensors = []
|
||||
for tensor in tensors:
|
||||
if (
|
||||
tensor.shape[1] != target_height
|
||||
or tensor.shape[2] != target_width
|
||||
):
|
||||
resized_tensor = F.interpolate(
|
||||
tensor.permute(0, 3, 1, 2),
|
||||
size=(target_height, target_width),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
resized_tensor = resized_tensor.permute(0, 2, 3, 1)
|
||||
resized_tensors.append(resized_tensor)
|
||||
else:
|
||||
resized_tensors.append(tensor)
|
||||
|
||||
tensors = resized_tensors
|
||||
|
||||
concatenated = torch.cat(tensors, dim=0)
|
||||
|
||||
# Update the batch size in the concatenated tensor
|
||||
concatenated_size = list(concatenated.size())
|
||||
concatenated_size[0] = sum(batch_sizes)
|
||||
concatenated = concatenated.view(*concatenated_size)
|
||||
|
||||
return (concatenated,)
|
||||
|
||||
|
||||
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,
|
||||
@@ -612,5 +1070,10 @@ __nodes__ = [
|
||||
MTB_AutoPanEquilateral,
|
||||
MTB_FloatsToFloat,
|
||||
MTB_FloatToFloats,
|
||||
MTB_FloatsToFloatList,
|
||||
MTB_FloatsToInts,
|
||||
MTB_TensorOps,
|
||||
MTB_BooleanNot,
|
||||
MTB_GetItem,
|
||||
MTB_ProxyTensor,
|
||||
]
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import comfy
|
||||
import comfy.model_management as model_management
|
||||
@@ -15,10 +14,13 @@ from ..utils import get_model_path
|
||||
|
||||
|
||||
class MTB_LoadFilmModel:
|
||||
"""Loads a FILM model"""
|
||||
"""Loads a FILM model
|
||||
|
||||
[DEPRECATED] Use ComfyUI-FrameInterpolation instead
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def get_models() -> List[Path]:
|
||||
def get_models() -> list[Path]:
|
||||
models_paths = get_model_path("FILM").iterdir()
|
||||
|
||||
return [x for x in models_paths if x.suffix in [".onnx", ".pth"]]
|
||||
@@ -37,6 +39,7 @@ class MTB_LoadFilmModel:
|
||||
RETURN_TYPES = ("FILM_MODEL",)
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "mtb/frame iterpolation"
|
||||
DEPRECATED = True
|
||||
|
||||
def load_model(self, film_model: str):
|
||||
model_path = get_model_path("FILM", film_model)
|
||||
@@ -56,7 +59,10 @@ class MTB_LoadFilmModel:
|
||||
|
||||
|
||||
class MTB_FilmInterpolation:
|
||||
"""Google Research FILM frame interpolation for large motion"""
|
||||
"""Google Research FILM frame interpolation for large motion
|
||||
|
||||
[DEPRECATED] Use ComfyUI-FrameInterpolation instead
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -71,6 +77,7 @@ class MTB_FilmInterpolation:
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "do_interpolation"
|
||||
CATEGORY = "mtb/frame iterpolation"
|
||||
DEPRECATED = True
|
||||
|
||||
def do_interpolation(
|
||||
self,
|
||||
|
||||
+506
-92
@@ -3,17 +3,19 @@ import json
|
||||
import math
|
||||
import os
|
||||
|
||||
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
|
||||
from skimage.util import compare_images
|
||||
|
||||
from ..log import log
|
||||
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
|
||||
from ..utils import np2tensor, pil2tensor, tensor2pil
|
||||
|
||||
# try:
|
||||
# from cv2.ximgproc import guidedFilter
|
||||
@@ -35,6 +37,398 @@ def gaussian_kernel(
|
||||
return g / g.sum()
|
||||
|
||||
|
||||
class MTB_CoordinatesToString:
|
||||
RETURN_TYPES = ("STRING",)
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "mtb/coordinates"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"coordinates": ("BATCH_COORDINATES",),
|
||||
"frame": ("INT",),
|
||||
}
|
||||
}
|
||||
|
||||
def convert(
|
||||
self, coordinates: list[list[tuple[int, int]]], frame: int
|
||||
) -> tuple[str]:
|
||||
frame = max(frame, len(coordinates) - 1)
|
||||
coords = coordinates[frame]
|
||||
output: list[dict[str, int]] = []
|
||||
|
||||
for x, y in coords:
|
||||
output.append({"x": x, "y": y})
|
||||
|
||||
return (json.dumps(output),)
|
||||
|
||||
|
||||
class MTB_ExtractCoordinatesFromImage:
|
||||
"""Extract 2D points from a batch of images based on a threshold."""
|
||||
|
||||
RETURN_TYPES = ("BATCH_COORDINATES", "IMAGE")
|
||||
FUNCTION = "extract"
|
||||
CATEGORY = "mtb/coordinates"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"threshold": (
|
||||
"FLOAT",
|
||||
{"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01},
|
||||
),
|
||||
"max_points": ("INT", {"default": 50, "min": 0}),
|
||||
},
|
||||
"optional": {"image": ("IMAGE",), "mask": ("MASK",)},
|
||||
}
|
||||
|
||||
def extract(
|
||||
self,
|
||||
threshold: float,
|
||||
max_points: int,
|
||||
image: torch.Tensor | None = None,
|
||||
mask: torch.Tensor | None = None,
|
||||
) -> tuple[list[list[tuple[int, int]]], torch.Tensor]:
|
||||
if image is None and mask is None:
|
||||
raise ValueError("Must provide either image or mask")
|
||||
|
||||
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=input_device,
|
||||
)
|
||||
|
||||
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:
|
||||
mask_slice = mask[i]
|
||||
value_threshold = mask_slice
|
||||
|
||||
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
|
||||
|
||||
points_yx = condition.nonzero(as_tuple=False)
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
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,
|
||||
color_tensor: torch.Tensor,
|
||||
):
|
||||
"""Draw a 5px circle on the image."""
|
||||
x0, y0 = center
|
||||
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:
|
||||
"""Various color correction methods using only Torch."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"force_gpu": ("BOOLEAN", {"default": True}),
|
||||
"clamp": ([True, False], {"default": True}),
|
||||
"gamma": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"contrast": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"exposure": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"offset": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"hue": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -0.5, "max": 0.5, "step": 0.01},
|
||||
),
|
||||
"saturation": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"value": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
},
|
||||
"optional": {"mask": ("MASK",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "correct"
|
||||
CATEGORY = "mtb/image processing"
|
||||
|
||||
@staticmethod
|
||||
def get_device(tensor: torch.Tensor, force_gpu: bool):
|
||||
if force_gpu:
|
||||
if torch.cuda.is_available():
|
||||
return torch.device("cuda")
|
||||
elif (
|
||||
hasattr(torch.backends, "mps")
|
||||
and torch.backends.mps.is_available()
|
||||
):
|
||||
return torch.device("mps")
|
||||
elif hasattr(torch, "hip") and torch.hip.is_available():
|
||||
return torch.device("hip")
|
||||
return (
|
||||
tensor.device
|
||||
) # model_management.get_torch_device() # torch.device("cpu")
|
||||
|
||||
@staticmethod
|
||||
def rgb_to_hsv(image: torch.Tensor):
|
||||
r, g, b = image.unbind(-1)
|
||||
max_rgb, argmax_rgb = image.max(-1)
|
||||
min_rgb, _ = image.min(-1)
|
||||
|
||||
diff = max_rgb - min_rgb
|
||||
|
||||
h = torch.empty_like(max_rgb)
|
||||
s = diff / (max_rgb + 1e-7)
|
||||
v = max_rgb
|
||||
|
||||
h[argmax_rgb == 0] = (g - b)[argmax_rgb == 0] / (diff + 1e-7)[
|
||||
argmax_rgb == 0
|
||||
]
|
||||
h[argmax_rgb == 1] = (
|
||||
2.0 + (b - r)[argmax_rgb == 1] / (diff + 1e-7)[argmax_rgb == 1]
|
||||
)
|
||||
h[argmax_rgb == 2] = (
|
||||
4.0 + (r - g)[argmax_rgb == 2] / (diff + 1e-7)[argmax_rgb == 2]
|
||||
)
|
||||
h = (h / 6.0) % 1.0
|
||||
|
||||
h = h.unsqueeze(-1)
|
||||
s = s.unsqueeze(-1)
|
||||
v = v.unsqueeze(-1)
|
||||
|
||||
return torch.cat((h, s, v), dim=-1)
|
||||
|
||||
@staticmethod
|
||||
def hsv_to_rgb(hsv: torch.Tensor):
|
||||
h, s, v = hsv.unbind(-1)
|
||||
h = h * 6.0
|
||||
|
||||
i = torch.floor(h)
|
||||
f = h - i
|
||||
p = v * (1.0 - s)
|
||||
q = v * (1.0 - s * f)
|
||||
t = v * (1.0 - s * (1.0 - f))
|
||||
|
||||
i = i.long() % 6
|
||||
|
||||
mask = torch.stack(
|
||||
(i == 0, i == 1, i == 2, i == 3, i == 4, i == 5), -1
|
||||
)
|
||||
|
||||
rgb = torch.stack(
|
||||
(
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
q,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
p,
|
||||
torch.where(mask[..., 4], t, v),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
t,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
q,
|
||||
torch.where(mask[..., 4], p, p),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
t,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
v,
|
||||
torch.where(mask[..., 4], v, q),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
return rgb
|
||||
|
||||
def correct(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
force_gpu: bool,
|
||||
clamp: bool,
|
||||
gamma: float = 1.0,
|
||||
contrast: float = 1.0,
|
||||
exposure: float = 0.0,
|
||||
offset: float = 0.0,
|
||||
hue: float = 0.0,
|
||||
saturation: float = 1.0,
|
||||
value: float = 1.0,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
device = self.get_device(image, force_gpu)
|
||||
image = image.to(device)
|
||||
|
||||
if mask is not None:
|
||||
if mask.shape[0] != image.shape[0]:
|
||||
mask = mask.expand(image.shape[0], -1, -1)
|
||||
|
||||
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
|
||||
mask = mask.to(device)
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
adjusted = image.pow(1 / gamma) * (2.0**exposure) * contrast + offset
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
hsv = self.rgb_to_hsv(adjusted)
|
||||
hsv[..., 0] = (hsv[..., 0] + hue) % 1.0 # Hue
|
||||
hsv[..., 1] = hsv[..., 1] * saturation # Saturation
|
||||
hsv[..., 2] = hsv[..., 2] * value # Value
|
||||
adjusted = self.hsv_to_rgb(hsv)
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
if clamp:
|
||||
adjusted = torch.clamp(adjusted, 0.0, 1.0)
|
||||
|
||||
# apply mask
|
||||
result = (
|
||||
adjusted
|
||||
if mask is None
|
||||
else torch.where(mask > 0, adjusted, image)
|
||||
)
|
||||
|
||||
if not force_gpu:
|
||||
result = result.cpu()
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
class MTB_ColorCorrect:
|
||||
"""Various color correction methods"""
|
||||
|
||||
@@ -72,7 +466,8 @@ class MTB_ColorCorrect:
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
}
|
||||
},
|
||||
"optional": {"mask": ("MASK",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
@@ -87,13 +482,13 @@ class MTB_ColorCorrect:
|
||||
@staticmethod
|
||||
def contrast_adjustment_tensor(image, contrast):
|
||||
r, g, b = image.unbind(-1)
|
||||
|
||||
|
||||
# Using Adobe RGB luminance weights.
|
||||
luminance_image = 0.33 * r + 0.71 * g + 0.06 * b
|
||||
luminance_mean = torch.mean(luminance_image.unsqueeze(-1))
|
||||
|
||||
# Blend original with mean luminance using contrast factor as blend ratio.
|
||||
contrasted = image * contrast + (1.0 - contrast) * luminance_mean
|
||||
contrasted = image * contrast + (1.0 - contrast) * luminance_mean
|
||||
return torch.clamp(contrasted, 0.0, 1.0)
|
||||
|
||||
@staticmethod
|
||||
@@ -188,18 +583,31 @@ class MTB_ColorCorrect:
|
||||
hue: float = 0.0,
|
||||
saturation: float = 1.0,
|
||||
value: float = 1.0,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
if mask is not None:
|
||||
if mask.shape[0] != image.shape[0]:
|
||||
mask = mask.expand(image.shape[0], -1, -1)
|
||||
|
||||
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
|
||||
|
||||
# Apply color correction operations
|
||||
image = self.gamma_correction_tensor(image, gamma)
|
||||
image = self.contrast_adjustment_tensor(image, contrast)
|
||||
image = self.exposure_adjustment_tensor(image, exposure)
|
||||
image = self.offset_adjustment_tensor(image, offset)
|
||||
image = self.hsv_adjustment(image, hue, saturation, value)
|
||||
adjusted = self.gamma_correction_tensor(image, gamma)
|
||||
adjusted = self.contrast_adjustment_tensor(adjusted, contrast)
|
||||
adjusted = self.exposure_adjustment_tensor(adjusted, exposure)
|
||||
adjusted = self.offset_adjustment_tensor(adjusted, offset)
|
||||
adjusted = self.hsv_adjustment(adjusted, hue, saturation, value)
|
||||
|
||||
if clamp:
|
||||
image = torch.clamp(image, 0.0, 1.0)
|
||||
adjusted = torch.clamp(adjusted, 0.0, 1.0)
|
||||
|
||||
return (image,)
|
||||
result = (
|
||||
adjusted
|
||||
if mask is None
|
||||
else torch.where(mask > 0, adjusted, image)
|
||||
)
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
class MTB_ImageCompare:
|
||||
@@ -350,7 +758,6 @@ class MTB_Blur:
|
||||
)
|
||||
blurred_images.append(blurred)
|
||||
|
||||
image_np = np.array(blurred_images)
|
||||
else:
|
||||
for i in range(image.size(0)):
|
||||
blurred = gaussian(
|
||||
@@ -358,8 +765,7 @@ class MTB_Blur:
|
||||
)
|
||||
blurred_images.append(blurred)
|
||||
|
||||
image_np = np.array(blurred_images)
|
||||
return (np2tensor(image_np).squeeze(0),)
|
||||
return (np2tensor(blurred_images),)
|
||||
|
||||
|
||||
class MTB_Sharpen:
|
||||
@@ -473,9 +879,15 @@ class MTB_MaskToImage:
|
||||
return {
|
||||
"required": {
|
||||
"mask": ("MASK",),
|
||||
"color": ("COLOR",),
|
||||
"background": ("COLOR", {"default": "#000000"}),
|
||||
}
|
||||
"color": ("COLOR", {"widgetType": "MTB_COLOR"}),
|
||||
"background": (
|
||||
"COLOR",
|
||||
{"default": "#000000", "widgetType": "MTB_COLOR"},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"invert": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/generate"
|
||||
@@ -484,11 +896,12 @@ class MTB_MaskToImage:
|
||||
|
||||
FUNCTION = "render_mask"
|
||||
|
||||
def render_mask(self, mask, color, background):
|
||||
masks = tensor2np(mask)[0]
|
||||
def render_mask(self, mask, color, background, invert=False):
|
||||
masks = tensor2pil(1.0 - mask) if invert else tensor2pil(mask)
|
||||
images = []
|
||||
|
||||
for m in masks:
|
||||
_mask = Image.fromarray(m).convert("L")
|
||||
_mask = m.convert("L")
|
||||
|
||||
log.debug(
|
||||
f"Converted mask to PIL Image format, size: {_mask.size}"
|
||||
@@ -526,6 +939,11 @@ class MTB_ColoredImage:
|
||||
"optional": {
|
||||
"foreground_image": ("IMAGE",),
|
||||
"foreground_mask": ("MASK",),
|
||||
"invert": ("BOOLEAN", {"default": False}),
|
||||
"mask_opacity": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.1, "min": 0},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -535,28 +953,19 @@ class MTB_ColoredImage:
|
||||
|
||||
FUNCTION = "render_img"
|
||||
|
||||
def resize_and_crop(self, img, target_size):
|
||||
# Calculate scaling factors for both dimensions
|
||||
scale_x = target_size[0] / img.width
|
||||
scale_y = target_size[1] / img.height
|
||||
|
||||
# Use the smaller scaling factor to maintain aspect ratio
|
||||
scale = max(scale_x, scale_y)
|
||||
|
||||
# Resize the image based on calculated scale
|
||||
def resize_and_crop(self, img: Image.Image, target_size: tuple[int, int]):
|
||||
scale = max(target_size[0] / img.width, target_size[1] / img.height)
|
||||
new_size = (int(img.width * scale), int(img.height * scale))
|
||||
img = img.resize(new_size, Image.LANCZOS)
|
||||
left = (img.width - target_size[0]) // 2
|
||||
top = (img.height - target_size[1]) // 2
|
||||
return img.crop(
|
||||
(left, top, left + target_size[0], top + target_size[1])
|
||||
)
|
||||
|
||||
# Calculate cropping coordinates
|
||||
left = (img.width - target_size[0]) / 2
|
||||
top = (img.height - target_size[1]) / 2
|
||||
right = (img.width + target_size[0]) / 2
|
||||
bottom = (img.height + target_size[1]) / 2
|
||||
|
||||
# Crop and return the image
|
||||
return img.crop((left, top, right, bottom))
|
||||
|
||||
def resize_and_crop_thumbnails(self, img, target_size):
|
||||
def resize_and_crop_thumbnails(
|
||||
self, img: Image.Image, target_size: tuple[int, int]
|
||||
):
|
||||
img.thumbnail(target_size, Image.LANCZOS)
|
||||
left = (img.width - target_size[0]) / 2
|
||||
top = (img.height - target_size[1]) / 2
|
||||
@@ -564,69 +973,71 @@ class MTB_ColoredImage:
|
||||
bottom = (img.height + target_size[1]) / 2
|
||||
return img.crop((left, top, right, bottom))
|
||||
|
||||
@staticmethod
|
||||
def process_mask(
|
||||
mask: torch.Tensor | None,
|
||||
invert: bool,
|
||||
# opacity: float,
|
||||
batch_size: int,
|
||||
) -> list[Image.Image] | None:
|
||||
if mask is None:
|
||||
return [None] * batch_size
|
||||
|
||||
masks = tensor2pil(mask if not invert else 1.0 - mask)
|
||||
|
||||
if len(masks) == 1 and batch_size > 1:
|
||||
masks = masks * batch_size
|
||||
|
||||
if len(masks) != batch_size:
|
||||
raise ValueError(
|
||||
"Foreground image and mask must have the same batch size"
|
||||
)
|
||||
|
||||
return masks
|
||||
|
||||
def render_img(
|
||||
self,
|
||||
color,
|
||||
width,
|
||||
height,
|
||||
color: str,
|
||||
width: int,
|
||||
height: int,
|
||||
foreground_image: torch.Tensor | None = None,
|
||||
foreground_mask: torch.Tensor | None = None,
|
||||
):
|
||||
image = Image.new("RGBA", (width, height), color=color)
|
||||
output = []
|
||||
if foreground_image is not None:
|
||||
fg_masks = [None] * foreground_image.size()[0]
|
||||
invert: bool = False,
|
||||
mask_opacity: float = 1.0,
|
||||
) -> tuple[torch.Tensor]:
|
||||
background = Image.new("RGBA", (width, height), color=color)
|
||||
|
||||
if foreground_mask is not None:
|
||||
fg_size = foreground_image.size()[0]
|
||||
mask_size = foreground_mask.size()[0]
|
||||
if foreground_image is None:
|
||||
return (pil2tensor([background.convert("RGB")]),)
|
||||
|
||||
if fg_size == 1 and mask_size > fg_size:
|
||||
foreground_image = foreground_image.repeat(
|
||||
mask_size, 1, 1, 1
|
||||
)
|
||||
fg_images = tensor2pil(foreground_image)
|
||||
fg_masks = self.process_mask(foreground_mask, invert, len(fg_images))
|
||||
|
||||
if foreground_image.size()[0] != foreground_mask.size()[0]:
|
||||
output: list[Image.Image] = []
|
||||
for fg_image, fg_mask in zip(fg_images, fg_masks, strict=False):
|
||||
fg_image = self.resize_and_crop(fg_image, background.size)
|
||||
|
||||
if fg_mask:
|
||||
fg_mask = self.resize_and_crop(fg_mask, background.size)
|
||||
|
||||
fg_mask_array = np.array(fg_mask)
|
||||
fg_mask_array = (fg_mask_array * mask_opacity).astype(np.uint8)
|
||||
fg_mask = Image.fromarray(fg_mask_array)
|
||||
output.append(
|
||||
Image.composite(
|
||||
fg_image.convert("RGBA"), background, fg_mask
|
||||
).convert("RGB")
|
||||
)
|
||||
else:
|
||||
if fg_image.mode != "RGBA":
|
||||
raise ValueError(
|
||||
"Foreground image and mask must have same batch size"
|
||||
f"Foreground image must be in 'RGBA' mode when no mask is provided, got {fg_image.mode}"
|
||||
)
|
||||
fg_masks = tensor2pil(foreground_mask.unsqueeze(-1))
|
||||
output.append(
|
||||
Image.alpha_composite(background, fg_image).convert("RGB")
|
||||
)
|
||||
|
||||
fg_images = tensor2pil(foreground_image)
|
||||
|
||||
for fg_image, fg_mask in zip(fg_images, fg_masks):
|
||||
# Resize and crop if dimensions mismatch
|
||||
if fg_image.size != image.size:
|
||||
fg_image = self.resize_and_crop(fg_image, image.size)
|
||||
if fg_mask:
|
||||
fg_mask = self.resize_and_crop(fg_mask, image.size)
|
||||
|
||||
if fg_mask:
|
||||
output.append(
|
||||
Image.composite(
|
||||
fg_image.convert("RGBA"),
|
||||
image,
|
||||
fg_mask,
|
||||
).convert("RGB")
|
||||
)
|
||||
else:
|
||||
if fg_image.mode != "RGBA":
|
||||
raise ValueError(
|
||||
"Foreground image must be in 'RGBA' mode "
|
||||
f"when no mask is provided, got {fg_image.mode}"
|
||||
)
|
||||
output.append(
|
||||
Image.alpha_composite(image, fg_image).convert("RGB")
|
||||
)
|
||||
|
||||
else:
|
||||
if foreground_mask is not None:
|
||||
log.warn("Mask ignored because no foreground image is given")
|
||||
output.append(image.convert("RGB"))
|
||||
|
||||
output = pil2tensor(output)
|
||||
|
||||
return (output,)
|
||||
return (pil2tensor(output),)
|
||||
|
||||
|
||||
class MTB_ImagePremultiply:
|
||||
@@ -924,6 +1335,7 @@ class MTB_ImageTileOffset:
|
||||
|
||||
__nodes__ = [
|
||||
MTB_ColorCorrect,
|
||||
MTB_ColorCorrectGPU,
|
||||
MTB_ImageCompare,
|
||||
MTB_ImageTileOffset,
|
||||
MTB_Blur,
|
||||
@@ -935,4 +1347,6 @@ __nodes__ = [
|
||||
MTB_SaveImageGrid,
|
||||
MTB_LoadImageFromUrl,
|
||||
MTB_Sharpen,
|
||||
MTB_ExtractCoordinatesFromImage,
|
||||
MTB_CoordinatesToString,
|
||||
]
|
||||
|
||||
+193
-29
@@ -1,4 +1,11 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from comfy.cli_args import args
|
||||
from PIL import Image
|
||||
from PIL.PngImagePlugin import PngInfo
|
||||
|
||||
from ..log import log
|
||||
|
||||
@@ -8,13 +15,25 @@ class MTB_StackImages:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {"vertical": ("BOOLEAN", {"default": False})}}
|
||||
return {
|
||||
"required": {"vertical": ("BOOLEAN", {"default": False})},
|
||||
"optional": {
|
||||
"match_method": (
|
||||
["error", "smallest", "largest"],
|
||||
{"default": "error"},
|
||||
),
|
||||
"output_rgb": (
|
||||
"BOOLEAN",
|
||||
{"default": True, "tooltip": "Output RGB instead of RGBA"},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "stack"
|
||||
CATEGORY = "mtb/image utils"
|
||||
|
||||
def stack(self, vertical, **kwargs):
|
||||
def stack(self, vertical, match_method="error", output_rgb=True, **kwargs):
|
||||
if not kwargs:
|
||||
raise ValueError("At least one tensor must be provided.")
|
||||
|
||||
@@ -24,34 +43,68 @@ 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)
|
||||
for tensor in normalized_tensors
|
||||
]
|
||||
|
||||
if vertical:
|
||||
width = normalized_tensors[0].shape[2]
|
||||
if any(tensor.shape[2] != width for tensor in normalized_tensors):
|
||||
raise ValueError(
|
||||
"All tensors must have the same width "
|
||||
"for vertical stacking."
|
||||
if match_method != "error":
|
||||
if vertical:
|
||||
# match widths
|
||||
widths = [tensor.shape[2] for tensor in normalized_tensors]
|
||||
target_width = (
|
||||
min(widths) if match_method == "smallest" else max(widths)
|
||||
)
|
||||
dim = 1
|
||||
normalized_tensors = [
|
||||
self.resize_tensor(tensor, width=target_width)
|
||||
for tensor in normalized_tensors
|
||||
]
|
||||
else:
|
||||
# match heights
|
||||
heights = [tensor.shape[1] for tensor in normalized_tensors]
|
||||
target_height = (
|
||||
min(heights)
|
||||
if match_method == "smallest"
|
||||
else max(heights)
|
||||
)
|
||||
normalized_tensors = [
|
||||
self.resize_tensor(tensor, height=target_height)
|
||||
for tensor in normalized_tensors
|
||||
]
|
||||
else:
|
||||
height = normalized_tensors[0].shape[1]
|
||||
if any(tensor.shape[1] != height for tensor in normalized_tensors):
|
||||
raise ValueError(
|
||||
"All tensors must have the same height "
|
||||
"for horizontal stacking."
|
||||
)
|
||||
dim = 2
|
||||
if vertical:
|
||||
width = normalized_tensors[0].shape[2]
|
||||
if any(
|
||||
tensor.shape[2] != width for tensor in normalized_tensors
|
||||
):
|
||||
raise ValueError(
|
||||
"All tensors must have the same width "
|
||||
"for vertical stacking."
|
||||
)
|
||||
else:
|
||||
height = normalized_tensors[0].shape[1]
|
||||
if any(
|
||||
tensor.shape[1] != height for tensor in normalized_tensors
|
||||
):
|
||||
raise ValueError(
|
||||
"All tensors must have the same height "
|
||||
"for horizontal stacking."
|
||||
)
|
||||
|
||||
dim = 1 if vertical else 2
|
||||
|
||||
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):
|
||||
@@ -64,7 +117,7 @@ class MTB_StackImages:
|
||||
elif channels == 3:
|
||||
alpha_channel = torch.ones(
|
||||
tensor.shape[:-1] + (1,), device=tensor.device
|
||||
) # Add an alpha channel
|
||||
)
|
||||
return torch.cat((tensor, alpha_channel), dim=-1)
|
||||
else:
|
||||
raise ValueError(
|
||||
@@ -87,6 +140,30 @@ class MTB_StackImages:
|
||||
else:
|
||||
return tensor
|
||||
|
||||
def resize_tensor(self, tensor, width=None, height=None):
|
||||
"""Resize tensor to specified width or height while maintaining aspect ratio."""
|
||||
current_height, current_width = tensor.shape[1:3]
|
||||
|
||||
if width is not None and width != current_width:
|
||||
scale_factor = width / current_width
|
||||
new_height = int(current_height * scale_factor)
|
||||
new_width = width
|
||||
elif height is not None and height != current_height:
|
||||
scale_factor = height / current_height
|
||||
new_width = int(current_width * scale_factor)
|
||||
new_height = height
|
||||
else:
|
||||
return tensor
|
||||
|
||||
resized = torch.nn.functional.interpolate(
|
||||
tensor.permute(0, 3, 1, 2),
|
||||
size=(new_height, new_width),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
|
||||
return resized.permute(0, 2, 3, 1)
|
||||
|
||||
|
||||
class MTB_PickFromBatch:
|
||||
"""Pick a specific number of images from a batch.
|
||||
@@ -101,30 +178,117 @@ 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)
|
||||
if count < batch_size:
|
||||
log.warning(
|
||||
f"Requested {count} images, "
|
||||
f"but only {batch_size} are available."
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
__nodes__ = [MTB_StackImages, MTB_PickFromBatch]
|
||||
import folder_paths
|
||||
|
||||
|
||||
class MTB_SaveImage:
|
||||
def __init__(self):
|
||||
self.output_dir = folder_paths.get_output_directory()
|
||||
self.type = "output"
|
||||
self.prefix_append = ""
|
||||
self.compress_level = 4
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"images": ("IMAGE", {"tooltip": "The images to save."}),
|
||||
"filename_prefix": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "ComfyUI",
|
||||
"tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "save_images"
|
||||
|
||||
# OUTPUT_NODE = True
|
||||
|
||||
CATEGORY = "mtb/image utils"
|
||||
DESCRIPTION = """Saves the input images to your ComfyUI output directory.
|
||||
This behaves exactly like the native SaveImage node but isn't an output node.
|
||||
The reason I made this is to allow 'inlining' image save in loops for instance,
|
||||
using the native node there wouldn't run for each iteration of the loop."""
|
||||
|
||||
def save_images(
|
||||
self,
|
||||
images,
|
||||
filename_prefix="ComfyUI",
|
||||
prompt=None,
|
||||
extra_pnginfo=None,
|
||||
):
|
||||
filename_prefix += self.prefix_append
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = (
|
||||
folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
self.output_dir,
|
||||
images[0].shape[1],
|
||||
images[0].shape[0],
|
||||
)
|
||||
)
|
||||
results = list()
|
||||
for batch_number, image in enumerate(images):
|
||||
i = 255.0 * image.cpu().numpy()
|
||||
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
|
||||
metadata = None
|
||||
if not args.disable_metadata:
|
||||
metadata = PngInfo()
|
||||
if prompt is not None:
|
||||
metadata.add_text("prompt", json.dumps(prompt))
|
||||
if extra_pnginfo is not None:
|
||||
for x in extra_pnginfo:
|
||||
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
||||
|
||||
filename_with_batch_num = filename.replace(
|
||||
"%batch_num%", str(batch_number)
|
||||
)
|
||||
file = f"{filename_with_batch_num}_{counter:05}_.png"
|
||||
img.save(
|
||||
os.path.join(full_output_folder, file),
|
||||
pnginfo=metadata,
|
||||
compress_level=self.compress_level,
|
||||
)
|
||||
results.append(
|
||||
{"filename": file, "subfolder": subfolder, "type": self.type}
|
||||
)
|
||||
counter += 1
|
||||
|
||||
return {"ui": {"images": results}, "result": (images,)}
|
||||
|
||||
|
||||
__nodes__ = [MTB_StackImages, MTB_PickFromBatch, MTB_SaveImage]
|
||||
|
||||
+55
-19
@@ -2,9 +2,9 @@ import json
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
|
||||
import comfy.model_management as model_management
|
||||
import comfy.utils
|
||||
import folder_paths
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -41,6 +41,7 @@ class MTB_ReadPlaylist:
|
||||
RETURN_TYPES = ("PLAYLIST",)
|
||||
FUNCTION = "read_playlist"
|
||||
CATEGORY = "mtb/IO"
|
||||
EXPERIMENTAL = True
|
||||
|
||||
def read_playlist(
|
||||
self,
|
||||
@@ -83,6 +84,7 @@ class MTB_AddToPlaylist:
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "add_to_playlist"
|
||||
CATEGORY = "mtb/IO"
|
||||
EXPERIMENTAL = True
|
||||
|
||||
def add_to_playlist(
|
||||
self,
|
||||
@@ -117,7 +119,10 @@ class MTB_AddToPlaylist:
|
||||
|
||||
|
||||
class MTB_ExportWithFfmpeg:
|
||||
"""Export with FFmpeg (Experimental)"""
|
||||
"""Export with FFmpeg (Experimental).
|
||||
|
||||
[DEPRACATED] Use VHS nodes instead
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -143,6 +148,7 @@ class MTB_ExportWithFfmpeg:
|
||||
RETURN_TYPES = ("VIDEO",)
|
||||
OUTPUT_NODE = True
|
||||
FUNCTION = "export_prores"
|
||||
DEPRECATED = True
|
||||
CATEGORY = "mtb/IO"
|
||||
|
||||
def export_prores(
|
||||
@@ -151,10 +157,9 @@ class MTB_ExportWithFfmpeg:
|
||||
prefix: str,
|
||||
format: str,
|
||||
codec: str,
|
||||
images: Optional[torch.Tensor] = None,
|
||||
playlist: Optional[List[str]] = None,
|
||||
images: torch.Tensor | None = None,
|
||||
playlist: list[str] | None = None,
|
||||
):
|
||||
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
|
||||
file_ext = format
|
||||
file_id = f"{prefix}_{uuid.uuid4()}.{file_ext}"
|
||||
|
||||
@@ -208,9 +213,11 @@ class MTB_ExportWithFfmpeg:
|
||||
frames = tensor2np(images)
|
||||
log.debug(f"Frames type {type(frames[0])}")
|
||||
log.debug(f"Exporting {len(frames)} frames")
|
||||
height, width, channels = frames[0].shape
|
||||
has_alpha = channels == 4
|
||||
out_path = (output_dir / file_id).as_posix()
|
||||
|
||||
if codec == "gif":
|
||||
out_path = (output_dir / file_id).as_posix()
|
||||
command = [
|
||||
"ffmpeg",
|
||||
"-f",
|
||||
@@ -233,12 +240,28 @@ class MTB_ExportWithFfmpeg:
|
||||
|
||||
process.stdin.close()
|
||||
process.wait()
|
||||
return (out_path,)
|
||||
else:
|
||||
frames = [frame.astype(np.uint16) * 257 for frame in frames]
|
||||
|
||||
height, width, _ = frames[0].shape
|
||||
|
||||
out_path = (output_dir / file_id).as_posix()
|
||||
if has_alpha:
|
||||
if codec in ["prores_ks", "libx264", "libx265"]:
|
||||
pix_fmt = (
|
||||
"yuva444p" if codec == "prores_ks" else "yuva420p"
|
||||
)
|
||||
frames = [
|
||||
frame.astype(np.uint16) * 257 for frame in frames
|
||||
]
|
||||
else:
|
||||
log.warning(
|
||||
f"Alpha channel not supported for codec {codec}. Alpha will be ignored."
|
||||
)
|
||||
frames = [
|
||||
frame[:, :, :3].astype(np.uint16) * 257
|
||||
for frame in frames
|
||||
]
|
||||
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
|
||||
else:
|
||||
pix_fmt = "rgb48le" if codec == "prores_ks" else "yuv420p"
|
||||
frames = [frame.astype(np.uint16) * 257 for frame in frames]
|
||||
|
||||
# Prepare the FFmpeg command
|
||||
command = [
|
||||
@@ -258,17 +281,26 @@ class MTB_ExportWithFfmpeg:
|
||||
"-",
|
||||
"-c:v",
|
||||
codec,
|
||||
"-r",
|
||||
str(fps),
|
||||
"-y",
|
||||
out_path,
|
||||
]
|
||||
if codec == "prores_ks":
|
||||
command.extend(["-profile:v", "4444"])
|
||||
|
||||
command.extend(
|
||||
[
|
||||
"-r",
|
||||
str(fps),
|
||||
"-y",
|
||||
out_path,
|
||||
]
|
||||
)
|
||||
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE)
|
||||
|
||||
pbar = comfy.utils.ProgressBar(len(frames))
|
||||
|
||||
for frame in frames:
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
process.stdin.write(frame.tobytes())
|
||||
pbar.update(1)
|
||||
|
||||
process.stdin.close()
|
||||
process.wait()
|
||||
@@ -280,9 +312,9 @@ def prepare_animated_batch(
|
||||
batch: torch.Tensor,
|
||||
pingpong=False,
|
||||
resize_by=1.0,
|
||||
resample_filter: Optional[Image.Resampling] = None,
|
||||
resample_filter: Image.Resampling | None = None,
|
||||
image_type=np.uint8,
|
||||
) -> List[Image.Image]:
|
||||
) -> list[Image.Image]:
|
||||
images = tensor2np(batch)
|
||||
images = [frame.astype(image_type) for frame in images]
|
||||
|
||||
@@ -308,7 +340,10 @@ def prepare_animated_batch(
|
||||
|
||||
# todo: deprecate for apng
|
||||
class MTB_SaveGif:
|
||||
"""Save the images from the batch as a GIF"""
|
||||
"""Save the images from the batch as a GIF.
|
||||
|
||||
[DEPRACATED] Use VHS nodes instead
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -328,6 +363,7 @@ class MTB_SaveGif:
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "mtb/IO"
|
||||
FUNCTION = "save_gif"
|
||||
DEPRECATED = True
|
||||
|
||||
def save_gif(
|
||||
self,
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import node_helpers
|
||||
import torch
|
||||
|
||||
from ..log import log
|
||||
|
||||
|
||||
class MTB_LatentLerp:
|
||||
"""Linear interpolation (blend) between two latent vectors"""
|
||||
@@ -20,6 +23,9 @@ class MTB_LatentLerp:
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "lerp_latent"
|
||||
|
||||
# should fix or remove
|
||||
DEPRECATED = True
|
||||
|
||||
CATEGORY = "mtb/latent"
|
||||
|
||||
def lerp_latent(self, A, B, t):
|
||||
@@ -31,6 +37,52 @@ class MTB_LatentLerp:
|
||||
return (a,)
|
||||
|
||||
|
||||
class MTB_ReferenceLatents:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"positive": ("CONDITIONING",),
|
||||
"negative": ("CONDITIONING",),
|
||||
"vae": ("VAE",),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING", "CONDITIONING")
|
||||
RETURN_NAMES = ("positive", "negative")
|
||||
FUNCTION = "execute"
|
||||
CATEGORY = "mtb/latent"
|
||||
|
||||
def execute(self, positive, negative, vae, **kwargs):
|
||||
if not kwargs:
|
||||
raise ValueError("At least one image must be provided.")
|
||||
|
||||
image_refs = list(kwargs.values())
|
||||
# device = image_refs[0].device
|
||||
|
||||
for im in image_refs:
|
||||
# encode
|
||||
log.debug("Encoding reference image to latents")
|
||||
log.debug(f"Image shape: {im.shape}")
|
||||
latent = vae.encode(im)
|
||||
|
||||
if positive is not None:
|
||||
positive = node_helpers.conditioning_set_values(
|
||||
positive,
|
||||
{"reference_latents": [latent]},
|
||||
append=True,
|
||||
)
|
||||
if negative is not None:
|
||||
negative = node_helpers.conditioning_set_values(
|
||||
negative,
|
||||
{"reference_latents": [latent]},
|
||||
append=True,
|
||||
)
|
||||
|
||||
return (positive, negative)
|
||||
|
||||
|
||||
__nodes__ = [
|
||||
MTB_LatentLerp,
|
||||
MTB_ReferenceLatents,
|
||||
]
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
from ..utils import hex_to_rgb
|
||||
|
||||
|
||||
class MTB_ColorInput:
|
||||
RETURN_TYPES = ("COLOR","STRING","STRING")
|
||||
RETURN_NAMES = ("color","hex","r,g,b")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"Color in mtb format (internaly just a hex string)",
|
||||
"Hex color string",
|
||||
"RGB values as comma-separated string",
|
||||
)
|
||||
FUNCTION = "color"
|
||||
CATEGORY = "mtb/color"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"color": ("MTB_COLOR", {"default": "#ffffff"})},
|
||||
}
|
||||
|
||||
def color(self, color:str):
|
||||
# convert hex to rgb
|
||||
r, g, b = hex_to_rgb(color)
|
||||
|
||||
# TODO: official COLOR will be without the #
|
||||
return (color,color,f"{r},{g},{b}")
|
||||
|
||||
|
||||
__nodes__ = [MTB_ColorInput]
|
||||
@@ -0,0 +1,69 @@
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
import folder_paths
|
||||
|
||||
|
||||
class MTB_LoraLoaderModelOnlyByPath:
|
||||
def __init__(self):
|
||||
self.loaded_lora = None
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
all_loras = folder_paths.get_filename_list("loras")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"lora_name": (
|
||||
"STRING",
|
||||
{"default": next(iter(all_loras), "no lora found")},
|
||||
),
|
||||
"strength_model": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": -100.0,
|
||||
"max": 100.0,
|
||||
"step": 0.01,
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
|
||||
OUTPUT_TOOLTIPS = ("The modified diffusion model.",)
|
||||
CATEGORY = "mtb/lora"
|
||||
FUNCTION = "load_lora_model_only"
|
||||
DESCRIPTION = "Exact copy of the native node using string instead of combo, useful to 'build' paths from the graph."
|
||||
|
||||
def load_lora_model_only(self, model, lora_name, strength_model):
|
||||
return (self.load_lora(model, None, lora_name, strength_model, 0)[0],)
|
||||
|
||||
def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
|
||||
if strength_model == 0 and strength_clip == 0:
|
||||
return (model, clip)
|
||||
|
||||
# all_loras = folder_paths.get_filename_list("loras")
|
||||
# if lora_name not in all_loras:
|
||||
# raise ValueError(f"{lora_name} not in {folder_paths.get_filename_list('loras')}")
|
||||
|
||||
lora_path = folder_paths.get_full_path_or_raise("loras", lora_name)
|
||||
lora = None
|
||||
if self.loaded_lora is not None:
|
||||
if self.loaded_lora[0] == lora_path:
|
||||
lora = self.loaded_lora[1]
|
||||
else:
|
||||
self.loaded_lora = None
|
||||
|
||||
if lora is None:
|
||||
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||
self.loaded_lora = (lora_path, lora)
|
||||
|
||||
model_lora, clip_lora = comfy.sd.load_lora_for_models(
|
||||
model, clip, lora, strength_model, strength_clip
|
||||
)
|
||||
return (model_lora, clip_lora)
|
||||
|
||||
|
||||
__nodes__ = [MTB_LoraLoaderModelOnlyByPath]
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
|
||||
|
||||
class ImageH264Compression:
|
||||
"""Encodes the input with h264 compression using a configurable CRF."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "The input image tensor to be compressed and decompressed."
|
||||
},
|
||||
),
|
||||
"crf": (
|
||||
"INT",
|
||||
{
|
||||
"default": 23,
|
||||
"min": 0,
|
||||
"max": 51,
|
||||
"step": 1,
|
||||
"tooltip": "Constant Rate Factor for h264 encoding (lower values mean higher quality).",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "compress_and_decompress"
|
||||
|
||||
CATEGORY = "image"
|
||||
DESCRIPTION = """
|
||||
**Encodes the input with h264 compression using a configurable CRF**.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> This node is not really needed with the latest version of LTXVideo.
|
||||
|
||||
> [!NOTE]
|
||||
> This was recommended by the creators of LTX over banodoco's discord.
|
||||
|
||||
*Orginal code from [mix](https://github.com/XmYx)*"""
|
||||
|
||||
def _compress_decompress_ffmpeg(self, img_array, crf):
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
input_path = os.path.join(temp_dir, "input.png")
|
||||
output_path = os.path.join(temp_dir, "output.mp4")
|
||||
decoded_path = os.path.join(temp_dir, "decoded.png")
|
||||
|
||||
Image.fromarray(img_array).save(input_path)
|
||||
|
||||
encode_command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
input_path,
|
||||
"-c:v",
|
||||
"libx264",
|
||||
"-crf",
|
||||
str(crf),
|
||||
"-pix_fmt",
|
||||
"yuv420p",
|
||||
"-frames:v",
|
||||
"1",
|
||||
output_path,
|
||||
]
|
||||
subprocess.run(encode_command, capture_output=True)
|
||||
|
||||
decode_command = [
|
||||
"ffmpeg",
|
||||
"-y",
|
||||
"-i",
|
||||
output_path,
|
||||
"-frames:v",
|
||||
"1",
|
||||
decoded_path,
|
||||
]
|
||||
subprocess.run(decode_command, capture_output=True)
|
||||
|
||||
decoded_img = np.array(Image.open(decoded_path))
|
||||
return decoded_img
|
||||
|
||||
def compress_and_decompress(self, image, crf):
|
||||
import io
|
||||
|
||||
output_images = []
|
||||
|
||||
try:
|
||||
import av
|
||||
|
||||
for img_tensor in image:
|
||||
img_array = img_tensor.cpu().numpy()
|
||||
img_array = (img_array * 255).astype(np.uint8)
|
||||
img_array = img_array.copy(
|
||||
order="C"
|
||||
) # Ensure contiguous array
|
||||
|
||||
output = io.BytesIO()
|
||||
|
||||
# Encode the image to h264 with the given CRF
|
||||
container = av.open(output, mode="w", format="mp4")
|
||||
stream = container.add_stream("h264", rate=1)
|
||||
stream.width = img_array.shape[1]
|
||||
stream.height = img_array.shape[0]
|
||||
stream.pix_fmt = "yuv420p"
|
||||
stream.options = {"crf": str(crf)}
|
||||
|
||||
frame = av.VideoFrame.from_ndarray(img_array, format="rgb24")
|
||||
for packet in stream.encode(frame):
|
||||
container.mux(packet)
|
||||
for packet in stream.encode():
|
||||
container.mux(packet)
|
||||
container.close()
|
||||
|
||||
# Decode the video back to an image
|
||||
output.seek(0)
|
||||
container = av.open(output, mode="r", format="mp4")
|
||||
decoded_frames = []
|
||||
for frame in container.decode(video=0):
|
||||
img_decoded = frame.to_ndarray(format="rgb24")
|
||||
decoded_frames.append(img_decoded)
|
||||
container.close()
|
||||
|
||||
if len(decoded_frames) > 0:
|
||||
img_decoded = decoded_frames[0]
|
||||
img_decoded = torch.from_numpy(
|
||||
img_decoded.astype(np.float32) / 255.0
|
||||
)
|
||||
output_images.append(img_decoded)
|
||||
else:
|
||||
# If decoding failed, use the original image
|
||||
output_images.append(img_tensor)
|
||||
except ImportError:
|
||||
log.warning(
|
||||
"PyAv is not installed... Falling back to the ffmpeg cli"
|
||||
)
|
||||
for img_tensor in image:
|
||||
img_array = (img_tensor.cpu().numpy() * 255).astype(np.uint8)
|
||||
decoded_img = self._compress_decompress_ffmpeg(img_array, crf)
|
||||
img_decoded = torch.from_numpy(
|
||||
decoded_img.astype(np.float32) / 255.0
|
||||
)
|
||||
output_images.append(img_decoded)
|
||||
|
||||
output_images = torch.stack(output_images).to(image.device)
|
||||
return (output_images,)
|
||||
|
||||
|
||||
# fmt: off
|
||||
__nodes__ = [
|
||||
ImageH264Compression
|
||||
]
|
||||
+3
-2
@@ -1,6 +1,5 @@
|
||||
import comfy.utils
|
||||
from PIL import Image
|
||||
from rembg import remove
|
||||
|
||||
from ..utils import pil2tensor, tensor2pil
|
||||
|
||||
@@ -35,7 +34,7 @@ class MTB_ImageRemoveBackgroundRembg:
|
||||
),
|
||||
"bgcolor": (
|
||||
"COLOR",
|
||||
{"default": "#000000"},
|
||||
{"default": "#000000","widgetType": "MTB_COLOR"},
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -64,6 +63,8 @@ class MTB_ImageRemoveBackgroundRembg:
|
||||
post_process_mask,
|
||||
bgcolor,
|
||||
):
|
||||
from rembg import remove
|
||||
|
||||
pbar = comfy.utils.ProgressBar(image.size(0))
|
||||
images = tensor2pil(image)
|
||||
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import comfy.utils
|
||||
import torch
|
||||
|
||||
from ..log import log
|
||||
from ..utils import nextAvailable, tensor2pil
|
||||
|
||||
RELATIVE_NOTICE = """
|
||||
Absolute paths are kept as is, relatives are from the output directory.
|
||||
"""
|
||||
|
||||
|
||||
class MTB_PostshotTrain:
|
||||
CATEGORY = "mtb/postshot"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"images": (
|
||||
"IMAGE",
|
||||
{"tooltip": "These image will get save to disk first"},
|
||||
),
|
||||
"profile": (
|
||||
[
|
||||
"NeRF L",
|
||||
"NeRF M",
|
||||
"NeRF S",
|
||||
"NeRF XL",
|
||||
"NeRF XXL",
|
||||
"Splat ADC",
|
||||
"Splat MCMC",
|
||||
],
|
||||
{
|
||||
"default": "Splat MCMC",
|
||||
"tooltip": "The radiance field model profile to train",
|
||||
},
|
||||
),
|
||||
"image_select": (
|
||||
["all", "best"],
|
||||
{
|
||||
"default": "best",
|
||||
"tooltip": "How to select training images from the source image sets",
|
||||
},
|
||||
),
|
||||
"train_steps_limit": (
|
||||
"INT",
|
||||
{
|
||||
"default": 30,
|
||||
"min": 1,
|
||||
"max": 1000,
|
||||
"tooltip": "Number of kSteps to train the model for",
|
||||
},
|
||||
),
|
||||
"output_path": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "output",
|
||||
"tooltip": (
|
||||
"path to save the project to" f"{RELATIVE_NOTICE}"
|
||||
),
|
||||
},
|
||||
),
|
||||
"postshot_cli": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "C:/Program Files/Jawset Postshot/bin/postshot-cli.exe"
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"gpu": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 255,
|
||||
"tooltip": "Specify the index of the GPU to use",
|
||||
},
|
||||
),
|
||||
"num_train_images": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"tooltip": "If image-select best is used, specifies the number of training images to select",
|
||||
},
|
||||
),
|
||||
"max_image_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1600,
|
||||
"min": 0,
|
||||
"tooltip": "Downscale training images such that their longer edge is at most this value in pixels. Disabled if zero.",
|
||||
},
|
||||
),
|
||||
"max_num_features": (
|
||||
"INT",
|
||||
{
|
||||
"default": 8,
|
||||
"min": 1,
|
||||
"tooltip": "Maximum number of 2D kFeatures extracted from each image.",
|
||||
},
|
||||
),
|
||||
"splat_density": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.0,
|
||||
"min": 0.125,
|
||||
"max": 8.0,
|
||||
"tooltip": (
|
||||
"Controls how much additional splats "
|
||||
"are generated during training."
|
||||
"Applies only in 'Splat ADC' profile."
|
||||
),
|
||||
},
|
||||
),
|
||||
"max_num_splats": (
|
||||
"INT",
|
||||
{
|
||||
"default": 3000,
|
||||
"min": 1,
|
||||
"tooltip": (
|
||||
"Sets the maximum number of splats (in kSplats)"
|
||||
" created during training. "
|
||||
"Applies only in 'Splat MCMC' profile."
|
||||
),
|
||||
},
|
||||
),
|
||||
"export_splat_ply": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "",
|
||||
"tooltip": (
|
||||
"If not empty will also save a ply file."
|
||||
f"{RELATIVE_NOTICE}"
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
OUTPUT_NODE = True
|
||||
RETURN_NAMES = ("project_file_path",)
|
||||
FUNCTION = "train_model"
|
||||
|
||||
def train_model(
|
||||
self,
|
||||
images: torch.Tensor,
|
||||
profile: str,
|
||||
image_select: str,
|
||||
train_steps_limit: int,
|
||||
output_path: str,
|
||||
gpu=0,
|
||||
num_train_images=0,
|
||||
max_image_size=1600,
|
||||
max_num_features=8,
|
||||
splat_density=1.0,
|
||||
max_num_splats=3000,
|
||||
export_splat_ply="",
|
||||
postshot_cli="",
|
||||
):
|
||||
if not output_path.endswith(".psht"):
|
||||
output_path += ".psht"
|
||||
|
||||
output_path = nextAvailable(output_path)
|
||||
output_path.parent.mkdir(exist_ok=True)
|
||||
|
||||
pbar = comfy.utils.ProgressBar(200 + images.size(0))
|
||||
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
image_paths = []
|
||||
images_pil = tensor2pil(images)
|
||||
for i, img in enumerate(images_pil):
|
||||
try:
|
||||
img_path = os.path.join(temp_dir, f"image_{i:04d}.png")
|
||||
img.save(img_path)
|
||||
image_paths.append(img_path)
|
||||
except Exception as e:
|
||||
raise RuntimeError(
|
||||
f"Failed to save image {i}: {str(e)}"
|
||||
) from e
|
||||
pbar.update(1)
|
||||
|
||||
if not image_paths:
|
||||
raise ValueError("No valid images to process")
|
||||
|
||||
cmd = [postshot_cli, "train"]
|
||||
|
||||
for img_path in image_paths:
|
||||
cmd.extend(["-i", img_path])
|
||||
|
||||
cmd.extend(
|
||||
[
|
||||
"-p",
|
||||
profile,
|
||||
"--image-select",
|
||||
image_select,
|
||||
"-s",
|
||||
str(train_steps_limit),
|
||||
"-o",
|
||||
output_path.as_posix(),
|
||||
]
|
||||
)
|
||||
|
||||
if gpu is not None:
|
||||
cmd.extend(["--gpu", str(gpu)])
|
||||
if num_train_images > 0 and image_select == "best":
|
||||
cmd.extend(["--num-train-images", str(num_train_images)])
|
||||
if max_image_size > 0:
|
||||
cmd.extend(["--max-image-size", str(max_image_size)])
|
||||
if max_num_features != 8:
|
||||
cmd.extend(["--max-num-features", str(max_num_features)])
|
||||
if profile == "Splat ADC" and splat_density != 1.0:
|
||||
cmd.extend(["--splat-density", str(splat_density)])
|
||||
if profile == "Splat MCMC" and max_num_splats != 3000:
|
||||
cmd.extend(["--max-num-splats", str(max_num_splats)])
|
||||
if export_splat_ply:
|
||||
export_splat_ply = nextAvailable(export_splat_ply)
|
||||
cmd.extend(
|
||||
["--export-splat-ply", export_splat_ply.as_posix()]
|
||||
)
|
||||
|
||||
log.debug(f"Running {cmd}")
|
||||
|
||||
process = subprocess.Popen(
|
||||
cmd,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
universal_newlines=True,
|
||||
)
|
||||
|
||||
last_step_c = 0
|
||||
last_step_t = 0
|
||||
while True:
|
||||
output = process.stdout.readline()
|
||||
if output == "" and process.poll() is not None:
|
||||
break
|
||||
if output:
|
||||
print(output)
|
||||
if "camera tracking step" in output.lower():
|
||||
try:
|
||||
current_step = int(
|
||||
output.split("%")[0].split(":")[1].strip()
|
||||
)
|
||||
if current_step > last_step_c:
|
||||
pbar.update(1)
|
||||
last_step_c = current_step
|
||||
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
|
||||
if "training radiance field:" in output.lower():
|
||||
try:
|
||||
current_step = int(
|
||||
output.split("%")[0].split(":")[1].strip()
|
||||
)
|
||||
if current_step > last_step_t:
|
||||
pbar.update(1)
|
||||
last_step_t = current_step
|
||||
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
|
||||
if process.returncode != 0:
|
||||
_, stderr = process.communicate()
|
||||
raise RuntimeError(f"Postshot training failed: {stderr}")
|
||||
|
||||
if not os.path.exists(output_path):
|
||||
raise RuntimeError("Output file was not created")
|
||||
|
||||
return (output_path.as_posix(),)
|
||||
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Training failed: {str(e)}")
|
||||
finally:
|
||||
pbar.update(train_steps_limit)
|
||||
|
||||
|
||||
class MTB_PostshotExport:
|
||||
CATEGORY = "mtb/postshot"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"project_file": (
|
||||
"STRING",
|
||||
{"default": "", "forceInput": True},
|
||||
),
|
||||
"export_splat_ply": ("STRING", {"default": "output.ply"}),
|
||||
"postshot_cli": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "C:/Program Files/Jawset Postshot/bin/postshot-cli.exe"
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("exported_ply_path",)
|
||||
FUNCTION = "export_model"
|
||||
|
||||
def export_model(
|
||||
self, project_file: str, export_splat_ply: str, postshot_cli: str
|
||||
):
|
||||
if not project_file.endswith(".psht"):
|
||||
raise ValueError("Project file must have .psht extension")
|
||||
|
||||
if not os.path.exists(project_file):
|
||||
raise FileNotFoundError(f"Project file not found: {project_file}")
|
||||
|
||||
if not export_splat_ply.endswith(".ply"):
|
||||
export_splat_ply += ".ply"
|
||||
|
||||
_export_splat_ply = nextAvailable(export_splat_ply)
|
||||
_export_splat_ply.parent.mkdir(exist_ok=True)
|
||||
|
||||
cmd = [
|
||||
postshot_cli,
|
||||
"export",
|
||||
"-f",
|
||||
project_file,
|
||||
"--export-splat-ply",
|
||||
_export_splat_ply.as_posix(),
|
||||
]
|
||||
|
||||
try:
|
||||
_result = subprocess.run(
|
||||
cmd, check=True, capture_output=True, text=True
|
||||
)
|
||||
|
||||
if not _export_splat_ply.exists():
|
||||
log.error("Export file was not created")
|
||||
|
||||
return (_export_splat_ply.as_posix(),)
|
||||
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise RuntimeError(f"Export failed: {e.stderr}")
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Export failed: {str(e)}")
|
||||
|
||||
|
||||
__nodes__ = [MTB_PostshotExport, MTB_PostshotTrain]
|
||||
@@ -0,0 +1,68 @@
|
||||
class MTB_PromptPresets:
|
||||
RETURN_TYPES = ("STRING",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
FUNCTION = "enprompt"
|
||||
CATEGORY = "mtb/prompt"
|
||||
EXPERIMENTAL = True
|
||||
|
||||
_all_prompts = {}
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
from ..utils import comfy_dir
|
||||
import json
|
||||
|
||||
cls._all_prompts = {}
|
||||
prompt_dir = comfy_dir / "prompts"
|
||||
if prompt_dir.exists():
|
||||
json_files = prompt_dir.glob("*.json")
|
||||
# merge them
|
||||
for json_file in json_files:
|
||||
try:
|
||||
with open(json_file, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, list):
|
||||
for item in data:
|
||||
if isinstance(item, dict) and 'name' in item and 'prompts' in item:
|
||||
name = item['name']
|
||||
prompts = item['prompts']
|
||||
if isinstance(prompts, list):
|
||||
cls._all_prompts[name] = prompts
|
||||
except Exception as e:
|
||||
print(f"Error loading prompts from {json_file}: {e}")
|
||||
return {
|
||||
"required": {
|
||||
"name": (list(cls._all_prompts.keys()) if cls._all_prompts else ["No prompts found"],),
|
||||
"size": ("INT", {"default": -1, "min": -1, "max": 100, "step": 1}),
|
||||
"random": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
},
|
||||
}
|
||||
|
||||
def enprompt(self, name, size, random, seed=None):
|
||||
import random as rand
|
||||
|
||||
if name not in self._all_prompts:
|
||||
return ([],)
|
||||
|
||||
prompts = self._all_prompts[name].copy()
|
||||
|
||||
if random:
|
||||
if seed is not None or seed != -1:
|
||||
rand.seed(seed)
|
||||
else:
|
||||
import time
|
||||
rand.seed(int(time.time() * 1000000) % 0xffffffffffffffff)
|
||||
rand.shuffle(prompts)
|
||||
|
||||
# Return all prompts
|
||||
if size == -1:
|
||||
return (prompts,)
|
||||
else:
|
||||
clamped_size = min(size, len(prompts))
|
||||
return (prompts[:clamped_size],)
|
||||
|
||||
|
||||
__nodes__ = [MTB_PromptPresets]
|
||||
@@ -0,0 +1,85 @@
|
||||
import qrcode
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
from ..utils import pil2tensor
|
||||
|
||||
|
||||
class MTB_QrCode:
|
||||
"""Basic QR Code generator."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"url": ("STRING", {"default": "https://www.github.com"}),
|
||||
"width": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
|
||||
"box_size": (
|
||||
"INT",
|
||||
{"default": 10, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"border": (
|
||||
"INT",
|
||||
{"default": 4, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"invert": (("BOOLEAN",), {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "do_qr"
|
||||
CATEGORY = "mtb/generate"
|
||||
|
||||
def do_qr(
|
||||
self,
|
||||
*,
|
||||
url: str,
|
||||
width: int,
|
||||
height: int,
|
||||
error_correct: str,
|
||||
box_size: int,
|
||||
border: int,
|
||||
invert: bool,
|
||||
) -> tuple[torch.Tensor]:
|
||||
log.warning(
|
||||
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
|
||||
)
|
||||
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_L
|
||||
elif error_correct == "M":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_M
|
||||
elif error_correct == "Q":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_Q
|
||||
else:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_H
|
||||
|
||||
qr = qrcode.QRCode(
|
||||
version=1,
|
||||
error_correction=error_correct,
|
||||
box_size=box_size,
|
||||
border=border,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
back_color = (255, 255, 255) if invert else (0, 0, 0)
|
||||
fill_color = (0, 0, 0) if invert else (255, 255, 255)
|
||||
|
||||
code = qr.make_image(back_color=back_color, fill_color=fill_color)
|
||||
|
||||
# that we now resize without filtering
|
||||
code = code.resize((width, height), Image.NEAREST)
|
||||
|
||||
return (pil2tensor(code),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_QrCode]
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import textwrap
|
||||
|
||||
from comfy.comfy_types import IO
|
||||
|
||||
from ..repl import SOCKET_COUNT, ComfyREPLBackend
|
||||
from ..utils import log
|
||||
|
||||
|
||||
class MTB_Repl:
|
||||
"""Write python code from within a comfy graph."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"uuid": ("STRING",),
|
||||
"code": ("CODE_EDITOR", {"lang": "python"}),
|
||||
},
|
||||
"optional": {
|
||||
f"input_{i:02d}": (IO.ANY,) for i in range(1, SOCKET_COUNT + 1)
|
||||
}
|
||||
| {
|
||||
"reset": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"label_on": "reset state at each run",
|
||||
"label_off": "keep mutated state",
|
||||
},
|
||||
),
|
||||
"propagate": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"label_on": "allow",
|
||||
"label_off": "block forward",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
EXPERIMENTAL = True
|
||||
RETURN_TYPES = tuple(IO.ANY for _ in range(SOCKET_COUNT))
|
||||
RETURN_NAMES = tuple(f"output_{i:02d}" for i in range(1, SOCKET_COUNT + 1))
|
||||
FUNCTION = "run"
|
||||
CATEGORY = "mtb/repl"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
# @classmethod
|
||||
# def IS_CHANGED(cls, code: str, **kwargs):
|
||||
# code_hash = hashlib.sha256(code.encode("utf-8")).hexdigest()
|
||||
# return code_hash
|
||||
|
||||
# TODO: hide uuid from the frontend
|
||||
# same for propagate, it should be managed from our run button in js
|
||||
def run(
|
||||
self, *, uuid: str, code: str, reset=False, propagate=True, **kwargs
|
||||
):
|
||||
log.debug(f"Received code from frontend:\n{code}")
|
||||
log.debug(f"Kwargs: {kwargs}")
|
||||
|
||||
repl_backend = ComfyREPLBackend()
|
||||
|
||||
console = repl_backend.get_console(uuid, reset=reset)
|
||||
|
||||
if not console:
|
||||
# TODO: handle this case automatically
|
||||
raise RuntimeError(
|
||||
textwrap.dedent(f"""
|
||||
No matching console found for {uuid}
|
||||
active console: {ComfyREPLBackend.active_consoles}
|
||||
""")
|
||||
)
|
||||
|
||||
inputs = list(kwargs.values())
|
||||
|
||||
console.locals["IS_LIVE"] = False
|
||||
|
||||
ui = repl_backend.execute_code(
|
||||
code,
|
||||
console=console,
|
||||
inputs=inputs,
|
||||
# , reset=True
|
||||
)
|
||||
if ui is None:
|
||||
ui = {"output_html": [""], "error": [""]}
|
||||
else:
|
||||
ui = {"output_html": [ui["output_html"]], "error": [ui["error"]]}
|
||||
|
||||
# process outputs
|
||||
outputs = repl_backend.get_outputs(console=console)
|
||||
|
||||
log.debug(ui)
|
||||
# return outputs
|
||||
if propagate:
|
||||
results = tuple(outputs)
|
||||
else:
|
||||
from comfy_execution.graph import ExecutionBlocker
|
||||
|
||||
results = [ExecutionBlocker(None)] * SOCKET_COUNT
|
||||
|
||||
return {"ui": ui, "result": results}
|
||||
|
||||
|
||||
__nodes__ = [MTB_Repl]
|
||||
+267
@@ -0,0 +1,267 @@
|
||||
import logging
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
|
||||
def lerp(v0, v1, t):
|
||||
return v0 * (1.0 - t) + v1 * t
|
||||
|
||||
|
||||
def interpolate_box(box1, box2, t):
|
||||
"""Linearly interpolate between two boxes (tuples of 4 ints)."""
|
||||
if box1 is None or box2 is None:
|
||||
return None
|
||||
x1 = lerp(box1[0], box2[0], t)
|
||||
y1 = lerp(box1[1], box2[1], t)
|
||||
x2 = lerp(box1[2], box2[2], t)
|
||||
y2 = lerp(box1[3], box2[3], t)
|
||||
return (int(x1), int(y1), int(x2), int(y2))
|
||||
|
||||
|
||||
class MTB_FaceMeshBatchToSEGSAndFill:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
bool_true_widget = (
|
||||
"BOOLEAN",
|
||||
{"default": True, "label_on": "Enabled", "label_off": "Disabled"},
|
||||
)
|
||||
bool_false_widget = (
|
||||
"BOOLEAN",
|
||||
{"default": False, "label_on": "Enabled", "label_off": "Disabled"},
|
||||
)
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"interpolation": (
|
||||
["linear", "hold_last"],
|
||||
{"default": "linear"},
|
||||
),
|
||||
"fill_shape": (
|
||||
["interpolate_contour", "bbox"],
|
||||
{"default": "interpolate_contour"},
|
||||
),
|
||||
"crop_factor": (
|
||||
"FLOAT",
|
||||
{"default": 3.0, "min": 1.0, "max": 100, "step": 0.1},
|
||||
),
|
||||
"bbox_fill": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"label_on": "enabled",
|
||||
"label_off": "disabled",
|
||||
},
|
||||
),
|
||||
"drop_size": (
|
||||
"INT",
|
||||
{"min": 1, "max": 8192, "step": 1, "default": 1},
|
||||
),
|
||||
"dilation": (
|
||||
"INT",
|
||||
{"default": 0, "min": -512, "max": 512, "step": 1},
|
||||
),
|
||||
"face": bool_true_widget,
|
||||
"mouth": bool_false_widget,
|
||||
"left_eyebrow": bool_false_widget,
|
||||
"left_eye": bool_false_widget,
|
||||
"left_pupil": bool_false_widget,
|
||||
"right_eyebrow": bool_false_widget,
|
||||
"right_eye": bool_false_widget,
|
||||
"right_pupil": bool_false_widget,
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("SEGS",)
|
||||
FUNCTION = "generate_and_fill"
|
||||
CATEGORY = "ImpactPack/Operation"
|
||||
|
||||
def generate_and_fill(
|
||||
self,
|
||||
image,
|
||||
interpolation,
|
||||
fill_shape,
|
||||
crop_factor,
|
||||
bbox_fill,
|
||||
drop_size,
|
||||
dilation,
|
||||
face,
|
||||
mouth,
|
||||
left_eyebrow,
|
||||
left_eye,
|
||||
left_pupil,
|
||||
right_eyebrow,
|
||||
right_eye,
|
||||
right_pupil,
|
||||
):
|
||||
import cv2
|
||||
import impact.core as core
|
||||
|
||||
total_frames = image.shape[0]
|
||||
logging.info(
|
||||
f"[FaceMesh Batch & Fill] Starting. Processing {total_frames} frames. Mode: {interpolation}/{fill_shape}."
|
||||
)
|
||||
|
||||
all_labels_found = set()
|
||||
structured_segs = {}
|
||||
for i in range(total_frames):
|
||||
single_frame_batch = image[i : i + 1]
|
||||
_, segs_for_this_frame = core.mediapipe_facemesh_to_segs(
|
||||
single_frame_batch,
|
||||
crop_factor,
|
||||
bbox_fill,
|
||||
50,
|
||||
drop_size,
|
||||
dilation,
|
||||
face,
|
||||
mouth,
|
||||
left_eyebrow,
|
||||
left_eye,
|
||||
left_pupil,
|
||||
right_eyebrow,
|
||||
right_eye,
|
||||
right_pupil,
|
||||
)
|
||||
for seg in segs_for_this_frame:
|
||||
if seg.label not in all_labels_found:
|
||||
all_labels_found.add(seg.label)
|
||||
structured_segs[seg.label] = [None] * total_frames
|
||||
structured_segs[seg.label][i] = seg
|
||||
|
||||
for label, timeline in structured_segs.items():
|
||||
if interpolation == "linear":
|
||||
last_valid_idx = -1
|
||||
for i in range(total_frames):
|
||||
if timeline[i] is not None:
|
||||
if i > last_valid_idx + 1 and last_valid_idx != -1:
|
||||
start_seg, end_seg = (
|
||||
timeline[last_valid_idx],
|
||||
timeline[i],
|
||||
)
|
||||
gap_size = i - last_valid_idx
|
||||
for j in range(1, gap_size):
|
||||
t = j / float(gap_size)
|
||||
new_bbox = interpolate_box(
|
||||
start_seg.bbox, end_seg.bbox, t
|
||||
)
|
||||
new_crop = interpolate_box(
|
||||
start_seg.crop_region,
|
||||
end_seg.crop_region,
|
||||
t,
|
||||
)
|
||||
|
||||
if new_crop is None:
|
||||
continue
|
||||
crop_h, crop_w = (
|
||||
new_crop[3] - new_crop[1],
|
||||
new_crop[2] - new_crop[0],
|
||||
)
|
||||
if crop_h <= 0 or crop_w <= 0:
|
||||
continue
|
||||
|
||||
new_mask = None
|
||||
if fill_shape == "interpolate_contour":
|
||||
start_mask = start_seg.cropped_mask
|
||||
end_mask = end_seg.cropped_mask
|
||||
|
||||
start_resized = cv2.resize(
|
||||
start_mask,
|
||||
(crop_w, crop_h),
|
||||
interpolation=cv2.INTER_LINEAR,
|
||||
)
|
||||
end_resized = cv2.resize(
|
||||
end_mask,
|
||||
(crop_w, crop_h),
|
||||
interpolation=cv2.INTER_LINEAR,
|
||||
)
|
||||
|
||||
new_mask = lerp(
|
||||
start_resized, end_resized, t
|
||||
)
|
||||
else:
|
||||
new_mask = np.ones(
|
||||
(crop_h, crop_w), dtype=np.float32
|
||||
)
|
||||
|
||||
timeline[last_valid_idx + j] = core.SEG(
|
||||
None,
|
||||
new_mask,
|
||||
1.0,
|
||||
new_crop,
|
||||
new_bbox,
|
||||
label,
|
||||
None,
|
||||
)
|
||||
last_valid_idx = i
|
||||
|
||||
last_valid_seg = None
|
||||
for i in range(total_frames):
|
||||
if timeline[i] is not None:
|
||||
last_valid_seg = timeline[i]
|
||||
elif last_valid_seg is not None:
|
||||
timeline[i] = last_valid_seg
|
||||
|
||||
if last_valid_seg is not None:
|
||||
for i in range(total_frames - 1, -1, -1):
|
||||
if timeline[i] is not None:
|
||||
last_valid_seg = timeline[i]
|
||||
elif last_valid_seg is not None:
|
||||
timeline[i] = last_valid_seg
|
||||
|
||||
final_segs_by_frame = [[] for _ in range(total_frames)]
|
||||
for label in sorted(list(all_labels_found)):
|
||||
timeline = structured_segs[label]
|
||||
for i in range(total_frames):
|
||||
if timeline[i] is not None:
|
||||
final_segs_by_frame[i].append(timeline[i])
|
||||
|
||||
original_dims = (image.shape[1], image.shape[2])
|
||||
final_segs_object = (original_dims, final_segs_by_frame)
|
||||
logging.info(
|
||||
f"[FaceMesh Batch & Fill] Completed. Processed {len(final_segs_by_frame)} frames."
|
||||
)
|
||||
return (final_segs_object,)
|
||||
|
||||
|
||||
class MTB_SegsToCombinedMaskBatch:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"segs": ("SEGS",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MASK",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "ImpactPack/Operation"
|
||||
|
||||
def doit(self, segs):
|
||||
import impact.core as core
|
||||
import impact.utils as utils
|
||||
|
||||
outputs = []
|
||||
if isinstance(segs[1], list) and len(segs[1]):
|
||||
if isinstance(segs[1][0], list):
|
||||
for seg in segs[1]:
|
||||
mask = core.segs_to_combined_mask((segs[0], seg))
|
||||
mask = utils.make_3d_mask(mask)
|
||||
outputs.append(mask)
|
||||
|
||||
return (
|
||||
torch.stack(outputs, dim=0)
|
||||
.permute(0, 2, 3, 1)
|
||||
.squeeze(-1),
|
||||
)
|
||||
|
||||
else:
|
||||
mask = core.segs_to_combined_mask(segs)
|
||||
mask = utils.make_3d_mask(mask)
|
||||
|
||||
return (mask,)
|
||||
return (torch.zeros((0, 10, 10, 1)),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_FaceMeshBatchToSEGSAndFill, MTB_SegsToCombinedMaskBatch]
|
||||
+95
-12
@@ -43,7 +43,38 @@ class MTB_TransformImage:
|
||||
["edge", "constant", "reflect", "symmetric"],
|
||||
{"default": "edge"},
|
||||
),
|
||||
"constant_color": ("COLOR", {"default": "#000000"}),
|
||||
"constant_color": (
|
||||
"COLOR",
|
||||
{"default": "#000000", "widgetType": "MTB_COLOR"},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"filter_type": (
|
||||
[
|
||||
"nearest",
|
||||
"box",
|
||||
"bilinear",
|
||||
"hamming",
|
||||
"bicubic",
|
||||
"lanczos",
|
||||
],
|
||||
{"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.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -61,21 +92,36 @@ class MTB_TransformImage:
|
||||
shear: float,
|
||||
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,
|
||||
"box": Image.BOX,
|
||||
"bilinear": Image.BILINEAR,
|
||||
"hamming": Image.HAMMING,
|
||||
"bicubic": Image.BICUBIC,
|
||||
"lanczos": Image.LANCZOS,
|
||||
}
|
||||
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),
|
||||
@@ -106,18 +152,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
|
||||
),
|
||||
)
|
||||
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])
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import cv2
|
||||
import numpy as np
|
||||
import torch
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
from ..utils import models_dir, np2tensor
|
||||
|
||||
# TODO: check if I can make a torch script device independant
|
||||
# for now I forced it to use cuda.
|
||||
|
||||
|
||||
class MTB_LoadVitMatteModel:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"kind": (("Composition-1K", "Distinctions-646"),),
|
||||
"autodownload": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("VITMATTE_MODEL",)
|
||||
RETURN_NAMES = ("torch_script",)
|
||||
CATEGORY = "mtb/vitmatte"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(self, *, kind: str, autodownload: bool):
|
||||
dest = models_dir / "vitmatte"
|
||||
dest.mkdir(exist_ok=True)
|
||||
name = "dist" if kind == "Distinctions-646" else "com"
|
||||
|
||||
file = hf_hub_download(
|
||||
repo_id="melmass/pytorch-scripts",
|
||||
filename=f"vitmatte_b_{name}.pt",
|
||||
local_dir=dest.as_posix(),
|
||||
local_files_only=not autodownload,
|
||||
)
|
||||
model = torch.jit.load(file).to("cuda")
|
||||
|
||||
return (model,)
|
||||
|
||||
|
||||
class MTB_GenerateTrimap:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
# "image": ("IMAGE",),
|
||||
"mask": ("MASK",),
|
||||
"erode": ("INT", {"default": 10}),
|
||||
"dilate": ("INT", {"default": 10}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("trimap",)
|
||||
|
||||
CATEGORY = "mtb/vitmatte"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(
|
||||
self,
|
||||
# image:torch.Tensor,
|
||||
mask: torch.Tensor,
|
||||
erode: int = 10,
|
||||
dilate: int = 10,
|
||||
):
|
||||
# TODO: not sure what's the most practical between IMAGE or MASK
|
||||
|
||||
# image = image.to("cuda").half()
|
||||
mask = mask.to("cuda").half()
|
||||
|
||||
trimaps = []
|
||||
for m in mask:
|
||||
mask_arr = m.squeeze(0).to(torch.uint8).cpu().numpy() * 255
|
||||
erode_kernel = np.ones((erode, erode), np.uint8)
|
||||
dilate_kernel = np.ones((dilate, dilate), np.uint8)
|
||||
eroded = cv2.erode(mask_arr, erode_kernel, iterations=5)
|
||||
dilated = cv2.dilate(mask_arr, dilate_kernel, iterations=5)
|
||||
trimap = np.zeros_like(mask_arr)
|
||||
trimap[dilated == 255] = 128
|
||||
trimap[eroded == 255] = 255
|
||||
trimaps.append(trimap)
|
||||
|
||||
return (np2tensor(trimaps),)
|
||||
|
||||
|
||||
class MTB_ApplyVitMatte:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("VITMATTE_MODEL",),
|
||||
"image": ("IMAGE",),
|
||||
"trimap": ("IMAGE",),
|
||||
"returns": (("RGB", "RGBA"),),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK")
|
||||
RETURN_NAMES = ("image (rgba)", "mask")
|
||||
CATEGORY = "mtb/utils"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(
|
||||
self, model, image: torch.Tensor, trimap: torch.Tensor, returns: str
|
||||
):
|
||||
im_count = image.shape[0]
|
||||
tm_count = trimap.shape[0]
|
||||
|
||||
if im_count != tm_count:
|
||||
raise ValueError("image and trimap must have the same batch size")
|
||||
|
||||
outputs_m: list[torch.Tensor] = []
|
||||
outputs_i: list[torch.Tensor] = []
|
||||
for i, im in enumerate(image):
|
||||
tm = trimap[i].half().unsqueeze(2).permute(2, 0, 1).to("cuda")
|
||||
im = im.half().permute(2, 0, 1).to("cuda")
|
||||
|
||||
inputs = {"image": im.unsqueeze(0), "trimap": tm.unsqueeze(0)}
|
||||
|
||||
fine_mask = model(inputs)
|
||||
foreground = im * fine_mask + (1 - fine_mask)
|
||||
|
||||
if returns == "RGBA":
|
||||
rgba_image = torch.cat(
|
||||
(foreground, fine_mask.unsqueeze(0)), dim=0
|
||||
)
|
||||
outputs_i.append(rgba_image.unsqueeze(0))
|
||||
else:
|
||||
outputs_i.append(foreground.unsqueeze(0))
|
||||
|
||||
outputs_m.append(fine_mask.unsqueeze(0))
|
||||
|
||||
result_m = torch.cat(outputs_m, dim=0)
|
||||
result_i = torch.cat(outputs_i, dim=0)
|
||||
|
||||
return (result_i.permute(0, 2, 3, 1), result_m)
|
||||
|
||||
|
||||
__nodes__ = [MTB_LoadVitMatteModel, MTB_GenerateTrimap, MTB_ApplyVitMatte]
|
||||
+152
-179
@@ -1,179 +1,152 @@
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "comfy-mtb"
|
||||
version = "0.1.5"
|
||||
description = "Animation oriented nodes pack for ComfyUI."
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
# repository = ""
|
||||
# url = "https://github.com/melMass/comfy_mtb"
|
||||
authors = [{ name = "Mel Massadian", email = "mel@melmassadian.com" }]
|
||||
classifiers = [
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Intended Audience :: Developers",
|
||||
]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"qrcode",
|
||||
"onnxruntime-gpu",
|
||||
"requirements-parserx",
|
||||
"rembg",
|
||||
"imageio_ffmpeg",
|
||||
"rich",
|
||||
"rich_argparse",
|
||||
"matplotlib",
|
||||
"pillow",
|
||||
]
|
||||
optional-dependencies = { mel = [
|
||||
"jupyterlab==4.1.6",
|
||||
], dev = [
|
||||
"black[jupyter]",
|
||||
"codespell",
|
||||
"mypy",
|
||||
"pre-commit",
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"pytest-random-order",
|
||||
"ruff",
|
||||
], doc = [
|
||||
"docutils==0.17.1",
|
||||
"jupyter-book>=0.15",
|
||||
"sphinx-autobuild",
|
||||
] }
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/melMass/comfy_mtb"
|
||||
Documentation = "https://github.com/melMass/comfy_mtb/wiki"
|
||||
Repository = "https://github.com/melMass/comfy_mtb"
|
||||
Issues = "https://github.com/melMass/comfy_mtb/issues"
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "mel"
|
||||
DisplayName = "comfy-mtb"
|
||||
Icon = "https://avatars.githubusercontent.com/u/7041726?v=4"
|
||||
|
||||
[tool.bumpversion]
|
||||
current_version = "0.1.5"
|
||||
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 = ["."]
|
||||
exclude = [
|
||||
"**/node_modules",
|
||||
"**/__pycache__",
|
||||
"src/experimental",
|
||||
"src/typestubs",
|
||||
]
|
||||
ignore = ["src/oldstuff"]
|
||||
defineConstant = { DEBUG = true }
|
||||
extraPaths = ["python", "../.."]
|
||||
stubPath = "src/stubs"
|
||||
|
||||
reportMissingImports = true
|
||||
reportMissingTypeStubs = false
|
||||
typeCheckingMode = "basic"
|
||||
|
||||
pythonVersion = "3.10"
|
||||
pythonPlatform = "Windows"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
log_level = "DEBUG"
|
||||
log_cli = true
|
||||
markers = [
|
||||
"wip: tests that aren't fully finished yet",
|
||||
"heavy: marks tests as heavy (deselect with '-m \"not heavy\"')",
|
||||
|
||||
]
|
||||
filterwarnings = ["ignore::UserWarning", 'ignore::DeprecationWarning']
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
line_length = 88
|
||||
auto_identify_namespace_packages = false
|
||||
# NOTE:
|
||||
# pyright doesn't like implicit namespace + single line (related to https://github.com/microsoft/pyright/issues/2882?) but it's horible so I'll live with it
|
||||
force_single_line = false
|
||||
known_first_party = ["mtb"]
|
||||
extend_skip = ["archives"]
|
||||
combine_straight_imports = true
|
||||
|
||||
[tool.coverage.run]
|
||||
parallel = true
|
||||
source = ["docs", "tests", "comfy-mtb"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 90
|
||||
show_missing = true
|
||||
|
||||
[tool.coverage.html]
|
||||
show_contexts = true
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 79
|
||||
select = ["A", "B", "C", "D", "E", "F", "FBT", "I", "N", "S", "SIM", "UP", "W"]
|
||||
# NOTE:
|
||||
# D102 - undocumented-public-method (noisy)
|
||||
# D103 - undocumented-public-function (noisy)
|
||||
# D100 - undocumented-public-module (noisy)
|
||||
# N802 - invalid-function-name (forced by comfy's arch)
|
||||
ignore = ["D103", "D102", "D100", "N802"]
|
||||
# exclude auto generated file
|
||||
extend-exclude = ["./docs/conf.py"]
|
||||
|
||||
[tool.ruff.per-file-ignores]
|
||||
# imported but unused
|
||||
"__init__.py" = ["F401"]
|
||||
# use of assert detected
|
||||
"tests/*" = ["S101"]
|
||||
|
||||
[tool.ruff.pydocstyle]
|
||||
convention = "numpy"
|
||||
|
||||
[tool.mypy]
|
||||
pretty = true
|
||||
ignore_missing_imports = true
|
||||
# exclude auto generated file
|
||||
exclude = ["docs/conf.py"]
|
||||
|
||||
[tool.codespell]
|
||||
# exclude auto generated file
|
||||
skip = "./docs/conf.py,poetry.lock"
|
||||
check-filenames = true
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "comfy-mtb"
|
||||
version = "0.6.0"
|
||||
description = "Animation oriented nodes pack for ComfyUI."
|
||||
license = { text = "MIT" }
|
||||
readme = "README.md"
|
||||
# repository = ""
|
||||
# url = "https://github.com/melMass/comfy_mtb"
|
||||
authors = [{ name = "Mel Massadian", email = "mel@melmassadian.com" }]
|
||||
classifiers = [
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Intended Audience :: Developers",
|
||||
]
|
||||
requires-python = ">=3.10"
|
||||
dependencies = [
|
||||
"qrcode",
|
||||
"cachetools",
|
||||
"onnxruntime-gpu",
|
||||
"requirements-parserx",
|
||||
"rembg",
|
||||
"imageio_ffmpeg",
|
||||
"rich",
|
||||
"rich_argparse",
|
||||
"matplotlib",
|
||||
"pillow",
|
||||
]
|
||||
optional-dependencies = { mel = [
|
||||
"jupyterlab==4.1.6",
|
||||
], dev = [
|
||||
"black[jupyter]",
|
||||
"codespell",
|
||||
"marimo",
|
||||
"mypy",
|
||||
"pre-commit",
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"pytest-random-order",
|
||||
"ruff",
|
||||
], doc = [
|
||||
"docutils==0.17.1",
|
||||
"jupyter-book>=0.15",
|
||||
"sphinx-autobuild",
|
||||
] }
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/melMass/comfy_mtb"
|
||||
Documentation = "https://github.com/melMass/comfy_mtb/wiki"
|
||||
Repository = "https://github.com/melMass/comfy_mtb"
|
||||
Issues = "https://github.com/melMass/comfy_mtb/issues"
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "mel"
|
||||
DisplayName = "comfy-mtb"
|
||||
Icon = "https://avatars.githubusercontent.com/u/7041726?v=4"
|
||||
|
||||
# INFO: All those remaining keys are meant for local dev
|
||||
[tool.pyright]
|
||||
include = ["."]
|
||||
exclude = [
|
||||
"**/node_modules",
|
||||
"**/__pycache__",
|
||||
"src/experimental",
|
||||
"src/typestubs",
|
||||
"extern/",
|
||||
]
|
||||
ignore = ["src/oldstuff"]
|
||||
defineConstant = { DEBUG = true }
|
||||
extraPaths = ["python", "../..", "../ComfyUI-Impact-Pack/modules"]
|
||||
stubPath = "src/stubs"
|
||||
|
||||
reportMissingImports = true
|
||||
reportMissingTypeStubs = false
|
||||
reportExplicitAny = false
|
||||
typeCheckingMode = "basic"
|
||||
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"')''',
|
||||
]
|
||||
filterwarnings = ["ignore::UserWarning", 'ignore::DeprecationWarning']
|
||||
|
||||
[tool.isort]
|
||||
profile = "black"
|
||||
line_length = 88
|
||||
auto_identify_namespace_packages = false
|
||||
# NOTE:
|
||||
# pyright doesn't like implicit namespace + single line (related to https://github.com/microsoft/pyright/issues/2882?) but it's horible so I'll live with it
|
||||
force_single_line = false
|
||||
known_first_party = ["mtb"]
|
||||
extend_skip = ["archives"]
|
||||
combine_straight_imports = true
|
||||
|
||||
[tool.coverage.run]
|
||||
parallel = true
|
||||
source = ["docs", "tests", "comfy-mtb"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 90
|
||||
show_missing = true
|
||||
|
||||
[tool.coverage.html]
|
||||
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)
|
||||
# D103 - undocumented-public-function (noisy)
|
||||
# D100 - undocumented-public-module (noisy)
|
||||
# D101 - undocumented-public-class (kept for DESCRIPTION definitions)
|
||||
# N801 - classname should use CapWord (forced by mtb registration (for now))
|
||||
# N802 - invalid-function-name (forced by comfy's arch)
|
||||
ignore = ["D103", "D102", "D100", "N801", "N802"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# imported but unused
|
||||
"__init__.py" = ["F401"]
|
||||
# use of assert detected
|
||||
"tests/*" = ["S101"]
|
||||
|
||||
[tool.ruff.lint.pydocstyle]
|
||||
convention = "numpy"
|
||||
|
||||
[tool.mypy]
|
||||
pretty = true
|
||||
ignore_missing_imports = true
|
||||
# exclude auto generated file
|
||||
exclude = ["docs/conf.py"]
|
||||
|
||||
[tool.codespell]
|
||||
# exclude auto generated file
|
||||
skip = "./docs/conf.py,poetry.lock"
|
||||
check-filenames = true
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -8,3 +8,5 @@ rich
|
||||
rich_argparse
|
||||
matplotlib
|
||||
pillow
|
||||
cachetools
|
||||
transformers
|
||||
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,20 +1,28 @@
|
||||
import contextlib
|
||||
import functools
|
||||
import importlib
|
||||
import math
|
||||
import operator
|
||||
import os
|
||||
import shlex
|
||||
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
|
||||
import requests
|
||||
import torch
|
||||
from PIL import Image
|
||||
@@ -45,6 +53,35 @@ def make_report():
|
||||
# endregion
|
||||
|
||||
|
||||
# region decorators
|
||||
class classproperty:
|
||||
def __init__(self, method=None):
|
||||
self.fget = method
|
||||
|
||||
def __get__(self, instance, cls=None):
|
||||
if self.fget:
|
||||
return self.fget(cls)
|
||||
|
||||
def getter(self, method):
|
||||
self.fget = method
|
||||
return self
|
||||
|
||||
|
||||
def singleton(cls):
|
||||
"""Turn a class into a singleton."""
|
||||
instances = {}
|
||||
|
||||
def get_instance(*args, **kwargs):
|
||||
if cls not in instances:
|
||||
instances[cls] = cls(*args, **kwargs)
|
||||
return instances[cls]
|
||||
|
||||
return get_instance
|
||||
|
||||
|
||||
# endregion
|
||||
|
||||
|
||||
# region NFOV
|
||||
class numpy_NFOV:
|
||||
def __init__(self, fov=None, height: int = 400, width: int = 800):
|
||||
@@ -161,9 +198,9 @@ class IPChecker:
|
||||
def __init__(self):
|
||||
self.ips = list(self.get_local_ips())
|
||||
log.debug(f"Found {len(self.ips)} local ips")
|
||||
self.checked_ips = set()
|
||||
self.checked_ips: set[str] = set()
|
||||
|
||||
def get_working_ip(self, test_url_template):
|
||||
def get_working_ip(self, test_url_template: str):
|
||||
for ip in self.ips:
|
||||
if ip not in self.checked_ips:
|
||||
self.checked_ips.add(ip)
|
||||
@@ -173,7 +210,7 @@ class IPChecker:
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def get_local_ips(prefix="192.168."):
|
||||
def get_local_ips(prefix: str = "192.168."):
|
||||
hostname = socket.gethostname()
|
||||
log.debug(f"Getting local ips for {hostname}")
|
||||
for info in socket.getaddrinfo(hostname, None):
|
||||
@@ -183,9 +220,9 @@ class IPChecker:
|
||||
if info[0] == socket.AF_INET and info[4][0].startswith(prefix):
|
||||
yield info[4][0]
|
||||
|
||||
def _test_url(self, url):
|
||||
def _test_url(self, url: str):
|
||||
try:
|
||||
response = requests.get(url)
|
||||
response = requests.get(url, timeout=10)
|
||||
return response.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
@@ -196,7 +233,7 @@ def get_server_info():
|
||||
from comfy.cli_args import args
|
||||
|
||||
ip_checker = IPChecker()
|
||||
base_url = args.listen
|
||||
base_url: str = args.listen
|
||||
if base_url == "0.0.0.0":
|
||||
log.debug("Server set to 0.0.0.0, we will try to resolve the host IP")
|
||||
base_url = ip_checker.get_working_ip(
|
||||
@@ -210,6 +247,37 @@ def get_server_info():
|
||||
|
||||
|
||||
# region MISC Utilities
|
||||
def glob_multiple(
|
||||
path: Path, patterns: list[str], recursive: bool = False
|
||||
) -> list[Path]:
|
||||
"""Combine multiple glob patterns into a single iterator."""
|
||||
return list(reduce(operator.or_, (set(path.glob(p)) for p in patterns)))
|
||||
|
||||
|
||||
def build_glob_patterns(
|
||||
extensions: list[str], recursive: bool = False
|
||||
) -> list[str]:
|
||||
"""Build glob patterns for given extensions."""
|
||||
prefix = "**/" if recursive else ""
|
||||
return [f"{prefix}*.{ext}" for ext in extensions]
|
||||
|
||||
|
||||
class SortMode(Enum):
|
||||
NONE = "none"
|
||||
MODIFIED = "modified"
|
||||
MODIFIED_REVERSE = "modified-reverse"
|
||||
NAME = "name"
|
||||
NAME_REVERSE = "name-reverse"
|
||||
|
||||
@classmethod
|
||||
def from_str(cls, value: str | None) -> "SortMode|None":
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
return cls(value.lower())
|
||||
except ValueError:
|
||||
log.warning(f"Sort mode {value} not supported")
|
||||
return None
|
||||
|
||||
|
||||
# TODO: use mtb.core directly instead of copying parts here
|
||||
@@ -425,25 +493,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
|
||||
|
||||
|
||||
@@ -463,7 +512,12 @@ here = Path(__file__).parent.absolute()
|
||||
# - Construct the absolute path to the ComfyUI directory
|
||||
comfy_dir = Path(folder_paths.base_path)
|
||||
models_dir = Path(folder_paths.models_dir)
|
||||
|
||||
|
||||
# NOTE: these aren't reliable, better call the getters each time
|
||||
output_dir = Path(folder_paths.output_directory)
|
||||
input_dir = Path(folder_paths.input_directory)
|
||||
|
||||
styles_dir = comfy_dir / "styles"
|
||||
session_id = str(uuid.uuid4())
|
||||
# - Construct the path to the font file
|
||||
@@ -473,9 +527,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)
|
||||
@@ -501,52 +556,310 @@ PIL_FILTER_MAP = {
|
||||
|
||||
|
||||
# region TENSOR Utilities
|
||||
def tensor2pil(image: torch.Tensor) -> list[Image.Image]:
|
||||
batch_count = image.size(0) if len(image.shape) > 3 else 1
|
||||
if batch_count > 1:
|
||||
out = []
|
||||
for i in range(batch_count):
|
||||
out.extend(tensor2pil(image[i]))
|
||||
return out
|
||||
|
||||
return [
|
||||
Image.fromarray(
|
||||
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(
|
||||
np.uint8
|
||||
|
||||
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 pil2tensor(image: Image.Image | list[Image.Image]) -> torch.Tensor:
|
||||
if isinstance(image, list):
|
||||
return torch.cat([pil2tensor(img) for img in image], dim=0)
|
||||
def get_torch_tensor_info(
|
||||
tensor: torch.Tensor | LazyProxyTensor | np.ndarray,
|
||||
*,
|
||||
name: str | None = None,
|
||||
):
|
||||
mem_str = "N/A"
|
||||
|
||||
return torch.from_numpy(
|
||||
np.array(image).astype(np.float32) / 255.0
|
||||
).unsqueeze(0)
|
||||
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 np2tensor(img_np: np.ndarray | list[np.ndarray]) -> torch.Tensor:
|
||||
if isinstance(img_np, list):
|
||||
return torch.cat([np2tensor(img) for img in img_np], dim=0)
|
||||
|
||||
return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
|
||||
def to_numpy(image: torch.Tensor) -> npt.NDArray[np.uint8]:
|
||||
"""Converts a tensor to a ndarray with proper scaling and type conversion."""
|
||||
np_array = np.clip(255.0 * image.cpu().numpy(), 0, 255).astype(np.uint8)
|
||||
return np_array
|
||||
|
||||
|
||||
def tensor2np(tensor: torch.Tensor) -> list[np.ndarray]:
|
||||
batch_count = tensor.size(0) if len(tensor.shape) > 3 else 1
|
||||
if batch_count > 1:
|
||||
out = []
|
||||
for i in range(batch_count):
|
||||
out.extend(tensor2np(tensor[i]))
|
||||
return out
|
||||
def handle_batch(
|
||||
tensor: torch.Tensor,
|
||||
func: Callable[[torch.Tensor], Image.Image | npt.NDArray[np.uint8]],
|
||||
) -> list[Image.Image] | list[npt.NDArray[np.uint8]]:
|
||||
"""Handle batch processing for a given tensor and conversion function."""
|
||||
return [func(tensor[i]) for i in range(tensor.shape[0])]
|
||||
|
||||
return [
|
||||
np.clip(255.0 * tensor.cpu().numpy().squeeze(), 0, 255).astype(
|
||||
np.uint8
|
||||
)
|
||||
]
|
||||
|
||||
def tensor2pil(tensor: torch.Tensor) -> list[Image.Image]:
|
||||
"""Convert a batch of tensors to a list of PIL Images."""
|
||||
|
||||
def single_tensor2pil(t: torch.Tensor) -> Image.Image:
|
||||
np_array = to_numpy(t)
|
||||
if np_array.ndim == 2: # (H, W) for masks
|
||||
return Image.fromarray(np_array, mode="L")
|
||||
elif np_array.ndim == 3: # (H, W, C) for RGB/RGBA
|
||||
if np_array.shape[2] == 3:
|
||||
return Image.fromarray(np_array, mode="RGB")
|
||||
elif np_array.shape[2] == 4:
|
||||
return Image.fromarray(np_array, mode="RGBA")
|
||||
raise ValueError(f"Invalid tensor shape: {t.shape}")
|
||||
|
||||
return handle_batch(tensor, single_tensor2pil)
|
||||
|
||||
|
||||
def pil2tensor(images: Image.Image | list[Image.Image]) -> torch.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
|
||||
if np_image.ndim == 2: # Grayscale
|
||||
return torch.from_numpy(np_image).unsqueeze(0) # (1, H, W)
|
||||
else: # RGB or RGBA
|
||||
return torch.from_numpy(np_image).unsqueeze(0) # (1, H, W, C)
|
||||
|
||||
if isinstance(images, Image.Image):
|
||||
return single_pil2tensor(images)
|
||||
else:
|
||||
return torch.cat([single_pil2tensor(img) for img in images], dim=0)
|
||||
|
||||
|
||||
def np2tensor(
|
||||
np_array: npt.NDArray[np.float32] | Sequence[npt.NDArray[np.float32]],
|
||||
) -> torch.Tensor:
|
||||
"""Converts a NumPy array or a list of NumPy arrays to a tensor."""
|
||||
|
||||
def single_np2tensor(array: npt.NDArray[np.float32]) -> torch.Tensor:
|
||||
if array.ndim == 2: # (H, W) for masks
|
||||
return torch.from_numpy(
|
||||
array.astype(np.float32) / 255.0
|
||||
).unsqueeze(0) # (1, H, W)
|
||||
elif array.ndim == 3: # (H, W, C) for RGB/RGBA
|
||||
return torch.from_numpy(
|
||||
array.astype(np.float32) / 255.0
|
||||
).unsqueeze(0) # (1, H, W, C)
|
||||
raise ValueError(f"Invalid array shape: {array.shape}")
|
||||
|
||||
if isinstance(np_array, np.ndarray):
|
||||
return single_np2tensor(np_array)
|
||||
else:
|
||||
return torch.cat([single_np2tensor(arr) for arr in np_array], dim=0)
|
||||
|
||||
|
||||
def tensor2np(tensor: torch.Tensor) -> list[npt.NDArray[np.uint8]]:
|
||||
"""Converts a batch of tensors to a list of NumPy arrays."""
|
||||
|
||||
def single_tensor2np(t: torch.Tensor) -> npt.NDArray[np.uint8]:
|
||||
t = t.squeeze() # Remove any singleton dimensions
|
||||
if t.ndim == 2: # (H, W) for masks
|
||||
return to_numpy(t)
|
||||
elif t.ndim == 3: # (C, H, W) for RGB/RGBA
|
||||
if t.shape[0] in [1, 3, 4]: # Channel-first format
|
||||
t = t.permute(1, 2, 0)
|
||||
return to_numpy(t)
|
||||
else:
|
||||
raise ValueError(f"Invalid tensor shape: {t.shape}")
|
||||
|
||||
return handle_batch(tensor, single_tensor2np)
|
||||
|
||||
|
||||
def nextAvailable(path: Path | str) -> Path:
|
||||
"""
|
||||
Find the next available path by adding a numbered suffix. (mimics comfy's version).
|
||||
|
||||
Args:
|
||||
path (Path): The original path to check
|
||||
|
||||
Returns
|
||||
-------
|
||||
Path: A path that doesn't exist yet
|
||||
"""
|
||||
path = Path(path)
|
||||
|
||||
if not path.is_absolute():
|
||||
path = output_dir / path
|
||||
|
||||
if not path.exists():
|
||||
return path
|
||||
|
||||
stem = path.stem
|
||||
suffix = path.suffix
|
||||
parent = path.parent
|
||||
|
||||
counter = 1
|
||||
while True:
|
||||
new_path = parent / f"{stem}_{counter:04d}{suffix}"
|
||||
if not new_path.exists():
|
||||
return new_path
|
||||
counter += 1
|
||||
|
||||
|
||||
def pad(img, left, right, top, bottom):
|
||||
@@ -746,6 +1059,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"
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptAlchemy.Bridge",
|
||||
|
||||
setup() {
|
||||
// Listen for messages from parent window
|
||||
window.addEventListener('message', async (event) => {
|
||||
// Optionally verify origin
|
||||
const { type, ...payload } = event.data || {};
|
||||
|
||||
switch (type) {
|
||||
case 'loadWorkflow':
|
||||
await app.loadGraphData(payload.workflow);
|
||||
this.sendToParent({ type: 'workflowLoaded' });
|
||||
break;
|
||||
|
||||
case 'getWorkflow':
|
||||
const workflow = app.graph.serialize();
|
||||
this.sendToParent({ type: 'workflow', workflow });
|
||||
break;
|
||||
|
||||
case 'queuePrompt':
|
||||
app.queuePrompt(0); // 0 = front of queue
|
||||
break;
|
||||
|
||||
case 'getPrompt':
|
||||
const prompt = await app.graphToPrompt();
|
||||
this.sendToParent({ type: 'prompt', prompt });
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
console.log("Alchemy Bridge Extension Loaded");
|
||||
|
||||
// Notify parent we're ready
|
||||
this.sendToParent({ type: 'ready' });
|
||||
},
|
||||
|
||||
sendToParent(data) {
|
||||
if (window.parent !== window) {
|
||||
window.parent.postMessage(data, '*');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
+5
-1066
File diff suppressed because it is too large
Load Diff
+132
-82
@@ -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, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Vendored
+3
-3
File diff suppressed because one or more lines are too long
Vendored
-3
File diff suppressed because one or more lines are too long
+4
-3
@@ -61,10 +61,11 @@ app.registerExtension({
|
||||
name: 'mtb.ImageFeed',
|
||||
setup: () => {
|
||||
app.ui.settings.addSetting({
|
||||
id: 'mtb.imageFeed.enabled',
|
||||
name: '[⚡mtb] Enable image feed',
|
||||
id: 'mtb.Main.image-feed-enabled',
|
||||
category: ['mtb', ' Main', 'image-feed-enabled'],
|
||||
name: 'Enable Image Feed',
|
||||
type: 'boolean',
|
||||
defaultValue: true,
|
||||
defaultValue: false,
|
||||
attrs: {
|
||||
style: {
|
||||
fontFamily: 'monospace',
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* MTB API Authoring Layer
|
||||
* This file imports the compiled TypeScript bundle and registers the extension.
|
||||
*
|
||||
* The source code is in web_source/src/mtb_api/
|
||||
* Build with: cd web_source && bun run build
|
||||
*/
|
||||
|
||||
import { registerMtbApiExtension } from './dist/mtb_api.js'
|
||||
|
||||
// Register the extension with ComfyUI
|
||||
registerMtbApiExtension()
|
||||
@@ -0,0 +1,640 @@
|
||||
import { app } from '../../scripts/app.js'
|
||||
import * as shared from './comfy_shared.js'
|
||||
|
||||
import { errorLogger, infoLogger } from './comfy_shared.js'
|
||||
import * as mtb_ui from './mtb_ui.js'
|
||||
|
||||
const defaultOptions = {
|
||||
capabilities: {
|
||||
execute: false,
|
||||
},
|
||||
lint: false,
|
||||
mode: 'python',
|
||||
theme: 'dracula',
|
||||
}
|
||||
|
||||
// wrapper around ACE
|
||||
export class MtbEditor {
|
||||
setOptions(options) {
|
||||
this.options = shared.deepMerge(defaultOptions, options || {})
|
||||
if (
|
||||
this.options.capabilities.execute === false &&
|
||||
this.options.lint === true
|
||||
) {
|
||||
infoLogger('ME: Disabling lint because execute is disabled')
|
||||
this.options.lint = false
|
||||
}
|
||||
|
||||
if (this.options.lint) {
|
||||
this.debouncedLint = shared.debounce(this.lintCode.bind(this), 500)
|
||||
}
|
||||
}
|
||||
constructor(node, options) {
|
||||
infoLogger('ME: construct')
|
||||
|
||||
this.uuid = shared.makeUUID()
|
||||
this._code = ''
|
||||
|
||||
// sanitize options
|
||||
this.setOptions(options)
|
||||
this.setupUI()
|
||||
|
||||
infoLogger('ME: inputDiv', this.inputDiv)
|
||||
|
||||
if (node) {
|
||||
infoLogger('ME: Hooking up parent node', shared.safe_json(node))
|
||||
this.parentNode = node
|
||||
const editor = this
|
||||
infoLogger('ME: NODE', shared.safe_json(this.parentNode))
|
||||
|
||||
infoLogger(
|
||||
'ME: NODE KEYS',
|
||||
shared.safe_json(Object.keys(this.parentNode).sort()),
|
||||
)
|
||||
|
||||
|
||||
shared.chainCallback(this.parentNode, 'onExecuted', function (res) {
|
||||
infoLogger('Executed', res)
|
||||
const { error, output_html } = res
|
||||
if (error[0]) {
|
||||
editor.appendOutput(
|
||||
`<div style="color: #f00; font-weight: bold;">Error:</div>${output_html[0]}`,
|
||||
)
|
||||
} else {
|
||||
editor.appendOutput(output_html[0])
|
||||
}
|
||||
})
|
||||
|
||||
shared.chainCallback(this.parentNode, 'onConfigure', function (serial) {
|
||||
shared
|
||||
.infoLogger('ME Node: configure called', { node: this, serial })
|
||||
.notify()
|
||||
|
||||
// editor.setCode(serial.properties.inputCode)
|
||||
// if (serial.properties.uuid) {
|
||||
// editor.uuid = serial.properties.uuid
|
||||
// }
|
||||
|
||||
})
|
||||
shared.chainCallback(this.parentNode, 'onRemoved', function (...serial) {
|
||||
errorLogger('ME Node: removed called TODO', {
|
||||
node: this,
|
||||
serial,
|
||||
})
|
||||
})
|
||||
shared.chainCallback(this.parentNode, 'onSerialize', function (serial) {
|
||||
infoLogger('ME Node: serialize called', {
|
||||
editor,
|
||||
node: this,
|
||||
serial,
|
||||
})
|
||||
|
||||
// if (editor.aceEditor) {
|
||||
// serial.properties.inputCode = editor.aceEditor.getValue()
|
||||
// }
|
||||
|
||||
const uuid_widget = this.widgets.find((e) => e.name === 'uuid')
|
||||
if (uuid_widget) {
|
||||
if (uuid_widget.value) {
|
||||
editor.uuid = uuid_widget.value
|
||||
} else {
|
||||
uuid_widget.value = editor.uuid
|
||||
}
|
||||
}
|
||||
|
||||
// serial.properties.inputHeightRatio = this.properties.inputHeightRatio
|
||||
})
|
||||
|
||||
// shared.chainCallback(this.parentNode,"onResize", function(size) {
|
||||
// editor.container.style.width = `${size[0] - 10}px` // Account for padding
|
||||
// container.style.height = `${size[1] - 10}px`
|
||||
//
|
||||
// })
|
||||
|
||||
infoLogger('ME: callback setup on node')
|
||||
this.debouncedUpdateNodeProperty = shared.debounce(() => {
|
||||
if (this.aceEditor && this.parentNode) {
|
||||
const currentCode = this.aceEditor.getValue()
|
||||
// this.parentNode.setProperty('inputCode', currentCode)
|
||||
this._widget.value = currentCode
|
||||
infoLogger("ME: Node property 'inputCode' updated.")
|
||||
}
|
||||
}, 300)
|
||||
}
|
||||
this.loadAceEditor()
|
||||
}
|
||||
|
||||
setupUI() {
|
||||
this.container = mtb_ui.makeElement('div', {
|
||||
boxSizing: 'border-box',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
fontFamily: 'monospace',
|
||||
height: '100%',
|
||||
padding: '5px',
|
||||
width: '100%',
|
||||
})
|
||||
|
||||
this.inputDiv = mtb_ui.makeElement(
|
||||
'div',
|
||||
{
|
||||
// backgroundColor: '#333',
|
||||
// color: '#eee',
|
||||
// border: '1px solid #555',
|
||||
// borderRadius: '4px',
|
||||
// marginBottom: '5px',
|
||||
boxSizing: 'border-box',
|
||||
minHeight: '100px',
|
||||
width: 'calc(100% - 10px)',
|
||||
// overflow: 'hidden',
|
||||
},
|
||||
this.container,
|
||||
)
|
||||
|
||||
if (this.options.capabilities.execute) {
|
||||
this.handleDiv = mtb_ui.makeElement(
|
||||
'div',
|
||||
{
|
||||
backgroundColor: '#666',
|
||||
borderRadius: '2px',
|
||||
cursor: 'ns-resize',
|
||||
height: '5px',
|
||||
marginBottom: '5px',
|
||||
width: '100%',
|
||||
},
|
||||
this.container,
|
||||
)
|
||||
this.handleDiv.addEventListener(
|
||||
'mousedown',
|
||||
this.startResizing.bind(this),
|
||||
)
|
||||
|
||||
const runButton = mtb_ui.makeElement(
|
||||
'button',
|
||||
{
|
||||
backgroundColor: '#555',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
color: '#fff',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
marginBottom: '5px',
|
||||
padding: '8px',
|
||||
width: '100%',
|
||||
},
|
||||
this.container,
|
||||
)
|
||||
runButton.textContent = 'Run Code (Alt+Enter)'
|
||||
runButton.onclick = () => {
|
||||
// node.__repl('RUN') //node.executeCode()
|
||||
this.executeCode()
|
||||
}
|
||||
const clearButton = mtb_ui.makeElement(
|
||||
'button',
|
||||
{
|
||||
backgroundColor: '#555',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
color: '#fff',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
marginBottom: '5px',
|
||||
padding: '8px',
|
||||
width: '100%',
|
||||
},
|
||||
this.container,
|
||||
)
|
||||
clearButton.textContent = 'Clear Output'
|
||||
clearButton.onclick = () => {
|
||||
this.outputArea.innerHTML = ''
|
||||
// this.properties.outputHistory = ''
|
||||
this.parentNode?.setProperty('outputHistory', '')
|
||||
}
|
||||
|
||||
this.outputArea = mtb_ui.makeElement(
|
||||
'div',
|
||||
{
|
||||
backgroundColor: '#222',
|
||||
border: '1px solid #555',
|
||||
borderRadius: '4px',
|
||||
boxSizing: 'border-box',
|
||||
color: '#ddd',
|
||||
flexGrow: '1',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '14px',
|
||||
overflowY: 'auto',
|
||||
padding: '5px',
|
||||
whiteSpace: 'pre-wrap',
|
||||
width: 'calc(100% - 10px)',
|
||||
},
|
||||
this.container,
|
||||
)
|
||||
|
||||
// augment the node
|
||||
// node.__repl = function (msg) {
|
||||
// console.log('Called msg on api REPl', { msg, node: this })
|
||||
// }
|
||||
// node.setProperty('inputCode', '')
|
||||
// node.title = '🐍 REPL (mtb)'
|
||||
}
|
||||
}
|
||||
get code() {
|
||||
return this._code
|
||||
}
|
||||
async lintCode() {
|
||||
if (this.options.mode !== 'python') {
|
||||
errorLogger('ME: Only python supports lint').notify()
|
||||
return
|
||||
}
|
||||
if (!this.aceEditor) {
|
||||
shared.warnLogger('ME: Ace Editor not loaded yet')
|
||||
return
|
||||
}
|
||||
const code = this.aceEditor.getValue()
|
||||
if (!code.trim()) {
|
||||
this.aceEditor.session.setAnnotations([])
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/mtb/lint', {
|
||||
body: JSON.stringify({ code: code, name: this.uuid }),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
errorLogger('ME: Failed to lint', 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) {
|
||||
errorLogger('ME: Linting Error', e)
|
||||
this.aceEditor.session.setAnnotations([
|
||||
{
|
||||
column: 0,
|
||||
row: 0,
|
||||
text: `Linting failed: ${e.message}`,
|
||||
type: 'error',
|
||||
},
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
setupWidget(name, typeName) {
|
||||
if (this._widget) {
|
||||
throw Error('Widget already setup, this should not happen')
|
||||
}
|
||||
|
||||
this._widget = this.parentNode.addDOMWidget(
|
||||
name,
|
||||
typeName,
|
||||
this.container,
|
||||
{
|
||||
getValue: () => {
|
||||
// infoLogger(
|
||||
// 'Called get value of Code Editor',
|
||||
// node.properties,
|
||||
// editor.code,
|
||||
// )
|
||||
// return 'foobar'
|
||||
// return node.properties.inputCode
|
||||
// return this.parentNode?.properties?.inputCode // editor.code
|
||||
return this.code
|
||||
},
|
||||
hideOnZoom: false,
|
||||
setValue: (v) => {
|
||||
infoLogger('Called set value of Code Editor with:', v)
|
||||
// this.parentNode.setProperty('inputCode', v)
|
||||
this._code = v
|
||||
},
|
||||
},
|
||||
)
|
||||
return this._widget
|
||||
}
|
||||
|
||||
// --- Resizing Logic ---
|
||||
startResizing(e) {
|
||||
if (!this.inputDiv) {
|
||||
infoLogger("The input div isn't ready", this)
|
||||
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.aceEditor || !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.parentNode.setProperty(
|
||||
'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
|
||||
}
|
||||
|
||||
setCode(code) {
|
||||
infoLogger('called set code')
|
||||
this._code = code || this._code
|
||||
if (!this._code) {
|
||||
return
|
||||
}
|
||||
if (this._widget) {
|
||||
this._widget.value = this._code
|
||||
}
|
||||
|
||||
if (this.reference) {
|
||||
this.reference.value = this._code
|
||||
}
|
||||
if (this.aceEditor) {
|
||||
this.aceEditor.setValue(this._code)
|
||||
}
|
||||
// if (this.parentNode) {
|
||||
// this.parentNode.setProperty('inputCode', this._code)
|
||||
// }
|
||||
// TODO: probably shouldn't be auto called depending on the call chain..
|
||||
if (this.options.lint) {
|
||||
this.debouncedLint()
|
||||
}
|
||||
}
|
||||
|
||||
loadAceEditor() {
|
||||
if (window.MTB?.ace_loaded) {
|
||||
if (this.aceEditor) {
|
||||
infoLogger('ACE is already loaded, nothing to do')
|
||||
} else {
|
||||
this.initAceEditor()
|
||||
}
|
||||
return
|
||||
}
|
||||
// NOTE: this need more testing, globals can come from other extensions...
|
||||
//
|
||||
// let NEED_PATCH = false
|
||||
if (window.ace) {
|
||||
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) => {
|
||||
infoLogger('ACE was loaded', m)
|
||||
// window.MTB_ACE = window.ace
|
||||
if (!window.MTB) {
|
||||
// might happen now that we don't control the lifecycle
|
||||
window.MTB = {}
|
||||
}
|
||||
|
||||
window.MTB.ace_loaded = true
|
||||
this.initAceEditor()
|
||||
// this.aceEditor.setValue(this.properties.inputCode, -1)
|
||||
// this.aceEditor.setValue(this.properties.inputCode, -1)
|
||||
this.setCode()
|
||||
})
|
||||
.catch((e) => {
|
||||
errorLogger(`Error loading ace: ${e}`)
|
||||
})
|
||||
.finally(() => {
|
||||
// if (NEED_PATCH) {
|
||||
// console.log('Patching back window object')
|
||||
// window.ace = window._backupAce
|
||||
// }
|
||||
})
|
||||
}
|
||||
|
||||
appendOutput(html) {
|
||||
this.outputArea.innerHTML += html
|
||||
this.outputArea.scrollTop = this.outputArea.scrollHeight
|
||||
|
||||
if (this.parentNode) {
|
||||
const currentHistory = this.parentNode.properties.outputHistory || ''
|
||||
this.parentNode.setProperty('outputHistory', currentHistory + html)
|
||||
}
|
||||
|
||||
this.outputArea.scrollTop = this.outputArea.scrollHeight
|
||||
}
|
||||
|
||||
async executeCode() {
|
||||
if (!this.aceEditor) {
|
||||
infoLogger('Editor is gone, recreating it.')
|
||||
this.initAceEditor()
|
||||
}
|
||||
|
||||
const code = this.aceEditor.getValue()
|
||||
if (!code.trim()) {
|
||||
infoLogger('No code to execute')
|
||||
return
|
||||
}
|
||||
|
||||
const inputPrompt = `<div style="color:#888; margin-top: 10px;">>>> ${code}</div>`
|
||||
|
||||
this.appendOutput(inputPrompt)
|
||||
|
||||
try {
|
||||
const response = await fetch('/mtb/execute', {
|
||||
body: JSON.stringify({ code: code, name: this.uuid, reset: true }),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const result = await response.json()
|
||||
infoLogger('Received from backend', result)
|
||||
const outputHtml = result.output_html || ''
|
||||
const error = result.error
|
||||
|
||||
if (error) {
|
||||
this.appendOutput(
|
||||
`<div style="color: #f00; font-weight: bold;">Error:</div>${outputHtml}`,
|
||||
)
|
||||
} else {
|
||||
this.appendOutput(outputHtml)
|
||||
}
|
||||
} catch (e) {
|
||||
const errorMessage = `<div style="color: #f00;">Frontend Error: ${e.message}</div>`
|
||||
|
||||
this.appendOutput(errorMessage)
|
||||
errorLogger('MTBEditor Backend Error:', e).notify()
|
||||
} finally {
|
||||
// Not clearing
|
||||
// this.inputArea.value = '' // Clear input after execution
|
||||
// this.properties.inputCode = '' // Clear persisted input
|
||||
}
|
||||
}
|
||||
|
||||
initAceEditor() {
|
||||
if (!window.MTB?.ace_loaded) {
|
||||
errorLogger('ACE editor not loaded. Cannot set up editors.')
|
||||
return
|
||||
}
|
||||
|
||||
if (!this.inputDiv) {
|
||||
errorLogger('Input div not found for Ace editor initialization.')
|
||||
return
|
||||
}
|
||||
this.aceEditor = ace.edit(this.inputDiv)
|
||||
this.aceEditor.setTheme(`ace/theme/${this.options.theme || 'dracula'}`) //"ace/theme/monokai", "ace/theme/github"
|
||||
this.aceEditor.session.setMode(`ace/mode/${this.options.mode}`)
|
||||
this.aceEditor.setOptions({
|
||||
autoScrollEditorIntoView: true,
|
||||
behavioursEnabled: true,
|
||||
cursorStyle: 'ace', // "ace" | "slim" | "smooth" | "wide"
|
||||
displayIndentGuides: true,
|
||||
fixedWidthGutter: true,
|
||||
fontFamily: 'monospace',
|
||||
// enableBasicAutocompletion: true,
|
||||
// enableLiveAutocompletion: true,
|
||||
// enableSnippets: true,
|
||||
fontSize: '14px',
|
||||
hasCssTransforms: true,
|
||||
highlightActiveLine: true,
|
||||
highlightSelectedWord: true,
|
||||
scrollPastEnd: 0.5,
|
||||
showPrintMargin: false,
|
||||
tabSize: 4,
|
||||
useSoftTabs: true,
|
||||
wrap: true,
|
||||
})
|
||||
|
||||
// Custom keybinding for Ctrl+Enter
|
||||
// this.aceEditor.commands.addCommand({
|
||||
// name: 'runCode',
|
||||
// bindKey: { win: 'Ctrl-Enter', mac: 'Command-Enter' },
|
||||
// exec: () => this.executeCode(),
|
||||
// })
|
||||
|
||||
// this.addCommand = this.aceEditor.commands.addCommand
|
||||
|
||||
if (this.options.capabilities.execute) {
|
||||
this.aceEditor.commands.addCommand({
|
||||
bindKey: { mac: 'Alt-Enter', win: 'Alt-Enter' },
|
||||
exec: () => this.executeCode(),
|
||||
name: 'runCode',
|
||||
})
|
||||
}
|
||||
|
||||
// Listen for changes to trigger linting
|
||||
// for now keeping it like that but we might just not register
|
||||
// the event at all.
|
||||
this.aceEditor.session.on('change', () => {
|
||||
this.debouncedUpdateNodeProperty()
|
||||
if (this.options.lint) {
|
||||
this.debouncedLint()
|
||||
}
|
||||
})
|
||||
|
||||
infoLogger('ACE editor created', { aceEditor: this.aceEditor })
|
||||
// this.outputArea.scrollTop = this.outputArea.scrollHeight
|
||||
}
|
||||
}
|
||||
|
||||
// the widget
|
||||
// This is a bit hacky and backward but the simplest I could
|
||||
// find for the bidirectionality
|
||||
export const CODE_EDITOR = (node, name, inputData, _app) => {
|
||||
infoLogger('CODE EDITOR NODE NOW', {
|
||||
inputData: shared.safe_json(inputData),
|
||||
node: shared.safe_json(node),
|
||||
})
|
||||
|
||||
const [typeName, options] = inputData
|
||||
|
||||
infoLogger('CODE_EDITOR', { name, node, options })
|
||||
switch (
|
||||
options.lang //(node.type || node.title) {
|
||||
) {
|
||||
case undefined: {
|
||||
shared
|
||||
.errorLogger(
|
||||
'Using CODE_EDITOR without specifying lang is not supported anymore',
|
||||
)
|
||||
.notify()
|
||||
break
|
||||
}
|
||||
// case 'Repl (mtb)': {
|
||||
case 'python': {
|
||||
infoLogger('Handling python editor', { node })
|
||||
|
||||
const editor = new MtbEditor(node, {
|
||||
capabilities: {
|
||||
execute: true, // options.allow_exec
|
||||
},
|
||||
lang: 'python',
|
||||
})
|
||||
infoLogger('MTBEditor created', editor)
|
||||
|
||||
return editor.setupWidget(name, typeName)
|
||||
|
||||
}
|
||||
default: {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
getCustomWidgets: () => {
|
||||
return {
|
||||
CODE_EDITOR,
|
||||
}
|
||||
},
|
||||
name: 'mtb.code_editor',
|
||||
})
|
||||
@@ -0,0 +1,688 @@
|
||||
/// <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 {
|
||||
// defineCSSClass,
|
||||
ensureMTBStyles,
|
||||
makeElement,
|
||||
makeSelect,
|
||||
makeSlider,
|
||||
renderSidebar,
|
||||
} from './mtb_ui.js'
|
||||
|
||||
// pagination state
|
||||
let pageOffset = 0
|
||||
let isLoadingPage = false
|
||||
let hasMorePages = true
|
||||
let pageSizeCache = undefined
|
||||
|
||||
let observer = null
|
||||
// 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)) {
|
||||
const w = node.widgets?.find((w) => w.name === 'image')
|
||||
if (w) {
|
||||
w.value = image
|
||||
w.callback()
|
||||
}
|
||||
} else if (VIDEO_NODES.includes(node.type)) {
|
||||
const w = node.widgets?.find((w) => w.name === 'video')
|
||||
if (w) {
|
||||
node.updateParameters({ filename: image }, true)
|
||||
}
|
||||
} else {
|
||||
console.warn('No method to update', node.type)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
const elem = currentMode === 'video' ? 'video' : 'img'
|
||||
|
||||
for (const [key, url] of Object.entries(urls)) {
|
||||
const a = makeElement(elem)
|
||||
a.src = url
|
||||
a.width = currentWidth
|
||||
if (elem === 'img') {
|
||||
a.loading = 'lazy'
|
||||
a.decoding = 'async'
|
||||
} else {
|
||||
// video
|
||||
a.preload = 'metadata'
|
||||
}
|
||||
if (currentMode === 'input') {
|
||||
a.onclick = (_e) => {
|
||||
if (subfolder !== '') {
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'Subfolder not supported',
|
||||
detail: "The LoadImage node doesn't support subfolders",
|
||||
life: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
const selected = app.canvas.selected_nodes
|
||||
if (selected && Object.keys(selected).length === 0) {
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'No node selected!',
|
||||
detail:
|
||||
'For now the only action when clicking images in the sidebar is to set the image on all selected LoadImage nodes.',
|
||||
life: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
for (const [_id, node] of Object.entries(app.canvas.selected_nodes)) {
|
||||
updateImage(node, key)
|
||||
}
|
||||
}
|
||||
} else if (currentMode === 'output') {
|
||||
a.onclick = async (_e) => {
|
||||
const params = new URLSearchParams()
|
||||
params.set('filename', key)
|
||||
params.set('type', 'output')
|
||||
if (subfolder) params.set('subfolder', subfolder)
|
||||
params.set('workflow', 'true')
|
||||
const url = `/mtb/view?${params.toString()}`
|
||||
try {
|
||||
const res = await api.fetchApi(url)
|
||||
if (!res?.ok) throw new Error(`Request failed (${res?.status})`)
|
||||
const data = await res.json()
|
||||
const workflow = data?.workflow || data?.prompt
|
||||
if (!workflow) {
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'No workflow in image',
|
||||
detail: 'This file does not contain embedded workflow metadata.',
|
||||
life: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Try to import via File first; fallback to blob URL
|
||||
const jsonText = JSON.stringify(workflow, null, 2)
|
||||
const blob = new Blob([jsonText], { type: 'application/json' })
|
||||
const suggestedName = `${(key || 'workflow').replace(/\.[^.]+$/, '')}-workflow.json`
|
||||
let loaded = false
|
||||
try {
|
||||
const file = new File([blob], suggestedName, {
|
||||
type: 'application/json',
|
||||
})
|
||||
await app.handleFile(file)
|
||||
loaded = true
|
||||
} catch (_err) {
|
||||
const blobUrl = URL.createObjectURL(blob)
|
||||
try {
|
||||
await app.handleFile(blobUrl)
|
||||
loaded = true
|
||||
} finally {
|
||||
URL.revokeObjectURL(blobUrl)
|
||||
}
|
||||
}
|
||||
|
||||
if (loaded) {
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'success',
|
||||
summary: 'Workflow loaded',
|
||||
detail: 'Imported workflow from image metadata.',
|
||||
life: 3000,
|
||||
})
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Failed to load workflow from output image:', err)
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'error',
|
||||
summary: 'Import failed',
|
||||
detail: String(err?.message || err),
|
||||
life: 6000,
|
||||
})
|
||||
}
|
||||
}
|
||||
} else {
|
||||
a.autoplay = true
|
||||
|
||||
a.muted = true
|
||||
a.loop = true
|
||||
a.onclick = (_e) => {
|
||||
const selected = app.canvas.selected_nodes
|
||||
if (selected && Object.keys(selected).length === 0) {
|
||||
app.extensionManager.toast.add({
|
||||
severity: 'warn',
|
||||
summary: 'No node selected!',
|
||||
detail:
|
||||
"For now the only action when clicking videos in the sidebar is to set the video on all selected 'Load Video (Upload)' nodes.",
|
||||
life: 5000,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
for (const [_id, node] of Object.entries(app.canvas.selected_nodes)) {
|
||||
updateImage(node, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
imgs.push(a)
|
||||
}
|
||||
if (target !== undefined) {
|
||||
if (options.prepend) target.prepend(...imgs)
|
||||
else target.append(...imgs)
|
||||
}
|
||||
return imgs
|
||||
}
|
||||
|
||||
const getModes = async () => {
|
||||
const inputs = await shared.runAction('getUserImageFolders')
|
||||
return inputs
|
||||
}
|
||||
const getUrls = async (subfolder, countOverride, offsetOverride) => {
|
||||
const count =
|
||||
typeof countOverride === 'number'
|
||||
? countOverride
|
||||
: (await api.getSetting('mtb.io-sidebar.count')) || 1000
|
||||
const offset = typeof offsetOverride === 'number' ? offsetOverride : pageOffset
|
||||
pageSizeCache = count
|
||||
// console.debug('Sidebar count', count, 'offset', offset)
|
||||
if (currentMode === 'video') {
|
||||
const output = await shared.runAction(
|
||||
'getUserVideos',
|
||||
targetWidth,
|
||||
count,
|
||||
offset,
|
||||
currentSort,
|
||||
)
|
||||
return output || {}
|
||||
}
|
||||
const output = await shared.runAction(
|
||||
'getUserImages',
|
||||
currentMode,
|
||||
targetWidth,
|
||||
count,
|
||||
offset,
|
||||
currentSort,
|
||||
false,
|
||||
subfolder,
|
||||
saltUrls,
|
||||
)
|
||||
return output || {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize pagination (loader, end-of-results message, sentinel, and IntersectionObserver)
|
||||
* for the provided grid container. Safely disconnects any previous observer.
|
||||
* @param {HTMLElement} imgGrid
|
||||
*/
|
||||
function initPagination(imgGrid) {
|
||||
// disconnect any existing observer to avoid duplicates
|
||||
if (observer) {
|
||||
try {
|
||||
observer.disconnect()
|
||||
} catch { }
|
||||
observer = null
|
||||
}
|
||||
|
||||
// create footer UI elements
|
||||
const loader = makeElement('div', {}, imgGrid)
|
||||
Object.assign(loader.style, {
|
||||
display: 'none',
|
||||
width: '100%',
|
||||
padding: '8px 0',
|
||||
textAlign: 'center',
|
||||
color: 'var(--mtb-text, #ccc)',
|
||||
fontSize: '12px',
|
||||
})
|
||||
loader.textContent = 'Loading…'
|
||||
|
||||
const endMsg = makeElement('div', {}, imgGrid)
|
||||
Object.assign(endMsg.style, {
|
||||
display: 'none',
|
||||
width: '100%',
|
||||
padding: '8px 0',
|
||||
textAlign: 'center',
|
||||
color: 'var(--mtb-text, #888)',
|
||||
fontSize: '12px',
|
||||
})
|
||||
endMsg.textContent = 'No more items'
|
||||
|
||||
const sentinel = makeElement('div', {}, imgGrid)
|
||||
sentinel.style.height = '1px'
|
||||
sentinel.style.width = '100%'
|
||||
sentinel.style.marginTop = '1px'
|
||||
|
||||
const loadNextPage = async () => {
|
||||
if (isLoadingPage || !hasMorePages) return
|
||||
isLoadingPage = true
|
||||
loader.style.display = 'block'
|
||||
try {
|
||||
const nextUrls = await getUrls(subfolder, undefined, pageOffset)
|
||||
const keys = Object.keys(nextUrls || {})
|
||||
if (!keys.length) {
|
||||
hasMorePages = false
|
||||
if (observer) observer.disconnect()
|
||||
loader.style.display = 'none'
|
||||
endMsg.style.display = 'block'
|
||||
return
|
||||
}
|
||||
getImgsFromUrls(nextUrls, imgGrid)
|
||||
if (pageSizeCache != null) pageOffset += pageSizeCache
|
||||
// keep footer elements and sentinel at the bottom
|
||||
imgGrid.appendChild(loader)
|
||||
imgGrid.appendChild(endMsg)
|
||||
imgGrid.appendChild(sentinel)
|
||||
} catch (e) {
|
||||
console.error('Failed to load next page:', e)
|
||||
hasMorePages = false
|
||||
if (observer) observer.disconnect()
|
||||
loader.style.display = 'none'
|
||||
endMsg.style.display = 'block'
|
||||
} finally {
|
||||
isLoadingPage = false
|
||||
if (hasMorePages) loader.style.display = 'none'
|
||||
}
|
||||
}
|
||||
|
||||
observer = new IntersectionObserver((entries) => {
|
||||
for (const entry of entries) {
|
||||
if (entry.isIntersecting) loadNextPage()
|
||||
}
|
||||
})
|
||||
observer.observe(sentinel)
|
||||
|
||||
}
|
||||
|
||||
//NOTE: do not load if using the old ui
|
||||
if (window?.__COMFYUI_FRONTEND_VERSION__) {
|
||||
// NOTE: removed this for now since I'm not actually exposing anything a client
|
||||
// cannot already access from "/view"...
|
||||
// let exposed = false
|
||||
|
||||
const sidebar_extension = {
|
||||
name: 'mtb.io-sidebar',
|
||||
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)",
|
||||
},
|
||||
{
|
||||
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
|
||||
},
|
||||
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: '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',
|
||||
})
|
||||
|
||||
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
|
||||
},
|
||||
|
||||
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',
|
||||
type: 'combo',
|
||||
|
||||
onChange: (v) => {
|
||||
// alert(`Sort is now ${v}`)
|
||||
currentSort = v
|
||||
},
|
||||
|
||||
defaultValue: 'Modified',
|
||||
// tooltip: "It's recommended to keep it at 512px",
|
||||
options: [
|
||||
'None',
|
||||
'Modified',
|
||||
'Modified-Reverse',
|
||||
'Name',
|
||||
'Name-Reverse',
|
||||
],
|
||||
},
|
||||
{
|
||||
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',
|
||||
icon: 'pi pi-images',
|
||||
title: 'Input & Outputs',
|
||||
tooltip: 'MTB: Browse inputs and outputs directories.',
|
||||
type: 'custom',
|
||||
|
||||
// this is run everytime the tab's diplay is toggled on.
|
||||
render: async (el) => {
|
||||
if (handle) {
|
||||
handle.unregister()
|
||||
handle = undefined
|
||||
}
|
||||
|
||||
if (el.parentNode) {
|
||||
el.parentNode.style.overflowY = 'clip'
|
||||
}
|
||||
|
||||
const allModes = await getModes()
|
||||
const input_modes = allModes.input.map((m) => `input - ${m}`)
|
||||
const output_modes = allModes.output.map((m) => `output - ${m}`)
|
||||
//- reset pagination state for fresh render
|
||||
pageOffset = 0
|
||||
isLoadingPage = false
|
||||
hasMorePages = true
|
||||
const urls = await getUrls(undefined, undefined, 0)
|
||||
if (pageSizeCache != null) pageOffset += pageSizeCache
|
||||
let imgs = {}
|
||||
|
||||
const cont = makeElement('div.mtb_sidebar')
|
||||
|
||||
const imgGrid = makeElement('div.mtb_img_grid')
|
||||
const selector = makeSelect(
|
||||
['input', 'output', 'video', ...output_modes, ...input_modes],
|
||||
currentMode,
|
||||
)
|
||||
|
||||
selector.addEventListener('change', async (e) => {
|
||||
let newMode = e.target.value
|
||||
let changed = false
|
||||
let newSub = ''
|
||||
if (newMode !== 'input' && newMode !== 'output') {
|
||||
if (newMode.startsWith('input - ')) {
|
||||
newSub = newMode.replace('input - ', '')
|
||||
newMode = 'input'
|
||||
} else if (newMode.startsWith('output - ')) {
|
||||
newSub = newMode.replace('output - ', '')
|
||||
newMode = 'output'
|
||||
}
|
||||
}
|
||||
changed = newMode !== currentMode || newSub !== subfolder
|
||||
currentMode = newMode
|
||||
subfolder = newSub
|
||||
if (changed) {
|
||||
imgGrid.innerHTML = ''
|
||||
//- reset pagination on mode change
|
||||
pageOffset = 0
|
||||
isLoadingPage = false
|
||||
hasMorePages = true
|
||||
const urls = await getUrls(subfolder, undefined, 0)
|
||||
if (pageSizeCache != null) pageOffset += pageSizeCache
|
||||
if (urls) {
|
||||
imgs = getImgsFromUrls(urls, imgGrid)
|
||||
}
|
||||
// re-init pagination after content reset
|
||||
initPagination(imgGrid)
|
||||
}
|
||||
})
|
||||
|
||||
const imgTools = makeElement('div.mtb_tools')
|
||||
const orderSelect = makeSelect(
|
||||
['None', 'Modified', 'Modified-Reverse', 'Name', 'Name-Reverse'],
|
||||
currentSort,
|
||||
)
|
||||
|
||||
orderSelect.addEventListener('change', async (e) => {
|
||||
const newSort = e.target.value
|
||||
const changed = newSort !== currentSort
|
||||
currentSort = newSort
|
||||
if (changed) {
|
||||
imgGrid.innerHTML = ''
|
||||
//- reset pagination on sort change
|
||||
pageOffset = 0
|
||||
isLoadingPage = false
|
||||
hasMorePages = true
|
||||
const urls = await getUrls(subfolder, undefined, 0)
|
||||
if (pageSizeCache != null) pageOffset += pageSizeCache
|
||||
if (urls) {
|
||||
imgs = getImgsFromUrls(urls, imgGrid)
|
||||
}
|
||||
// re-init pagination after content reset
|
||||
initPagination(imgGrid)
|
||||
}
|
||||
})
|
||||
|
||||
const sizeSlider = makeSlider(64, 1024, currentWidth, 1)
|
||||
imgTools.appendChild(orderSelect)
|
||||
imgTools.appendChild(sizeSlider)
|
||||
|
||||
imgs = getImgsFromUrls(urls, imgGrid)
|
||||
// Setup infinite pagination for the initial render
|
||||
initPagination(imgGrid)
|
||||
|
||||
let pendingWidth = null
|
||||
let rafToken = null
|
||||
sizeSlider.addEventListener('input', (e) => {
|
||||
pendingWidth = e.target.value
|
||||
if (rafToken) return
|
||||
rafToken = requestAnimationFrame(() => {
|
||||
rafToken = null
|
||||
if (pendingWidth == null) return
|
||||
currentWidth = pendingWidth
|
||||
pendingWidth = null
|
||||
for (const img of imgs) {
|
||||
img.style.width = `${currentWidth}px`
|
||||
}
|
||||
})
|
||||
})
|
||||
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')
|
||||
}
|
||||
// Attempt to disconnect any stray observers to avoid retained callbacks
|
||||
if (observer) observer.disconnect()
|
||||
},
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
app.registerExtension(sidebar_extension)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** Python REPL for the frontend (uses rich)*/
|
||||
|
||||
import { app } from '../../scripts/app.js'
|
||||
|
||||
// import * as mtb_ui from './mtb_ui.js'
|
||||
|
||||
// #endregion
|
||||
|
||||
const repl = {
|
||||
name: 'mtb.repl',
|
||||
|
||||
// async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
}
|
||||
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
/**
|
||||
* Adds a named stylesheet to the document with an optional ability to replace an existing one.
|
||||
*
|
||||
* @param {string} name - The unique name (ID) of the stylesheet.
|
||||
* @param {string} css - The CSS rules as a string.
|
||||
* @param {boolean} [force=false] - Whether to replace the existing stylesheet if it exists.
|
||||
* @returns {void}
|
||||
*/
|
||||
export function addNamedStyleSheet(name, css, force = false) {
|
||||
const existingStyleSheet = document.getElementById(name)
|
||||
|
||||
if (existingStyleSheet && !force) {
|
||||
console.debug(
|
||||
`Stylesheet with name "${name}" already exists. Skipping addition.`,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
if (existingStyleSheet && force) {
|
||||
console.debug(`Stylesheet with name "${name}" exists. Replacing...`)
|
||||
existingStyleSheet.remove()
|
||||
}
|
||||
|
||||
const styleElement = document.createElement('style')
|
||||
styleElement.id = name
|
||||
styleElement.type = 'text/css'
|
||||
|
||||
styleElement.appendChild(document.createTextNode(css))
|
||||
document.head.appendChild(styleElement)
|
||||
|
||||
console.debug(`Stylesheet with name "${name}" added.`)
|
||||
}
|
||||
|
||||
export const ensureMTBStyles = () => {
|
||||
const S = {
|
||||
fg: 'var(--fg-color)',
|
||||
bgi: 'var(--comfy-input-bg)',
|
||||
bgm: 'var(--comfy-menu-bg)',
|
||||
border: 'var(--comfy-border)',
|
||||
borderHover: 'var(--comfy-border-hover)',
|
||||
box: 'var(--comfy-box)',
|
||||
accent: 'var(--p-button-text-primary-color)',
|
||||
}
|
||||
const common = `
|
||||
.mtb_sidebar {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: ${S.bgm};
|
||||
}
|
||||
.mtb_img_grid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
overflow: scroll;
|
||||
gap: 1em;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
}
|
||||
.mtb_tools {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
}
|
||||
`
|
||||
const inputs = `
|
||||
/* SELECT */
|
||||
.mtb_select {
|
||||
appearance: none;
|
||||
display: grid;
|
||||
grid-template-areas: "select";
|
||||
padding: 10px;
|
||||
background-color: ${S.bgi};
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
font-size: 14px;
|
||||
color: ${S.fg};
|
||||
cursor: pointer;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
@supports (-moz-appearance:none) {
|
||||
.mtb_select{
|
||||
grid-area: select;
|
||||
background: ${S.bgi} url('data:image/gif;base64,R0lGODlhBgAGAKEDAFVVVX9/f9TU1CgmNyH5BAEKAAMALAAAAAAGAAYAAAIODA4hCDKWxlhNvmCnGwUAOw==') right center no-repeat !important;
|
||||
background-position: calc(100% - 5px) center !important;
|
||||
-moz-appearance:none !important;
|
||||
}
|
||||
|
||||
/* styling the dropdown arrow for browsers that support it */
|
||||
.mtb_select:after {
|
||||
content: "";
|
||||
width: 0.8em;
|
||||
height: 0.5em;
|
||||
background-color: ${S.fg};
|
||||
clip-path: polygon(100% 0%, 0 0%, 50% 100%);
|
||||
}
|
||||
|
||||
.mtb_select:focus {
|
||||
outline: none;
|
||||
border-color: #0056b3;
|
||||
}
|
||||
|
||||
.mtb_select > option {
|
||||
padding: 10px;
|
||||
background-color: ${S.bgi};
|
||||
border:none;
|
||||
color: ${S.fg};
|
||||
}
|
||||
|
||||
.mtb_select > option:hover {
|
||||
background-color: red;
|
||||
color: ${S.fg};
|
||||
}
|
||||
|
||||
/* SLIDER */
|
||||
.mtb_slider[type="range"] {
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
background: ${S.bgm};
|
||||
border-radius: 5px;
|
||||
outline: none;
|
||||
opacity: 0.7;
|
||||
transition: opacity .2s;
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
/* slider track */
|
||||
.mtb_slider[type="range"]::-webkit-slider-runnable-track,
|
||||
.mtb_slider[type="range"]::-moz-range-track {
|
||||
width: 100%;
|
||||
height: 10px;
|
||||
background: ${S.bgi};
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
|
||||
/* progress */
|
||||
.mtb_slider[type="range"]::-moz-range-progress {
|
||||
background-color: ${S.accent};
|
||||
height:10px;
|
||||
border-radius: 5px;
|
||||
}
|
||||
|
||||
/* slider thumb (the handle) */
|
||||
.mtb_slider[type="range"]::-webkit-slider-thumb,
|
||||
.mtb_slider[type="range"]::-moz-range-thumb
|
||||
{
|
||||
-webkit-appearance: none;
|
||||
appearance: none;
|
||||
width: 15px;
|
||||
height: 15px;
|
||||
border-radius: 50%;
|
||||
background: ${S.fg};
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
filter: drop-shadow(1px 1px 4px black);
|
||||
}
|
||||
|
||||
.mtb_slider[type="range"]:focus {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.mtb_slider[type=range]:-moz-focusring{
|
||||
outline: 1px solid red;
|
||||
outline-offset: -1px;
|
||||
}
|
||||
|
||||
.mtb_slider[type="range"]:hover::-webkit-slider-thumb,
|
||||
.mtb_slider[type="range"]:active::-webkit-slider-thumb {
|
||||
background-color: ${S.accent};
|
||||
}
|
||||
`
|
||||
addNamedStyleSheet(
|
||||
'mtb_ui',
|
||||
`
|
||||
${common}
|
||||
${inputs}
|
||||
`,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* @param {string} kind - The tag name of the element. Supports class and id syntax (e.g. 'div.class#id').
|
||||
* @param {Object} [style] - CSS styles to apply to the element.
|
||||
* @returns {HTMLElement} - The created DOM element.
|
||||
*/
|
||||
export const makeElement = (kind, style, parent) => {
|
||||
let [real_kind, className] = kind.split('.')
|
||||
let id
|
||||
|
||||
if (className?.includes('#')) {
|
||||
;[className, id] = className.split('#')
|
||||
}
|
||||
|
||||
const el = document.createElement(real_kind)
|
||||
|
||||
if (style) {
|
||||
Object.assign(el.style, style)
|
||||
}
|
||||
|
||||
if (className) {
|
||||
el.classList.add(...className.split(' ')) // Support multiple classes
|
||||
}
|
||||
|
||||
if (id) {
|
||||
el.id = id
|
||||
}
|
||||
if (parent) {
|
||||
parent.appendChild(el)
|
||||
}
|
||||
|
||||
return el
|
||||
}
|
||||
/**
|
||||
* Clears all child elements of the given parent element.
|
||||
*
|
||||
* @param {HTMLElement} el - The parent element whose children should be removed.
|
||||
*/
|
||||
export const clearElement = (el) => {
|
||||
while (el.firstChild) {
|
||||
el.removeChild(el.firstChild)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Creates a labeled element (input, select, etc.).
|
||||
*
|
||||
* @param {HTMLElement} el - The element to label.
|
||||
* @param {string} labelText - The label text.
|
||||
* @returns {HTMLDivElement} - A div containing the label and the element.
|
||||
*/
|
||||
export const makeLabeledElement = (el, labelText) => {
|
||||
const wrapper = makeElement('div.mtb_labeled_element', {
|
||||
marginBottom: '1em',
|
||||
})
|
||||
const label = makeElement('label', {
|
||||
display: 'block',
|
||||
marginBottom: '0.5em',
|
||||
})
|
||||
label.textContent = labelText
|
||||
wrapper.appendChild(label)
|
||||
wrapper.appendChild(el)
|
||||
return wrapper
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a camelCase CSS property to kebab-case.
|
||||
*
|
||||
* @param {string} prop - The camelCase CSS property.
|
||||
* @returns {string} - The kebab-case CSS property.
|
||||
*/
|
||||
const camelToKebab = (prop) =>
|
||||
prop.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`)
|
||||
|
||||
/**
|
||||
* Parses the style string into an object of CSS property-value pairs.
|
||||
*
|
||||
* @param {string} styleString - The CSS rule text (e.g., "color: red; background-color: blue;").
|
||||
* @returns {Object} - An object with camelCase CSS properties.
|
||||
*/
|
||||
const parseStyleString = (styleString) => {
|
||||
const styleObj = {}
|
||||
for (const rule of styleString.split(';')) {
|
||||
const [property, value] = rule.split(':').map((item) => item.trim())
|
||||
if (property && value) {
|
||||
const camelProp = property.replace(/-([a-z])/g, (g) => g[1].toUpperCase())
|
||||
styleObj[camelProp] = value
|
||||
}
|
||||
}
|
||||
return styleObj
|
||||
}
|
||||
|
||||
/**
|
||||
* Defines a new CSS class with the provided styles, or skips if the class already exists.
|
||||
*
|
||||
* @param {string} className - The name of the CSS class to define.
|
||||
* @param {Object} classStyles - An object containing camelCase CSS property-value pairs.
|
||||
*/
|
||||
export function defineCSSClass(className, classStyles) {
|
||||
const styleSheets = document.styleSheets
|
||||
let classExists = false
|
||||
let existingStyleString = ''
|
||||
const classExistsInStyleSheet = (styleSheet) => {
|
||||
const rules = styleSheet.rules || styleSheet.cssRules
|
||||
for (const rule of rules) {
|
||||
if (rule.selectorText === `.${className}`) {
|
||||
classExists = true
|
||||
existingStyleString = rule.style.cssText // Capture existing styles
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
for (const styleSheet of styleSheets) {
|
||||
if (classExistsInStyleSheet(styleSheet)) {
|
||||
console.debug(`Class ${className} already exists, merging styles...`)
|
||||
break
|
||||
}
|
||||
}
|
||||
const existingStyles = classExists
|
||||
? parseStyleString(existingStyleString)
|
||||
: {}
|
||||
const mergedStyles = { ...existingStyles, ...classStyles }
|
||||
|
||||
const stylesString = Object.entries(mergedStyles)
|
||||
.map(([key, value]) => `${camelToKebab(key)}: ${value};`)
|
||||
.join(' ')
|
||||
|
||||
if (!classExists) {
|
||||
console.debug(`Defining new class ${className}...`)
|
||||
if (styleSheets[0].insertRule) {
|
||||
styleSheets[0].insertRule(`.${className} { ${stylesString} }`, 0)
|
||||
} else if (styleSheets[0].addRule) {
|
||||
styleSheets[0].addRule(`.${className}`, stylesString, 0)
|
||||
}
|
||||
} else {
|
||||
console.debug(`Updating existing class ${className} with merged styles...`)
|
||||
for (const styleSheet of styleSheets) {
|
||||
const rules = styleSheet.rules || styleSheet.cssRules
|
||||
for (const rule of rules) {
|
||||
if (rule.selectorText === `.${className}`) {
|
||||
rule.style.cssText = stylesString // Update the existing rule
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.debug(
|
||||
`Class ${className} has been defined/updated with styles:`,
|
||||
mergedStyles,
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a sidebar and ensures it resizes correctly when the window is resized.
|
||||
*
|
||||
* @param {HTMLElement} el - The element where the sidebar is rendered.
|
||||
* @param {HTMLElement} cont - The content container of the sidebar.
|
||||
* @param {HTMLElement[]} elems - Array of elements to append to the sidebar.
|
||||
* @returns {Object} - A handle with a method to unregister the resize event.
|
||||
*/
|
||||
export const renderSidebar = (el, cont, elems) => {
|
||||
el.appendChild(cont)
|
||||
|
||||
if (!el.parentNode) {
|
||||
return
|
||||
}
|
||||
el.parentNode.style.overflowY = 'clip'
|
||||
cont.style.height = `${el.parentNode.offsetHeight}px`
|
||||
|
||||
const resizeHandler = () => {
|
||||
cont.style.height = `${el.parentNode.offsetHeight}px`
|
||||
}
|
||||
window.addEventListener('resize', resizeHandler)
|
||||
|
||||
for (const elem of elems) {
|
||||
cont.appendChild(elem)
|
||||
}
|
||||
|
||||
return {
|
||||
unregister: () => {
|
||||
window.removeEventListener('resize', resizeHandler)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a <select> dropdown with given options.
|
||||
*
|
||||
* @param {string[]} options - The options for the select element.
|
||||
* @param {string} [current] - The currently selected option (optional).
|
||||
* @returns {HTMLSelectElement} - The created <select> element.
|
||||
*/
|
||||
export const makeSelect = (options, current = undefined) => {
|
||||
const selector = makeElement('select.mtb_select', {
|
||||
width: 'auto',
|
||||
margin: '1em',
|
||||
})
|
||||
|
||||
for (const option of options) {
|
||||
const opt = makeElement('option')
|
||||
opt.value = option
|
||||
opt.innerHTML = option
|
||||
selector.appendChild(opt)
|
||||
}
|
||||
|
||||
if (current !== undefined) {
|
||||
if (options.includes(current)) {
|
||||
selector.value = current
|
||||
} else {
|
||||
console.error(
|
||||
`You tried to select an option that doesn't exist (${current}). Options: ${options}`,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return selector
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an <input type="range"> slider element with given parameters.
|
||||
*
|
||||
* @param {number} min - Minimum value of the slider.
|
||||
* @param {number} max - Maximum value of the slider.
|
||||
* @param {number} [value] - Initial value of the slider.
|
||||
* @param {number} [step] - Step value for the slider.
|
||||
* @returns {HTMLInputElement} - The created slider element.
|
||||
*/
|
||||
export const makeSlider = (min, max, value = undefined, step = undefined) => {
|
||||
const slider = makeElement('input.mtb_slider', {
|
||||
width: '100%',
|
||||
})
|
||||
|
||||
slider.type = 'range'
|
||||
slider.min = min || 0
|
||||
slider.max = max || 100
|
||||
slider.value = value || slider.min
|
||||
slider.step = step || 1
|
||||
|
||||
return slider
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a button element.
|
||||
*
|
||||
* @param {string} label - The label for the button.
|
||||
* @param {Object} [style] - Optional styles to apply to the button.
|
||||
* @param {Function} [onClick] - Optional click handler.
|
||||
* @returns {HTMLButtonElement} - The created button element.
|
||||
*/
|
||||
export const makeButton = (label, style = {}, onClick = undefined) => {
|
||||
const button = makeElement('button.mtb_button', style)
|
||||
button.textContent = label
|
||||
|
||||
if (onClick) {
|
||||
button.addEventListener('click', onClick)
|
||||
}
|
||||
|
||||
return button
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a resizable splitter between two elements.
|
||||
*
|
||||
* @param {HTMLElement} el1 - The first element.
|
||||
* @param {HTMLElement} el2 - The second element.
|
||||
* @param {'vertical' | 'horizontal'} direction - Splitter direction (vertical or horizontal).
|
||||
* @param {'absolute' | 'normal'} mode - Splitter mode: 'absolute' for free resizing, 'normal' for layout-based resizing.
|
||||
* @returns {HTMLDivElement} - The container with resizable splitter.
|
||||
*/
|
||||
export const makeSplitter = (
|
||||
el1,
|
||||
el2,
|
||||
direction = 'vertical',
|
||||
mode = 'normal',
|
||||
) => {
|
||||
const container = makeElement('div.mtb_splitter_container', {
|
||||
display: mode === 'absolute' ? 'block' : 'flex',
|
||||
flexDirection: direction === 'vertical' ? 'row' : 'column',
|
||||
position: mode === 'absolute' ? 'relative' : 'static',
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
})
|
||||
|
||||
const handle = makeElement('div.mtb_splitter_handle', {
|
||||
backgroundColor: '#ccc',
|
||||
cursor: direction === 'vertical' ? 'col-resize' : 'row-resize',
|
||||
width: direction === 'vertical' ? '5px' : '100%',
|
||||
height: direction === 'horizontal' ? '5px' : '100%',
|
||||
})
|
||||
|
||||
let isResizing = false
|
||||
|
||||
handle.addEventListener('mousedown', () => {
|
||||
isResizing = true
|
||||
})
|
||||
|
||||
window.addEventListener('mouseup', () => {
|
||||
isResizing = false
|
||||
})
|
||||
|
||||
window.addEventListener('mousemove', (e) => {
|
||||
if (!isResizing) return
|
||||
if (direction === 'vertical') {
|
||||
const newWidth = e.clientX - container.offsetLeft
|
||||
el1.style.width = `${newWidth}px`
|
||||
el2.style.width = `${container.offsetWidth - newWidth}px`
|
||||
} else {
|
||||
const newHeight = e.clientY - container.offsetTop
|
||||
el1.style.height = `${newHeight}px`
|
||||
el2.style.height = `${container.offsetHeight - newHeight}px`
|
||||
}
|
||||
})
|
||||
|
||||
container.appendChild(el1)
|
||||
container.appendChild(handle)
|
||||
container.appendChild(el2)
|
||||
|
||||
return container
|
||||
}
|
||||
+389
-133
@@ -14,13 +14,14 @@
|
||||
import { app } from '../../scripts/app.js'
|
||||
import { api } from '../../scripts/api.js'
|
||||
|
||||
import * as mtb_ui from './mtb_ui.js'
|
||||
import parseCss from './extern/parse-css.js'
|
||||
import * as shared from './comfy_shared.js'
|
||||
import { infoLogger } from './comfy_shared.js'
|
||||
import { NumberInputWidget } from './numberInput.js'
|
||||
|
||||
// NOTE: new widget types registered by MTB Widgets
|
||||
const newTypes = [/*'BOOL'*/ , 'COLOR', 'BBOX']
|
||||
const newTypes = [/*'BOOL'*/ 'COLOR', 'MTB_COLOR', 'BBOX']
|
||||
|
||||
const deprecated_nodes = {
|
||||
// 'Animation Builder':
|
||||
@@ -96,7 +97,7 @@ export function addVectorWidgetW(
|
||||
name,
|
||||
value,
|
||||
vector_size,
|
||||
callback,
|
||||
_callback,
|
||||
app,
|
||||
) {
|
||||
// const inputEl = document.createElement('div')
|
||||
@@ -119,7 +120,7 @@ export function addVectorWidgetW(
|
||||
'number',
|
||||
`${name}_${VECTOR_AXIS[i]}`,
|
||||
value[VECTOR_AXIS[i]],
|
||||
(val) => {},
|
||||
(val) => { },
|
||||
)
|
||||
|
||||
inputs.push(input)
|
||||
@@ -243,7 +244,7 @@ export const MtbWidgets = {
|
||||
y: 0,
|
||||
options: { default: Array.from({ length: size }, () => 0.0) },
|
||||
_value: val || Array.from({ length: size }, () => 0.0),
|
||||
draw: function (ctx, node, width, widgetY, height) {
|
||||
draw: (ctx, node, width, widgetY, height) => {
|
||||
ctx.textAlign = 'left'
|
||||
ctx.strokeStyle = outline_color
|
||||
ctx.fillStyle = background_color
|
||||
@@ -311,7 +312,7 @@ export const MtbWidgets = {
|
||||
value: val?.default || [0, 0, 0, 0],
|
||||
options: {},
|
||||
|
||||
draw: function (ctx, node, widget_width, widgetY, height) {
|
||||
draw: function (ctx, _node, widget_width, widgetY, _height) {
|
||||
const hide = this.type !== 'BBOX' && app.canvas.ds.scale > 0.5
|
||||
|
||||
const show_text = true
|
||||
@@ -321,13 +322,13 @@ export const MtbWidgets = {
|
||||
const secondary_text_color = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR
|
||||
const H = LiteGraph.NODE_WIDGET_HEIGHT
|
||||
|
||||
let margin = 15
|
||||
let numWidgets = 4 // Number of stacked widgets
|
||||
const margin = 15
|
||||
const numWidgets = 4 // Number of stacked widgets
|
||||
|
||||
if (hide) return
|
||||
|
||||
for (let i = 0; i < numWidgets; i++) {
|
||||
let currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
|
||||
const currentY = widgetY + i * (H + margin) // Adjust Y position for each widget
|
||||
|
||||
ctx.textAlign = 'left'
|
||||
ctx.strokeStyle = outline_color
|
||||
@@ -447,7 +448,7 @@ export const MtbWidgets = {
|
||||
try {
|
||||
//solve the equation if possible
|
||||
v = eval(v)
|
||||
} catch (e) {}
|
||||
} catch (e) { }
|
||||
}
|
||||
this.value = Number(v)
|
||||
shared.inner_value_change(this, this.value, event)
|
||||
@@ -535,21 +536,34 @@ export const MtbWidgets = {
|
||||
picker.type = 'color'
|
||||
picker.value = this.value
|
||||
|
||||
picker.style.position = 'absolute'
|
||||
picker.style.left = '999999px' //(window.innerWidth / 2) + "px";
|
||||
picker.style.top = '999999px' //(window.innerHeight / 2) + "px";
|
||||
Object.assign(picker.style, {
|
||||
position: 'fixed',
|
||||
left: `${e.clientX}px`,
|
||||
top: `${e.clientY}px`,
|
||||
height: '0px',
|
||||
width: '0px',
|
||||
padding: '0px',
|
||||
opacity: 0,
|
||||
})
|
||||
|
||||
picker.addEventListener('blur', () => {
|
||||
this.callback?.(this.value)
|
||||
node.graph._version++
|
||||
picker.remove()
|
||||
})
|
||||
picker.addEventListener('input', () => {
|
||||
if (!picker.value) return
|
||||
|
||||
this.value = picker.value
|
||||
app.canvas.setDirty(true)
|
||||
})
|
||||
|
||||
document.body.appendChild(picker)
|
||||
|
||||
picker.addEventListener('change', () => {
|
||||
this.value = picker.value
|
||||
this.callback?.(this.value)
|
||||
node.graph._version++
|
||||
node.setDirtyCanvas(true, true)
|
||||
picker.remove()
|
||||
requestAnimationFrame(() => {
|
||||
picker.showPicker()
|
||||
picker.focus()
|
||||
})
|
||||
|
||||
picker.click()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -658,29 +672,38 @@ const mtb_widgets = {
|
||||
init: async () => {
|
||||
infoLogger('Registering mtb.widgets')
|
||||
try {
|
||||
const res = await api.fetchApi('/mtb/debug')
|
||||
const msg = await res.json()
|
||||
const msg = await shared.getServerInfo()
|
||||
if (!window.MTB) {
|
||||
window.MTB = {}
|
||||
}
|
||||
window.MTB.DEBUG = msg.enabled
|
||||
window.MTB.DEBUG = msg.debug
|
||||
} catch (e) {
|
||||
console.error('Error:', error)
|
||||
console.error('Error:', e)
|
||||
}
|
||||
},
|
||||
|
||||
setup: () => {
|
||||
app.ui.settings.addSetting({
|
||||
id: 'mtb.Debug.enabled',
|
||||
name: '[⚡mtb] Enable Debug (py and js)',
|
||||
id: 'mtb.postshot.path',
|
||||
category: ['mtb', 'PostShot', 'path'],
|
||||
name: 'Path to Postshot CLI',
|
||||
type: 'string',
|
||||
defaultValue: 'C:/Program Files/Jawset Postshot/bin/postshot-cli.exe',
|
||||
tooltip: 'The path to the postshot CLI',
|
||||
})
|
||||
|
||||
app.ui.settings.addSetting({
|
||||
id: 'mtb.Main.debug-enabled',
|
||||
category: ['mtb', ' Main', 'debug-enabled'],
|
||||
name: 'Enable Debug (py and js)',
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
|
||||
tooltip:
|
||||
'This will enable debug messages in the console and in the python console respectively',
|
||||
'This will enable debug messages in the console and in the python console respectively, no need to restart the server, but do reload the webui',
|
||||
attrs: {
|
||||
style: {
|
||||
fontFamily: 'monospace',
|
||||
// fontFamily: 'monospace',
|
||||
},
|
||||
},
|
||||
async onChange(value) {
|
||||
@@ -692,37 +715,30 @@ const mtb_widgets = {
|
||||
infoLogger('Enabled DEBUG mode')
|
||||
}
|
||||
|
||||
await api
|
||||
.fetchApi('/mtb/debug', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
enabled: value,
|
||||
}),
|
||||
})
|
||||
.then((_response) => {})
|
||||
.catch((error) => {
|
||||
console.error('Error:', error)
|
||||
})
|
||||
try {
|
||||
shared.setServerInfo({ debug: value })
|
||||
} catch (err) {
|
||||
console.error('Error:', err)
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
getCustomWidgets: () => {
|
||||
return {
|
||||
BOOL: (node, inputName, inputData, _app) => {
|
||||
console.debug('Registering bool')
|
||||
|
||||
return {
|
||||
widget: node.addCustomWidget(
|
||||
MtbWidgets.BOOL(inputName, inputData[1]?.default || false),
|
||||
),
|
||||
minWidth: 150,
|
||||
minHeight: 30,
|
||||
}
|
||||
},
|
||||
// BOOL: (node, inputName, inputData, _app) => {
|
||||
// console.debug('Registering bool')
|
||||
//
|
||||
// return {
|
||||
// widget: node.addCustomWidget(
|
||||
// MtbWidgets.BOOL(inputName, inputData[1]?.default || false),
|
||||
// ),
|
||||
// minWidth: 150,
|
||||
// minHeight: 30,
|
||||
// }
|
||||
// },
|
||||
|
||||
COLOR: (node, inputName, inputData, _app) => {
|
||||
console.debug('Registering color')
|
||||
return {
|
||||
widget: node.addCustomWidget(
|
||||
MtbWidgets.COLOR(inputName, inputData[1]?.default || '#ff0000'),
|
||||
@@ -731,6 +747,16 @@ const mtb_widgets = {
|
||||
minHeight: 30,
|
||||
}
|
||||
},
|
||||
MTB_COLOR: (node, inputName, inputData, _app) => {
|
||||
return {
|
||||
widget: node.addCustomWidget(
|
||||
MtbWidgets.COLOR(inputName, inputData[1]?.default || '#ff0000'),
|
||||
),
|
||||
minWidth: 150,
|
||||
minHeight: 30,
|
||||
}
|
||||
},
|
||||
|
||||
// BBOX: (node, inputName, inputData, app) => {
|
||||
// console.debug("Registering bbox")
|
||||
// return {
|
||||
@@ -751,7 +777,7 @@ const mtb_widgets = {
|
||||
// const rinputs = nodeData.input?.required
|
||||
|
||||
let has_custom = false
|
||||
if (nodeData.input && nodeData.input.required) {
|
||||
if (nodeData.input?.required) {
|
||||
for (const i of Object.keys(nodeData.input.required)) {
|
||||
const input_type = nodeData.input.required[i][0]
|
||||
|
||||
@@ -764,10 +790,8 @@ const mtb_widgets = {
|
||||
if (has_custom) {
|
||||
//- Add widgets on node creation
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
nodeType.prototype.onNodeCreated = function (...args) {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
|
||||
this.serialize_widgets = true
|
||||
this.setSize?.(this.computeSize())
|
||||
|
||||
@@ -785,8 +809,8 @@ const mtb_widgets = {
|
||||
? origGetExtraMenuOptions.apply(this, arguments)
|
||||
: undefined
|
||||
if (this.widgets) {
|
||||
let toInput = []
|
||||
let toWidget = []
|
||||
const toInput = []
|
||||
const toWidget = []
|
||||
for (const w of this.widgets) {
|
||||
if (w.type === shared.CONVERTED_TYPE) {
|
||||
//- This is already handled by widgetinputs.js
|
||||
@@ -832,7 +856,8 @@ const mtb_widgets = {
|
||||
//- Extending Python Nodes
|
||||
switch (nodeData.name) {
|
||||
//TODO: remove this non sense
|
||||
case 'Get Batch From History (mtb)': {
|
||||
case 'Get Batch From History (mtb)':
|
||||
case 'Get Batch From History V2 (mtb)': {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this, []) : undefined
|
||||
@@ -855,6 +880,22 @@ const mtb_widgets = {
|
||||
|
||||
break
|
||||
}
|
||||
case 'Postshot Train (mtb)':
|
||||
case 'Postshot Export (mtb)': {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function (...args) {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
|
||||
const { postshot_cli } = shared.getNamedWidget(this, 'postshot_cli')
|
||||
|
||||
shared.hideWidgetForGood(this, postshot_cli)
|
||||
|
||||
api.getSetting('mtb.postshot.path').then((p) => {
|
||||
postshot_cli._value = p
|
||||
})
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
case 'Save Gif (mtb)':
|
||||
case 'Save Animated Image (mtb)': {
|
||||
const onExecuted = nodeType.prototype.onExecuted
|
||||
@@ -877,7 +918,7 @@ const mtb_widgets = {
|
||||
imgURLs = imgURLs.concat(
|
||||
message.gif.map((params) => {
|
||||
return api.apiURL(
|
||||
'/view?' + new URLSearchParams(params).toString(),
|
||||
`/view?${new URLSearchParams(params).toString()}`,
|
||||
)
|
||||
}),
|
||||
)
|
||||
@@ -886,7 +927,7 @@ const mtb_widgets = {
|
||||
imgURLs = imgURLs.concat(
|
||||
message.apng.map((params) => {
|
||||
return api.apiURL(
|
||||
'/view?' + new URLSearchParams(params).toString(),
|
||||
`/view?${new URLSearchParams(params).toString()}`,
|
||||
)
|
||||
}),
|
||||
)
|
||||
@@ -914,37 +955,73 @@ const mtb_widgets = {
|
||||
}
|
||||
case 'Animation Builder (mtb)': {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
nodeType.prototype.onNodeCreated = function (...args) {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this, args) : undefined
|
||||
|
||||
this.changeMode(LiteGraph.ALWAYS)
|
||||
|
||||
const raw_iteration = this.widgets.find(
|
||||
(w) => w.name === 'raw_iteration',
|
||||
)
|
||||
const raw_loop = this.widgets.find((w) => w.name === 'raw_loop')
|
||||
|
||||
const total_frames = this.widgets.find(
|
||||
(w) => w.name === 'total_frames',
|
||||
)
|
||||
const loop_count = this.widgets.find((w) => w.name === 'loop_count')
|
||||
const { raw_iteration, raw_loop, total_frames, loop_count } =
|
||||
shared.getNamedWidget(
|
||||
this,
|
||||
'raw_iteration',
|
||||
'raw_loop',
|
||||
'total_frames',
|
||||
'loop_count',
|
||||
)
|
||||
|
||||
shared.hideWidgetForGood(this, raw_iteration)
|
||||
shared.hideWidgetForGood(this, raw_loop)
|
||||
|
||||
raw_iteration._value = 0
|
||||
|
||||
const value_preview = this.addCustomWidget(
|
||||
MtbWidgets['DEBUG_STRING']('value_preview', 'Idle'),
|
||||
)
|
||||
value_preview.parent = this
|
||||
// const value_preview = this.addCustomWidget(
|
||||
// MtbWidgets.DEBUG_STRING('value_preview', 'Idle'),
|
||||
// )
|
||||
|
||||
const loop_preview = this.addCustomWidget(
|
||||
MtbWidgets['DEBUG_STRING']('loop_preview', 'Iteration: Idle'),
|
||||
const dom_value_preview = mtb_ui.makeElement('p', {
|
||||
fontWeigth: '700',
|
||||
textAlign: 'center',
|
||||
fontSize: '1.5em',
|
||||
margin: 0,
|
||||
})
|
||||
const value_preview = this.addDOMWidget(
|
||||
'value_preview',
|
||||
'DISPLAY',
|
||||
dom_value_preview,
|
||||
{
|
||||
hideOnZoom: false,
|
||||
setValue: (val) => {
|
||||
if (val) {
|
||||
value_preview.element.innerHTML = val
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
loop_preview.parent = this
|
||||
value_preview.value = 'Idle'
|
||||
|
||||
const dom_loop_preview = mtb_ui.makeElement('p', {
|
||||
textAlign: 'center',
|
||||
margin: 0,
|
||||
})
|
||||
|
||||
const loop_preview = this.addDOMWidget(
|
||||
'loop_preview',
|
||||
'DISPLAY',
|
||||
dom_loop_preview,
|
||||
{
|
||||
hideOnZoom: false,
|
||||
setValue: (val) => {
|
||||
if (val) {
|
||||
dom_loop_preview.innerHTML = val
|
||||
}
|
||||
},
|
||||
getValue: () => {
|
||||
dom_loop_preview.innerHTML
|
||||
},
|
||||
},
|
||||
)
|
||||
loop_preview.value = 'Iteration: Idle'
|
||||
|
||||
let cancelQueue = false
|
||||
|
||||
const onReset = () => {
|
||||
raw_iteration.value = 0
|
||||
@@ -952,23 +1029,51 @@ const mtb_widgets = {
|
||||
|
||||
value_preview.value = 'Idle'
|
||||
loop_preview.value = 'Iteration: Idle'
|
||||
cancelQueue = false
|
||||
|
||||
app.canvas.setDirty(true)
|
||||
}
|
||||
|
||||
// reset button
|
||||
this.addWidget('button', `Reset`, 'reset', onReset)
|
||||
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 = () => {
|
||||
@@ -980,16 +1085,14 @@ const mtb_widgets = {
|
||||
this.value++
|
||||
raw_loop.value = Math.floor(this.value / total_frames.value)
|
||||
|
||||
value_preview.value = `frame: ${
|
||||
raw_iteration.value % total_frames.value
|
||||
} / ${total_frames.value - 1}`
|
||||
value_preview.value = `frame: ${raw_iteration.value % total_frames.value
|
||||
} / ${total_frames.value - 1}`
|
||||
|
||||
if (raw_loop.value + 1 > loop_count.value) {
|
||||
loop_preview.value = 'Done 😎!'
|
||||
} else {
|
||||
loop_preview.value = `current loop: ${raw_loop.value + 1}/${
|
||||
loop_count.value
|
||||
}`
|
||||
loop_preview.value = `current loop: ${raw_loop.value + 1}/${loop_count.value
|
||||
}`
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1000,9 +1103,9 @@ const mtb_widgets = {
|
||||
}
|
||||
case 'Interpolate Clip Sequential (mtb)': {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
nodeType.prototype.onNodeCreated = function (...args) {
|
||||
const r = onNodeCreated
|
||||
? onNodeCreated.apply(this, arguments)
|
||||
? onNodeCreated.apply(this, ...args)
|
||||
: undefined
|
||||
const addReplacement = () => {
|
||||
const input = this.addInput(
|
||||
@@ -1014,19 +1117,14 @@ const mtb_widgets = {
|
||||
this.addWidget('STRING', `replacement_${this.widgets.length}`, '')
|
||||
}
|
||||
//- add
|
||||
this.addWidget('button', '+', 'add', function (value, widget, node) {
|
||||
this.addWidget('button', '+', 'add', (value, widget, node) => {
|
||||
console.log('Button clicked', value, widget, node)
|
||||
addReplacement()
|
||||
})
|
||||
//- remove
|
||||
this.addWidget(
|
||||
'button',
|
||||
'-',
|
||||
'remove',
|
||||
function (value, widget, node) {
|
||||
console.log(`Button clicked: ${value}`, widget, node)
|
||||
},
|
||||
)
|
||||
this.addWidget('button', '-', 'remove', (value, widget, node) => {
|
||||
console.log(`Button clicked: ${value}`, widget, node)
|
||||
})
|
||||
|
||||
return r
|
||||
}
|
||||
@@ -1041,16 +1139,10 @@ const mtb_widgets = {
|
||||
|
||||
const getStyle = async (node) => {
|
||||
try {
|
||||
const getStyles = await api.fetchApi('/mtb/actions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name: 'getStyles',
|
||||
args:
|
||||
node.widgets && node.widgets[0].value
|
||||
? node.widgets[0].value
|
||||
: '',
|
||||
}),
|
||||
})
|
||||
const getStyles = await runAction(
|
||||
'getStyles',
|
||||
node.widgets?.[0].value ? node.widgets[0].value : '',
|
||||
)
|
||||
|
||||
const output = await getStyles.json()
|
||||
return output?.result
|
||||
@@ -1111,7 +1203,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)': {
|
||||
@@ -1122,6 +1216,10 @@ const mtb_widgets = {
|
||||
shared.setupDynamicConnections(nodeType, 'video', 'VIDEO')
|
||||
break
|
||||
}
|
||||
case 'Interpolate Condition (mtb)': {
|
||||
shared.setupDynamicConnections(nodeType, 'condition', 'CONDITIONING')
|
||||
break
|
||||
}
|
||||
case 'Psd Save (mtb)': {
|
||||
shared.setupDynamicConnections(nodeType, 'input_', 'PSDLAYER')
|
||||
break
|
||||
@@ -1131,9 +1229,14 @@ const mtb_widgets = {
|
||||
// break
|
||||
// }
|
||||
case 'Stack Images (mtb)':
|
||||
case 'Reference Latents (mtb)':
|
||||
case 'Concat Images (mtb)': {
|
||||
shared.setupDynamicConnections(nodeType, 'image', 'IMAGE')
|
||||
|
||||
break
|
||||
}
|
||||
case 'Audio Sequence (mtb)':
|
||||
case 'Audio Stack (mtb)': {
|
||||
shared.setupDynamicConnections(nodeType, 'audio', 'AUDIO')
|
||||
break
|
||||
}
|
||||
case 'Batch Float Assemble (mtb)':
|
||||
@@ -1142,6 +1245,8 @@ const mtb_widgets = {
|
||||
shared.setupDynamicConnections(nodeType, 'floats', 'FLOATS')
|
||||
break
|
||||
}
|
||||
case 'Batch Sequence (mtb)':
|
||||
case 'Batch Sequence Plus (mtb)':
|
||||
case 'Batch Merge (mtb)': {
|
||||
shared.setupDynamicConnections(nodeType, 'batches', 'IMAGE')
|
||||
|
||||
@@ -1154,13 +1259,13 @@ const mtb_widgets = {
|
||||
const r = onNodeCreated
|
||||
? onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
this.addInput(`x`, '*')
|
||||
this.addInput('x', '*')
|
||||
return r
|
||||
}
|
||||
|
||||
const onConnectionsChange = nodeType.prototype.onConnectionsChange
|
||||
nodeType.prototype.onConnectionsChange = function (
|
||||
type,
|
||||
_type,
|
||||
index,
|
||||
connected,
|
||||
link_info,
|
||||
@@ -1175,7 +1280,7 @@ const mtb_widgets = {
|
||||
//- infer type
|
||||
if (link_info) {
|
||||
const fromNode = this.graph._nodes.find(
|
||||
(otherNode) => otherNode.id == link_info.origin_id,
|
||||
(otherNode) => otherNode.id !== link_info.origin_id,
|
||||
)
|
||||
const type = fromNode.outputs[link_info.origin_slot].type
|
||||
this.inputs[index].type = type
|
||||
@@ -1190,8 +1295,34 @@ const mtb_widgets = {
|
||||
|
||||
break
|
||||
}
|
||||
case 'String Replace (mtb)': {
|
||||
shared.addMenuHandler(nodeType, function (_app, options) {
|
||||
/** @type {ContextMenuItem} */
|
||||
const item = {
|
||||
content: 'swap',
|
||||
title: 'Swap Old/New ⚡',
|
||||
callback: (_menuItem) => {
|
||||
const old_w = this.widgets.find((w) => w.name === 'old')
|
||||
const novel_w = this.widgets.find(
|
||||
(w) => w.name === 'new',
|
||||
)
|
||||
|
||||
const old = old_w.value
|
||||
const novel = novel_w.value
|
||||
|
||||
novel_w.value = old
|
||||
old_w.value = novel
|
||||
|
||||
},
|
||||
}
|
||||
|
||||
options.push(item)
|
||||
return [item]
|
||||
})
|
||||
break
|
||||
}
|
||||
case 'Batch Shape (mtb)':
|
||||
case 'Mask To Image (mtb)':
|
||||
case 'Text To Image (mtb)': {
|
||||
shared.addMenuHandler(nodeType, function (_app, options) {
|
||||
/** @type {ContextMenuItem} */
|
||||
@@ -1217,23 +1348,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
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
// web/note_plus.constants.js
|
||||
|
||||
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_MODE = 'markdown'
|
||||
export const DEFAULT_THEME = 'one_dark'
|
||||
|
||||
export const DEMO_CONTENT = `
|
||||
# @mtb/svelte-markdown.
|
||||
## This is a subheader
|
||||
|
||||
[](https://github.com/melMass/comfy_mtb/actions/workflows/test_embedded.yml)
|
||||

|
||||
|
||||
<details>
|
||||
<summary>More details about the inception of the project</summary>
|
||||
|
||||
\`\`\`js
|
||||
class YesMan{
|
||||
constructor(){
|
||||
this.started = false
|
||||
}
|
||||
}
|
||||
\`\`\`
|
||||
</details>
|
||||
|
||||
This is a paragraph. If it goes over the maximum width it will not automatically wrap unless it reaches the max-w of \`prose\` check [styles](/styles) for more info.
|
||||
|
||||
This component is useful for building some tools on top. Or even just a static system using svelte at its core. My personal blog is fully powered by **@mtb/svelte-markdown**
|
||||
|
||||
| And this is | A table |
|
||||
|-------------|---------|
|
||||
| With two | columns |
|
||||
|
||||
We also support github callout:
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> Highlights information that users should take into account, even when skimming.
|
||||
> [!TIP]
|
||||
> Optional information to help a user be more successful.
|
||||
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Crucial information necessary for users to succeed.
|
||||
|
||||
> [!WARNING]
|
||||
> Critical content demanding immediate user attention due to potential risks.
|
||||
|
||||
> [!CAUTION]
|
||||
> Negative potential consequences of an action.
|
||||
`
|
||||
|
||||
export const THEMES = [
|
||||
'ambiance',
|
||||
'chaos',
|
||||
'chrome',
|
||||
'cloud9_day',
|
||||
'cloud9_night',
|
||||
'cloud9_night_low_color',
|
||||
'cloud_editor',
|
||||
'cloud_editor_dark',
|
||||
'clouds',
|
||||
'clouds_midnight',
|
||||
'cobalt',
|
||||
'crimson_editor',
|
||||
'dawn',
|
||||
'dracula',
|
||||
'dreamweaver',
|
||||
'eclipse',
|
||||
'github',
|
||||
'github_dark',
|
||||
'gob',
|
||||
'gruvbox',
|
||||
'gruvbox_dark_hard',
|
||||
'gruvbox_light_hard',
|
||||
'idle_fingers',
|
||||
'iplastic',
|
||||
'katzenmilch',
|
||||
'kr_theme',
|
||||
'kuroir',
|
||||
'merbivore',
|
||||
'merbivore_soft',
|
||||
'mono_industrial',
|
||||
'monokai',
|
||||
'nord_dark',
|
||||
'one_dark',
|
||||
'pastel_on_dark',
|
||||
'solarized_dark',
|
||||
'solarized_light',
|
||||
'sqlserver',
|
||||
'terminal',
|
||||
'textmate',
|
||||
'tomorrow',
|
||||
'tomorrow_night',
|
||||
'tomorrow_night_blue',
|
||||
'tomorrow_night_bright',
|
||||
'tomorrow_night_eighties',
|
||||
'twilight',
|
||||
'vibrant_ink',
|
||||
'vscode',
|
||||
]
|
||||
|
||||
export const CSS_RESET = `
|
||||
* {
|
||||
line-height: 1.25em;
|
||||
}
|
||||
.shiki{
|
||||
padding: 1em;
|
||||
width: 100%;
|
||||
}
|
||||
.markdown-callout-title {
|
||||
.octicon{
|
||||
fill:white;
|
||||
width:29px;
|
||||
height:29px;
|
||||
}
|
||||
/* background: var(--current-color); */
|
||||
color: var(--current-color);
|
||||
font-weight: bold;
|
||||
/* border-start-end-radius: var(--radius); */
|
||||
/* border-start-start-radius: var(--radius); */
|
||||
padding: 0.5em;
|
||||
padding-inline-start: 1em;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.markdown-callout-content {
|
||||
padding: 1em;
|
||||
}
|
||||
.markdown-callout {
|
||||
--radius: 8px;
|
||||
--current-color: purple;
|
||||
/* border-start-end-radius: var(--radius); */
|
||||
/* border-start-start-radius: var(--radius); */
|
||||
border-left: 3px solid var(--current-color);
|
||||
margin-bottom: 1em;
|
||||
margin-top: 1em;
|
||||
|
||||
}
|
||||
.markdown-callout p:nth-child(2) {
|
||||
padding:1em;
|
||||
}
|
||||
|
||||
|
||||
.markdown-callout-tip {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #50e3c2;
|
||||
}
|
||||
|
||||
.markdown-callout-note {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #0070f3;
|
||||
}
|
||||
.markdown-callout-important {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #7928ca;
|
||||
}
|
||||
.markdown-callout-warning {
|
||||
--current-color: #f5a623;
|
||||
}
|
||||
.markdown-callout-caution {
|
||||
--current-color: #e60000;
|
||||
}
|
||||
|
||||
|
||||
.note-plus-preview {
|
||||
display:flex;
|
||||
flex-direction:column;
|
||||
align-items: flex-start;
|
||||
width:95%;
|
||||
/*margin-left: 20px;*/
|
||||
/*margin-top:20px;*/
|
||||
|
||||
/*background-color: rgba(255,0,0,0.5)!important;*/
|
||||
}
|
||||
|
||||
/* allowed to be selected*/
|
||||
h1, h2, h3, h4, h5, h6,a, p, ul, ol, dl, blockquote,details,summary {
|
||||
pointer-events:auto;
|
||||
user-select:text;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
display:inline-block;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
p, ul, ol, dl, blockquote {
|
||||
margin: 0.3em;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
ul, ol {
|
||||
padding-left: 1em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
pointer-events: all;
|
||||
color: cyan;
|
||||
}
|
||||
|
||||
img {
|
||||
padding: 1em 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
iframe {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border:none;
|
||||
pointer-events:all;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #ccc;
|
||||
padding-left: 1em;
|
||||
margin-left: 0;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
pre, code {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #000;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
th, td {
|
||||
border-left: 1px solid #000;
|
||||
border-right: 1px solid #000;
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
border: 1px solid #000;
|
||||
background-color: rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-right: 10px;
|
||||
}
|
||||
`
|
||||
+612
-436
File diff suppressed because it is too large
Load Diff
+12
-3
@@ -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`
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,768 @@
|
||||
{
|
||||
"lockfileVersion": 1,
|
||||
"configVersion": 0,
|
||||
"workspaces": {
|
||||
"": {
|
||||
"name": "vite-project",
|
||||
"dependencies": {
|
||||
"@untemps/svelte-palette": "^4.1.0",
|
||||
"iconify-icon": "^3.0.0",
|
||||
"vite-plugin-css-injected-by-js": "^3.5.2",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@comfyorg/comfyui-frontend-types": "^1.20.2",
|
||||
"@comfyorg/litegraph": "^0.15.15",
|
||||
"@neodrag/svelte": "^2.3.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.1.0",
|
||||
"@swc/cli": "^0.7.7",
|
||||
"@swc/core": "^1.11.31",
|
||||
"@types/node": "^22.15.30",
|
||||
"prettier-plugin-svelte": "^3.2.7",
|
||||
"sass": "^1.89.1",
|
||||
"svelte": "^5.33.14",
|
||||
"svelte-awesome-color-picker": "^4.0.2",
|
||||
"svelte-dnd-action": "^0.9.61",
|
||||
"svelte-portal": "^2.2.1",
|
||||
"syncpack": "^13.0.0",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-no-bundle": "^4.0.0",
|
||||
},
|
||||
},
|
||||
},
|
||||
"trustedDependencies": [
|
||||
"@swc/core",
|
||||
"@parcel/watcher",
|
||||
],
|
||||
"packages": {
|
||||
"@ampproject/remapping": ["@ampproject/remapping@2.3.0", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw=="],
|
||||
|
||||
"@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="],
|
||||
|
||||
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.27.1", "", {}, "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA=="],
|
||||
|
||||
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.27.1", "", {}, "sha512-D2hP9eA+Sqx1kBZgzxZh0y1trbuU+JoDkiEwqhQ36nodYqJwyEIhPSdMNd7lOm/4io72luTPWH20Yda0xOuUow=="],
|
||||
|
||||
"@babel/parser": ["@babel/parser@7.27.5", "", { "dependencies": { "@babel/types": "^7.27.3" }, "bin": "./bin/babel-parser.js" }, "sha512-OsQd175SxWkGlzbny8J3K8TnnDD0N3lrIUtB92xwyRpzaenGZhxDvxN/JgU00U3CDZNj9tPuDJ5H0WS4Nt3vKg=="],
|
||||
|
||||
"@babel/runtime": ["@babel/runtime@7.24.5", "", { "dependencies": { "regenerator-runtime": "^0.14.0" } }, "sha512-Nms86NXrsaeU9vbBJKni6gXiEXZ4CVpYVzEjDH9Sb8vmZ3UljyA1GSOJl/6LGPO8EHLuSF9H+IxNXHPX8QHJ4g=="],
|
||||
|
||||
"@babel/types": ["@babel/types@7.27.3", "", { "dependencies": { "@babel/helper-string-parser": "^7.27.1", "@babel/helper-validator-identifier": "^7.27.1" } }, "sha512-Y1GkI4ktrtvmawoSq+4FCVHNryea6uR+qUQy0AGxLSsjCX0nVmkYQMBLHDkXZuo5hGx7eYdnIaslsdBFm7zbUw=="],
|
||||
|
||||
"@comfyorg/comfyui-frontend-types": ["@comfyorg/comfyui-frontend-types@1.21.7", "", { "dependencies": { "@comfyorg/litegraph": "^0.15.15" }, "peerDependencies": { "vue": "^3.5.13", "zod": "^3.23.8" } }, "sha512-IqfqUYIeFremdlMo+MSZdrro2PcuI2biUO+j4OPF1jWEZboAUEiLTlo8RH5nhA/tWgZaLd2/LJ0GvfgeGRdcjA=="],
|
||||
|
||||
"@comfyorg/litegraph": ["@comfyorg/litegraph@0.15.15", "", {}, "sha512-otOKgTxNPV6gEa6PW1fHGMMF8twjnZkP0vWQhGsRISK4vN8tPfX8O9sC9Hnq3nV8axaMv4/Ff49+7mMVcFEKeA=="],
|
||||
|
||||
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.5", "", { "os": "aix", "cpu": "ppc64" }, "sha512-9o3TMmpmftaCMepOdA5k/yDw8SfInyzWWTjYTFCX3kPSDJMROQTb8jg+h9Cnwnmm1vOzvxN7gIfB5V2ewpjtGA=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.5", "", { "os": "android", "cpu": "arm" }, "sha512-AdJKSPeEHgi7/ZhuIPtcQKr5RQdo6OO2IL87JkianiMYMPbCtot9fxPbrMiBADOWWm3T2si9stAiVsGbTQFkbA=="],
|
||||
|
||||
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.25.5", "", { "os": "android", "cpu": "arm64" }, "sha512-VGzGhj4lJO+TVGV1v8ntCZWJktV7SGCs3Pn1GRWI1SBFtRALoomm8k5E9Pmwg3HOAal2VDc2F9+PM/rEY6oIDg=="],
|
||||
|
||||
"@esbuild/android-x64": ["@esbuild/android-x64@0.25.5", "", { "os": "android", "cpu": "x64" }, "sha512-D2GyJT1kjvO//drbRT3Hib9XPwQeWd9vZoBJn+bu/lVsOZ13cqNdDeqIF/xQ5/VmWvMduP6AmXvylO/PIc2isw=="],
|
||||
|
||||
"@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.25.5", "", { "os": "darwin", "cpu": "arm64" }, "sha512-GtaBgammVvdF7aPIgH2jxMDdivezgFu6iKpmT+48+F8Hhg5J/sfnDieg0aeG/jfSvkYQU2/pceFPDKlqZzwnfQ=="],
|
||||
|
||||
"@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.25.5", "", { "os": "darwin", "cpu": "x64" }, "sha512-1iT4FVL0dJ76/q1wd7XDsXrSW+oLoquptvh4CLR4kITDtqi2e/xwXwdCVH8hVHU43wgJdsq7Gxuzcs6Iq/7bxQ=="],
|
||||
|
||||
"@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.25.5", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-nk4tGP3JThz4La38Uy/gzyXtpkPW8zSAmoUhK9xKKXdBCzKODMc2adkB2+8om9BDYugz+uGV7sLmpTYzvmz6Sw=="],
|
||||
|
||||
"@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.25.5", "", { "os": "freebsd", "cpu": "x64" }, "sha512-PrikaNjiXdR2laW6OIjlbeuCPrPaAl0IwPIaRv+SMV8CiM8i2LqVUHFC1+8eORgWyY7yhQY+2U2fA55mBzReaw=="],
|
||||
|
||||
"@esbuild/linux-arm": ["@esbuild/linux-arm@0.25.5", "", { "os": "linux", "cpu": "arm" }, "sha512-cPzojwW2okgh7ZlRpcBEtsX7WBuqbLrNXqLU89GxWbNt6uIg78ET82qifUy3W6OVww6ZWobWub5oqZOVtwolfw=="],
|
||||
|
||||
"@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.25.5", "", { "os": "linux", "cpu": "arm64" }, "sha512-Z9kfb1v6ZlGbWj8EJk9T6czVEjjq2ntSYLY2cw6pAZl4oKtfgQuS4HOq41M/BcoLPzrUbNd+R4BXFyH//nHxVg=="],
|
||||
|
||||
"@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.25.5", "", { "os": "linux", "cpu": "ia32" }, "sha512-sQ7l00M8bSv36GLV95BVAdhJ2QsIbCuCjh/uYrWiMQSUuV+LpXwIqhgJDcvMTj+VsQmqAHL2yYaasENvJ7CDKA=="],
|
||||
|
||||
"@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.25.5", "", { "os": "linux", "cpu": "none" }, "sha512-0ur7ae16hDUC4OL5iEnDb0tZHDxYmuQyhKhsPBV8f99f6Z9KQM02g33f93rNH5A30agMS46u2HP6qTdEt6Q1kg=="],
|
||||
|
||||
"@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.25.5", "", { "os": "linux", "cpu": "none" }, "sha512-kB/66P1OsHO5zLz0i6X0RxlQ+3cu0mkxS3TKFvkb5lin6uwZ/ttOkP3Z8lfR9mJOBk14ZwZ9182SIIWFGNmqmg=="],
|
||||
|
||||
"@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.25.5", "", { "os": "linux", "cpu": "ppc64" }, "sha512-UZCmJ7r9X2fe2D6jBmkLBMQetXPXIsZjQJCjgwpVDz+YMcS6oFR27alkgGv3Oqkv07bxdvw7fyB71/olceJhkQ=="],
|
||||
|
||||
"@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.25.5", "", { "os": "linux", "cpu": "none" }, "sha512-kTxwu4mLyeOlsVIFPfQo+fQJAV9mh24xL+y+Bm6ej067sYANjyEw1dNHmvoqxJUCMnkBdKpvOn0Ahql6+4VyeA=="],
|
||||
|
||||
"@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.25.5", "", { "os": "linux", "cpu": "s390x" }, "sha512-K2dSKTKfmdh78uJ3NcWFiqyRrimfdinS5ErLSn3vluHNeHVnBAFWC8a4X5N+7FgVE1EjXS1QDZbpqZBjfrqMTQ=="],
|
||||
|
||||
"@esbuild/linux-x64": ["@esbuild/linux-x64@0.25.5", "", { "os": "linux", "cpu": "x64" }, "sha512-uhj8N2obKTE6pSZ+aMUbqq+1nXxNjZIIjCjGLfsWvVpy7gKCOL6rsY1MhRh9zLtUtAI7vpgLMK6DxjO8Qm9lJw=="],
|
||||
|
||||
"@esbuild/netbsd-arm64": ["@esbuild/netbsd-arm64@0.25.5", "", { "os": "none", "cpu": "arm64" }, "sha512-pwHtMP9viAy1oHPvgxtOv+OkduK5ugofNTVDilIzBLpoWAM16r7b/mxBvfpuQDpRQFMfuVr5aLcn4yveGvBZvw=="],
|
||||
|
||||
"@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.25.5", "", { "os": "none", "cpu": "x64" }, "sha512-WOb5fKrvVTRMfWFNCroYWWklbnXH0Q5rZppjq0vQIdlsQKuw6mdSihwSo4RV/YdQ5UCKKvBy7/0ZZYLBZKIbwQ=="],
|
||||
|
||||
"@esbuild/openbsd-arm64": ["@esbuild/openbsd-arm64@0.25.5", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-7A208+uQKgTxHd0G0uqZO8UjK2R0DDb4fDmERtARjSHWxqMTye4Erz4zZafx7Di9Cv+lNHYuncAkiGFySoD+Mw=="],
|
||||
|
||||
"@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.25.5", "", { "os": "openbsd", "cpu": "x64" }, "sha512-G4hE405ErTWraiZ8UiSoesH8DaCsMm0Cay4fsFWOOUcz8b8rC6uCvnagr+gnioEjWn0wC+o1/TAHt+It+MpIMg=="],
|
||||
|
||||
"@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.25.5", "", { "os": "sunos", "cpu": "x64" }, "sha512-l+azKShMy7FxzY0Rj4RCt5VD/q8mG/e+mDivgspo+yL8zW7qEwctQ6YqKX34DTEleFAvCIUviCFX1SDZRSyMQA=="],
|
||||
|
||||
"@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.25.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-O2S7SNZzdcFG7eFKgvwUEZ2VG9D/sn/eIiz8XRZ1Q/DO5a3s76Xv0mdBzVM5j5R639lXQmPmSo0iRpHqUUrsxw=="],
|
||||
|
||||
"@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.25.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-onOJ02pqs9h1iMJ1PQphR+VZv8qBMQ77Klcsqv9CNW2w6yLqoURLcgERAIurY6QE63bbLuqgP9ATqajFLK5AMQ=="],
|
||||
|
||||
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.5", "", { "os": "win32", "cpu": "x64" }, "sha512-TXv6YnJ8ZMVdX+SXWVBo/0p8LTcrUYngpWjvm91TMjjBQii7Oz11Lw5lbDV5Y0TzuhSJHwiH4hEtC1I42mMS0g=="],
|
||||
|
||||
"@iconify/types": ["@iconify/types@2.0.0", "", {}, "sha512-+wluvCrRhXrhyOmRDJ3q8mux9JkKy5SJ/v8ol2tu4FVjyYvtEzkc/3pK15ET6RKg4b4w4BmTk1+gsCUhf21Ykg=="],
|
||||
|
||||
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.5", "", { "dependencies": { "@jridgewell/set-array": "^1.2.1", "@jridgewell/sourcemap-codec": "^1.4.10", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-IzL8ZoEDIBRWEzlCcRhOaCupYyN5gdIK+Q6fbFdPDg6HqX6jpkItn7DFIpW9LQzXG6Df9sA7+OKnq0qlz/GaQg=="],
|
||||
|
||||
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
|
||||
|
||||
"@jridgewell/set-array": ["@jridgewell/set-array@1.2.1", "", {}, "sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A=="],
|
||||
|
||||
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.0", "", {}, "sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ=="],
|
||||
|
||||
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.25", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ=="],
|
||||
|
||||
"@neodrag/svelte": ["@neodrag/svelte@2.3.2", "", { "peerDependencies": { "svelte": "^3.0.0 || ^4.0.0 || ^5.0.0" } }, "sha512-1aPgnv2LqikkPEoTVgCPCqtXUXOD7OjCHLAIssTv0hkmyHLG9i697Cu+Tzco4/Q4KgOQXCDnLsa4Fvya5wXP9g=="],
|
||||
|
||||
"@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="],
|
||||
|
||||
"@nodelib/fs.stat": ["@nodelib/fs.stat@2.0.5", "", {}, "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A=="],
|
||||
|
||||
"@nodelib/fs.walk": ["@nodelib/fs.walk@1.2.8", "", { "dependencies": { "@nodelib/fs.scandir": "2.1.5", "fastq": "^1.6.0" } }, "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg=="],
|
||||
|
||||
"@parcel/watcher": ["@parcel/watcher@2.5.1", "", { "dependencies": { "detect-libc": "^1.0.3", "is-glob": "^4.0.3", "micromatch": "^4.0.5", "node-addon-api": "^7.0.0" }, "optionalDependencies": { "@parcel/watcher-android-arm64": "2.5.1", "@parcel/watcher-darwin-arm64": "2.5.1", "@parcel/watcher-darwin-x64": "2.5.1", "@parcel/watcher-freebsd-x64": "2.5.1", "@parcel/watcher-linux-arm-glibc": "2.5.1", "@parcel/watcher-linux-arm-musl": "2.5.1", "@parcel/watcher-linux-arm64-glibc": "2.5.1", "@parcel/watcher-linux-arm64-musl": "2.5.1", "@parcel/watcher-linux-x64-glibc": "2.5.1", "@parcel/watcher-linux-x64-musl": "2.5.1", "@parcel/watcher-win32-arm64": "2.5.1", "@parcel/watcher-win32-ia32": "2.5.1", "@parcel/watcher-win32-x64": "2.5.1" } }, "sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg=="],
|
||||
|
||||
"@parcel/watcher-android-arm64": ["@parcel/watcher-android-arm64@2.5.1", "", { "os": "android", "cpu": "arm64" }, "sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA=="],
|
||||
|
||||
"@parcel/watcher-darwin-arm64": ["@parcel/watcher-darwin-arm64@2.5.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw=="],
|
||||
|
||||
"@parcel/watcher-darwin-x64": ["@parcel/watcher-darwin-x64@2.5.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg=="],
|
||||
|
||||
"@parcel/watcher-freebsd-x64": ["@parcel/watcher-freebsd-x64@2.5.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ=="],
|
||||
|
||||
"@parcel/watcher-linux-arm-glibc": ["@parcel/watcher-linux-arm-glibc@2.5.1", "", { "os": "linux", "cpu": "arm" }, "sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA=="],
|
||||
|
||||
"@parcel/watcher-linux-arm-musl": ["@parcel/watcher-linux-arm-musl@2.5.1", "", { "os": "linux", "cpu": "arm" }, "sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q=="],
|
||||
|
||||
"@parcel/watcher-linux-arm64-glibc": ["@parcel/watcher-linux-arm64-glibc@2.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w=="],
|
||||
|
||||
"@parcel/watcher-linux-arm64-musl": ["@parcel/watcher-linux-arm64-musl@2.5.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg=="],
|
||||
|
||||
"@parcel/watcher-linux-x64-glibc": ["@parcel/watcher-linux-x64-glibc@2.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-GcESn8NZySmfwlTsIur+49yDqSny2IhPeZfXunQi48DMugKeZ7uy1FX83pO0X22sHntJ4Ub+9k34XQCX+oHt2A=="],
|
||||
|
||||
"@parcel/watcher-linux-x64-musl": ["@parcel/watcher-linux-x64-musl@2.5.1", "", { "os": "linux", "cpu": "x64" }, "sha512-n0E2EQbatQ3bXhcH2D1XIAANAcTZkQICBPVaxMeaCVBtOpBZpWJuf7LwyWPSBDITb7In8mqQgJ7gH8CILCURXg=="],
|
||||
|
||||
"@parcel/watcher-win32-arm64": ["@parcel/watcher-win32-arm64@2.5.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw=="],
|
||||
|
||||
"@parcel/watcher-win32-ia32": ["@parcel/watcher-win32-ia32@2.5.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ=="],
|
||||
|
||||
"@parcel/watcher-win32-x64": ["@parcel/watcher-win32-x64@2.5.1", "", { "os": "win32", "cpu": "x64" }, "sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA=="],
|
||||
|
||||
"@rollup/rollup-android-arm-eabi": ["@rollup/rollup-android-arm-eabi@4.41.1", "", { "os": "android", "cpu": "arm" }, "sha512-NELNvyEWZ6R9QMkiytB4/L4zSEaBC03KIXEghptLGLZWJ6VPrL63ooZQCOnlx36aQPGhzuOMwDerC1Eb2VmrLw=="],
|
||||
|
||||
"@rollup/rollup-android-arm64": ["@rollup/rollup-android-arm64@4.41.1", "", { "os": "android", "cpu": "arm64" }, "sha512-DXdQe1BJ6TK47ukAoZLehRHhfKnKg9BjnQYUu9gzhI8Mwa1d2fzxA1aw2JixHVl403bwp1+/o/NhhHtxWJBgEA=="],
|
||||
|
||||
"@rollup/rollup-darwin-arm64": ["@rollup/rollup-darwin-arm64@4.41.1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5afxvwszzdulsU2w8JKWwY8/sJOLPzf0e1bFuvcW5h9zsEg+RQAojdW0ux2zyYAz7R8HvvzKCjLNJhVq965U7w=="],
|
||||
|
||||
"@rollup/rollup-darwin-x64": ["@rollup/rollup-darwin-x64@4.41.1", "", { "os": "darwin", "cpu": "x64" }, "sha512-egpJACny8QOdHNNMZKf8xY0Is6gIMz+tuqXlusxquWu3F833DcMwmGM7WlvCO9sB3OsPjdC4U0wHw5FabzCGZg=="],
|
||||
|
||||
"@rollup/rollup-freebsd-arm64": ["@rollup/rollup-freebsd-arm64@4.41.1", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-DBVMZH5vbjgRk3r0OzgjS38z+atlupJ7xfKIDJdZZL6sM6wjfDNo64aowcLPKIx7LMQi8vybB56uh1Ftck/Atg=="],
|
||||
|
||||
"@rollup/rollup-freebsd-x64": ["@rollup/rollup-freebsd-x64@4.41.1", "", { "os": "freebsd", "cpu": "x64" }, "sha512-3FkydeohozEskBxNWEIbPfOE0aqQgB6ttTkJ159uWOFn42VLyfAiyD9UK5mhu+ItWzft60DycIN1Xdgiy8o/SA=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-gnueabihf": ["@rollup/rollup-linux-arm-gnueabihf@4.41.1", "", { "os": "linux", "cpu": "arm" }, "sha512-wC53ZNDgt0pqx5xCAgNunkTzFE8GTgdZ9EwYGVcg+jEjJdZGtq9xPjDnFgfFozQI/Xm1mh+D9YlYtl+ueswNEg=="],
|
||||
|
||||
"@rollup/rollup-linux-arm-musleabihf": ["@rollup/rollup-linux-arm-musleabihf@4.41.1", "", { "os": "linux", "cpu": "arm" }, "sha512-jwKCca1gbZkZLhLRtsrka5N8sFAaxrGz/7wRJ8Wwvq3jug7toO21vWlViihG85ei7uJTpzbXZRcORotE+xyrLA=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-gnu": ["@rollup/rollup-linux-arm64-gnu@4.41.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-g0UBcNknsmmNQ8V2d/zD2P7WWfJKU0F1nu0k5pW4rvdb+BIqMm8ToluW/eeRmxCared5dD76lS04uL4UaNgpNA=="],
|
||||
|
||||
"@rollup/rollup-linux-arm64-musl": ["@rollup/rollup-linux-arm64-musl@4.41.1", "", { "os": "linux", "cpu": "arm64" }, "sha512-XZpeGB5TKEZWzIrj7sXr+BEaSgo/ma/kCgrZgL0oo5qdB1JlTzIYQKel/RmhT6vMAvOdM2teYlAaOGJpJ9lahg=="],
|
||||
|
||||
"@rollup/rollup-linux-loongarch64-gnu": ["@rollup/rollup-linux-loongarch64-gnu@4.41.1", "", { "os": "linux", "cpu": "none" }, "sha512-bkCfDJ4qzWfFRCNt5RVV4DOw6KEgFTUZi2r2RuYhGWC8WhCA8lCAJhDeAmrM/fdiAH54m0mA0Vk2FGRPyzI+tw=="],
|
||||
|
||||
"@rollup/rollup-linux-powerpc64le-gnu": ["@rollup/rollup-linux-powerpc64le-gnu@4.41.1", "", { "os": "linux", "cpu": "ppc64" }, "sha512-3mr3Xm+gvMX+/8EKogIZSIEF0WUu0HL9di+YWlJpO8CQBnoLAEL/roTCxuLncEdgcfJcvA4UMOf+2dnjl4Ut1A=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-gnu": ["@rollup/rollup-linux-riscv64-gnu@4.41.1", "", { "os": "linux", "cpu": "none" }, "sha512-3rwCIh6MQ1LGrvKJitQjZFuQnT2wxfU+ivhNBzmxXTXPllewOF7JR1s2vMX/tWtUYFgphygxjqMl76q4aMotGw=="],
|
||||
|
||||
"@rollup/rollup-linux-riscv64-musl": ["@rollup/rollup-linux-riscv64-musl@4.41.1", "", { "os": "linux", "cpu": "none" }, "sha512-LdIUOb3gvfmpkgFZuccNa2uYiqtgZAz3PTzjuM5bH3nvuy9ty6RGc/Q0+HDFrHrizJGVpjnTZ1yS5TNNjFlklw=="],
|
||||
|
||||
"@rollup/rollup-linux-s390x-gnu": ["@rollup/rollup-linux-s390x-gnu@4.41.1", "", { "os": "linux", "cpu": "s390x" }, "sha512-oIE6M8WC9ma6xYqjvPhzZYk6NbobIURvP/lEbh7FWplcMO6gn7MM2yHKA1eC/GvYwzNKK/1LYgqzdkZ8YFxR8g=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-gnu": ["@rollup/rollup-linux-x64-gnu@4.41.1", "", { "os": "linux", "cpu": "x64" }, "sha512-cWBOvayNvA+SyeQMp79BHPK8ws6sHSsYnK5zDcsC3Hsxr1dgTABKjMnMslPq1DvZIp6uO7kIWhiGwaTdR4Og9A=="],
|
||||
|
||||
"@rollup/rollup-linux-x64-musl": ["@rollup/rollup-linux-x64-musl@4.41.1", "", { "os": "linux", "cpu": "x64" }, "sha512-y5CbN44M+pUCdGDlZFzGGBSKCA4A/J2ZH4edTYSSxFg7ce1Xt3GtydbVKWLlzL+INfFIZAEg1ZV6hh9+QQf9YQ=="],
|
||||
|
||||
"@rollup/rollup-win32-arm64-msvc": ["@rollup/rollup-win32-arm64-msvc@4.41.1", "", { "os": "win32", "cpu": "arm64" }, "sha512-lZkCxIrjlJlMt1dLO/FbpZbzt6J/A8p4DnqzSa4PWqPEUUUnzXLeki/iyPLfV0BmHItlYgHUqJe+3KiyydmiNQ=="],
|
||||
|
||||
"@rollup/rollup-win32-ia32-msvc": ["@rollup/rollup-win32-ia32-msvc@4.41.1", "", { "os": "win32", "cpu": "ia32" }, "sha512-+psFT9+pIh2iuGsxFYYa/LhS5MFKmuivRsx9iPJWNSGbh2XVEjk90fmpUEjCnILPEPJnikAU6SFDiEUyOv90Pg=="],
|
||||
|
||||
"@rollup/rollup-win32-x64-msvc": ["@rollup/rollup-win32-x64-msvc@4.41.1", "", { "os": "win32", "cpu": "x64" }, "sha512-Wq2zpapRYLfi4aKxf2Xff0tN+7slj2d4R87WEzqw7ZLsVvO5zwYCIuEGSZYiK41+GlwUo1HiR+GdkLEJnCKTCw=="],
|
||||
|
||||
"@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="],
|
||||
|
||||
"@sindresorhus/is": ["@sindresorhus/is@5.6.0", "", {}, "sha512-TV7t8GKYaJWsn00tFDqBw8+Uqmr8A0fRU1tvTQhyZzGv0sJCGRQL3JGMI3ucuKo3XIZdUP+Lx7/gh2t3lewy7g=="],
|
||||
|
||||
"@sindresorhus/merge-streams": ["@sindresorhus/merge-streams@2.3.0", "", {}, "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg=="],
|
||||
|
||||
"@standard-schema/spec": ["@standard-schema/spec@1.0.0", "", {}, "sha512-m2bOd0f2RT9k8QJx1JN85cZYyH1RqFBdlwtkSlf4tBDYLCiiZnv1fIIwacK6cqwXavOydf0NPToMQgpKq+dVlA=="],
|
||||
|
||||
"@sveltejs/acorn-typescript": ["@sveltejs/acorn-typescript@1.0.5", "", { "peerDependencies": { "acorn": "^8.9.0" } }, "sha512-IwQk4yfwLdibDlrXVE04jTZYlLnwsTT2PIOQQGNLWfjavGifnk1JD1LcZjZaBTRcxZu2FfPfNLOE04DSu9lqtQ=="],
|
||||
|
||||
"@sveltejs/vite-plugin-svelte": ["@sveltejs/vite-plugin-svelte@5.1.0", "", { "dependencies": { "@sveltejs/vite-plugin-svelte-inspector": "^4.0.1", "debug": "^4.4.1", "deepmerge": "^4.3.1", "kleur": "^4.1.5", "magic-string": "^0.30.17", "vitefu": "^1.0.6" }, "peerDependencies": { "svelte": "^5.0.0", "vite": "^6.0.0" } }, "sha512-wojIS/7GYnJDYIg1higWj2ROA6sSRWvcR1PO/bqEyFr/5UZah26c8Cz4u0NaqjPeVltzsVpt2Tm8d2io0V+4Tw=="],
|
||||
|
||||
"@sveltejs/vite-plugin-svelte-inspector": ["@sveltejs/vite-plugin-svelte-inspector@4.0.1", "", { "dependencies": { "debug": "^4.3.7" }, "peerDependencies": { "@sveltejs/vite-plugin-svelte": "^5.0.0", "svelte": "^5.0.0", "vite": "^6.0.0" } }, "sha512-J/Nmb2Q2y7mck2hyCX4ckVHcR5tu2J+MtBEQqpDrrgELZ2uvraQcK/ioCV61AqkdXFgriksOKIceDcQmqnGhVw=="],
|
||||
|
||||
"@swc/cli": ["@swc/cli@0.7.7", "", { "dependencies": { "@swc/counter": "^0.1.3", "@xhmikosr/bin-wrapper": "^13.0.5", "commander": "^8.3.0", "fast-glob": "^3.2.5", "minimatch": "^9.0.3", "piscina": "^4.3.1", "semver": "^7.3.8", "slash": "3.0.0", "source-map": "^0.7.3" }, "peerDependencies": { "@swc/core": "^1.2.66", "chokidar": "^4.0.1" }, "optionalPeers": ["chokidar"], "bin": { "swc": "bin/swc.js", "swcx": "bin/swcx.js", "spack": "bin/spack.js" } }, "sha512-j4yYm9bx3pxWofaJKX1BFwj/3ngUDynN4UIQ2Xd2h0h/7Gt7zkReBTpDN7g5S13mgAYxacaTHTOUsz18097E8w=="],
|
||||
|
||||
"@swc/core": ["@swc/core@1.11.31", "", { "dependencies": { "@swc/counter": "^0.1.3", "@swc/types": "^0.1.21" }, "optionalDependencies": { "@swc/core-darwin-arm64": "1.11.31", "@swc/core-darwin-x64": "1.11.31", "@swc/core-linux-arm-gnueabihf": "1.11.31", "@swc/core-linux-arm64-gnu": "1.11.31", "@swc/core-linux-arm64-musl": "1.11.31", "@swc/core-linux-x64-gnu": "1.11.31", "@swc/core-linux-x64-musl": "1.11.31", "@swc/core-win32-arm64-msvc": "1.11.31", "@swc/core-win32-ia32-msvc": "1.11.31", "@swc/core-win32-x64-msvc": "1.11.31" }, "peerDependencies": { "@swc/helpers": ">=0.5.17" }, "optionalPeers": ["@swc/helpers"] }, "sha512-mAby9aUnKRjMEA7v8cVZS9Ah4duoRBnX7X6r5qrhTxErx+68MoY1TPrVwj/66/SWN3Bl+jijqAqoB8Qx0QE34A=="],
|
||||
|
||||
"@swc/core-darwin-arm64": ["@swc/core-darwin-arm64@1.11.31", "", { "os": "darwin", "cpu": "arm64" }, "sha512-NTEaYOts0OGSbJZc0O74xsji+64JrF1stmBii6D5EevWEtrY4wlZhm8SiP/qPrOB+HqtAihxWIukWkP2aSdGSQ=="],
|
||||
|
||||
"@swc/core-darwin-x64": ["@swc/core-darwin-x64@1.11.31", "", { "os": "darwin", "cpu": "x64" }, "sha512-THSGaSwT96JwXDwuXQ6yFBbn+xDMdyw7OmBpnweAWsh5DhZmQkALEm1DgdQO3+rrE99MkmzwAfclc0UmYro/OA=="],
|
||||
|
||||
"@swc/core-linux-arm-gnueabihf": ["@swc/core-linux-arm-gnueabihf@1.11.31", "", { "os": "linux", "cpu": "arm" }, "sha512-laKtQFnW7KHgE57Hx32os2SNAogcuIDxYE+3DYIOmDMqD7/1DCfJe6Rln2N9WcOw6HuDbDpyQavIwZNfSAa8vQ=="],
|
||||
|
||||
"@swc/core-linux-arm64-gnu": ["@swc/core-linux-arm64-gnu@1.11.31", "", { "os": "linux", "cpu": "arm64" }, "sha512-T+vGw9aPE1YVyRxRr1n7NAdkbgzBzrXCCJ95xAZc/0+WUwmL77Z+js0J5v1KKTRxw4FvrslNCOXzMWrSLdwPSA=="],
|
||||
|
||||
"@swc/core-linux-arm64-musl": ["@swc/core-linux-arm64-musl@1.11.31", "", { "os": "linux", "cpu": "arm64" }, "sha512-Mztp5NZkyd5MrOAG+kl+QSn0lL4Uawd4CK4J7wm97Hs44N9DHGIG5nOz7Qve1KZo407Y25lTxi/PqzPKHo61zQ=="],
|
||||
|
||||
"@swc/core-linux-x64-gnu": ["@swc/core-linux-x64-gnu@1.11.31", "", { "os": "linux", "cpu": "x64" }, "sha512-DDVE0LZcXOWwOqFU1Xi7gdtiUg3FHA0vbGb3trjWCuI1ZtDZHEQYL4M3/2FjqKZtIwASrDvO96w91okZbXhvMg=="],
|
||||
|
||||
"@swc/core-linux-x64-musl": ["@swc/core-linux-x64-musl@1.11.31", "", { "os": "linux", "cpu": "x64" }, "sha512-mJA1MzPPRIfaBUHZi0xJQ4vwL09MNWDeFtxXb0r4Yzpf0v5Lue9ymumcBPmw/h6TKWms+Non4+TDquAsweuKSw=="],
|
||||
|
||||
"@swc/core-win32-arm64-msvc": ["@swc/core-win32-arm64-msvc@1.11.31", "", { "os": "win32", "cpu": "arm64" }, "sha512-RdtakUkNVAb/FFIMw3LnfNdlH1/ep6KgiPDRlmyUfd0WdIQ3OACmeBegEFNFTzi7gEuzy2Yxg4LWf4IUVk8/bg=="],
|
||||
|
||||
"@swc/core-win32-ia32-msvc": ["@swc/core-win32-ia32-msvc@1.11.31", "", { "os": "win32", "cpu": "ia32" }, "sha512-hErXdCGsg7swWdG1fossuL8542I59xV+all751mYlBoZ8kOghLSKObGQTkBbuNvc0sUKWfWg1X0iBuIhAYar+w=="],
|
||||
|
||||
"@swc/core-win32-x64-msvc": ["@swc/core-win32-x64-msvc@1.11.31", "", { "os": "win32", "cpu": "x64" }, "sha512-5t7SGjUBMMhF9b5j17ml/f/498kiBJNf4vZFNM421UGUEETdtjPN9jZIuQrowBkoFGJTCVL/ECM4YRtTH30u/A=="],
|
||||
|
||||
"@swc/counter": ["@swc/counter@0.1.3", "", {}, "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ=="],
|
||||
|
||||
"@swc/types": ["@swc/types@0.1.21", "", { "dependencies": { "@swc/counter": "^0.1.3" } }, "sha512-2YEtj5HJVbKivud9N4bpPBAyZhj4S2Ipe5LkUG94alTpr7in/GU/EARgPAd3BwU+YOmFVJC2+kjqhGRi3r0ZpQ=="],
|
||||
|
||||
"@szmarczak/http-timer": ["@szmarczak/http-timer@5.0.1", "", { "dependencies": { "defer-to-connect": "^2.0.1" } }, "sha512-+PmQX0PiAYPMeVYe237LJAYvOMYW1j2rH5YROyS3b4CTVJum34HfRvKvAzozHAQG0TnHNdUfY9nCeUyRAs//cw=="],
|
||||
|
||||
"@tokenizer/token": ["@tokenizer/token@0.3.0", "", {}, "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="],
|
||||
|
||||
"@types/estree": ["@types/estree@1.0.5", "", {}, "sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw=="],
|
||||
|
||||
"@types/http-cache-semantics": ["@types/http-cache-semantics@4.0.4", "", {}, "sha512-1m0bIFVc7eJWyve9S0RnuRgcQqF/Xd5QsUZAZeQFr1Q3/p9JWoQQEqmVy+DPTNpGXwhgIetAoYF8JSc33q29QA=="],
|
||||
|
||||
"@types/node": ["@types/node@22.15.30", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-6Q7lr06bEHdlfplU6YRbgG1SFBdlsfNC4/lX+SkhiTs0cpJkOElmWls8PxDFv4yY/xKb8Y6SO0OmSX4wgqTZbA=="],
|
||||
|
||||
"@untemps/dom-observer": ["@untemps/dom-observer@2.0.0", "", {}, "sha512-oZBj7j9hYSbuveNFvyPLamRfNh15KvGJC5pLGGpWVcO61EzISMESL0wudwP0UZETEu+0WfaJ16rGXtEZHsq+xw=="],
|
||||
|
||||
"@untemps/svelte-palette": ["@untemps/svelte-palette@4.1.0", "", { "dependencies": { "@untemps/svelte-use-drop-outside": "^1.6.0", "@untemps/svelte-use-tooltip": "^2.8.0", "@untemps/utils": "^3.0.0" }, "peerDependencies": { "svelte": "^4.0.0" } }, "sha512-Hm+e17xhFDETSa/xLecfN5t+nRYBNdO6xRnH+5UaUsZytNFB3uFXd1KrusLakbqPvvps94nqgJE30pc1dnY3aQ=="],
|
||||
|
||||
"@untemps/svelte-use-drop-outside": ["@untemps/svelte-use-drop-outside@1.6.0", "", { "dependencies": { "@untemps/dom-observer": "^2.0.0", "@untemps/utils": "^2.0.0", "svelte": "3.49.0" } }, "sha512-izzpTG27DwMzx7QIIkt1S+Z5JAbzNAKn568JZWJXR1ZXWx6ZAJigj8oFlSDAVltlFjeasDPXPJSmGoXALgTw/A=="],
|
||||
|
||||
"@untemps/svelte-use-tooltip": ["@untemps/svelte-use-tooltip@2.8.0", "", { "dependencies": { "@untemps/dom-observer": "^2.0.0", "@untemps/utils": "^2.4.0", "svelte": "3.49.0" } }, "sha512-rXzYyU1JzKucyjAr4J+byrDUk0eFhwC8ggiitJE/v945OJDjjA29dA2d+DTjyppqlm2ZQZzGHYKY5hrdRKdrAg=="],
|
||||
|
||||
"@untemps/utils": ["@untemps/utils@3.0.0", "", {}, "sha512-Iv7a1nvbTzk7ho8bry5iN/RYtns4dwNRuTqD49ixq0N3dOpoMIdSlhvVanbxEmRBqtV7MirCBEfScpTjDbo0ag=="],
|
||||
|
||||
"@vue/compiler-core": ["@vue/compiler-core@3.5.16", "", { "dependencies": { "@babel/parser": "^7.27.2", "@vue/shared": "3.5.16", "entities": "^4.5.0", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-AOQS2eaQOaaZQoL1u+2rCJIKDruNXVBZSiUD3chnUrsoX5ZTQMaCvXlWNIfxBJuU15r1o7+mpo5223KVtIhAgQ=="],
|
||||
|
||||
"@vue/compiler-dom": ["@vue/compiler-dom@3.5.16", "", { "dependencies": { "@vue/compiler-core": "3.5.16", "@vue/shared": "3.5.16" } }, "sha512-SSJIhBr/teipXiXjmWOVWLnxjNGo65Oj/8wTEQz0nqwQeP75jWZ0n4sF24Zxoht1cuJoWopwj0J0exYwCJ0dCQ=="],
|
||||
|
||||
"@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.16", "", { "dependencies": { "@babel/parser": "^7.27.2", "@vue/compiler-core": "3.5.16", "@vue/compiler-dom": "3.5.16", "@vue/compiler-ssr": "3.5.16", "@vue/shared": "3.5.16", "estree-walker": "^2.0.2", "magic-string": "^0.30.17", "postcss": "^8.5.3", "source-map-js": "^1.2.1" } }, "sha512-rQR6VSFNpiinDy/DVUE0vHoIDUF++6p910cgcZoaAUm3POxgNOOdS/xgoll3rNdKYTYPnnbARDCZOyZ+QSe6Pw=="],
|
||||
|
||||
"@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.16", "", { "dependencies": { "@vue/compiler-dom": "3.5.16", "@vue/shared": "3.5.16" } }, "sha512-d2V7kfxbdsjrDSGlJE7my1ZzCXViEcqN6w14DOsDrUCHEA6vbnVCpRFfrc4ryCP/lCKzX2eS1YtnLE/BuC9f/A=="],
|
||||
|
||||
"@vue/reactivity": ["@vue/reactivity@3.5.16", "", { "dependencies": { "@vue/shared": "3.5.16" } }, "sha512-FG5Q5ee/kxhIm1p2bykPpPwqiUBV3kFySsHEQha5BJvjXdZTUfmya7wP7zC39dFuZAcf/PD5S4Lni55vGLMhvA=="],
|
||||
|
||||
"@vue/runtime-core": ["@vue/runtime-core@3.5.16", "", { "dependencies": { "@vue/reactivity": "3.5.16", "@vue/shared": "3.5.16" } }, "sha512-bw5Ykq6+JFHYxrQa7Tjr+VSzw7Dj4ldR/udyBZbq73fCdJmyy5MPIFR9IX/M5Qs+TtTjuyUTCnmK3lWWwpAcFQ=="],
|
||||
|
||||
"@vue/runtime-dom": ["@vue/runtime-dom@3.5.16", "", { "dependencies": { "@vue/reactivity": "3.5.16", "@vue/runtime-core": "3.5.16", "@vue/shared": "3.5.16", "csstype": "^3.1.3" } }, "sha512-T1qqYJsG2xMGhImRUV9y/RseB9d0eCYZQ4CWca9ztCuiPj/XWNNN+lkNBuzVbia5z4/cgxdL28NoQCvC0Xcfww=="],
|
||||
|
||||
"@vue/server-renderer": ["@vue/server-renderer@3.5.16", "", { "dependencies": { "@vue/compiler-ssr": "3.5.16", "@vue/shared": "3.5.16" }, "peerDependencies": { "vue": "3.5.16" } }, "sha512-BrX0qLiv/WugguGsnQUJiYOE0Fe5mZTwi6b7X/ybGB0vfrPH9z0gD/Y6WOR1sGCgX4gc25L1RYS5eYQKDMoNIg=="],
|
||||
|
||||
"@vue/shared": ["@vue/shared@3.5.16", "", {}, "sha512-c/0fWy3Jw6Z8L9FmTyYfkpM5zklnqqa9+a6dz3DvONRKW2NEbh46BP0FHuLFSWi2TnQEtp91Z6zOWNrU6QiyPg=="],
|
||||
|
||||
"@xhmikosr/archive-type": ["@xhmikosr/archive-type@7.0.0", "", { "dependencies": { "file-type": "^19.0.0" } }, "sha512-sIm84ZneCOJuiy3PpWR5bxkx3HaNt1pqaN+vncUBZIlPZCq8ASZH+hBVdu5H8znR7qYC6sKwx+ie2Q7qztJTxA=="],
|
||||
|
||||
"@xhmikosr/bin-check": ["@xhmikosr/bin-check@7.0.3", "", { "dependencies": { "execa": "^5.1.1", "isexe": "^2.0.0" } }, "sha512-4UnCLCs8DB+itHJVkqFp9Zjg+w/205/J2j2wNBsCEAm/BuBmtua2hhUOdAMQE47b1c7P9Xmddj0p+X1XVsfHsA=="],
|
||||
|
||||
"@xhmikosr/bin-wrapper": ["@xhmikosr/bin-wrapper@13.0.5", "", { "dependencies": { "@xhmikosr/bin-check": "^7.0.3", "@xhmikosr/downloader": "^15.0.1", "@xhmikosr/os-filter-obj": "^3.0.0", "bin-version-check": "^5.1.0" } }, "sha512-DT2SAuHDeOw0G5bs7wZbQTbf4hd8pJ14tO0i4cWhRkIJfgRdKmMfkDilpaJ8uZyPA0NVRwasCNAmMJcWA67osw=="],
|
||||
|
||||
"@xhmikosr/decompress": ["@xhmikosr/decompress@10.0.1", "", { "dependencies": { "@xhmikosr/decompress-tar": "^8.0.1", "@xhmikosr/decompress-tarbz2": "^8.0.1", "@xhmikosr/decompress-targz": "^8.0.1", "@xhmikosr/decompress-unzip": "^7.0.0", "graceful-fs": "^4.2.11", "make-dir": "^4.0.0", "strip-dirs": "^3.0.0" } }, "sha512-6uHnEEt5jv9ro0CDzqWlFgPycdE+H+kbJnwyxgZregIMLQ7unQSCNVsYG255FoqU8cP46DyggI7F7LohzEl8Ag=="],
|
||||
|
||||
"@xhmikosr/decompress-tar": ["@xhmikosr/decompress-tar@8.0.1", "", { "dependencies": { "file-type": "^19.0.0", "is-stream": "^2.0.1", "tar-stream": "^3.1.7" } }, "sha512-dpEgs0cQKJ2xpIaGSO0hrzz3Kt8TQHYdizHsgDtLorWajuHJqxzot9Hbi0huRxJuAGG2qiHSQkwyvHHQtlE+fg=="],
|
||||
|
||||
"@xhmikosr/decompress-tarbz2": ["@xhmikosr/decompress-tarbz2@8.0.2", "", { "dependencies": { "@xhmikosr/decompress-tar": "^8.0.1", "file-type": "^19.6.0", "is-stream": "^2.0.1", "seek-bzip": "^2.0.0", "unbzip2-stream": "^1.4.3" } }, "sha512-p5A2r/AVynTQSsF34Pig6olt9CvRj6J5ikIhzUd3b57pUXyFDGtmBstcw+xXza0QFUh93zJsmY3zGeNDlR2AQQ=="],
|
||||
|
||||
"@xhmikosr/decompress-targz": ["@xhmikosr/decompress-targz@8.0.1", "", { "dependencies": { "@xhmikosr/decompress-tar": "^8.0.1", "file-type": "^19.0.0", "is-stream": "^2.0.1" } }, "sha512-mvy5AIDIZjQ2IagMI/wvauEiSNHhu/g65qpdM4EVoYHUJBAmkQWqcPJa8Xzi1aKVTmOA5xLJeDk7dqSjlHq8Mg=="],
|
||||
|
||||
"@xhmikosr/decompress-unzip": ["@xhmikosr/decompress-unzip@7.0.0", "", { "dependencies": { "file-type": "^19.0.0", "get-stream": "^6.0.1", "yauzl": "^3.1.2" } }, "sha512-GQMpzIpWTsNr6UZbISawsGI0hJ4KA/mz5nFq+cEoPs12UybAqZWKbyIaZZyLbJebKl5FkLpsGBkrplJdjvUoSQ=="],
|
||||
|
||||
"@xhmikosr/downloader": ["@xhmikosr/downloader@15.0.1", "", { "dependencies": { "@xhmikosr/archive-type": "^7.0.0", "@xhmikosr/decompress": "^10.0.1", "content-disposition": "^0.5.4", "defaults": "^3.0.0", "ext-name": "^5.0.0", "file-type": "^19.0.0", "filenamify": "^6.0.0", "get-stream": "^6.0.1", "got": "^13.0.0" } }, "sha512-fiuFHf3Dt6pkX8HQrVBsK0uXtkgkVlhrZEh8b7VgoDqFf+zrgFBPyrwCqE/3nDwn3hLeNz+BsrS7q3mu13Lp1g=="],
|
||||
|
||||
"@xhmikosr/os-filter-obj": ["@xhmikosr/os-filter-obj@3.0.0", "", { "dependencies": { "arch": "^3.0.0" } }, "sha512-siPY6BD5dQ2SZPl3I0OZBHL27ZqZvLEosObsZRQ1NUB8qcxegwt0T9eKtV96JMFQpIz1elhkzqOg4c/Ri6Dp9A=="],
|
||||
|
||||
"acorn": ["acorn@8.14.1", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg=="],
|
||||
|
||||
"ansi-colors": ["ansi-colors@4.1.3", "", {}, "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw=="],
|
||||
|
||||
"ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="],
|
||||
|
||||
"arch": ["arch@3.0.0", "", {}, "sha512-AmIAC+Wtm2AU8lGfTtHsw0Y9Qtftx2YXEEtiBP10xFUtMOA+sHHx6OAddyL52mUKh1vsXQ6/w1mVDptZCyUt4Q=="],
|
||||
|
||||
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
|
||||
|
||||
"aria-query": ["aria-query@5.3.2", "", {}, "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw=="],
|
||||
|
||||
"axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="],
|
||||
|
||||
"b4a": ["b4a@1.6.7", "", {}, "sha512-OnAYlL5b7LEkALw87fUVafQw5rVR9RjwGd4KUwNQ6DrrNmaVaUCgLipfVlzrPQ4tWOR9P0IXGNOx50jYCCdSJg=="],
|
||||
|
||||
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
|
||||
|
||||
"bare-events": ["bare-events@2.5.4", "", {}, "sha512-+gFfDkR8pj4/TrWCGUGWmJIkBwuxPS5F+a5yWjOHQt2hHvNZd5YLzadjmDUtFmMM4y429bnKLa8bYBMHcYdnQA=="],
|
||||
|
||||
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
|
||||
|
||||
"bin-version": ["bin-version@6.0.0", "", { "dependencies": { "execa": "^5.0.0", "find-versions": "^5.0.0" } }, "sha512-nk5wEsP4RiKjG+vF+uG8lFsEn4d7Y6FVDamzzftSunXOoOcOOkzcWdKVlGgFFwlUQCj63SgnUkLLGF8v7lufhw=="],
|
||||
|
||||
"bin-version-check": ["bin-version-check@5.1.0", "", { "dependencies": { "bin-version": "^6.0.0", "semver": "^7.5.3", "semver-truncate": "^3.0.0" } }, "sha512-bYsvMqJ8yNGILLz1KP9zKLzQ6YpljV3ln1gqhuLkUtyfGi3qXKGuK2p+U4NAvjVFzDFiBBtOpCOSFNuYYEGZ5g=="],
|
||||
|
||||
"brace-expansion": ["brace-expansion@2.0.1", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA=="],
|
||||
|
||||
"braces": ["braces@3.0.2", "", { "dependencies": { "fill-range": "^7.0.1" } }, "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A=="],
|
||||
|
||||
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
|
||||
|
||||
"buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
|
||||
|
||||
"cacheable-lookup": ["cacheable-lookup@7.0.0", "", {}, "sha512-+qJyx4xiKra8mZrcwhjMRMUhD5NR1R8esPkzIYxX96JiecFoxAXFuz/GpR3+ev4PE1WamHip78wV0vcmPQtp8w=="],
|
||||
|
||||
"cacheable-request": ["cacheable-request@10.2.14", "", { "dependencies": { "@types/http-cache-semantics": "^4.0.2", "get-stream": "^6.0.1", "http-cache-semantics": "^4.1.1", "keyv": "^4.5.3", "mimic-response": "^4.0.0", "normalize-url": "^8.0.0", "responselike": "^3.0.0" } }, "sha512-zkDT5WAF4hSSoUgyfg5tFIxz8XQK+25W/TLVojJTMKBaxevLBBtLxgqguAuVQB8PVW79FVjHcU+GJ9tVbDZ9mQ=="],
|
||||
|
||||
"callsites": ["callsites@3.1.0", "", {}, "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ=="],
|
||||
|
||||
"chalk": ["chalk@5.4.1", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="],
|
||||
|
||||
"chalk-template": ["chalk-template@1.1.0", "", { "dependencies": { "chalk": "^5.2.0" } }, "sha512-T2VJbcDuZQ0Tb2EWwSotMPJjgpy1/tGee1BTpUNsGZ/qgNjV2t7Mvu+d4600U564nbLesN1x2dPL+xii174Ekg=="],
|
||||
|
||||
"chokidar": ["chokidar@4.0.3", "", { "dependencies": { "readdirp": "^4.0.1" } }, "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA=="],
|
||||
|
||||
"cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="],
|
||||
|
||||
"cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="],
|
||||
|
||||
"clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="],
|
||||
|
||||
"colord": ["colord@2.9.3", "", {}, "sha512-jeC1axXpnb0/2nn/Y1LPuLdgXBLH7aDcHu4KEKfqw3CUhX7ZpfBSlPKyqXE6btIgEzfWtrX3/tyBCaCvXvMkOw=="],
|
||||
|
||||
"commander": ["commander@8.3.0", "", {}, "sha512-OkTL9umf+He2DZkUq8f8J9of7yL6RJKI24dVITBmNfZBmri9zYZQrKkuXiKhyfPSu8tUhnVBB1iKXevvnlR4Ww=="],
|
||||
|
||||
"content-disposition": ["content-disposition@0.5.4", "", { "dependencies": { "safe-buffer": "5.2.1" } }, "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ=="],
|
||||
|
||||
"cosmiconfig": ["cosmiconfig@9.0.0", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-itvL5h8RETACmOTFc4UfIyB2RfEHi71Ax6E/PivVxq9NseKbOWpeyHEOIbmAw1rs8Ak0VursQNww7lf7YtUwzg=="],
|
||||
|
||||
"cross-spawn": ["cross-spawn@7.0.3", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w=="],
|
||||
|
||||
"csstype": ["csstype@3.1.3", "", {}, "sha512-M1uQkMl8rQK/szD0LNhtqxIPLpimGm8sOBwU7lLnCpSbTyY3yeU1Vc7l4KT5zT4s/yOxHH5O7tIuuLOCnLADRw=="],
|
||||
|
||||
"debug": ["debug@4.4.1", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ=="],
|
||||
|
||||
"decompress-response": ["decompress-response@6.0.0", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
|
||||
|
||||
"deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="],
|
||||
|
||||
"defaults": ["defaults@3.0.0", "", {}, "sha512-RsqXDEAALjfRTro+IFNKpcPCt0/Cy2FqHSIlnomiJp9YGadpQnrtbRpSgN2+np21qHcIKiva4fiOQGjS9/qR/A=="],
|
||||
|
||||
"defer-to-connect": ["defer-to-connect@2.0.1", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
|
||||
|
||||
"detect-libc": ["detect-libc@1.0.3", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="],
|
||||
|
||||
"effect": ["effect@3.16.4", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "fast-check": "^3.23.1" } }, "sha512-zJo5MRPEMROLjTHyrOJs0PUeEnRLy0ABwum3+HWlP8Y9LNF+NjipIRldVAcjSVQpJ7vY/OEGBxzw0USPzTfWag=="],
|
||||
|
||||
"emoji-regex": ["emoji-regex@10.4.0", "", {}, "sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw=="],
|
||||
|
||||
"enquirer": ["enquirer@2.4.1", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="],
|
||||
|
||||
"entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="],
|
||||
|
||||
"env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="],
|
||||
|
||||
"error-ex": ["error-ex@1.3.2", "", { "dependencies": { "is-arrayish": "^0.2.1" } }, "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g=="],
|
||||
|
||||
"esbuild": ["esbuild@0.25.5", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.5", "@esbuild/android-arm": "0.25.5", "@esbuild/android-arm64": "0.25.5", "@esbuild/android-x64": "0.25.5", "@esbuild/darwin-arm64": "0.25.5", "@esbuild/darwin-x64": "0.25.5", "@esbuild/freebsd-arm64": "0.25.5", "@esbuild/freebsd-x64": "0.25.5", "@esbuild/linux-arm": "0.25.5", "@esbuild/linux-arm64": "0.25.5", "@esbuild/linux-ia32": "0.25.5", "@esbuild/linux-loong64": "0.25.5", "@esbuild/linux-mips64el": "0.25.5", "@esbuild/linux-ppc64": "0.25.5", "@esbuild/linux-riscv64": "0.25.5", "@esbuild/linux-s390x": "0.25.5", "@esbuild/linux-x64": "0.25.5", "@esbuild/netbsd-arm64": "0.25.5", "@esbuild/netbsd-x64": "0.25.5", "@esbuild/openbsd-arm64": "0.25.5", "@esbuild/openbsd-x64": "0.25.5", "@esbuild/sunos-x64": "0.25.5", "@esbuild/win32-arm64": "0.25.5", "@esbuild/win32-ia32": "0.25.5", "@esbuild/win32-x64": "0.25.5" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-P8OtKZRv/5J5hhz0cUAdu/cLuPIKXpQl1R9pZtvmHWQvrAUVd0UNIPT4IB4W3rNOqVO0rlqHmCIbSwxh/c9yUQ=="],
|
||||
|
||||
"esm-env": ["esm-env@1.2.2", "", {}, "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA=="],
|
||||
|
||||
"esrap": ["esrap@1.4.7", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" } }, "sha512-0ZxW6guTF/AeKeKi7he93lmgv7Hx7giD1tBrOeVqkqsZGQJd2/kfnL7LdIsr9FT/AtkBK9XeDTov+gxprBqdEg=="],
|
||||
|
||||
"estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
|
||||
|
||||
"execa": ["execa@5.1.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],
|
||||
|
||||
"ext-list": ["ext-list@2.2.2", "", { "dependencies": { "mime-db": "^1.28.0" } }, "sha512-u+SQgsubraE6zItfVA0tBuCBhfU9ogSRnsvygI7wht9TS510oLkBRXBsqopeUG/GBOIQyKZO9wjTqIu/sf5zFA=="],
|
||||
|
||||
"ext-name": ["ext-name@5.0.0", "", { "dependencies": { "ext-list": "^2.0.0", "sort-keys-length": "^1.0.0" } }, "sha512-yblEwXAbGv1VQDmow7s38W77hzAgJAO50ztBLMcUyUBfxv1HC+LGwtiEN+Co6LtlqT/5uwVOxsD4TNIilWhwdQ=="],
|
||||
|
||||
"fast-check": ["fast-check@3.23.2", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||
|
||||
"fast-fifo": ["fast-fifo@1.3.2", "", {}, "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ=="],
|
||||
|
||||
"fast-glob": ["fast-glob@3.3.2", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.4" } }, "sha512-oX2ruAFQwf/Orj8m737Y5adxDQO0LAB7/S5MnxCdTNDd4p6BsyIVsv9JQsATbTSq8KHRpLwIHbVlUNatxd+1Ow=="],
|
||||
|
||||
"fastq": ["fastq@1.17.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-sRVD3lWVIXWg6By68ZN7vho9a1pQcN/WBFaAAsDDFzlJjvoGx0P8z7V1t72grFJfJhu3YPZBuu25f7Kaw2jN1w=="],
|
||||
|
||||
"fdir": ["fdir@6.4.5", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-4BG7puHpVsIYxZUbiUE3RqGloLaSSwzYie5jvasC4LWuBWzZawynvYouhjbQKw2JuIGYdm0DzIxl8iVidKlUEw=="],
|
||||
|
||||
"file-type": ["file-type@19.6.0", "", { "dependencies": { "get-stream": "^9.0.1", "strtok3": "^9.0.1", "token-types": "^6.0.0", "uint8array-extras": "^1.3.0" } }, "sha512-VZR5I7k5wkD0HgFnMsq5hOsSc710MJMu5Nc5QYsbe38NN5iPV/XTObYLc/cpttRTf6lX538+5uO1ZQRhYibiZQ=="],
|
||||
|
||||
"filename-reserved-regex": ["filename-reserved-regex@3.0.0", "", {}, "sha512-hn4cQfU6GOT/7cFHXBqeBg2TbrMBgdD0kcjLhvSQYYwm3s4B6cjvBfb7nBALJLAXqmU5xajSa7X2NnUud/VCdw=="],
|
||||
|
||||
"filenamify": ["filenamify@6.0.0", "", { "dependencies": { "filename-reserved-regex": "^3.0.0" } }, "sha512-vqIlNogKeyD3yzrm0yhRMQg8hOVwYcYRfjEoODd49iCprMn4HL85gK3HcykQE53EPIpX3HcAbGA5ELQv216dAQ=="],
|
||||
|
||||
"fill-range": ["fill-range@7.0.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ=="],
|
||||
|
||||
"find-versions": ["find-versions@5.1.0", "", { "dependencies": { "semver-regex": "^4.0.5" } }, "sha512-+iwzCJ7C5v5KgcBuueqVoNiHVoQpwiUK5XFLjf0affFTep+Wcw93tPvmb8tqujDNmzhBDPddnWV/qgWSXgq+Hg=="],
|
||||
|
||||
"form-data-encoder": ["form-data-encoder@2.1.4", "", {}, "sha512-yDYSgNMraqvnxiEXO4hi88+YZxaHC6QKzb5N84iRCTDeRO7ZALpir/lVmf/uXUhnwUr2O4HU8s/n6x+yNjQkHw=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"get-east-asian-width": ["get-east-asian-width@1.3.0", "", {}, "sha512-vpeMIQKxczTD/0s2CdEWHcb0eeJe6TFjxb+J5xgX7hScxqrGuyjmv4c1D4A/gelKfyox0gJJwIHF+fLjeaM8kQ=="],
|
||||
|
||||
"get-stream": ["get-stream@6.0.1", "", {}, "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg=="],
|
||||
|
||||
"glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"globby": ["globby@14.1.0", "", { "dependencies": { "@sindresorhus/merge-streams": "^2.1.0", "fast-glob": "^3.3.3", "ignore": "^7.0.3", "path-type": "^6.0.0", "slash": "^5.1.0", "unicorn-magic": "^0.3.0" } }, "sha512-0Ia46fDOaT7k4og1PDW4YbodWWr3scS2vAr2lTbsplOt2WkKp0vQbkI9wKis/T5LV/dqPjO3bpS/z6GTJB82LA=="],
|
||||
|
||||
"got": ["got@13.0.0", "", { "dependencies": { "@sindresorhus/is": "^5.2.0", "@szmarczak/http-timer": "^5.0.1", "cacheable-lookup": "^7.0.0", "cacheable-request": "^10.2.8", "decompress-response": "^6.0.0", "form-data-encoder": "^2.1.2", "get-stream": "^6.0.1", "http2-wrapper": "^2.1.10", "lowercase-keys": "^3.0.0", "p-cancelable": "^3.0.0", "responselike": "^3.0.0" } }, "sha512-XfBk1CxOOScDcMr9O1yKkNaQyy865NbYs+F7dr4H0LZMVgCj2Le59k6PqbNHoL5ToeaEQUYh6c6yMfVcc6SJxA=="],
|
||||
|
||||
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
|
||||
|
||||
"hosted-git-info": ["hosted-git-info@8.1.0", "", { "dependencies": { "lru-cache": "^10.0.1" } }, "sha512-Rw/B2DNQaPBICNXEm8balFz9a6WpZrkCGpcWFpy7nCj+NyhSdqXipmfvtmWt9xGfp0wZnBxB+iVpLmQMYt47Tw=="],
|
||||
|
||||
"http-cache-semantics": ["http-cache-semantics@4.1.1", "", {}, "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ=="],
|
||||
|
||||
"http2-wrapper": ["http2-wrapper@2.2.1", "", { "dependencies": { "quick-lru": "^5.1.1", "resolve-alpn": "^1.2.0" } }, "sha512-V5nVw1PAOgfI3Lmeaj2Exmeg7fenjhRUgz1lPSezy1CuhPYbgQtbQj4jZfEAEMlaL+vupsvhjqCyjzob0yxsmQ=="],
|
||||
|
||||
"human-signals": ["human-signals@2.1.0", "", {}, "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw=="],
|
||||
|
||||
"iconify-icon": ["iconify-icon@3.0.0", "", { "dependencies": { "@iconify/types": "^2.0.0" } }, "sha512-yPcnpkn8HUEUckrxxJBOer3jbGv3bqozHsLMLBRxhk3As1X76BgV2mS2a1HTNOIagR8nUs30H3qAd9GLe8Mnlg=="],
|
||||
|
||||
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
|
||||
|
||||
"ignore": ["ignore@7.0.5", "", {}, "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg=="],
|
||||
|
||||
"immutable": ["immutable@5.1.2", "", {}, "sha512-qHKXW1q6liAk1Oys6umoaZbDRqjcjgSrbnrifHsfsttza7zcvRAsL7mMV6xWcyhwQy7Xj5v4hhbr6b+iDYwlmQ=="],
|
||||
|
||||
"import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="],
|
||||
|
||||
"inspect-with-kind": ["inspect-with-kind@1.0.5", "", { "dependencies": { "kind-of": "^6.0.2" } }, "sha512-MAQUJuIo7Xqk8EVNP+6d3CKq9c80hi4tjIbIAT6lmGW9W6WzlHiu9PS8uSuUYU+Do+j1baiFp3H25XEVxDIG2g=="],
|
||||
|
||||
"is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="],
|
||||
|
||||
"is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="],
|
||||
|
||||
"is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="],
|
||||
|
||||
"is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="],
|
||||
|
||||
"is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
|
||||
|
||||
"is-plain-obj": ["is-plain-obj@1.1.0", "", {}, "sha512-yvkRyxmFKEOQ4pNXCmJG5AEQNlXJS5LaONXo5/cLdTZdWvsZ1ioJEonLGAosKlMWE8lwUy/bJzMjcw8az73+Fg=="],
|
||||
|
||||
"is-reference": ["is-reference@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="],
|
||||
|
||||
"is-stream": ["is-stream@2.0.1", "", {}, "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="],
|
||||
|
||||
"is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="],
|
||||
|
||||
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||
|
||||
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||
|
||||
"js-yaml": ["js-yaml@4.1.0", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA=="],
|
||||
|
||||
"json-buffer": ["json-buffer@3.0.1", "", {}, "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="],
|
||||
|
||||
"json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="],
|
||||
|
||||
"jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="],
|
||||
|
||||
"keyv": ["keyv@4.5.4", "", { "dependencies": { "json-buffer": "3.0.1" } }, "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw=="],
|
||||
|
||||
"kind-of": ["kind-of@6.0.3", "", {}, "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw=="],
|
||||
|
||||
"kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="],
|
||||
|
||||
"lines-and-columns": ["lines-and-columns@1.2.4", "", {}, "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg=="],
|
||||
|
||||
"locate-character": ["locate-character@3.0.0", "", {}, "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA=="],
|
||||
|
||||
"log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="],
|
||||
|
||||
"lowercase-keys": ["lowercase-keys@3.0.0", "", {}, "sha512-ozCC6gdQ+glXOQsveKD0YsDy8DSQFjDTz4zyzEHNV5+JP5D62LmfDZ6o1cycFx9ouG940M5dE8C8CTewdj2YWQ=="],
|
||||
|
||||
"lru-cache": ["lru-cache@10.4.3", "", {}, "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ=="],
|
||||
|
||||
"magic-string": ["magic-string@0.30.17", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0" } }, "sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA=="],
|
||||
|
||||
"make-dir": ["make-dir@4.0.0", "", { "dependencies": { "semver": "^7.5.3" } }, "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw=="],
|
||||
|
||||
"merge-stream": ["merge-stream@2.0.0", "", {}, "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w=="],
|
||||
|
||||
"merge2": ["merge2@1.4.1", "", {}, "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg=="],
|
||||
|
||||
"micromatch": ["micromatch@4.0.5", "", { "dependencies": { "braces": "^3.0.2", "picomatch": "^2.3.1" } }, "sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA=="],
|
||||
|
||||
"mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="],
|
||||
|
||||
"mimic-fn": ["mimic-fn@2.1.0", "", {}, "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg=="],
|
||||
|
||||
"mimic-function": ["mimic-function@5.0.1", "", {}, "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA=="],
|
||||
|
||||
"mimic-response": ["mimic-response@4.0.0", "", {}, "sha512-e5ISH9xMYU0DzrT+jl8q2ze9D6eWBto+I8CNpe+VI+K2J/F/k3PdkdTdz4wvGVH4NTpo+NRYTVIuMQEMMcsLqg=="],
|
||||
|
||||
"minimatch": ["minimatch@9.0.4", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-KqWh+VchfxcMNRAJjj2tnsSJdNbHsVgnkBhTNrW7AjVo6OvLtxw8zfT9oLw1JSohlFzJ8jCoTgaoXvJ+kHt6fw=="],
|
||||
|
||||
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
|
||||
|
||||
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
|
||||
|
||||
"nice-napi": ["nice-napi@1.0.2", "", { "dependencies": { "node-addon-api": "^3.0.0", "node-gyp-build": "^4.2.2" }, "os": "!win32" }, "sha512-px/KnJAJZf5RuBGcfD+Sp2pAKq0ytz8j+1NehvgIGFkvtvFrDM3T8E4x/JJODXK9WZow8RRGrbA9QQ3hs+pDhA=="],
|
||||
|
||||
"node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="],
|
||||
|
||||
"node-gyp-build": ["node-gyp-build@4.8.1", "", { "bin": { "node-gyp-build": "bin.js", "node-gyp-build-optional": "optional.js", "node-gyp-build-test": "build-test.js" } }, "sha512-OSs33Z9yWr148JZcbZd5WiAXhh/n9z8TxQcdMhIOlpN9AhWpLfvVFO73+m77bBABQMaY9XSvIa+qk0jlI7Gcaw=="],
|
||||
|
||||
"normalize-url": ["normalize-url@8.0.1", "", {}, "sha512-IO9QvjUMWxPQQhs60oOu10CRkWCiZzSUkzbXGGV9pviYl1fXYcvkzQ5jV9z8Y6un8ARoVRl4EtC6v6jNqbaJ/w=="],
|
||||
|
||||
"npm-package-arg": ["npm-package-arg@12.0.2", "", { "dependencies": { "hosted-git-info": "^8.0.0", "proc-log": "^5.0.0", "semver": "^7.3.5", "validate-npm-package-name": "^6.0.0" } }, "sha512-f1NpFjNI9O4VbKMOlA5QoBq/vSQPORHcTZ2feJpFkTHJ9eQkdlmZEKSjcAhxTGInC7RlEyScT9ui67NaOsjFWA=="],
|
||||
|
||||
"npm-run-path": ["npm-run-path@4.0.1", "", { "dependencies": { "path-key": "^3.0.0" } }, "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw=="],
|
||||
|
||||
"onetime": ["onetime@5.1.2", "", { "dependencies": { "mimic-fn": "^2.1.0" } }, "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg=="],
|
||||
|
||||
"ora": ["ora@8.2.0", "", { "dependencies": { "chalk": "^5.3.0", "cli-cursor": "^5.0.0", "cli-spinners": "^2.9.2", "is-interactive": "^2.0.0", "is-unicode-supported": "^2.0.0", "log-symbols": "^6.0.0", "stdin-discarder": "^0.2.2", "string-width": "^7.2.0", "strip-ansi": "^7.1.0" } }, "sha512-weP+BZ8MVNnlCm8c0Qdc1WSWq4Qn7I+9CJGm7Qali6g44e/PUzbjNqJX5NJ9ljlNMosfJvg1fKEGILklK9cwnw=="],
|
||||
|
||||
"p-cancelable": ["p-cancelable@3.0.0", "", {}, "sha512-mlVgR3PGuzlo0MmTdk4cXqXWlwQDLnONTAg6sm62XkMJEiRxN3GL3SffkYvqwonbkJBcrI7Uvv5Zh9yjvn2iUw=="],
|
||||
|
||||
"parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
|
||||
|
||||
"parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="],
|
||||
|
||||
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||
|
||||
"path-type": ["path-type@6.0.0", "", {}, "sha512-Vj7sf++t5pBD637NSfkxpHSMfWaeig5+DKWLhcqIYx6mWQz5hdJTGDVMQiJcw1ZYkhs7AazKDGpRVji1LJCZUQ=="],
|
||||
|
||||
"peek-readable": ["peek-readable@5.4.2", "", {}, "sha512-peBp3qZyuS6cNIJ2akRNG1uo1WJ1d0wTxg/fxMdZ0BqCVhx242bSFHM9eNqflfJVS9SsgkzgT/1UgnsurBOTMg=="],
|
||||
|
||||
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
|
||||
|
||||
"picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
|
||||
|
||||
"picomatch": ["picomatch@4.0.2", "", {}, "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg=="],
|
||||
|
||||
"piscina": ["piscina@4.4.0", "", { "optionalDependencies": { "nice-napi": "^1.0.2" } }, "sha512-+AQduEJefrOApE4bV7KRmp3N2JnnyErlVqq4P/jmko4FPz9Z877BCccl/iB3FdrWSUkvbGV9Kan/KllJgat3Vg=="],
|
||||
|
||||
"postcss": ["postcss@8.5.4", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-QSa9EBe+uwlGTFmHsPKokv3B/oEMQZxfqW0QqNCyhpa6mB1afzulwn8hihglqAb2pOw+BJgNlmXQ8la2VeHB7w=="],
|
||||
|
||||
"prettier": ["prettier@3.5.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw=="],
|
||||
|
||||
"prettier-plugin-svelte": ["prettier-plugin-svelte@3.4.0", "", { "peerDependencies": { "prettier": "^3.0.0", "svelte": "^3.2.0 || ^4.0.0-next.0 || ^5.0.0-next.0" } }, "sha512-pn1ra/0mPObzqoIQn/vUTR3ZZI6UuZ0sHqMK5x2jMLGrs53h0sXhkVuDcrlssHwIMk7FYrMjHBPoUSyyEEDlBQ=="],
|
||||
|
||||
"proc-log": ["proc-log@5.0.0", "", {}, "sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ=="],
|
||||
|
||||
"prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="],
|
||||
|
||||
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
|
||||
|
||||
"queue-microtask": ["queue-microtask@1.2.3", "", {}, "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A=="],
|
||||
|
||||
"quick-lru": ["quick-lru@5.1.1", "", {}, "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA=="],
|
||||
|
||||
"read-yaml-file": ["read-yaml-file@2.1.0", "", { "dependencies": { "js-yaml": "^4.0.0", "strip-bom": "^4.0.0" } }, "sha512-UkRNRIwnhG+y7hpqnycCL/xbTk7+ia9VuVTC0S+zVbwd65DI9eUpRMfsWIGrCWxTU/mi+JW8cHQCrv+zfCbEPQ=="],
|
||||
|
||||
"readdirp": ["readdirp@4.1.2", "", {}, "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg=="],
|
||||
|
||||
"regenerator-runtime": ["regenerator-runtime@0.14.1", "", {}, "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw=="],
|
||||
|
||||
"resolve-alpn": ["resolve-alpn@1.2.1", "", {}, "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="],
|
||||
|
||||
"resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="],
|
||||
|
||||
"responselike": ["responselike@3.0.0", "", { "dependencies": { "lowercase-keys": "^3.0.0" } }, "sha512-40yHxbNcl2+rzXvZuVkrYohathsSJlMTXKryG5y8uciHv1+xDLHQpgjG64JUO9nrEq2jGLH6IZ8BcZyw3wrweg=="],
|
||||
|
||||
"restore-cursor": ["restore-cursor@5.1.0", "", { "dependencies": { "onetime": "^7.0.0", "signal-exit": "^4.1.0" } }, "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA=="],
|
||||
|
||||
"reusify": ["reusify@1.0.4", "", {}, "sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw=="],
|
||||
|
||||
"rollup": ["rollup@4.41.1", "", { "dependencies": { "@types/estree": "1.0.7" }, "optionalDependencies": { "@rollup/rollup-android-arm-eabi": "4.41.1", "@rollup/rollup-android-arm64": "4.41.1", "@rollup/rollup-darwin-arm64": "4.41.1", "@rollup/rollup-darwin-x64": "4.41.1", "@rollup/rollup-freebsd-arm64": "4.41.1", "@rollup/rollup-freebsd-x64": "4.41.1", "@rollup/rollup-linux-arm-gnueabihf": "4.41.1", "@rollup/rollup-linux-arm-musleabihf": "4.41.1", "@rollup/rollup-linux-arm64-gnu": "4.41.1", "@rollup/rollup-linux-arm64-musl": "4.41.1", "@rollup/rollup-linux-loongarch64-gnu": "4.41.1", "@rollup/rollup-linux-powerpc64le-gnu": "4.41.1", "@rollup/rollup-linux-riscv64-gnu": "4.41.1", "@rollup/rollup-linux-riscv64-musl": "4.41.1", "@rollup/rollup-linux-s390x-gnu": "4.41.1", "@rollup/rollup-linux-x64-gnu": "4.41.1", "@rollup/rollup-linux-x64-musl": "4.41.1", "@rollup/rollup-win32-arm64-msvc": "4.41.1", "@rollup/rollup-win32-ia32-msvc": "4.41.1", "@rollup/rollup-win32-x64-msvc": "4.41.1", "fsevents": "~2.3.2" }, "bin": { "rollup": "dist/bin/rollup" } }, "sha512-cPmwD3FnFv8rKMBc1MxWCwVQFxwf1JEmSX3iQXrRVVG15zerAIXRjMFVWnd5Q5QvgKF7Aj+5ykXFhUl+QGnyOw=="],
|
||||
|
||||
"run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="],
|
||||
|
||||
"safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
|
||||
|
||||
"sass": ["sass@1.89.1", "", { "dependencies": { "chokidar": "^4.0.0", "immutable": "^5.0.2", "source-map-js": ">=0.6.2 <2.0.0" }, "optionalDependencies": { "@parcel/watcher": "^2.4.1" }, "bin": { "sass": "sass.js" } }, "sha512-eMLLkl+qz7tx/0cJ9wI+w09GQ2zodTkcE/aVfywwdlRcI3EO19xGnbmJwg/JMIm+5MxVJ6outddLZ4Von4E++Q=="],
|
||||
|
||||
"seek-bzip": ["seek-bzip@2.0.0", "", { "dependencies": { "commander": "^6.0.0" }, "bin": { "seek-bunzip": "bin/seek-bunzip", "seek-table": "bin/seek-bzip-table" } }, "sha512-SMguiTnYrhpLdk3PwfzHeotrcwi8bNV4iemL9tx9poR/yeaMYwB9VzR1w7b57DuWpuqR8n6oZboi0hj3AxZxQg=="],
|
||||
|
||||
"semver": ["semver@7.6.2", "", { "bin": "bin/semver.js" }, "sha512-FNAIBWCx9qcRhoHcgcJ0gvU7SN1lYU2ZXuSfl04bSC5OpvDHFyJCjdNHomPXxjQlCBU67YW64PzY7/VIEH7F2w=="],
|
||||
|
||||
"semver-regex": ["semver-regex@4.0.5", "", {}, "sha512-hunMQrEy1T6Jr2uEVjrAIqjwWcQTgOAcIM52C8MY1EZSD3DDNft04XzvYKPqjED65bNVVko0YI38nYeEHCX3yw=="],
|
||||
|
||||
"semver-truncate": ["semver-truncate@3.0.0", "", { "dependencies": { "semver": "^7.3.5" } }, "sha512-LJWA9kSvMolR51oDE6PN3kALBNaUdkxzAGcexw8gjMA8xr5zUqK0JiR3CgARSqanYF3Z1YHvsErb1KDgh+v7Rg=="],
|
||||
|
||||
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||
|
||||
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="],
|
||||
|
||||
"sisteransi": ["sisteransi@1.0.5", "", {}, "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg=="],
|
||||
|
||||
"slash": ["slash@3.0.0", "", {}, "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q=="],
|
||||
|
||||
"sort-keys": ["sort-keys@1.1.2", "", { "dependencies": { "is-plain-obj": "^1.0.0" } }, "sha512-vzn8aSqKgytVik0iwdBEi+zevbTYZogewTUM6dtpmGwEcdzbub/TX4bCzRhebDCRC3QzXgJsLRKB2V/Oof7HXg=="],
|
||||
|
||||
"sort-keys-length": ["sort-keys-length@1.0.1", "", { "dependencies": { "sort-keys": "^1.0.0" } }, "sha512-GRbEOUqCxemTAk/b32F2xa8wDTs+Z1QHOkbhJDQTvv/6G3ZkbJ+frYWsTcc7cBB3Fu4wy4XlLCuNtJuMn7Gsvw=="],
|
||||
|
||||
"source-map": ["source-map@0.7.4", "", {}, "sha512-l3BikUxvPOcn5E74dZiq5BGsTb5yEwhaTSzccU6t4sDOH8NWJCstKO5QT2CvtFoK6F0saL7p9xHAqHOlCPJygA=="],
|
||||
|
||||
"source-map-js": ["source-map-js@1.2.0", "", {}, "sha512-itJW8lvSA0TXEphiRoawsCksnlf8SyvmFzIhltqAHluXd88pkCd+cXJVHTDwdCr0IzwptSm035IHQktUu1QUMg=="],
|
||||
|
||||
"stdin-discarder": ["stdin-discarder@0.2.2", "", {}, "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ=="],
|
||||
|
||||
"streamx": ["streamx@2.22.1", "", { "dependencies": { "fast-fifo": "^1.3.2", "text-decoder": "^1.1.0" }, "optionalDependencies": { "bare-events": "^2.2.0" } }, "sha512-znKXEBxfatz2GBNK02kRnCXjV+AA4kjZIUxeWSr3UGirZMJfTE9uiwKHobnbgxWyL/JWro8tTq+vOqAK1/qbSA=="],
|
||||
|
||||
"string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
|
||||
|
||||
"strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
|
||||
|
||||
"strip-bom": ["strip-bom@4.0.0", "", {}, "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w=="],
|
||||
|
||||
"strip-dirs": ["strip-dirs@3.0.0", "", { "dependencies": { "inspect-with-kind": "^1.0.5", "is-plain-obj": "^1.1.0" } }, "sha512-I0sdgcFTfKQlUPZyAqPJmSG3HLO9rWDFnxonnIbskYNM3DwFOeTNB5KzVq3dA1GdRAc/25b5Y7UO2TQfKWw4aQ=="],
|
||||
|
||||
"strip-final-newline": ["strip-final-newline@2.0.0", "", {}, "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA=="],
|
||||
|
||||
"strtok3": ["strtok3@9.1.1", "", { "dependencies": { "@tokenizer/token": "^0.3.0", "peek-readable": "^5.3.1" } }, "sha512-FhwotcEqjr241ZbjFzjlIYg6c5/L/s4yBGWSMvJ9UoExiSqL+FnFA/CaeZx17WGaZMS/4SOZp8wH18jSS4R4lw=="],
|
||||
|
||||
"svelte": ["svelte@5.33.14", "", { "dependencies": { "@ampproject/remapping": "^2.3.0", "@jridgewell/sourcemap-codec": "^1.5.0", "@sveltejs/acorn-typescript": "^1.0.5", "@types/estree": "^1.0.5", "acorn": "^8.12.1", "aria-query": "^5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "esm-env": "^1.2.1", "esrap": "^1.4.6", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-kRlbhIlMTijbFmVDQFDeKXPLlX1/ovXwV0I162wRqQhRcygaqDIcu1d/Ese3H2uI+yt3uT8E7ndgDthQv5v5BA=="],
|
||||
|
||||
"svelte-awesome-color-picker": ["svelte-awesome-color-picker@4.0.2", "", { "dependencies": { "colord": "^2.9.3", "svelte-awesome-slider": "2.0.0" }, "peerDependencies": { "svelte": "^5.0.0" } }, "sha512-Ez72goMMNmw6sZhB1/BXEA8984lEkudPrdlNS+y3nHm2Lnk1w4nwy5NFyWPxTP7nFnLxhIqyV3VuJVG4PokKwg=="],
|
||||
|
||||
"svelte-awesome-slider": ["svelte-awesome-slider@2.0.0", "", { "peerDependencies": { "svelte": "^5.0.0" } }, "sha512-YBkOdYm1Feaqsn2JkJBRs+Kc/X3Qy/3GuVmI7GmoYDjBaHkjx9uH4khTuED22z57Hg3gGWeDhp/clIjWDdLNaw=="],
|
||||
|
||||
"svelte-dnd-action": ["svelte-dnd-action@0.9.61", "", { "peerDependencies": { "svelte": ">=3.23.0 || ^5.0.0-next.0" } }, "sha512-xj0jZNdV44MAMbdGIAuBYEombmK7A7ticemOtdR5ErWw0f3IxcfcnrRjlYEK0rRjsahVsU+VdGUMwjPVyXrSrA=="],
|
||||
|
||||
"svelte-portal": ["svelte-portal@2.2.1", "", {}, "sha512-uF7is5sM4aq5iN7QF/67XLnTUvQCf2iiG/B1BHTqLwYVY1dsVmTeXZ/LeEyU6dLjApOQdbEG9lkqHzxiQtOLEQ=="],
|
||||
|
||||
"syncpack": ["syncpack@13.0.4", "", { "dependencies": { "chalk": "^5.4.1", "chalk-template": "^1.1.0", "commander": "^13.1.0", "cosmiconfig": "^9.0.0", "effect": "^3.13.7", "enquirer": "^2.4.1", "fast-check": "^3.23.2", "globby": "^14.1.0", "jsonc-parser": "^3.3.1", "minimatch": "9.0.5", "npm-package-arg": "^12.0.2", "ora": "^8.2.0", "prompts": "^2.4.2", "read-yaml-file": "^2.1.0", "semver": "^7.7.1", "tightrope": "0.2.0", "ts-toolbelt": "^9.6.0" }, "bin": { "syncpack": "dist/bin.js", "syncpack-lint": "dist/bin-lint/index.js", "syncpack-list": "dist/bin-list/index.js", "syncpack-format": "dist/bin-format/index.js", "syncpack-prompt": "dist/bin-prompt/index.js", "syncpack-update": "dist/bin-update/index.js", "syncpack-fix-mismatches": "dist/bin-fix-mismatches/index.js", "syncpack-list-mismatches": "dist/bin-list-mismatches/index.js", "syncpack-set-semver-ranges": "dist/bin-set-semver-ranges/index.js", "syncpack-lint-semver-ranges": "dist/bin-lint-semver-ranges/index.js" } }, "sha512-kJ9VlRxNCsBD5pJAE29oXeBYbPLhEySQmK4HdpsLv81I6fcDDW17xeJqMwiU3H7/woAVsbgq25DJNS8BeiN5+w=="],
|
||||
|
||||
"tar-stream": ["tar-stream@3.1.7", "", { "dependencies": { "b4a": "^1.6.4", "fast-fifo": "^1.2.0", "streamx": "^2.15.0" } }, "sha512-qJj60CXt7IU1Ffyc3NJMjh6EkuCFej46zUqJ4J7pqYlThyd9bO0XBTmcOIhSzZJVWfsLks0+nle/j538YAW9RQ=="],
|
||||
|
||||
"text-decoder": ["text-decoder@1.2.3", "", { "dependencies": { "b4a": "^1.6.4" } }, "sha512-3/o9z3X0X0fTupwsYvR03pJ/DjWuqqrfwBgTQzdWDiQSm9KitAyz/9WqsT2JQW7KV2m+bC2ol/zqpW37NHxLaA=="],
|
||||
|
||||
"through": ["through@2.3.8", "", {}, "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg=="],
|
||||
|
||||
"tightrope": ["tightrope@0.2.0", "", {}, "sha512-Kw36UHxJEELq2VUqdaSGR2/8cAsPgMtvX8uGVU6Jk26O66PhXec0A5ZnRYs47btbtwPDpXXF66+Fo3vimCM9aQ=="],
|
||||
|
||||
"tinyglobby": ["tinyglobby@0.2.14", "", { "dependencies": { "fdir": "^6.4.4", "picomatch": "^4.0.2" } }, "sha512-tX5e7OM1HnYr2+a2C/4V0htOcSQcoSTH9KgJnVvNm5zm/cyEWKJ7j7YutsH9CxMdtOkkLFy2AHrMci9IM8IPZQ=="],
|
||||
|
||||
"to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
|
||||
|
||||
"token-types": ["token-types@6.0.0", "", { "dependencies": { "@tokenizer/token": "^0.3.0", "ieee754": "^1.2.1" } }, "sha512-lbDrTLVsHhOMljPscd0yitpozq7Ga2M5Cvez5AjGg8GASBjtt6iERCAJ93yommPmz62fb45oFIXHEZ3u9bfJEA=="],
|
||||
|
||||
"ts-toolbelt": ["ts-toolbelt@9.6.0", "", {}, "sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w=="],
|
||||
|
||||
"typescript": ["typescript@5.8.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ=="],
|
||||
|
||||
"uint8array-extras": ["uint8array-extras@1.4.0", "", {}, "sha512-ZPtzy0hu4cZjv3z5NW9gfKnNLjoz4y6uv4HlelAjDK7sY/xOkKZv9xK/WQpcsBB3jEybChz9DPC2U/+cusjJVQ=="],
|
||||
|
||||
"unbzip2-stream": ["unbzip2-stream@1.4.3", "", { "dependencies": { "buffer": "^5.2.1", "through": "^2.3.8" } }, "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg=="],
|
||||
|
||||
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
|
||||
|
||||
"unicorn-magic": ["unicorn-magic@0.3.0", "", {}, "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA=="],
|
||||
|
||||
"validate-npm-package-name": ["validate-npm-package-name@6.0.1", "", {}, "sha512-OaI//3H0J7ZkR1OqlhGA8cA+Cbk/2xFOQpJOt5+s27/ta9eZwpeervh4Mxh4w0im/kdgktowaqVNR7QOrUd7Yg=="],
|
||||
|
||||
"vite": ["vite@6.3.5", "", { "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", "picomatch": "^4.0.2", "postcss": "^8.5.3", "rollup": "^4.34.9", "tinyglobby": "^0.2.13" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0", "jiti": ">=1.21.0", "less": "*", "lightningcss": "^1.21.0", "sass": "*", "sass-embedded": "*", "stylus": "*", "sugarss": "*", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "jiti", "less", "lightningcss", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ=="],
|
||||
|
||||
"vite-plugin-css-injected-by-js": ["vite-plugin-css-injected-by-js@3.5.2", "", { "peerDependencies": { "vite": ">2.0.0-0" } }, "sha512-2MpU/Y+SCZyWUB6ua3HbJCrgnF0KACAsmzOQt1UvRVJCGF6S8xdA3ZUhWcWdM9ivG4I5az8PnQmwwrkC2CAQrQ=="],
|
||||
|
||||
"vite-plugin-no-bundle": ["vite-plugin-no-bundle@4.0.0", "", { "dependencies": { "fast-glob": "^3.3.2", "micromatch": "^4.0.5" } }, "sha512-DXsJGXtp/QLWNFBfBqr+arxaTHEgiPCAgf9bcOPGv4n3AsFigsFj+oL95nFdMt8cRbgRDtvyTX802IZNBGg3Xg=="],
|
||||
|
||||
"vitefu": ["vitefu@1.0.6", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" }, "optionalPeers": ["vite"] }, "sha512-+Rex1GlappUyNN6UfwbVZne/9cYC4+R2XDk9xkNXBKMw6HQagdX9PgZ8V2v1WUSK1wfBLp7qbI1+XSNIlB1xmA=="],
|
||||
|
||||
"vue": ["vue@3.5.16", "", { "dependencies": { "@vue/compiler-dom": "3.5.16", "@vue/compiler-sfc": "3.5.16", "@vue/runtime-dom": "3.5.16", "@vue/server-renderer": "3.5.16", "@vue/shared": "3.5.16" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-rjOV2ecxMd5SiAmof2xzh2WxntRcigkX/He4YFJ6WdRvVUrbt6DxC1Iujh10XLl8xCDRDtGKMeO3D+pRQ1PP9w=="],
|
||||
|
||||
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||
|
||||
"yauzl": ["yauzl@3.2.0", "", { "dependencies": { "buffer-crc32": "~0.2.3", "pend": "~1.2.0" } }, "sha512-Ow9nuGZE+qp1u4JIPvg+uCiUr7xGQWdff7JQSk5VGYTAZMDe2q8lxJ10ygv10qmSj031Ty/6FNJpLO4o1Sgc+w=="],
|
||||
|
||||
"zimmerframe": ["zimmerframe@1.1.2", "", {}, "sha512-rAbqEGa8ovJy4pyBxZM70hg4pE6gDgaQ0Sl9M3enG3I0d6H4XSAM3GeNGLKnsBpuijUow064sf7ww1nutC5/3w=="],
|
||||
|
||||
"zod": ["zod@3.25.51", "", {}, "sha512-TQSnBldh+XSGL+opiSIq0575wvDPqu09AqWe1F7JhUMKY+M91/aGlK4MhpVNO7MgYfHcVCB1ffwAUTJzllKJqg=="],
|
||||
|
||||
"@jridgewell/gen-mapping/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.4.15", "", {}, "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg=="],
|
||||
|
||||
"@jridgewell/trace-mapping/@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.4.15", "", {}, "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg=="],
|
||||
|
||||
"@untemps/svelte-use-drop-outside/@untemps/utils": ["@untemps/utils@2.6.0", "", { "dependencies": { "@babel/runtime": "^7.17.8" } }, "sha512-3B5bb4iYkh2h86vqtY8+Mo9vdX1s/NT1cltWpS4U3/WHXFgy/4lJ9180vELJv01MbNNhjlZPtJCMtBp7Fpsb1Q=="],
|
||||
|
||||
"@untemps/svelte-use-drop-outside/svelte": ["svelte@3.49.0", "", {}, "sha512-+lmjic1pApJWDfPCpUUTc1m8azDqYCG1JN9YEngrx/hUyIcFJo6VZhj0A1Ai0wqoHcEIuQy+e9tk+4uDgdtsFA=="],
|
||||
|
||||
"@untemps/svelte-use-tooltip/@untemps/utils": ["@untemps/utils@2.6.0", "", { "dependencies": { "@babel/runtime": "^7.17.8" } }, "sha512-3B5bb4iYkh2h86vqtY8+Mo9vdX1s/NT1cltWpS4U3/WHXFgy/4lJ9180vELJv01MbNNhjlZPtJCMtBp7Fpsb1Q=="],
|
||||
|
||||
"@untemps/svelte-use-tooltip/svelte": ["svelte@3.49.0", "", {}, "sha512-+lmjic1pApJWDfPCpUUTc1m8azDqYCG1JN9YEngrx/hUyIcFJo6VZhj0A1Ai0wqoHcEIuQy+e9tk+4uDgdtsFA=="],
|
||||
|
||||
"@vue/compiler-core/source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"@vue/compiler-sfc/source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"decompress-response/mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="],
|
||||
|
||||
"file-type/get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="],
|
||||
|
||||
"globby/fast-glob": ["fast-glob@3.3.3", "", { "dependencies": { "@nodelib/fs.stat": "^2.0.2", "@nodelib/fs.walk": "^1.2.3", "glob-parent": "^5.1.2", "merge2": "^1.3.0", "micromatch": "^4.0.8" } }, "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg=="],
|
||||
|
||||
"globby/slash": ["slash@5.1.0", "", {}, "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg=="],
|
||||
|
||||
"is-reference/@types/estree": ["@types/estree@1.0.7", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="],
|
||||
|
||||
"log-symbols/is-unicode-supported": ["is-unicode-supported@1.3.0", "", {}, "sha512-43r2mRvz+8JRIKnWJ+3j8JtjRKZ6GmjzfaE/qiBJnikNnYv/6bagRJ1kUhNk8R5EX/GkobD+r+sfxCPJsiKBLQ=="],
|
||||
|
||||
"micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"nice-napi/node-addon-api": ["node-addon-api@3.2.1", "", {}, "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A=="],
|
||||
|
||||
"npm-package-arg/semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="],
|
||||
|
||||
"ora/strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="],
|
||||
|
||||
"postcss/source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
|
||||
|
||||
"prompts/kleur": ["kleur@3.0.3", "", {}, "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w=="],
|
||||
|
||||
"restore-cursor/onetime": ["onetime@7.0.0", "", { "dependencies": { "mimic-function": "^5.0.0" } }, "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ=="],
|
||||
|
||||
"restore-cursor/signal-exit": ["signal-exit@4.1.0", "", {}, "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw=="],
|
||||
|
||||
"rollup/@types/estree": ["@types/estree@1.0.7", "", {}, "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ=="],
|
||||
|
||||
"seek-bzip/commander": ["commander@6.2.1", "", {}, "sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA=="],
|
||||
|
||||
"string-width/strip-ansi": ["strip-ansi@7.1.0", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-iq6eVVI64nQQTRYq2KtEg2d2uU7LElhTJwsH4YzIHZshxlgZms/wIc4VoDQTlG/IvVIrBKG06CrZnp0qv7hkcQ=="],
|
||||
|
||||
"syncpack/commander": ["commander@13.1.0", "", {}, "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw=="],
|
||||
|
||||
"syncpack/minimatch": ["minimatch@9.0.5", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow=="],
|
||||
|
||||
"syncpack/semver": ["semver@7.7.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA=="],
|
||||
|
||||
"file-type/get-stream/is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="],
|
||||
|
||||
"globby/fast-glob/micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="],
|
||||
|
||||
"ora/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="],
|
||||
|
||||
"string-width/strip-ansi/ansi-regex": ["ansi-regex@6.1.0", "", {}, "sha512-7HSX4QQb4CspciLpVFwyRe79O3xsIZDDLER21kERQ71oaPodF8jL725AgJMFAYbooIqolJoRLuM81SpeUkpkvA=="],
|
||||
|
||||
"globby/fast-glob/micromatch/braces": ["braces@3.0.3", "", { "dependencies": { "fill-range": "^7.1.1" } }, "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA=="],
|
||||
|
||||
"globby/fast-glob/micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="],
|
||||
|
||||
"globby/fast-glob/micromatch/braces/fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>mtb web source</title>
|
||||
</head>
|
||||
<body>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "comfy-mtb-web",
|
||||
"private": true,
|
||||
"version": "0.4.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build && bun run postbuild",
|
||||
"postbuild": "cp -r dist/* ../web/dist/",
|
||||
"preview": "vite preview",
|
||||
"check-deps": "bun x syncpack list"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@comfyorg/comfyui-frontend-types": "^1.20.2",
|
||||
"@comfyorg/litegraph": "^0.15.15",
|
||||
"@neodrag/svelte": "^2.3.2",
|
||||
"@sveltejs/vite-plugin-svelte": "^5.1.0",
|
||||
"@swc/cli": "^0.7.7",
|
||||
"@swc/core": "^1.11.31",
|
||||
"@types/node": "^22.15.30",
|
||||
"prettier-plugin-svelte": "^3.2.7",
|
||||
"sass": "^1.89.1",
|
||||
"svelte": "^5.33.14",
|
||||
"svelte-awesome-color-picker": "^4.0.2",
|
||||
"svelte-dnd-action": "^0.9.61",
|
||||
"svelte-portal": "^2.2.1",
|
||||
"syncpack": "^13.0.0",
|
||||
"typescript": "^5.7.2",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-no-bundle": "^4.0.0"
|
||||
},
|
||||
"packageManager": "bun@1.2.15",
|
||||
"volta": {
|
||||
"node": "22.14.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@untemps/svelte-palette": "^4.1.0",
|
||||
"iconify-icon": "^3.0.0",
|
||||
"vite-plugin-css-injected-by-js": "^3.5.2"
|
||||
},
|
||||
"trustedDependencies": ["@parcel/watcher", "@swc/core", "svelte-preprocess"]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<script>
|
||||
import Inspector from './lib/Inspector.svelte'
|
||||
import './app.css'
|
||||
</script>
|
||||
|
||||
<main>
|
||||
<Inspector />
|
||||
</main>
|
||||
|
||||
<style>
|
||||
</style>
|
||||
@@ -0,0 +1,85 @@
|
||||
:root {
|
||||
--fg-color: #fff;
|
||||
--bg-color: #202020;
|
||||
--comfy-menu-bg: #353535;
|
||||
--comfy-input-bg: #222;
|
||||
--input-text: #ddd;
|
||||
--descrip-text: #999;
|
||||
--drag-text: #ccc;
|
||||
--error-text: #ff4444;
|
||||
--border-color: #4e4e4e;
|
||||
--tr-even-bg-color: #222;
|
||||
--tr-odd-bg-color: #353535;
|
||||
|
||||
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
/* background-color: #242424; */
|
||||
|
||||
background-color: #646464;
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
display: flex;
|
||||
place-items: center;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
/**/
|
||||
/* button { */
|
||||
/* border-radius: 8px; */
|
||||
/* border: 1px solid transparent; */
|
||||
/* padding: 0.6em 1.2em; */
|
||||
/* font-size: 1em; */
|
||||
/* font-weight: 500; */
|
||||
/* font-family: inherit; */
|
||||
/* background-color: #1a1a1a; */
|
||||
/* cursor: pointer; */
|
||||
/* transition: border-color 0.25s; */
|
||||
/* } */
|
||||
/* button:hover { */
|
||||
/* border-color: #646cff; */
|
||||
/* } */
|
||||
/* button:focus, */
|
||||
/* button:focus-visible { */
|
||||
/* outline: 4px auto -webkit-focus-ring-color; */
|
||||
/* } */
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="comfyui-frontend-types" />
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Server API utilities
|
||||
*/
|
||||
|
||||
import { api } from '@/scripts/api'
|
||||
|
||||
export interface ActionResult {
|
||||
result: unknown
|
||||
}
|
||||
|
||||
export interface ServerInfo {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Run a server action
|
||||
*/
|
||||
export const runAction = async (name: string, ...args: unknown[]): Promise<unknown> => {
|
||||
const req = await api.fetchApi('/mtb/actions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
args,
|
||||
}),
|
||||
})
|
||||
|
||||
const res = (await req.json()) as ActionResult
|
||||
return res.result
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server info
|
||||
*/
|
||||
export const getServerInfo = async (): Promise<ServerInfo> => {
|
||||
const res = await api.fetchApi('/mtb/server-info')
|
||||
return (await res.json()) as ServerInfo
|
||||
}
|
||||
|
||||
/**
|
||||
* Set server info
|
||||
*/
|
||||
export const setServerInfo = async (opts: ServerInfo): Promise<void> => {
|
||||
await api.fetchApi('/mtb/server-info', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(opts),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* Color utilities
|
||||
*/
|
||||
|
||||
type RGB = [number, number, number]
|
||||
|
||||
function getBrightness(rgb: RGB): number {
|
||||
return Math.round(
|
||||
(Number.parseInt(String(rgb[0])) * 299 +
|
||||
Number.parseInt(String(rgb[1])) * 587 +
|
||||
Number.parseInt(String(rgb[2])) * 114) /
|
||||
1000,
|
||||
)
|
||||
}
|
||||
|
||||
export function isColorBright(rgb: RGB, threshold = 240): boolean {
|
||||
const brightness = getBrightness(rgb)
|
||||
return brightness > threshold
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
/**
|
||||
* Documentation widget for nodes
|
||||
*/
|
||||
|
||||
import { app } from '@/scripts/app'
|
||||
import type { MTBNode, NodeType, NodeData, DocumentationOptions, MarkdownParser } from './types'
|
||||
import { infoLogger } from './logger'
|
||||
|
||||
const create_documentation_stylesheet = (): void => {
|
||||
const tag = 'mtb-documentation-stylesheet'
|
||||
let styleTag = document.head.querySelector(`#${tag}`) as HTMLStyleElement | null
|
||||
|
||||
if (!styleTag) {
|
||||
styleTag = document.createElement('style')
|
||||
styleTag.type = 'text/css'
|
||||
styleTag.id = tag
|
||||
|
||||
styleTag.innerHTML = `
|
||||
.documentation-popup {
|
||||
background: var(--comfy-menu-bg);
|
||||
position: absolute;
|
||||
color: var(--fg-color);
|
||||
font: 12px monospace;
|
||||
line-height: 1.5em;
|
||||
padding: 10px;
|
||||
border-radius: 6px;
|
||||
pointer-events: "inherit";
|
||||
z-index: 5;
|
||||
overflow: hidden;
|
||||
}
|
||||
.documentation-wrapper {
|
||||
padding: 0 2em;
|
||||
overflow: auto;
|
||||
max-height: 100%;
|
||||
&::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
&::-webkit-scrollbar-track {
|
||||
background: var(--bg-color);
|
||||
}
|
||||
&::-webkit-scrollbar-thumb {
|
||||
background-color: var(--fg-color);
|
||||
border-radius: 6px;
|
||||
border: 3px solid var(--bg-color);
|
||||
}
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--fg-color) var(--bg-color);
|
||||
a {
|
||||
color: yellow;
|
||||
}
|
||||
a:visited {
|
||||
color: orange;
|
||||
}
|
||||
a:hover {
|
||||
color: red;
|
||||
}
|
||||
}
|
||||
.documentation-popup img {
|
||||
max-width: 100%;
|
||||
}
|
||||
.documentation-popup table {
|
||||
border-collapse: collapse;
|
||||
border: 1px var(--border-color) solid;
|
||||
}
|
||||
.documentation-popup th,
|
||||
.documentation-popup td {
|
||||
border: 1px var(--border-color) solid;
|
||||
}
|
||||
.documentation-popup th {
|
||||
background-color: var(--comfy-input-bg);
|
||||
}`
|
||||
document.head.appendChild(styleTag)
|
||||
}
|
||||
}
|
||||
|
||||
let parserPromise: Promise<MarkdownParser> | undefined
|
||||
const callbackQueue: Array<(parser: MarkdownParser) => void> = []
|
||||
|
||||
function runQueuedCallbacks(): void {
|
||||
while (callbackQueue.length) {
|
||||
const cb = callbackQueue.shift()
|
||||
if (cb && window.MTB?.mdParser) {
|
||||
cb(window.MTB.mdParser)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function loadParser(shiki: boolean): Promise<MarkdownParser> {
|
||||
if (!parserPromise) {
|
||||
parserPromise = import(
|
||||
shiki ? '/mtb_async/mtb_markdown_plus.umd.js' : '/mtb_async/mtb_markdown.umd.js'
|
||||
)
|
||||
.then(() => (shiki ? window.MTBMarkdownPlus!.getParser() : window.MTBMarkdown!.getParser()))
|
||||
.then((instance) => {
|
||||
window.MTB = window.MTB || {}
|
||||
window.MTB.mdParser = instance
|
||||
runQueuedCallbacks()
|
||||
return instance
|
||||
})
|
||||
.catch((error) => {
|
||||
// biome-ignore lint/suspicious/noConsole: error logging
|
||||
console.error('Error loading the parser:', error)
|
||||
throw error
|
||||
})
|
||||
}
|
||||
return parserPromise
|
||||
}
|
||||
|
||||
export const ensureMarkdownParser = async (
|
||||
callback?: (parser: MarkdownParser) => void,
|
||||
): Promise<MarkdownParser> => {
|
||||
infoLogger('Ensuring md parser')
|
||||
const use_shiki = app.extensionManager?.setting?.get('mtb.noteplus.use-shiki', false) as boolean
|
||||
|
||||
if (window.MTB?.mdParser) {
|
||||
infoLogger('Markdown parser found')
|
||||
callback?.(window.MTB.mdParser)
|
||||
return window.MTB.mdParser
|
||||
}
|
||||
|
||||
if (!parserPromise) {
|
||||
infoLogger('Running promise to fetch parser')
|
||||
try {
|
||||
loadParser(use_shiki)
|
||||
} catch (error) {
|
||||
// biome-ignore lint/suspicious/noConsole: error logging
|
||||
console.error('Error loading the parser:', error)
|
||||
}
|
||||
} else {
|
||||
infoLogger('A similar promise is already running, waiting for it to finish')
|
||||
}
|
||||
|
||||
if (callback) {
|
||||
callbackQueue.push(callback)
|
||||
}
|
||||
|
||||
await parserPromise
|
||||
|
||||
return window.MTB!.mdParser!
|
||||
}
|
||||
|
||||
/**
|
||||
* Add documentation widget to the given node.
|
||||
*/
|
||||
export const addDocumentation = (
|
||||
nodeData: NodeData,
|
||||
nodeType: NodeType,
|
||||
opts: DocumentationOptions = { icon_size: 14, icon_margin: 4 },
|
||||
): void => {
|
||||
if (!nodeData.description) {
|
||||
infoLogger(`Skipping ${nodeData.name} doesn't have a description, skipping...`)
|
||||
return
|
||||
}
|
||||
|
||||
const options = opts || {}
|
||||
const iconSize = options.icon_size || 14
|
||||
const iconMargin = options.icon_margin || 4
|
||||
|
||||
let docElement: HTMLDivElement | null = null
|
||||
let wrapper: HTMLDivElement | null = null
|
||||
|
||||
const onRem = nodeType.prototype.onRemoved
|
||||
|
||||
nodeType.prototype.onRemoved = function (this: MTBNode) {
|
||||
const r = onRem ? onRem.apply(this) : undefined
|
||||
|
||||
if (docElement) {
|
||||
docElement.remove()
|
||||
docElement = null
|
||||
}
|
||||
|
||||
if (wrapper) {
|
||||
wrapper.remove()
|
||||
wrapper = null
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
const drawFg = nodeType.prototype.onDrawForeground
|
||||
|
||||
nodeType.prototype.onDrawForeground = function (
|
||||
this: MTBNode,
|
||||
ctx: CanvasRenderingContext2D,
|
||||
canvas: unknown,
|
||||
) {
|
||||
const r = drawFg ? drawFg.apply(this, [ctx, canvas]) : undefined
|
||||
|
||||
if (this.flags.collapsed) return r
|
||||
|
||||
const x = this.size[0] - iconSize - iconMargin
|
||||
|
||||
// create it
|
||||
if (this.show_doc && docElement === null) {
|
||||
create_documentation_stylesheet()
|
||||
|
||||
docElement = document.createElement('div')
|
||||
docElement.classList.add('documentation-popup')
|
||||
document.body.appendChild(docElement)
|
||||
|
||||
wrapper = document.createElement('div')
|
||||
wrapper.classList.add('documentation-wrapper')
|
||||
docElement.appendChild(wrapper)
|
||||
|
||||
ensureMarkdownParser().then(() => {
|
||||
window.MTB!.mdParser!.parse(nodeData.description!).then((e) => {
|
||||
if (!wrapper) return
|
||||
wrapper.innerHTML = e
|
||||
|
||||
// resize handle
|
||||
const resizeHandle = document.createElement('div')
|
||||
resizeHandle.classList.add('doc-resize-handle')
|
||||
Object.assign(resizeHandle.style, {
|
||||
width: '0',
|
||||
height: '0',
|
||||
position: 'absolute',
|
||||
bottom: '0',
|
||||
right: '0',
|
||||
cursor: 'se-resize',
|
||||
userSelect: 'none',
|
||||
borderWidth: '15px',
|
||||
borderStyle: 'solid',
|
||||
borderColor: 'transparent var(--border-color) var(--border-color) transparent',
|
||||
})
|
||||
|
||||
wrapper.appendChild(resizeHandle)
|
||||
let isResizing = false
|
||||
let startX: number
|
||||
let startY: number
|
||||
let startWidth: number
|
||||
let startHeight: number
|
||||
|
||||
resizeHandle.addEventListener(
|
||||
'mousedown',
|
||||
(e) => {
|
||||
e.stopPropagation()
|
||||
isResizing = true
|
||||
startX = e.clientX
|
||||
startY = e.clientY
|
||||
startWidth = Number.parseInt(
|
||||
document.defaultView!.getComputedStyle(docElement!).width,
|
||||
10,
|
||||
)
|
||||
startHeight = Number.parseInt(
|
||||
document.defaultView!.getComputedStyle(docElement!).height,
|
||||
10,
|
||||
)
|
||||
},
|
||||
{ signal: this.docCtrl!.signal },
|
||||
)
|
||||
|
||||
document.addEventListener(
|
||||
'mousemove',
|
||||
(e) => {
|
||||
if (!isResizing || !docElement) return
|
||||
const scale = app.canvas.ds.scale
|
||||
const newWidth = startWidth + (e.clientX - startX) / scale
|
||||
const newHeight = startHeight + (e.clientY - startY) / scale
|
||||
|
||||
docElement.style.width = `${newWidth}px`
|
||||
docElement.style.height = `${newHeight}px`
|
||||
|
||||
this.docPos = {
|
||||
width: `${newWidth}px`,
|
||||
height: `${newHeight}px`,
|
||||
}
|
||||
},
|
||||
{ signal: this.docCtrl!.signal },
|
||||
)
|
||||
|
||||
document.addEventListener(
|
||||
'mouseup',
|
||||
() => {
|
||||
isResizing = false
|
||||
},
|
||||
{ signal: this.docCtrl!.signal },
|
||||
)
|
||||
})
|
||||
})
|
||||
} else if (!this.show_doc && docElement !== null) {
|
||||
docElement.remove()
|
||||
docElement = null
|
||||
}
|
||||
|
||||
// reposition
|
||||
if (this.show_doc && docElement !== null) {
|
||||
const rect = ctx.canvas.getBoundingClientRect()
|
||||
const scaleX = rect.width / ctx.canvas.width
|
||||
const scaleY = rect.height / ctx.canvas.height
|
||||
const transform = new DOMMatrix()
|
||||
.scaleSelf(scaleX, scaleY)
|
||||
.multiplySelf(ctx.getTransform())
|
||||
.translateSelf(this.size[0] * scaleX * Math.max(1.0, window.devicePixelRatio), 0)
|
||||
.translateSelf(10, -32)
|
||||
|
||||
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
|
||||
|
||||
Object.assign(docElement.style, {
|
||||
transformOrigin: '0 0',
|
||||
transform: scale.toString(),
|
||||
left: `${transform.a + rect.x + transform.e}px`,
|
||||
top: `${transform.d + rect.y + transform.f}px`,
|
||||
width: this.docPos ? this.docPos.width : `${this.size[0] * 1.5}px`,
|
||||
height: this.docPos?.height,
|
||||
})
|
||||
|
||||
if (this.docPos === undefined) {
|
||||
this.docPos = {
|
||||
width: docElement.style.width,
|
||||
height: docElement.style.height,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(x, iconSize - 34)
|
||||
ctx.scale(iconSize / 32, iconSize / 32)
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.3)'
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
ctx.lineWidth = 2.4
|
||||
ctx.font = 'bold 36px monospace'
|
||||
ctx.fillText('?', 0, 24)
|
||||
ctx.restore()
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
const mouseDown = nodeType.prototype.onMouseDown
|
||||
|
||||
nodeType.prototype.onMouseDown = function (
|
||||
this: MTBNode,
|
||||
event: MouseEvent,
|
||||
localPos: [number, number],
|
||||
graphCanvas: unknown,
|
||||
): boolean | void {
|
||||
const r = mouseDown ? mouseDown.apply(this, [event, localPos, graphCanvas]) : undefined
|
||||
const iconX = this.size[0] - iconSize - iconMargin
|
||||
const iconY = iconSize - 34
|
||||
|
||||
if (
|
||||
localPos[0] > iconX &&
|
||||
localPos[0] < iconX + iconSize &&
|
||||
localPos[1] > iconY &&
|
||||
localPos[1] < iconY + iconSize
|
||||
) {
|
||||
if (this.show_doc === undefined) {
|
||||
this.show_doc = true
|
||||
} else {
|
||||
this.show_doc = !this.show_doc
|
||||
}
|
||||
if (this.show_doc) {
|
||||
this.docCtrl = new AbortController()
|
||||
} else {
|
||||
this.docCtrl?.abort()
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* DOM and HTML utilities
|
||||
*/
|
||||
|
||||
import { infoLogger } from './logger'
|
||||
|
||||
/**
|
||||
* Calculate total height of DOM element children
|
||||
*/
|
||||
export function calculateTotalChildrenHeight(parentElement: HTMLElement | null): number {
|
||||
let totalHeight = 0
|
||||
|
||||
if (!parentElement || !parentElement.children) {
|
||||
return 0
|
||||
}
|
||||
|
||||
for (const child of parentElement.children) {
|
||||
const style = window.getComputedStyle(child)
|
||||
|
||||
const height = Number.parseFloat(style.height)
|
||||
const marginTop = Number.parseFloat(style.marginTop)
|
||||
const marginBottom = Number.parseFloat(style.marginBottom)
|
||||
|
||||
totalHeight += height + marginTop + marginBottom
|
||||
}
|
||||
|
||||
return Math.ceil(totalHeight)
|
||||
}
|
||||
|
||||
interface LoadScriptResult {
|
||||
status: boolean
|
||||
message?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamically load a script
|
||||
*/
|
||||
export const loadScript = (
|
||||
FILE_URL: string,
|
||||
async = true,
|
||||
type = 'text/javascript',
|
||||
): Promise<LoadScriptResult> => {
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
// Check if the script already exists
|
||||
let scriptEle = document.querySelector(`script[src="${FILE_URL}"]`) as HTMLScriptElement | null
|
||||
|
||||
if (scriptEle) {
|
||||
scriptEle.addEventListener('load', () => {
|
||||
resolve({ status: true })
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
scriptEle = document.createElement('script')
|
||||
scriptEle.type = type
|
||||
scriptEle.async = async
|
||||
scriptEle.src = FILE_URL
|
||||
|
||||
scriptEle.addEventListener('load', () => {
|
||||
resolve({ status: true })
|
||||
})
|
||||
|
||||
scriptEle.addEventListener('error', () => {
|
||||
reject({
|
||||
status: false,
|
||||
message: `Failed to load the script ${FILE_URL}`,
|
||||
})
|
||||
})
|
||||
|
||||
document.body.appendChild(scriptEle)
|
||||
} catch (error) {
|
||||
reject(error)
|
||||
} finally {
|
||||
infoLogger(`Finally loaded script: ${FILE_URL}`)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
/**
|
||||
* Dynamic connections management for nodes
|
||||
*/
|
||||
|
||||
import type { INodeInputSlot, INodeOutputSlot } from '@comfyorg/litegraph'
|
||||
import { app } from '@/scripts/app'
|
||||
import type { MTBNode, NodeType, DynamicConnectionOptions, ContextMenuItem } from './types'
|
||||
import { infoLogger, errorLogger } from './logger'
|
||||
import { nodesFromLink } from './widgets'
|
||||
|
||||
type SlotCondition = (slot: INodeInputSlot | INodeOutputSlot) => boolean
|
||||
|
||||
const isDynamicInput = (input: INodeInputSlot & { _isDynamic?: boolean }): boolean => {
|
||||
return input._isDynamic === true
|
||||
}
|
||||
|
||||
const addDynamicInput = (
|
||||
node: MTBNode,
|
||||
name: string,
|
||||
kind: string,
|
||||
): INodeInputSlot & { _isDynamic?: boolean } => {
|
||||
const input = node.addInput(name, kind) as INodeInputSlot & { _isDynamic?: boolean }
|
||||
input._isDynamic = true
|
||||
|
||||
update_dynamic_properties(node)
|
||||
set_slot_colors(node, ['cyan', undefined], isDynamicInput as SlotCondition)
|
||||
|
||||
return input
|
||||
}
|
||||
|
||||
const set_slot_colors = (
|
||||
node: MTBNode,
|
||||
colors: [string | undefined, string | undefined],
|
||||
condition?: SlotCondition,
|
||||
): void => {
|
||||
const check = condition || (() => true)
|
||||
|
||||
for (const slot of node.slots || []) {
|
||||
if (check(slot)) {
|
||||
;(slot as INodeInputSlot & { color_off?: string; color_on?: string }).color_off = colors[0]
|
||||
;(slot as INodeInputSlot & { color_on?: string }).color_on = colors[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const update_dynamic_properties = (node: MTBNode): void => {
|
||||
const dyn: string[] = []
|
||||
for (const input of node.inputs) {
|
||||
if (isDynamicInput(input)) {
|
||||
dyn.push(input.name)
|
||||
}
|
||||
}
|
||||
node.setProperty('dynamic_connections', dyn)
|
||||
}
|
||||
|
||||
/**
|
||||
* Setup dynamic connections for a node type
|
||||
*/
|
||||
export const setupDynamicConnections = (
|
||||
nodeType: NodeType,
|
||||
prefix: string,
|
||||
inputType: string | string[],
|
||||
opts?: Partial<DynamicConnectionOptions>,
|
||||
): void => {
|
||||
infoLogger(
|
||||
'Setting up dynamic connections for',
|
||||
(Object.getOwnPropertyDescriptor(nodeType, 'title')?.value as string) || 'unknown',
|
||||
)
|
||||
|
||||
const options: DynamicConnectionOptions = {
|
||||
separator: '_',
|
||||
start_index: 1,
|
||||
rename_menu: 'label',
|
||||
...opts,
|
||||
}
|
||||
|
||||
const is_valid_name = (_node: MTBNode, _val: string): boolean => {
|
||||
return true
|
||||
}
|
||||
|
||||
nodeType.prototype.getSlotMenuOptions = (slot): ContextMenuItem[] | undefined => {
|
||||
if (!slot.input) {
|
||||
return undefined
|
||||
}
|
||||
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>",
|
||||
{},
|
||||
) as HTMLElement & { close: () => void }
|
||||
|
||||
const dialogInput = dialog.querySelector('input') as HTMLInputElement | null
|
||||
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 = (): void => {
|
||||
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: KeyboardEvent) => {
|
||||
;(dialog as HTMLElement & { is_modified?: boolean }).is_modified = true
|
||||
if (e.keyCode === 27) {
|
||||
dialog.close()
|
||||
} else if (e.keyCode === 13) {
|
||||
inner()
|
||||
} else if (
|
||||
e.keyCode !== 13 &&
|
||||
(e.target as HTMLElement)?.localName !== 'textarea'
|
||||
) {
|
||||
return
|
||||
}
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
})
|
||||
dialogInput?.focus()
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
const onConfigure = nodeType.prototype.onConfigure
|
||||
|
||||
nodeType.prototype.onConfigure = function (this: MTBNode, data: unknown) {
|
||||
const r = onConfigure ? onConfigure.apply(this, [data]) : undefined
|
||||
|
||||
if (!('dynamic_connections' in this.properties)) {
|
||||
this.setProperty('dynamic_connections', [])
|
||||
} else {
|
||||
const dynamic_connections = this.properties.dynamic_connections as string[] | string
|
||||
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_slot_colors(this, ['cyan', undefined], isDynamicInput as SlotCondition)
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
const inputList = typeof inputType === 'object'
|
||||
|
||||
nodeType.prototype.onNodeCreated = function (this: MTBNode) {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this) : undefined
|
||||
|
||||
addDynamicInput(
|
||||
this,
|
||||
`${prefix}${options.separator}${options.start_index}`,
|
||||
inputList ? '*' : (inputType as string),
|
||||
)
|
||||
return r
|
||||
}
|
||||
|
||||
const onConnectionsChange = nodeType.prototype.onConnectionsChange
|
||||
|
||||
nodeType.prototype.onConnectionsChange = function (this: MTBNode, ...args) {
|
||||
const [type, slotIndex, isConnected, link, ioSlot] = args
|
||||
|
||||
options.link = link
|
||||
options.ioSlot = ioSlot
|
||||
const r = onConnectionsChange
|
||||
? onConnectionsChange.apply(this, [type, slotIndex, isConnected, link, ioSlot])
|
||||
: undefined
|
||||
|
||||
options.DEBUG = {
|
||||
node: this,
|
||||
type,
|
||||
slotIndex,
|
||||
isConnected,
|
||||
link,
|
||||
ioSlot,
|
||||
}
|
||||
|
||||
dynamic_connection(
|
||||
this,
|
||||
slotIndex,
|
||||
isConnected,
|
||||
`${prefix}${options.separator}`,
|
||||
inputType,
|
||||
options,
|
||||
)
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Main logic around dynamic inputs
|
||||
*/
|
||||
export const dynamic_connection = (
|
||||
node: MTBNode,
|
||||
index: number,
|
||||
connected: boolean,
|
||||
connectionPrefix = 'input_',
|
||||
connectionType: string | string[] = '*',
|
||||
opts?: Partial<DynamicConnectionOptions>,
|
||||
): void => {
|
||||
const options: DynamicConnectionOptions = {
|
||||
start_index: 1,
|
||||
...opts,
|
||||
}
|
||||
|
||||
if (node.inputs.length > 0 && !isDynamicInput(node.inputs[index])) {
|
||||
return
|
||||
}
|
||||
|
||||
const listConnection = typeof connectionType === 'object'
|
||||
const conType = listConnection ? '*' : connectionType
|
||||
const nameArray = options.nameArray || []
|
||||
|
||||
const clean_inputs = (): void => {
|
||||
if (node.id < 0) return // being duplicated
|
||||
if (node.inputs.length === 0) return
|
||||
|
||||
let w_count = node.widgets?.length || 0
|
||||
let i_count = node.inputs?.length || 0
|
||||
infoLogger(`Cleaning inputs: [BEFORE] (w: ${w_count} | inputs: ${i_count})`)
|
||||
|
||||
const to_remove: number[] = []
|
||||
for (let n = 1; n < node.inputs.length; n++) {
|
||||
const element = node.inputs[n]
|
||||
if (!element.link && isDynamicInput(element)) {
|
||||
if (node.widgets) {
|
||||
const w = node.widgets.find((w) => w.name === element.name)
|
||||
if (w) {
|
||||
w.onRemoved?.()
|
||||
node.widgets.length = node.widgets.length - 1
|
||||
}
|
||||
}
|
||||
infoLogger(`Removing input ${n}`)
|
||||
to_remove.push(n)
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < to_remove.length; i++) {
|
||||
const id = to_remove[i]
|
||||
try {
|
||||
node.removeInput(id)
|
||||
i_count -= 1
|
||||
} catch (err) {
|
||||
errorLogger('Cannot remove input', err)
|
||||
}
|
||||
}
|
||||
node.inputs.length = i_count
|
||||
|
||||
w_count = node.widgets?.length || 0
|
||||
i_count = node.inputs?.length || 0
|
||||
infoLogger(`Cleaning inputs: [AFTER] (w: ${w_count} | inputs: ${i_count})`)
|
||||
|
||||
infoLogger('Cleaning inputs: making it sequential again')
|
||||
// make inputs sequential again
|
||||
let prefixed_idx = options.start_index!
|
||||
for (let i = 0; i < node.inputs.length; i++) {
|
||||
let name = ''
|
||||
if (node.inputs[i].name.startsWith(connectionPrefix)) {
|
||||
name = `${connectionPrefix}${prefixed_idx}`
|
||||
prefixed_idx += 1
|
||||
} else {
|
||||
name = node.inputs[i].name
|
||||
}
|
||||
|
||||
if (nameArray.length > 0) {
|
||||
name = i < nameArray.length ? nameArray[i] : name
|
||||
}
|
||||
|
||||
// preserve label if it exists
|
||||
;(node.inputs[i] as INodeInputSlot & { label?: string }).label =
|
||||
(node.inputs[i] as INodeInputSlot & { label?: string }).label || name
|
||||
node.inputs[i].name = name
|
||||
}
|
||||
}
|
||||
|
||||
if (!connected) {
|
||||
if (!options.link) {
|
||||
infoLogger('Disconnecting', { options })
|
||||
clean_inputs()
|
||||
} else {
|
||||
if (!options.ioSlot?.link) {
|
||||
node.connectionTransit = true
|
||||
} else {
|
||||
node.connectionTransit = false
|
||||
clean_inputs()
|
||||
}
|
||||
infoLogger('Reconnecting', { options })
|
||||
}
|
||||
}
|
||||
|
||||
if (connected) {
|
||||
if (options.link) {
|
||||
const { from, to, type } = nodesFromLink(node, options.link)
|
||||
if (type === 'outgoing') return
|
||||
infoLogger('Connecting', { options, from, to, type })
|
||||
} else {
|
||||
infoLogger('Connecting', { options })
|
||||
}
|
||||
|
||||
if (node.connectionTransit) {
|
||||
infoLogger('In Transit')
|
||||
node.connectionTransit = false
|
||||
}
|
||||
|
||||
clean_inputs()
|
||||
|
||||
if (node.inputs.length === 0) return
|
||||
|
||||
// add an extra input
|
||||
if (node.inputs[node.inputs.length - 1].link !== null) {
|
||||
const nextIndex = node.inputs.reduce(
|
||||
(acc, cur) => (isDynamicInput(cur) ? ++acc : acc),
|
||||
0,
|
||||
)
|
||||
|
||||
const name =
|
||||
nextIndex < nameArray.length
|
||||
? nameArray[nextIndex]
|
||||
: `${connectionPrefix}${nextIndex + options.start_index!}`
|
||||
|
||||
infoLogger(`Adding input ${nextIndex + 1} (${name})`)
|
||||
addDynamicInput(node, name, conType as string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* MTB Shared Utilities
|
||||
* Main entry point - re-exports all modules
|
||||
*
|
||||
* NOTE: This bundle does NOT auto-execute anything.
|
||||
* Import the functions you need directly.
|
||||
*/
|
||||
|
||||
// Types
|
||||
export * from './types'
|
||||
|
||||
// Utilities
|
||||
export {
|
||||
getConvexHull,
|
||||
makeUUID,
|
||||
debounce,
|
||||
deepMerge,
|
||||
safe_json,
|
||||
getNodes,
|
||||
type Debounced,
|
||||
} from './utils'
|
||||
|
||||
// Storage
|
||||
export { LocalStorageManager } from './storage'
|
||||
|
||||
// Logging
|
||||
export {
|
||||
infoLogger,
|
||||
warnLogger,
|
||||
errorLogger,
|
||||
successLogger,
|
||||
log,
|
||||
} from './logger'
|
||||
|
||||
// Widgets
|
||||
export {
|
||||
CONVERTED_TYPE,
|
||||
hideWidget,
|
||||
showWidget,
|
||||
convertToWidget,
|
||||
convertToInput,
|
||||
hideWidgetForGood,
|
||||
fixWidgets,
|
||||
inner_value_change,
|
||||
getNamedWidget,
|
||||
nodesFromLink,
|
||||
hasWidgets,
|
||||
cleanupNode,
|
||||
offsetDOMWidget,
|
||||
getWidgetType,
|
||||
} from './widgets'
|
||||
|
||||
// Dynamic connections
|
||||
export {
|
||||
setupDynamicConnections,
|
||||
dynamic_connection,
|
||||
} from './dynamic-connections'
|
||||
|
||||
// Colors
|
||||
export { isColorBright } from './colors'
|
||||
|
||||
// DOM utilities
|
||||
export {
|
||||
calculateTotalChildrenHeight,
|
||||
loadScript,
|
||||
} from './dom'
|
||||
|
||||
// Documentation
|
||||
export {
|
||||
ensureMarkdownParser,
|
||||
addDocumentation,
|
||||
} from './documentation'
|
||||
|
||||
// Node extensions
|
||||
export {
|
||||
chainCallback,
|
||||
addMenuHandler,
|
||||
addDeprecation,
|
||||
} from './node-extensions'
|
||||
|
||||
// Server API
|
||||
export {
|
||||
runAction,
|
||||
getServerInfo,
|
||||
setServerInfo,
|
||||
} from './api'
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Logging utilities
|
||||
*/
|
||||
|
||||
import { app } from '@/scripts/app'
|
||||
|
||||
type ConsoleMethod = 'log' | 'warn' | 'error' | 'debug'
|
||||
type ToastSeverity = 'info' | 'warn' | 'error' | 'secondary'
|
||||
|
||||
const consoleMethodToSeverity = (method: ConsoleMethod): ToastSeverity => {
|
||||
switch (method) {
|
||||
case 'log':
|
||||
return 'info'
|
||||
case 'error':
|
||||
case 'warn':
|
||||
return method
|
||||
default:
|
||||
return 'secondary'
|
||||
}
|
||||
}
|
||||
|
||||
interface LogResult {
|
||||
notify: (timeout?: number) => void
|
||||
}
|
||||
|
||||
type Logger = (message: string, ...args: unknown[]) => LogResult
|
||||
|
||||
function createLogger(emoji: string, color: string, consoleMethod: ConsoleMethod = 'log'): Logger {
|
||||
return (message: string, ...args: unknown[]): LogResult => {
|
||||
if (window.MTB?.DEBUG) {
|
||||
// biome-ignore lint/suspicious/noConsole: logger wrapper
|
||||
console[consoleMethod](`%c${emoji} ${message}`, `color: ${color};`, ...args)
|
||||
}
|
||||
return {
|
||||
notify: (timeout = 3000) => {
|
||||
app.extensionManager?.toast?.add({
|
||||
severity: consoleMethodToSeverity(consoleMethod),
|
||||
summary: 'MTB',
|
||||
detail: `${emoji} ${message}`,
|
||||
life: timeout,
|
||||
})
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const infoLogger = createLogger('ℹ️', 'yellow')
|
||||
export const warnLogger = createLogger('⚠️', 'orange', 'warn')
|
||||
export const errorLogger = createLogger('🔥', 'red', 'error')
|
||||
export const successLogger = createLogger('✅', 'green')
|
||||
|
||||
export const log = (...args: unknown[]): void => {
|
||||
if (window.MTB?.DEBUG) {
|
||||
// biome-ignore lint/suspicious/noConsole: logger wrapper
|
||||
console.debug(...args)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* Node extension utilities
|
||||
*/
|
||||
|
||||
import type { MTBNode, NodeType, ContextMenuItem } from './types'
|
||||
import { errorLogger } from './logger'
|
||||
|
||||
/**
|
||||
* Extend an object, either replacing the original property or extending it.
|
||||
*/
|
||||
export function chainCallback<T extends object, K extends keyof T>(
|
||||
object: T | undefined,
|
||||
property: K,
|
||||
callback: T[K],
|
||||
): void {
|
||||
if (object === undefined) {
|
||||
errorLogger('Could not extend undefined object', { object, property })
|
||||
return
|
||||
}
|
||||
|
||||
if (property in object) {
|
||||
const callback_orig = object[property] as ((...args: unknown[]) => unknown) | undefined
|
||||
;(object as Record<K, unknown>)[property] = function (
|
||||
this: unknown,
|
||||
...args: unknown[]
|
||||
): unknown {
|
||||
const r = callback_orig?.apply(this, args)
|
||||
const n = (callback as (...args: unknown[]) => unknown).apply(this, args)
|
||||
return r || n
|
||||
}
|
||||
} else {
|
||||
object[property] = callback
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a callback to the extra menu options of a given node type.
|
||||
*/
|
||||
export function addMenuHandler(
|
||||
nodeType: NodeType,
|
||||
cb: (this: MTBNode, app: unknown, options: ContextMenuItem[]) => ContextMenuItem[],
|
||||
): void {
|
||||
const getOpts = nodeType.prototype.getExtraMenuOptions
|
||||
|
||||
nodeType.prototype.getExtraMenuOptions = function (
|
||||
this: MTBNode,
|
||||
app: unknown,
|
||||
options: ContextMenuItem[],
|
||||
): ContextMenuItem[] {
|
||||
const r = getOpts?.apply(this, [app, options]) || []
|
||||
const newItems = cb.apply(this, [app, options]) || []
|
||||
return [...r, ...newItems]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prefixes the node title with '[DEPRECATED]' and log the deprecation reason to the console.
|
||||
*/
|
||||
export const addDeprecation = (nodeType: NodeType, reason: string): void => {
|
||||
const title = nodeType.title || 'Unknown'
|
||||
nodeType.title = `[DEPRECATED] ${title}`
|
||||
|
||||
const styles = {
|
||||
title: 'font-size:1.3em;font-weight:900;color:yellow; background: black',
|
||||
reason: 'font-size:1.2em',
|
||||
}
|
||||
// biome-ignore lint/suspicious/noConsole: intentional deprecation warning
|
||||
console.log(`%c! ${title} is deprecated:%c ${reason}`, styles.title, styles.reason)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Local storage management with namespacing
|
||||
*/
|
||||
|
||||
export class LocalStorageManager {
|
||||
private namespace: string
|
||||
|
||||
constructor(namespace: string) {
|
||||
this.namespace = namespace
|
||||
}
|
||||
|
||||
private _namespacedKey(key: string): string {
|
||||
return `${this.namespace}:${key}`
|
||||
}
|
||||
|
||||
set<T>(key: string, value: T): void {
|
||||
const serializedValue = JSON.stringify(value)
|
||||
localStorage.setItem(this._namespacedKey(key), serializedValue)
|
||||
}
|
||||
|
||||
get<T>(key: string, default_val: T | null = null): T | null {
|
||||
const value = localStorage.getItem(this._namespacedKey(key))
|
||||
return value ? (JSON.parse(value) as T) : default_val
|
||||
}
|
||||
|
||||
remove(key: string): void {
|
||||
localStorage.removeItem(this._namespacedKey(key))
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
const prefix = `${this.namespace}:`
|
||||
const keysToRemove = Object.keys(localStorage).filter((k) => k.startsWith(prefix))
|
||||
for (const key of keysToRemove) {
|
||||
localStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* Type definitions for comfy_shared
|
||||
*/
|
||||
|
||||
import type { LGraphNode, IWidget, LLink, INodeInputSlot, INodeOutputSlot } from '@comfyorg/litegraph'
|
||||
|
||||
// Extend window for MTB globals
|
||||
declare global {
|
||||
interface Window {
|
||||
MTB?: {
|
||||
DEBUG?: boolean
|
||||
mdParser?: MarkdownParser
|
||||
}
|
||||
MTBMarkdown?: { getParser: () => Promise<MarkdownParser> }
|
||||
MTBMarkdownPlus?: { getParser: () => Promise<MarkdownParser> }
|
||||
}
|
||||
const LiteGraph: {
|
||||
NODE_SLOT_HEIGHT: number
|
||||
NODE_TITLE_HEIGHT: number
|
||||
NODE_COLLAPSED_RADIUS: number
|
||||
}
|
||||
}
|
||||
|
||||
export interface MarkdownParser {
|
||||
parse: (content: string) => Promise<string>
|
||||
}
|
||||
|
||||
// Widget types
|
||||
export interface MTBWidget extends IWidget {
|
||||
origType?: string
|
||||
origComputeSize?: () => [number, number]
|
||||
origSerializeValue?: () => unknown
|
||||
hidden?: boolean
|
||||
linkedWidgets?: MTBWidget[]
|
||||
last_y?: number
|
||||
canvas?: HTMLCanvasElement
|
||||
inputEl?: HTMLElement
|
||||
onRemoved?: () => void
|
||||
parent?: { inputHeight?: number }
|
||||
}
|
||||
|
||||
export interface MTBNode extends LGraphNode {
|
||||
widgets?: MTBWidget[]
|
||||
inputs: (INodeInputSlot & { widget?: { name: string; config?: unknown }; _isDynamic?: boolean })[]
|
||||
outputs: INodeOutputSlot[]
|
||||
properties: Record<string, unknown>
|
||||
color?: string
|
||||
flags: { collapsed?: boolean }
|
||||
show_doc?: boolean
|
||||
docCtrl?: AbortController
|
||||
docPos?: { width: string; height: string }
|
||||
connectionTransit?: boolean
|
||||
setProperty: (name: string, value: unknown) => void
|
||||
addInput: (name: string, type: string, extra?: Record<string, unknown>) => INodeInputSlot
|
||||
removeInput: (index: number) => void
|
||||
setSize: (size: [number, number]) => void
|
||||
graph: {
|
||||
getLink: (id: number) => LLink
|
||||
getNodeById: (id: number) => MTBNode
|
||||
beforeChange: () => void
|
||||
afterChange: () => void
|
||||
}
|
||||
slots: (INodeInputSlot | INodeOutputSlot)[]
|
||||
}
|
||||
|
||||
export interface NodeType {
|
||||
title?: string
|
||||
prototype: {
|
||||
onNodeCreated?: (this: MTBNode) => void
|
||||
onConfigure?: (this: MTBNode, data: unknown) => void
|
||||
onConnectionsChange?: (this: MTBNode, ...args: OnConnectionsChangeParams) => void
|
||||
onDrawForeground?: (this: MTBNode, ctx: CanvasRenderingContext2D, canvas: unknown) => void
|
||||
onMouseDown?: (this: MTBNode, ...args: OnMouseDownParams) => boolean | void
|
||||
onRemoved?: (this: MTBNode) => void
|
||||
getExtraMenuOptions?: (this: MTBNode, app: unknown, options: ContextMenuItem[]) => ContextMenuItem[]
|
||||
getSlotMenuOptions?: (slot: SlotMenuContext) => ContextMenuItem[]
|
||||
}
|
||||
}
|
||||
|
||||
export interface NodeData {
|
||||
name: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export type OnConnectionsChangeParams = [
|
||||
type: number,
|
||||
slotIndex: number,
|
||||
isConnected: boolean,
|
||||
link: LLink | null,
|
||||
ioSlot: INodeInputSlot | INodeOutputSlot,
|
||||
]
|
||||
|
||||
export type OnMouseDownParams = [
|
||||
event: MouseEvent,
|
||||
localPos: [number, number],
|
||||
graphCanvas: unknown,
|
||||
]
|
||||
|
||||
export interface ContextMenuItem {
|
||||
content: string
|
||||
callback?: (...args: unknown[]) => void
|
||||
}
|
||||
|
||||
export interface SlotMenuContext {
|
||||
input?: INodeInputSlot & { label?: string; name: string }
|
||||
node: MTBNode
|
||||
}
|
||||
|
||||
export interface DocumentationOptions {
|
||||
icon_size?: number
|
||||
icon_margin?: number
|
||||
}
|
||||
|
||||
export interface DynamicConnectionOptions {
|
||||
separator?: string
|
||||
rename_menu?: 'label' | 'name'
|
||||
start_index?: number
|
||||
link?: LLink | null
|
||||
ioSlot?: INodeInputSlot | INodeOutputSlot
|
||||
nameArray?: string[]
|
||||
DEBUG?: unknown
|
||||
}
|
||||
|
||||
export interface LinkInfo {
|
||||
to: MTBNode
|
||||
from: MTBNode
|
||||
type: 'error' | 'incoming' | 'outgoing'
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Base utilities
|
||||
*/
|
||||
|
||||
/**
|
||||
* Computes the convex hull of a set of points using the Monotone Chain algorithm.
|
||||
*/
|
||||
export const getConvexHull = (points: [number, number][]): [number, number][] => {
|
||||
if (points.length <= 3) {
|
||||
return points
|
||||
}
|
||||
|
||||
const sorted = [...points].sort((a, b) => a[0] - b[0] || a[1] - b[1])
|
||||
|
||||
const cross_product = (o: [number, number], a: [number, number], b: [number, number]) => {
|
||||
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
|
||||
}
|
||||
|
||||
const lower: [number, number][] = []
|
||||
for (const p of sorted) {
|
||||
while (
|
||||
lower.length >= 2 &&
|
||||
cross_product(lower[lower.length - 2], lower[lower.length - 1], p) <= 0
|
||||
) {
|
||||
lower.pop()
|
||||
}
|
||||
lower.push(p)
|
||||
}
|
||||
|
||||
const upper: [number, number][] = []
|
||||
for (let i = sorted.length - 1; i >= 0; i--) {
|
||||
const p = sorted[i]
|
||||
while (
|
||||
upper.length >= 2 &&
|
||||
cross_product(upper[upper.length - 2], upper[upper.length - 1], p) <= 0
|
||||
) {
|
||||
upper.pop()
|
||||
}
|
||||
upper.push(p)
|
||||
}
|
||||
|
||||
return lower.slice(0, lower.length - 1).concat(upper.slice(0, upper.length - 1))
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a crude UUID v4
|
||||
*/
|
||||
export function makeUUID(): string {
|
||||
let dt = new Date().getTime()
|
||||
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
|
||||
const r = ((dt + Math.random() * 16) % 16) | 0
|
||||
dt = Math.floor(dt / 16)
|
||||
return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
|
||||
})
|
||||
return uuid
|
||||
}
|
||||
|
||||
export interface Debounced<T extends (...args: unknown[]) => void> {
|
||||
(...args: Parameters<T>): void
|
||||
cancel: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic debounce decorator
|
||||
*/
|
||||
export function debounce<T extends (...args: unknown[]) => void>(
|
||||
func: T,
|
||||
delay: number,
|
||||
): Debounced<T> {
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
const debounced = function (this: unknown, ...args: Parameters<T>) {
|
||||
clearTimeout(timeout)
|
||||
timeout = setTimeout(() => func.apply(this, args), delay)
|
||||
} as Debounced<T>
|
||||
|
||||
debounced.cancel = () => {
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
|
||||
return debounced
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep merge two objects.
|
||||
*/
|
||||
export function deepMerge<T extends Record<string, unknown>>(
|
||||
target: T,
|
||||
...sources: Partial<T>[]
|
||||
): T {
|
||||
if (!sources.length) return target
|
||||
const source = sources.shift()
|
||||
|
||||
if (source) {
|
||||
for (const key in source) {
|
||||
const sourceValue = source[key]
|
||||
if (sourceValue instanceof Object && !Array.isArray(sourceValue)) {
|
||||
if (!target[key]) Object.assign(target, { [key]: {} })
|
||||
deepMerge(target[key] as Record<string, unknown>, sourceValue as Record<string, unknown>)
|
||||
} else {
|
||||
Object.assign(target, { [key]: sourceValue })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return deepMerge(target, ...sources)
|
||||
}
|
||||
|
||||
type Replacer = (value: unknown) => unknown
|
||||
|
||||
/**
|
||||
* Safely serialize an object to JSON, handling circular references
|
||||
*/
|
||||
export const safe_json = (object: unknown, replacer?: Replacer): unknown => {
|
||||
const objects = new WeakMap<object, string>()
|
||||
|
||||
const derez = (value: unknown, path: string): unknown => {
|
||||
if (replacer !== undefined) {
|
||||
value = replacer(value)
|
||||
}
|
||||
|
||||
if (
|
||||
typeof value === 'object' &&
|
||||
value !== null &&
|
||||
!(value instanceof Boolean) &&
|
||||
!(value instanceof Date) &&
|
||||
!(value instanceof Number) &&
|
||||
!(value instanceof RegExp) &&
|
||||
!(value instanceof String)
|
||||
) {
|
||||
const old_path = objects.get(value)
|
||||
if (old_path !== undefined) {
|
||||
return { $ref: old_path }
|
||||
}
|
||||
objects.set(value, path)
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const nu: unknown[] = []
|
||||
value.forEach((element, i) => {
|
||||
nu[i] = derez(element, `${path}[${i}]`)
|
||||
})
|
||||
return nu
|
||||
} else {
|
||||
const nu: Record<string, unknown> = {}
|
||||
Object.keys(value).forEach((name) => {
|
||||
nu[name] = derez(
|
||||
(value as Record<string, unknown>)[name],
|
||||
path + '[' + JSON.stringify(name) + ']',
|
||||
)
|
||||
})
|
||||
return nu
|
||||
}
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
return derez(object, '$')
|
||||
}
|
||||
|
||||
// Declare app global for ComfyUI
|
||||
declare const app: {
|
||||
graph: {
|
||||
_nodes: import('./types').MTBNode[]
|
||||
computeExecutionOrder?: (onlyOnExecute: boolean) => import('./types').MTBNode[]
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all nodes from the current graph
|
||||
* @param sorted - If true, returns nodes in execution order
|
||||
*/
|
||||
export function getNodes(sorted = false): import('./types').MTBNode[] {
|
||||
if (!app?.graph?._nodes) {
|
||||
return []
|
||||
}
|
||||
|
||||
if (sorted) {
|
||||
// computeExecutionOrder returns nodes in dependency order
|
||||
return app.graph.computeExecutionOrder?.(false) ?? app.graph._nodes
|
||||
}
|
||||
|
||||
return app.graph._nodes
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
/**
|
||||
* Widget utilities for LiteGraph nodes
|
||||
*/
|
||||
|
||||
import type { LLink } from '@comfyorg/litegraph'
|
||||
import type { MTBNode, MTBWidget, LinkInfo } from './types'
|
||||
import { log } from './logger'
|
||||
|
||||
export const CONVERTED_TYPE = 'converted-widget'
|
||||
|
||||
export function hideWidget(node: MTBNode, widget: MTBWidget, suffix = ''): void {
|
||||
widget.origType = widget.type as string
|
||||
widget.hidden = true
|
||||
widget.origComputeSize = widget.computeSize
|
||||
widget.origSerializeValue = widget.serializeValue
|
||||
widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
|
||||
widget.type = CONVERTED_TYPE + suffix
|
||||
widget.serializeValue = () => {
|
||||
// Prevent serializing the widget if we have no input linked
|
||||
const input = node.inputs?.find((i) => i.widget?.name === widget.name)
|
||||
if (input?.link == null) {
|
||||
return undefined
|
||||
}
|
||||
return widget.origSerializeValue ? widget.origSerializeValue() : widget.value
|
||||
}
|
||||
|
||||
// Hide any linked widgets, e.g. seed+seedControl
|
||||
if (widget.linkedWidgets) {
|
||||
for (const w of widget.linkedWidgets) {
|
||||
hideWidget(node, w, `:${widget.name}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function showWidget(widget: MTBWidget): void {
|
||||
widget.type = widget.origType!
|
||||
widget.computeSize = widget.origComputeSize!
|
||||
widget.serializeValue = widget.origSerializeValue
|
||||
|
||||
delete widget.origType
|
||||
delete widget.origComputeSize
|
||||
delete widget.origSerializeValue
|
||||
|
||||
// Show any linked widgets, e.g. seed+seedControl
|
||||
if (widget.linkedWidgets) {
|
||||
for (const w of widget.linkedWidgets) {
|
||||
showWidget(w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function convertToWidget(node: MTBNode, widget: MTBWidget): void {
|
||||
showWidget(widget)
|
||||
const sz = node.size
|
||||
const inputIndex = node.inputs.findIndex((i) => i.widget?.name === widget.name)
|
||||
if (inputIndex >= 0) {
|
||||
node.removeInput(inputIndex)
|
||||
}
|
||||
|
||||
if (node.widgets) {
|
||||
for (const w of node.widgets) {
|
||||
if (w.last_y !== undefined) {
|
||||
w.last_y -= LiteGraph.NODE_SLOT_HEIGHT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore original size but grow if needed
|
||||
node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the type and link type from a widget config object.
|
||||
*/
|
||||
export function getWidgetType(config: unknown[]): { type: string; linkType: string } {
|
||||
let type = config?.[0]
|
||||
let linkType = type as string
|
||||
if (Array.isArray(type)) {
|
||||
linkType = type.join(',')
|
||||
type = 'COMBO'
|
||||
}
|
||||
return { type: type as string, linkType }
|
||||
}
|
||||
|
||||
export function convertToInput(
|
||||
node: MTBNode,
|
||||
widget: MTBWidget,
|
||||
config: unknown[],
|
||||
): void {
|
||||
hideWidget(node, widget)
|
||||
|
||||
const { linkType } = getWidgetType(config)
|
||||
|
||||
// Add input and store widget config for creating on primitive node
|
||||
const sz = node.size
|
||||
node.addInput(widget.name, linkType, {
|
||||
widget: { name: widget.name, config },
|
||||
})
|
||||
|
||||
if (node.widgets) {
|
||||
for (const w of node.widgets) {
|
||||
if (w.last_y !== undefined) {
|
||||
w.last_y += LiteGraph.NODE_SLOT_HEIGHT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore original size but grow if needed
|
||||
node.setSize([Math.max(sz[0], node.size[0]), Math.max(sz[1], node.size[1])])
|
||||
}
|
||||
|
||||
export function hideWidgetForGood(node: MTBNode, widget: MTBWidget, suffix = ''): void {
|
||||
widget.origType = widget.type as string
|
||||
widget.origComputeSize = widget.computeSize
|
||||
widget.origSerializeValue = widget.serializeValue
|
||||
widget.computeSize = () => [0, -4]
|
||||
widget.hidden = true
|
||||
widget.type = CONVERTED_TYPE + suffix
|
||||
|
||||
// Hide any linked widgets
|
||||
if (widget.linkedWidgets) {
|
||||
for (const w of widget.linkedWidgets) {
|
||||
hideWidgetForGood(node, w, `:${widget.name}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function fixWidgets(node: MTBNode): void {
|
||||
if (!node.inputs) return
|
||||
|
||||
for (const input of node.inputs) {
|
||||
log(input)
|
||||
if (input.widget || node.widgets) {
|
||||
const matching_widget = node.widgets?.find((w) => w.name === input.name)
|
||||
if (matching_widget) {
|
||||
const w = node.widgets?.find((w) => w.name === matching_widget.name)
|
||||
if (w && w.type !== CONVERTED_TYPE) {
|
||||
log(w)
|
||||
log(`hiding ${w.name}(${w.type}) from ${node.type}`)
|
||||
log(node)
|
||||
hideWidget(node, w)
|
||||
} else {
|
||||
log(`converting to widget ${w}`)
|
||||
if (w) convertToWidget(node, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function inner_value_change(
|
||||
node: MTBNode,
|
||||
widget: MTBWidget,
|
||||
val: unknown,
|
||||
pos?: [number, number],
|
||||
event?: Event,
|
||||
): void {
|
||||
let value = val
|
||||
if (widget.type === 'number' || widget.type === 'BBOX') {
|
||||
value = Number(value)
|
||||
} else if (widget.type === 'BOOL') {
|
||||
value = Boolean(value)
|
||||
}
|
||||
widget.value = value
|
||||
|
||||
const property = (widget.options as { property?: string } | undefined)?.property
|
||||
if (property && node.properties[property] !== undefined) {
|
||||
node.setProperty(property, value)
|
||||
}
|
||||
|
||||
if (widget.callback) {
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
widget.callback(widget.value, app.canvas, node, pos, event)
|
||||
}
|
||||
}
|
||||
|
||||
export const getNamedWidget = <T extends string>(
|
||||
node: MTBNode,
|
||||
...names: T[]
|
||||
): Record<T, MTBWidget | undefined> => {
|
||||
const out = {} as Record<T, MTBWidget | undefined>
|
||||
|
||||
for (const name of names) {
|
||||
out[name] = node.widgets?.find((w) => w.name === name)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
export const nodesFromLink = (node: MTBNode, link: LLink | number): LinkInfo => {
|
||||
let resolvedLink: LLink
|
||||
if (typeof link === 'number') {
|
||||
resolvedLink = node.graph.getLink(link)
|
||||
} else {
|
||||
resolvedLink = link
|
||||
}
|
||||
|
||||
const fromNode = node.graph.getNodeById(resolvedLink.origin_id)
|
||||
const toNode = node.graph.getNodeById(resolvedLink.target_id)
|
||||
|
||||
let tp: 'error' | 'incoming' | 'outgoing' = 'error'
|
||||
|
||||
if (fromNode.id === node.id) {
|
||||
tp = 'outgoing'
|
||||
} else if (toNode.id === node.id) {
|
||||
tp = 'incoming'
|
||||
}
|
||||
|
||||
return { to: toNode, from: fromNode, type: tp }
|
||||
}
|
||||
|
||||
export const hasWidgets = (node: MTBNode): boolean => {
|
||||
if (!node.widgets || !node.widgets?.[Symbol.iterator]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export const cleanupNode = (node: MTBNode): void => {
|
||||
if (!hasWidgets(node)) {
|
||||
return
|
||||
}
|
||||
for (const w of node.widgets!) {
|
||||
if (w.canvas) {
|
||||
w.canvas.remove()
|
||||
}
|
||||
if (w.inputEl) {
|
||||
w.inputEl.remove()
|
||||
}
|
||||
w.onRemoved?.()
|
||||
}
|
||||
}
|
||||
|
||||
export function offsetDOMWidget(
|
||||
widget: MTBWidget,
|
||||
ctx: CanvasRenderingContext2D,
|
||||
node: MTBNode,
|
||||
widgetWidth: number,
|
||||
widgetY: number,
|
||||
height?: number,
|
||||
): void {
|
||||
if (!widget.inputEl) return
|
||||
|
||||
const margin = 10
|
||||
const elRect = ctx.canvas.getBoundingClientRect()
|
||||
const transform = new DOMMatrix()
|
||||
.scaleSelf(elRect.width / ctx.canvas.width, elRect.height / ctx.canvas.height)
|
||||
.multiplySelf(ctx.getTransform())
|
||||
.translateSelf(margin, margin + widgetY)
|
||||
|
||||
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
|
||||
Object.assign(widget.inputEl.style, {
|
||||
transformOrigin: '0 0',
|
||||
transform: scale.toString(),
|
||||
left: `${transform.a + transform.e}px`,
|
||||
top: `${transform.d + transform.f}px`,
|
||||
width: `${widgetWidth - margin * 2}px`,
|
||||
height: `${(height || widget.parent?.inputHeight || 32) - margin * 2}px`,
|
||||
position: 'absolute',
|
||||
background: !node.color ? '' : node.color,
|
||||
color: !node.color ? '' : 'white',
|
||||
zIndex: '5',
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// import './app.css'
|
||||
// import App from './App.svelte'
|
||||
import Inspector from './lib/Inspector.svelte'
|
||||
|
||||
export const createOutliner = (target, opts) => {
|
||||
const options = opts || {}
|
||||
const tgt = target || document.body
|
||||
|
||||
const app = new Inspector({
|
||||
// target: document.getElementById('app'),
|
||||
target: tgt,
|
||||
props: options,
|
||||
})
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
<script lang="ts">
|
||||
import { fade } from 'svelte/transition'
|
||||
import { resizeHandle } from './actions.js'
|
||||
|
||||
import InspectorPreview from './InspectorPreview.svelte'
|
||||
import Tabs from './Tabs.svelte'
|
||||
import TabUi from './TabUI.svelte'
|
||||
import TabHelp from './TabHelp.svelte'
|
||||
import { inComfy } from './utils'
|
||||
import { onMount } from 'svelte'
|
||||
import { graphToPrompt } from '../mtb_api/graph-to-prompt'
|
||||
|
||||
interface InputItem {
|
||||
id: number
|
||||
name: string
|
||||
type: string
|
||||
options?: string[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
let {
|
||||
visible = true,
|
||||
inputs = {} as Record<string, InputItem>,
|
||||
} = $props()
|
||||
|
||||
const items = $derived(
|
||||
Object.keys(inputs).map((k) => ({
|
||||
...inputs[k],
|
||||
original_name: inputs[k].original_name ?? k,
|
||||
}))
|
||||
)
|
||||
|
||||
onMount(() => {
|
||||
console.log('Mounted API Inspector')
|
||||
})
|
||||
|
||||
async function exportApi() {
|
||||
if (!inComfy()) return
|
||||
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
const { output } = await graphToPrompt(app)
|
||||
|
||||
const json = JSON.stringify(output, null, 2)
|
||||
const blob = new Blob([json], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = 'workflow_api.json'
|
||||
a.click()
|
||||
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
</script>
|
||||
|
||||
{#if visible}
|
||||
<div transition:fade={{ duration: 120 }} use:resizeHandle class="mtb-panel">
|
||||
<header class="mtb-panel-header">
|
||||
<div class="mtb-panel-title">
|
||||
<span class="mtb-panel-icon">⚡</span>
|
||||
<span>API Controls</span>
|
||||
</div>
|
||||
<span class="mtb-panel-badge">{items.length}</span>
|
||||
</header>
|
||||
|
||||
<div class="mtb-panel-content">
|
||||
<InspectorPreview />
|
||||
|
||||
<Tabs
|
||||
items={[
|
||||
{
|
||||
label: 'Inputs',
|
||||
value: 1,
|
||||
component: TabUi,
|
||||
props: { inputs: items },
|
||||
},
|
||||
{
|
||||
label: 'Help',
|
||||
value: 2,
|
||||
component: TabHelp,
|
||||
props: {},
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<footer class="mtb-panel-footer">
|
||||
<button class="mtb-btn mtb-btn-primary" onclick={() => {
|
||||
if (!inComfy()) return
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
app.queuePrompt(0, 1)
|
||||
}}>
|
||||
<span class="mtb-btn-icon">▶</span>
|
||||
Queue
|
||||
</button>
|
||||
<button class="mtb-btn mtb-btn-secondary" onclick={exportApi}>Export</button>
|
||||
</footer>
|
||||
|
||||
<div class="mtb-panel-status">
|
||||
<span class="mtb-status-dot"></span>
|
||||
<span>Ready</span>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
/* MTB Panel - Vercel-inspired minimal design */
|
||||
.mtb-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
background: var(--comfy-menu-bg, #1a1a1a);
|
||||
color: var(--fg-color, #fafafa);
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
.mtb-panel-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--border-color, rgba(255,255,255,0.08));
|
||||
background: var(--comfy-menu-bg, #1a1a1a);
|
||||
}
|
||||
|
||||
.mtb-panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 500;
|
||||
font-size: 13px;
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.mtb-panel-icon {
|
||||
font-size: 14px;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.mtb-panel-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 20px;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
background: var(--mtb-api-color, #2930b0);
|
||||
color: white;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
border-radius: 10px;
|
||||
}
|
||||
|
||||
/* Content */
|
||||
.mtb-panel-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--fg-color, #888) transparent;
|
||||
}
|
||||
|
||||
.mtb-panel-content::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
}
|
||||
|
||||
.mtb-panel-content::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.mtb-panel-content::-webkit-scrollbar-thumb {
|
||||
background: var(--border-color, rgba(255,255,255,0.15));
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.mtb-panel-content::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--fg-color, rgba(255,255,255,0.25));
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.mtb-panel-footer {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
padding: 12px 16px;
|
||||
border-top: 1px solid var(--border-color, rgba(255,255,255,0.08));
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.mtb-btn {
|
||||
flex: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
height: 32px;
|
||||
padding: 0 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.mtb-btn-primary {
|
||||
background: var(--mtb-api-color, #2930b0);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.mtb-btn-primary:hover {
|
||||
background: color-mix(in srgb, var(--mtb-api-color, #2930b0), white 10%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.mtb-btn-secondary {
|
||||
background: var(--comfy-input-bg, rgba(255,255,255,0.05));
|
||||
color: var(--fg-color, #fafafa);
|
||||
border: 1px solid var(--border-color, rgba(255,255,255,0.1));
|
||||
}
|
||||
|
||||
.mtb-btn-secondary:hover {
|
||||
background: var(--border-color, rgba(255,255,255,0.1));
|
||||
border-color: var(--fg-color, rgba(255,255,255,0.2));
|
||||
}
|
||||
|
||||
.mtb-btn-icon {
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* Status bar */
|
||||
.mtb-panel-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding: 6px 16px;
|
||||
font-size: 11px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.5));
|
||||
background: rgba(0,0,0,0.2);
|
||||
}
|
||||
|
||||
.mtb-status-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
background: #10b981;
|
||||
border-radius: 50%;
|
||||
animation: pulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% { opacity: 1; }
|
||||
50% { opacity: 0.5; }
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,212 @@
|
||||
<script lang="ts">
|
||||
import ColorPicker, { ChromeVariant } from 'svelte-awesome-color-picker'
|
||||
import Wrapper from './Wrapper.svelte'
|
||||
|
||||
let element: HTMLElement
|
||||
|
||||
let {
|
||||
item = { type: 'NUMBER' },
|
||||
onInput = (e: Event, val?: unknown) => console.log(e, val),
|
||||
id = undefined,
|
||||
value = $bindable(''),
|
||||
} = $props()
|
||||
|
||||
const shared = {
|
||||
autocomplete: 'off',
|
||||
'data-lpignore': true,
|
||||
'data-form-type': 'other',
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mtb-input-wrapper">
|
||||
{#if item.type === 'NUMBER'}
|
||||
<input
|
||||
class="mtb-input"
|
||||
oninput={onInput}
|
||||
{...shared}
|
||||
{id}
|
||||
bind:value
|
||||
bind:this={element}
|
||||
type="number"
|
||||
/>
|
||||
{:else if item.type === 'MODEL' || item.type === 'COMBO'}
|
||||
{@const options = item.options || item.widgets?.[0]?.options?.values || []}
|
||||
<select class="mtb-select" oninput={onInput} bind:value {...shared} {id} bind:this={element}>
|
||||
{#each options as option}
|
||||
<option selected={item.widget?.value === option} value={option}>{option}</option>
|
||||
{/each}
|
||||
</select>
|
||||
{:else if item.type === 'STRING'}
|
||||
{#if item.widgets?.[0]?.type === 'customtext'}
|
||||
<textarea
|
||||
class="mtb-textarea"
|
||||
oninput={onInput}
|
||||
bind:value
|
||||
{...shared}
|
||||
{id}
|
||||
bind:this={element}
|
||||
rows="3"
|
||||
></textarea>
|
||||
{:else}
|
||||
<input
|
||||
class="mtb-input"
|
||||
oninput={onInput}
|
||||
bind:value
|
||||
{...shared}
|
||||
{id}
|
||||
type="text"
|
||||
bind:this={element}
|
||||
/>
|
||||
{/if}
|
||||
{:else if item.type === 'BOOLEAN'}
|
||||
{@const isChecked = value === true || value === 'true' || value === 1 || value === '1' || value === 'on'}
|
||||
<label class="mtb-toggle">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onchange={(e) => {
|
||||
// ComfyUI toggles use booleans - 'off' string is truthy so doesn't work!
|
||||
const newValue = e.currentTarget.checked
|
||||
value = newValue
|
||||
onInput(e, newValue)
|
||||
}}
|
||||
/>
|
||||
<span class="mtb-toggle-slider"></span>
|
||||
<span class="mtb-toggle-label">{isChecked ? 'On' : 'Off'}</span>
|
||||
</label>
|
||||
{:else if item.type === 'COLOR'}
|
||||
<ColorPicker
|
||||
label=""
|
||||
bind:hex={value}
|
||||
components={{ ...ChromeVariant, wrapper: Wrapper }}
|
||||
sliderDirection="horizontal"
|
||||
--picker-z-index="9000"
|
||||
oninput={(event) => {
|
||||
value = event.detail.hex
|
||||
}}
|
||||
/>
|
||||
{:else}
|
||||
<input class="mtb-input" oninput={onInput} bind:value {...shared} {id} bind:this={element} />
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.mtb-input-wrapper {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Base input styles */
|
||||
.mtb-input,
|
||||
.mtb-select,
|
||||
.mtb-textarea {
|
||||
width: 100%;
|
||||
padding: 8px 12px;
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
color: var(--fg-color, #fafafa);
|
||||
background: var(--comfy-input-bg, rgba(255,255,255,0.05));
|
||||
border: 1px solid var(--border-color, rgba(255,255,255,0.1));
|
||||
border-radius: 6px;
|
||||
outline: none;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.mtb-input:hover,
|
||||
.mtb-select:hover,
|
||||
.mtb-textarea:hover {
|
||||
border-color: var(--border-color, rgba(255,255,255,0.2));
|
||||
}
|
||||
|
||||
.mtb-input:focus,
|
||||
.mtb-select:focus,
|
||||
.mtb-textarea:focus {
|
||||
border-color: var(--mtb-api-color, #2930b0);
|
||||
box-shadow: 0 0 0 3px rgba(41, 48, 176, 0.15);
|
||||
}
|
||||
|
||||
/* Number input */
|
||||
.mtb-input[type='number'] {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.mtb-input[type='number']::-webkit-inner-spin-button,
|
||||
.mtb-input[type='number']::-webkit-outer-spin-button {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.mtb-input[type='number']:hover::-webkit-inner-spin-button,
|
||||
.mtb-input[type='number']:hover::-webkit-outer-spin-button {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Select */
|
||||
.mtb-select {
|
||||
cursor: pointer;
|
||||
appearance: none;
|
||||
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='%23888' stroke-width='2'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E");
|
||||
background-repeat: no-repeat;
|
||||
background-position: right 12px center;
|
||||
padding-right: 36px;
|
||||
}
|
||||
|
||||
.mtb-select option {
|
||||
background: var(--comfy-menu-bg, #1a1a1a);
|
||||
color: var(--fg-color, #fafafa);
|
||||
}
|
||||
|
||||
/* Textarea */
|
||||
.mtb-textarea {
|
||||
resize: vertical;
|
||||
min-height: 60px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Toggle switch */
|
||||
.mtb-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.mtb-toggle input {
|
||||
position: absolute;
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.mtb-toggle-slider {
|
||||
position: relative;
|
||||
width: 36px;
|
||||
height: 20px;
|
||||
background: var(--border-color, rgba(255,255,255,0.15));
|
||||
border-radius: 10px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.mtb-toggle-slider::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
background: white;
|
||||
border-radius: 50%;
|
||||
transition: transform 0.2s ease;
|
||||
}
|
||||
|
||||
.mtb-toggle input:checked + .mtb-toggle-slider {
|
||||
background: var(--mtb-api-color, #2930b0);
|
||||
}
|
||||
|
||||
.mtb-toggle input:checked + .mtb-toggle-slider::after {
|
||||
transform: translateX(16px);
|
||||
}
|
||||
|
||||
.mtb-toggle-label {
|
||||
font-size: 12px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.6));
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,221 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack } from 'svelte'
|
||||
import InspectorInput from './InspectorInput.svelte'
|
||||
import { inComfy } from './utils.js'
|
||||
|
||||
interface ItemType {
|
||||
name: string
|
||||
type: string
|
||||
node_id?: number
|
||||
id: number
|
||||
value?: unknown
|
||||
widgets?: { value: unknown }[]
|
||||
options?: string[]
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
interface Action {
|
||||
label: string
|
||||
icon?: string
|
||||
callback: () => void
|
||||
}
|
||||
|
||||
let {
|
||||
item = {
|
||||
name: 'KSampler',
|
||||
type: 'STRING',
|
||||
node_id: 123,
|
||||
id: 4,
|
||||
} as ItemType,
|
||||
extra_actions = {} as Record<string, Action>,
|
||||
} = $props()
|
||||
|
||||
let actions = $state<Record<string, Action>>({})
|
||||
|
||||
// Derive value from widget - updates when widget value changes
|
||||
const getWidgetValue = () => item.widgets?.[0]?.value ?? item.value ?? ''
|
||||
let value = $state<unknown>(getWidgetValue())
|
||||
|
||||
// Sync value from widget when it changes (Node → Panel)
|
||||
// Use untrack to prevent reacting to local value changes (avoids reverting user input)
|
||||
$effect(() => {
|
||||
const widgetVal = getWidgetValue()
|
||||
untrack(() => {
|
||||
if (widgetVal !== value) {
|
||||
value = widgetVal
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
onMount(() => {
|
||||
actions = {
|
||||
goToNode: {
|
||||
label: 'Focus',
|
||||
icon: '↗',
|
||||
callback: () => {
|
||||
const id = item.node_id
|
||||
if (!id) return
|
||||
if (!inComfy()) return
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
const app = window.app
|
||||
const node = app.graph.getNodeById(id)
|
||||
app.canvas.centerOnNode(node)
|
||||
app.canvas.setZoom(1)
|
||||
app.canvas.selectNode(node)
|
||||
},
|
||||
},
|
||||
...extra_actions,
|
||||
}
|
||||
if (item.name.toLowerCase() === 'seed') {
|
||||
actions.randomize = {
|
||||
label: 'Random',
|
||||
icon: '⚄',
|
||||
callback: () => {
|
||||
value = Math.floor(Math.random() * 1e9)
|
||||
if (!inComfy()) return
|
||||
onInput(null, value)
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
window.app.canvas.setDirty(true)
|
||||
},
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const onInput = (e: Event | null, val?: unknown) => {
|
||||
if (!inComfy()) return
|
||||
if (item.widgets) {
|
||||
for (const w of item.widgets as Array<{
|
||||
value: unknown
|
||||
callback?: (value: unknown) => void
|
||||
options?: { callback?: (value: unknown) => void }
|
||||
}>) {
|
||||
const newVal = val ?? (e?.target as HTMLInputElement)?.value
|
||||
w.value = newVal
|
||||
// Trigger widget callback to notify ComfyUI of the change
|
||||
w.callback?.(newVal)
|
||||
w.options?.callback?.(newVal)
|
||||
}
|
||||
// @ts-expect-error - app is global in ComfyUI
|
||||
window.app.canvas.setDirty(true)
|
||||
}
|
||||
}
|
||||
|
||||
const typeLabels: Record<string, string> = {
|
||||
STRING: 'Text',
|
||||
NUMBER: 'Number',
|
||||
COMBO: 'Select',
|
||||
MODEL: 'Model',
|
||||
BOOLEAN: 'Toggle',
|
||||
IMAGE: 'Image',
|
||||
COLOR: 'Color',
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mtb-input-row">
|
||||
<div class="mtb-input-header">
|
||||
<label class="mtb-input-label" for="input-{item.id}">{item.name}</label>
|
||||
<span class="mtb-input-type">{typeLabels[item.type] || item.type}</span>
|
||||
</div>
|
||||
|
||||
<div class="mtb-input-field">
|
||||
<InspectorInput {onInput} bind:value id={item.id} {item} />
|
||||
</div>
|
||||
|
||||
{#if Object.keys(actions).length > 0}
|
||||
<div class="mtb-input-actions">
|
||||
{#each Object.keys(actions) as k}
|
||||
{@const action = actions[k]}
|
||||
<button
|
||||
class="mtb-action-btn"
|
||||
onclick={action.callback}
|
||||
title={action.label}
|
||||
>
|
||||
{#if action.icon}
|
||||
<span class="mtb-action-icon">{action.icon}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.mtb-input-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
padding: 12px 16px;
|
||||
border-bottom: 1px solid var(--border-color, rgba(255,255,255,0.06));
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
.mtb-input-row:hover {
|
||||
background: rgba(255,255,255,0.02);
|
||||
}
|
||||
|
||||
.mtb-input-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.mtb-input-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mtb-input-label {
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--fg-color, #fafafa);
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.mtb-input-type {
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.4));
|
||||
padding: 2px 6px;
|
||||
background: rgba(255,255,255,0.05);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.mtb-input-field {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.mtb-input-actions {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.mtb-action-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-color, rgba(255,255,255,0.1));
|
||||
border-radius: 4px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.5));
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.mtb-action-btn:hover {
|
||||
background: var(--mtb-api-color, #2930b0);
|
||||
border-color: var(--mtb-api-color, #2930b0);
|
||||
color: white;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.mtb-action-icon {
|
||||
font-size: 12px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,107 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte'
|
||||
import { inComfy } from './utils'
|
||||
import type { NodeId } from '@comfyorg/litegraph'
|
||||
import type { ComfyApi } from '@comfyorg/comfyui-frontend-types'
|
||||
|
||||
let nodeId: NodeId | undefined = $state()
|
||||
let img: string | undefined = $state()
|
||||
|
||||
const show = (src: string, node?: NodeId | null) => {
|
||||
img = src
|
||||
nodeId = Number(node)
|
||||
}
|
||||
let api: ComfyApi
|
||||
|
||||
onMount(() => {
|
||||
if (!inComfy()) return
|
||||
import('@/scripts/api').then((e) => {
|
||||
api = e.api
|
||||
api.addEventListener('executed', ({ detail }) => {
|
||||
const images = detail?.output?.images
|
||||
if (!images || !images.length) return
|
||||
const format = window.app?.getPreviewFormatParam()
|
||||
const src = [
|
||||
`./view?filename=${encodeURIComponent(images[0].filename)}`,
|
||||
`type=${images[0].type}`,
|
||||
`subfolder=${encodeURIComponent(images[0].subfolder)}`,
|
||||
`t=${+new Date()}${format}`,
|
||||
].join('&')
|
||||
show(src, detail.node)
|
||||
})
|
||||
|
||||
api.addEventListener('b_preview', ({ detail }) => {
|
||||
show(URL.createObjectURL(detail), window.app?.runningNodeId)
|
||||
})
|
||||
})
|
||||
})
|
||||
</script>
|
||||
|
||||
<button
|
||||
class="mtb-preview"
|
||||
onclick={(e) => {
|
||||
if (!inComfy()) return
|
||||
e.stopPropagation()
|
||||
e.preventDefault()
|
||||
const node = window.app?.graph.getNodeById(nodeId)
|
||||
if (!node) return
|
||||
window.app?.canvas.centerOnNode(node)
|
||||
window.app?.canvas.setZoom(1)
|
||||
}}
|
||||
>
|
||||
{#if img}
|
||||
<img src={img} alt="Preview output" />
|
||||
{:else}
|
||||
<div class="mtb-preview-empty">
|
||||
<span class="mtb-preview-icon">🖼</span>
|
||||
<span class="mtb-preview-text">No preview yet</span>
|
||||
</div>
|
||||
{/if}
|
||||
</button>
|
||||
|
||||
<style>
|
||||
.mtb-preview {
|
||||
width: 100%;
|
||||
min-height: 180px;
|
||||
max-height: 320px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(0, 0, 0, 0.3);
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--border-color, rgba(255,255,255,0.06));
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.mtb-preview:hover {
|
||||
background: rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
.mtb-preview img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
max-height: 320px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.mtb-preview-empty {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 40px;
|
||||
}
|
||||
|
||||
.mtb-preview-icon {
|
||||
font-size: 32px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.mtb-preview-text {
|
||||
font-size: 12px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.3));
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
</script>
|
||||
|
||||
<h3>How to use this panel?</h3>
|
||||
<p>
|
||||
This panel was mainly developed to ease the authoring of workflows to use
|
||||
externaly with the API
|
||||
</p>
|
||||
|
||||
<style>
|
||||
section {
|
||||
width: 100%;
|
||||
padding: 0.3em;
|
||||
overflow: auto;
|
||||
}
|
||||
div {
|
||||
padding: 0.2em;
|
||||
margin: 0.15em 0;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,161 @@
|
||||
<script lang="ts">
|
||||
import { dndzone } from 'svelte-dnd-action'
|
||||
import InspectorItem from './InspectorItem.svelte'
|
||||
import { flip } from 'svelte/animate'
|
||||
import { notifyOrderChanged } from '../mtb_api/panel.svelte'
|
||||
|
||||
interface InputItem {
|
||||
id: number
|
||||
node_id?: number
|
||||
original_name?: string
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
let { inputs = [] as InputItem[] } = $props()
|
||||
|
||||
const flipDurationMs = 100
|
||||
let locked = $state(false)
|
||||
|
||||
function handleDndConsider(e: CustomEvent<{ items: InputItem[] }>) {
|
||||
inputs = e.detail.items
|
||||
}
|
||||
|
||||
function handleDndFinalize(e: CustomEvent<{ items: InputItem[] }>) {
|
||||
inputs = e.detail.items
|
||||
// Persist the new order back to the nodes
|
||||
const orderedInputs = inputs.map((item, index) => ({
|
||||
node_id: item.node_id as number,
|
||||
original_name: item.original_name as string,
|
||||
order: index,
|
||||
}))
|
||||
notifyOrderChanged(orderedInputs)
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="mtb-tab-ui">
|
||||
<div class="mtb-tab-toolbar">
|
||||
<button
|
||||
class="mtb-toolbar-btn"
|
||||
class:active={locked}
|
||||
onclick={() => (locked = !locked)}
|
||||
title={locked ? 'Unlock reordering' : 'Lock reordering'}
|
||||
>
|
||||
{#if locked}
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
|
||||
<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
|
||||
</svg>
|
||||
{:else}
|
||||
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
|
||||
<path d="M7 11V7a5 5 0 0 1 9.9-1"></path>
|
||||
</svg>
|
||||
{/if}
|
||||
</button>
|
||||
<span class="mtb-toolbar-label">{inputs.length} input{inputs.length !== 1 ? 's' : ''}</span>
|
||||
</div>
|
||||
|
||||
{#if inputs.length === 0}
|
||||
<div class="mtb-empty-state">
|
||||
<div class="mtb-empty-icon">⚡</div>
|
||||
<p class="mtb-empty-text">No API inputs</p>
|
||||
<p class="mtb-empty-hint">Right-click a node and select "Mark API" to expose its inputs</p>
|
||||
</div>
|
||||
{:else}
|
||||
<div
|
||||
class="mtb-inputs-list"
|
||||
use:dndzone={{ items: inputs, flipDurationMs, dragDisabled: locked }}
|
||||
onconsider={handleDndConsider}
|
||||
onfinalize={handleDndFinalize}
|
||||
>
|
||||
{#each inputs as item (item.id)}
|
||||
<div animate:flip={{ duration: flipDurationMs }}>
|
||||
<InspectorItem {item} />
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.mtb-tab-ui {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.mtb-tab-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 16px;
|
||||
border-bottom: 1px solid var(--border-color, rgba(255,255,255,0.06));
|
||||
}
|
||||
|
||||
.mtb-toolbar-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-color, rgba(255,255,255,0.1));
|
||||
border-radius: 6px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.5));
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
}
|
||||
|
||||
.mtb-toolbar-btn:hover {
|
||||
background: rgba(255,255,255,0.05);
|
||||
border-color: rgba(255,255,255,0.2);
|
||||
}
|
||||
|
||||
.mtb-toolbar-btn.active {
|
||||
background: var(--mtb-api-color, #2930b0);
|
||||
border-color: var(--mtb-api-color, #2930b0);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.mtb-toolbar-label {
|
||||
font-size: 11px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.4));
|
||||
}
|
||||
|
||||
.mtb-inputs-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* Empty state */
|
||||
.mtb-empty-state {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 40px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mtb-empty-icon {
|
||||
font-size: 32px;
|
||||
margin-bottom: 12px;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.mtb-empty-text {
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
color: var(--fg-color, #fafafa);
|
||||
margin: 0 0 8px;
|
||||
}
|
||||
|
||||
.mtb-empty-hint {
|
||||
font-size: 12px;
|
||||
color: var(--descrip-text, rgba(255,255,255,0.4));
|
||||
margin: 0;
|
||||
max-width: 200px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user