Compare commits
92
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d576190f07 | ||
|
|
247ad12ec3 | ||
|
|
881573e2f2 | ||
|
|
6f3a5b5c71 | ||
|
|
fa017fbb81 | ||
|
|
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 | ||
|
|
e10faab458 | ||
|
|
bb5682aa6d | ||
|
|
59612fd811 | ||
|
|
30eb5b0091 | ||
|
|
1edc2cd10d | ||
|
|
fa3199be2b | ||
|
|
43d65ae68c | ||
|
|
dfd17f6d78 | ||
|
|
1070edd024 | ||
|
|
9f0ed85cc1 | ||
|
|
35622e3a5e | ||
|
|
644371e5b5 | ||
|
|
f3d468cfc2 | ||
|
|
6cd448b026 | ||
|
|
5951c90b10 | ||
|
|
6abac2e470 | ||
|
|
01c73e1c5e | ||
|
|
5060c56135 | ||
|
|
acc2d687d5 | ||
|
|
780c52f03a | ||
|
|
2fe0859476 | ||
|
|
1186239751 | ||
|
|
96a0da9dbd | ||
|
|
f9d2ebf91d | ||
|
|
1b7ae27cc1 | ||
|
|
e312b02ad2 | ||
|
|
63ee25d001 | ||
|
|
1caf7c18c3 | ||
|
|
349a8524c6 | ||
|
|
15330eab65 | ||
|
|
1571782d01 | ||
|
|
5b4030288d | ||
|
|
ab58c36212 | ||
|
|
5a0ef0dadd | ||
|
|
967e72fc66 | ||
|
|
78a86daaf7 | ||
|
|
bee3f47a14 | ||
|
|
2159395389 | ||
|
|
b11346aba8 | ||
|
|
30982fa488 | ||
|
|
92b79906cd | ||
|
|
76f365b5ee | ||
|
|
da67e766c2 | ||
|
|
49cea8d945 | ||
|
|
b1d74adb15 | ||
|
|
652ac3f3b9 | ||
|
|
060e733605 | ||
|
|
eedbb4bc65 | ||
|
|
fa2397585f | ||
|
|
77348c4adb | ||
|
|
0d0fb8e13a |
@@ -0,0 +1,18 @@
|
||||
name: 📦 Publish to Comfy registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: ♻️ Check out code
|
||||
uses: actions/checkout@v4
|
||||
- name: 📦 Publish Custom Node
|
||||
uses: Comfy-Org/publish-node-action@main
|
||||
with:
|
||||
personal_access_token: ${{ secrets.COMFY_REGISTRY_TOKEN }}
|
||||
@@ -0,0 +1,8 @@
|
||||
default_language_version:
|
||||
python: python3.10
|
||||
repos:
|
||||
- repo: https://github.com/melmass/hooks
|
||||
rev: e8c6c18175ed4f6e30f23991de7989411e09c73b
|
||||
hooks:
|
||||
- id: fix-trailing-whitespace
|
||||
- id: bump-version
|
||||
@@ -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)
|
||||
@@ -4,177 +4,8 @@
|
||||

|
||||
|
||||
<!-- 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)
|
||||
|
||||
+85
-27
@@ -6,21 +6,27 @@
|
||||
# Copyright (c) 2023 Mel Massadian
|
||||
#
|
||||
###
|
||||
|
||||
__version__ = "0.1.6"
|
||||
|
||||
import os
|
||||
|
||||
# todo: don't override this if the user has that setup already
|
||||
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
|
||||
os.environ["TF_GPU_ALLOCATOR"] = "cuda_malloc_async"
|
||||
# TODO: don't override this if the user has that setup already
|
||||
if not os.environ.get("TF_FORCE_GPU_ALLOW_GROWTH"):
|
||||
os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
|
||||
|
||||
if not os.environ.get("TF_GPU_ALLOCATOR"):
|
||||
os.environ["TF_GPU_ALLOCATOR"] = "cuda_malloc_async"
|
||||
|
||||
import ast
|
||||
import contextlib
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import traceback
|
||||
from importlib import reload
|
||||
from pathlib import Path
|
||||
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
@@ -36,14 +42,11 @@ NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
NODE_CLASS_MAPPINGS_DEBUG = {}
|
||||
WEB_DIRECTORY = "./web"
|
||||
|
||||
__version__ = "0.2.0"
|
||||
|
||||
|
||||
def extract_nodes_from_source(filename):
|
||||
def extract_nodes_from_source(filename: Path):
|
||||
source_code = ""
|
||||
|
||||
with open(filename, encoding="utf8") as file:
|
||||
source_code = file.read()
|
||||
source_code = filename.read_text(encoding="utf-8")
|
||||
|
||||
nodes = []
|
||||
|
||||
@@ -68,7 +71,7 @@ def extract_nodes_from_source(filename):
|
||||
|
||||
|
||||
def load_nodes():
|
||||
errors = []
|
||||
errors: list[str] = []
|
||||
nodes = []
|
||||
nodes_failed = []
|
||||
|
||||
@@ -85,9 +88,11 @@ def load_nodes():
|
||||
log.debug(f"Imported {module_name} nodes")
|
||||
|
||||
except AttributeError:
|
||||
log.debug(f"Skipping wip module {module_name}")
|
||||
pass # wip nodes
|
||||
except Exception:
|
||||
error_message = traceback.format_exc().splitlines()[-1]
|
||||
|
||||
errors.append(
|
||||
f"Failed to import module {module_name} because {error_message}"
|
||||
)
|
||||
@@ -107,28 +112,81 @@ def load_nodes():
|
||||
|
||||
|
||||
# - REGISTER WEB EXTENSIONS
|
||||
web_extensions_root = comfy_dir / "web" / "extensions"
|
||||
web_mtb = web_extensions_root / "mtb"
|
||||
def uninstall_old_web_extensions():
|
||||
web_extensions_root = comfy_dir / "web" / "extensions"
|
||||
web_mtb = web_extensions_root / "mtb"
|
||||
|
||||
if web_mtb.exists() and hasattr(nodes, "EXTENSION_WEB_DIRS"):
|
||||
try:
|
||||
if web_mtb.is_symlink():
|
||||
web_mtb.unlink()
|
||||
else:
|
||||
shutil.rmtree(web_mtb)
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
f"Failed to remove web mtb directory: {e}\nPlease manually remove it from disk ({web_mtb}) and restart the server."
|
||||
)
|
||||
if web_mtb.exists() and hasattr(nodes, "EXTENSION_WEB_DIRS"):
|
||||
try:
|
||||
if web_mtb.is_symlink():
|
||||
web_mtb.unlink()
|
||||
else:
|
||||
shutil.rmtree(web_mtb)
|
||||
except Exception as e:
|
||||
log.warning(
|
||||
f"Failed to remove web mtb directory: {e}\nPlease manually remove it from disk ({web_mtb}) and restart the server."
|
||||
)
|
||||
|
||||
|
||||
# uninstall_old_web_extensions()
|
||||
|
||||
|
||||
# - GATHER WIKI PAGES
|
||||
def wiki_to_classname(s: str):
|
||||
wiki_name = s.replace("nodes-", "", 1)
|
||||
return "MTB_" + "".join(
|
||||
[part.capitalize() for part in wiki_name.split("-")]
|
||||
)
|
||||
|
||||
|
||||
def classname_to_wiki(s: str):
|
||||
classname = s.replace("MTB_", "")
|
||||
parts = []
|
||||
start = 0
|
||||
for i in range(1, len(classname)):
|
||||
if classname[i].isupper():
|
||||
parts.append(classname[start:i].lower())
|
||||
start = i
|
||||
parts.append(classname[start:].lower())
|
||||
return "nodes-" + "-".join(parts)
|
||||
|
||||
|
||||
wiki = here / "wiki"
|
||||
node_docs = {}
|
||||
if wiki.exists() and wiki.is_dir():
|
||||
node_docs = {
|
||||
wiki_to_classname(x.stem): x.read_text(encoding="utf-8")
|
||||
for x in (wiki / "nodes").glob("*.md")
|
||||
}
|
||||
|
||||
|
||||
# - REGISTER NODES
|
||||
|
||||
|
||||
MTB_EXPORT = os.environ.get("MTB_EXPORT")
|
||||
|
||||
nodes, failed = load_nodes()
|
||||
for node_class in nodes:
|
||||
class_name = node_class.__name__
|
||||
# fallback to __doc__
|
||||
if not hasattr(node_class, "DESCRIPTION") and node_class.__doc__:
|
||||
node_class.DESCRIPTION = node_class.__doc__
|
||||
class_name: str = node_class.__name__
|
||||
linked_doc = node_docs.get(class_name)
|
||||
|
||||
if not hasattr(node_class, "DESCRIPTION"):
|
||||
if linked_doc:
|
||||
log.debug(f"Found linked doc for {class_name}, using it")
|
||||
node_class.DESCRIPTION = linked_doc
|
||||
elif node_class.__doc__:
|
||||
log.debug(f"Using __doc__ as description for {class_name}")
|
||||
node_class.DESCRIPTION = node_class.__doc__
|
||||
if MTB_EXPORT:
|
||||
wiki_name = classname_to_wiki(class_name)
|
||||
(wiki / "nodes" / (wiki_name + ".md")).write_text(
|
||||
node_class.__doc__, encoding="utf-8"
|
||||
)
|
||||
|
||||
else:
|
||||
log.debug(
|
||||
f"None of the methods could retrieve documentation for {class_name}"
|
||||
)
|
||||
|
||||
node_label = f"{get_label(class_name)} (mtb)"
|
||||
NODE_CLASS_MAPPINGS[node_label] = node_class
|
||||
@@ -279,7 +337,7 @@ if hasattr(PromptServer, "instance"):
|
||||
<a href="/mtb/manage">manage</a>
|
||||
<a href="/mtb/debug">debug</a>
|
||||
<a href="/mtb/status">status</a>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
return web.Response(
|
||||
text=endpoint.render_base_template("MTB", html_response),
|
||||
|
||||
+31
-19
@@ -1,19 +1,31 @@
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true
|
||||
}
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "single",
|
||||
"semicolons": "asNeeded",
|
||||
"indentWidth": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
"$schema": "https://biomejs.dev/schemas/1.6.1/schema.json",
|
||||
"organizeImports": {
|
||||
"enabled": true
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"suspicious": {
|
||||
"noConsoleLog": "warn"
|
||||
},
|
||||
"style": {
|
||||
"noParameterAssign": "off",
|
||||
"noShoutyConstants": "warn",
|
||||
"useNamingConvention": "off"
|
||||
}
|
||||
}
|
||||
},
|
||||
"formatter": {
|
||||
"indentStyle": "space",
|
||||
"indentWidth": 2,
|
||||
"lineEnding": "lf"
|
||||
},
|
||||
"javascript": {
|
||||
"formatter": {
|
||||
"quoteStyle": "single",
|
||||
"semicolons": "asNeeded"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+35
-13
@@ -3,12 +3,17 @@ import csv
|
||||
from aiohttp import web
|
||||
|
||||
from .log import mklog
|
||||
from .utils import backup_file, here, import_install, reqs_map, run_command, styles_dir
|
||||
from .utils import (
|
||||
backup_file,
|
||||
import_install,
|
||||
reqs_map,
|
||||
run_command,
|
||||
styles_dir,
|
||||
)
|
||||
|
||||
endlog = mklog("mtb endpoint")
|
||||
|
||||
# - ACTIONS
|
||||
import platform
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -22,7 +27,9 @@ def ACTIONS_installDependency(dependency_names=None):
|
||||
# reqs = []
|
||||
resolved_names = [reqs_map.get(name, name) for name in dependency_names]
|
||||
try:
|
||||
run_command([Path(sys.executable), "-m", "pip", "install"] + resolved_names)
|
||||
run_command(
|
||||
[Path(sys.executable), "-m", "pip", "install"] + resolved_names
|
||||
)
|
||||
return {"success": True}
|
||||
|
||||
except Exception as e:
|
||||
@@ -44,9 +51,9 @@ def ACTIONS_installDependency(dependency_names=None):
|
||||
|
||||
|
||||
def ACTIONS_getStyles(style_name=None):
|
||||
from .nodes.conditions import StylesLoader
|
||||
from .nodes.conditions import MTB_StylesLoader
|
||||
|
||||
styles = StylesLoader.options
|
||||
styles = MTB_StylesLoader.options
|
||||
match_list = ["name"]
|
||||
if styles:
|
||||
filtered_styles = {
|
||||
@@ -55,7 +62,9 @@ def ACTIONS_getStyles(style_name=None):
|
||||
if not key.startswith("__") and key not in match_list
|
||||
}
|
||||
if style_name:
|
||||
return filtered_styles.get(style_name, {"error": "Style not found"})
|
||||
return filtered_styles.get(
|
||||
style_name, {"error": "Style not found"}
|
||||
)
|
||||
return filtered_styles
|
||||
return {"error": "No styles found"}
|
||||
|
||||
@@ -75,7 +84,9 @@ def ACTIONS_saveStyle(data):
|
||||
break
|
||||
|
||||
if not target:
|
||||
endlog.warning(f"Could not determine the target file for {data.keys()}")
|
||||
endlog.warning(
|
||||
f"Could not determine the target file for {data.keys()}"
|
||||
)
|
||||
return {"error": "Could not determine the target file for the style"}
|
||||
|
||||
backup_file(target)
|
||||
@@ -103,11 +114,16 @@ async def do_action(request) -> web.Response:
|
||||
return web.json_response({"result": result})
|
||||
|
||||
available_methods = [
|
||||
attr[len("ACTIONS_") :] for attr in globals() if attr.startswith("ACTIONS_")
|
||||
attr[len("ACTIONS_") :]
|
||||
for attr in globals()
|
||||
if attr.startswith("ACTIONS_")
|
||||
]
|
||||
|
||||
return web.json_response(
|
||||
{"error": "Invalid method name.", "available_methods": available_methods}
|
||||
{
|
||||
"error": "Invalid method name.",
|
||||
"available_methods": available_methods,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -127,7 +143,7 @@ def csv_editor():
|
||||
|
||||
style_files = {}
|
||||
for file in inputs:
|
||||
with open(file, "r", encoding="utf8") as f:
|
||||
with open(file, encoding="utf8") as f:
|
||||
parsed = csv.reader(f)
|
||||
style_files[file.name] = []
|
||||
for row in parsed:
|
||||
@@ -235,7 +251,9 @@ def add_split_pane(left_content, right_content, vertical=True):
|
||||
|
||||
|
||||
def add_dropdown(title, options):
|
||||
option_str = "\n".join([f"<option value='{opt}'>{opt}</option>" for opt in options])
|
||||
option_str = "\n".join(
|
||||
[f"<option value='{opt}'>{opt}</option>" for opt in options]
|
||||
)
|
||||
return f"""
|
||||
<select>
|
||||
<option disabled selected>{title}</option>
|
||||
@@ -254,11 +272,15 @@ def render_table(table_dict, sort=True, title=None):
|
||||
if isinstance(item, dict):
|
||||
if "dependencies" in item:
|
||||
table_rows += f"<tr><td>{name}</td><td>"
|
||||
table_rows += f"{dependencies_button(name,item['dependencies'])}"
|
||||
table_rows += (
|
||||
f"{dependencies_button(name,item['dependencies'])}"
|
||||
)
|
||||
|
||||
table_rows += "</td></tr>"
|
||||
else:
|
||||
table_rows += f"<tr><td>{name}</td><td>{render_table(item)}</td></tr>"
|
||||
table_rows += (
|
||||
f"<tr><td>{name}</td><td>{render_table(item)}</td></tr>"
|
||||
)
|
||||
# elif isinstance(item, str):
|
||||
# table_rows += f"<tr><td>{name}</td><td>{item}</td></tr>"
|
||||
else:
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
# NOTE: This file is only use for development you can ignore it
|
||||
|
||||
def get_root [--clean] {
|
||||
if $clean {
|
||||
$env.COMFY_CLEAN_ROOT
|
||||
} else {
|
||||
$env.COMFY_ROOT
|
||||
}
|
||||
}
|
||||
|
||||
export def "comfy build-web" [] {
|
||||
cd $env.COMFY_MTB
|
||||
cd web_source
|
||||
npm run build
|
||||
cp dist/*.js ../web/dist
|
||||
}
|
||||
|
||||
export def "comfy dev-web" [] {
|
||||
cd $env.COMFY_MTB
|
||||
cd web_source
|
||||
npm run dev
|
||||
}
|
||||
|
||||
|
||||
# start the comfy server
|
||||
export def "comfy start" [--clean,--old-ui, --listen] {
|
||||
|
||||
let root = get_root --clean=($clean)
|
||||
cd $root
|
||||
MTB_DEBUG=true python main.py --port 3000 ...(if $old_ui { ["--front-end-version", "Comfy-Org/ComfyUI_legacy_frontend@latest"]} else {[]}) --preview-method auto ...(if $listen {["--listen"]} else {[]})
|
||||
}
|
||||
|
||||
# update comfy itself and merge master in current branch
|
||||
export def "comfy update" [
|
||||
--clean # ??
|
||||
--rebase # Rebase instead of merge
|
||||
] {
|
||||
let root = get_root --clean=($clean)
|
||||
let models = $"($root)/models"
|
||||
let inputs = $"($root)/input"
|
||||
cd $root
|
||||
let branch_name = (git rev-parse --abbrev-ref HEAD | str trim)
|
||||
print $"(ansi yellow_italic)Backing up and removing models symlinks(ansi reset)"
|
||||
|
||||
if not $clean {
|
||||
cd $models
|
||||
# find all symlinks
|
||||
let links = (ls -la |
|
||||
where not ($it.target | is-empty) |
|
||||
select name target |
|
||||
sort-by name)
|
||||
|
||||
|
||||
if not ($links | is-empty) {
|
||||
$links | save -f links.nuon
|
||||
# remove them
|
||||
open links.nuon | each {|p| rm $p.name }
|
||||
}
|
||||
} else {
|
||||
rm $models
|
||||
rm $inputs
|
||||
}
|
||||
|
||||
cd $root
|
||||
|
||||
print $"(ansi yellow_italic)Checking out to master(ansi reset)"
|
||||
git checkout master
|
||||
|
||||
print $"(ansi yellow_italic)Fetching and pulling remote updates(ansi reset)"
|
||||
git fetch
|
||||
git pull
|
||||
|
||||
print $"(ansi yellow_italic)Back to our branch \(($branch_name)\)(ansi reset)"
|
||||
git checkout -
|
||||
|
||||
if $rebase {
|
||||
print $"(ansi yellow_italic)Rebasing changes(ansi reset)"
|
||||
git rebase master
|
||||
|
||||
} else {
|
||||
print $"(ansi yellow_italic)Merging changes(ansi reset)"
|
||||
git merge master
|
||||
}
|
||||
|
||||
print $"(ansi yellow_italic)Linking back the models(ansi reset)"
|
||||
|
||||
if not $clean {
|
||||
cd $models
|
||||
# resymlink them
|
||||
open links.nuon | each {|p| link -a $p.target $p.name }
|
||||
} else {
|
||||
let master = (get_root)
|
||||
link ($master | path join models) $models
|
||||
link ($master | path join input) $inputs
|
||||
}
|
||||
|
||||
let commit_count = (git rev-list --count $branch_name $"^origin/($branch_name)")
|
||||
|
||||
|
||||
print $"(ansi green_bold)Update successful \(($commit_count) new commits\)(ansi reset)"
|
||||
|
||||
|
||||
}
|
||||
|
||||
export def "comfy toggle_extensions" [--clean] {
|
||||
let root = get_root --clean=($clean)
|
||||
cd $root
|
||||
cd custom_nodes
|
||||
let exts = (ls | where type in ["dir","symlink"] | get name)
|
||||
let choices = ($exts | input list -m "choose extension to toggle")
|
||||
if ($choices | is-empty) {
|
||||
return
|
||||
}
|
||||
|
||||
print $choices
|
||||
|
||||
let filtered = $choices | wrap name | upsert enabled {|p| not ($p.name | str ends-with ".disabled")}
|
||||
|
||||
print $filtered
|
||||
$filtered | each {|f|
|
||||
let new_name = ($f.name | str replace ".disabled" "")
|
||||
|
||||
let new_name = if $f.enabled {
|
||||
$"($new_name).disabled"
|
||||
} else {
|
||||
$new_name
|
||||
}
|
||||
print $"Moving ($f.name) to ($new_name)"
|
||||
mv $f.name $new_name
|
||||
}
|
||||
}
|
||||
|
||||
# git pull all extensions
|
||||
export def "comfy update_extensions" [--clean] {
|
||||
let root = get_root --clean=($clean)
|
||||
cd $root
|
||||
cd custom_nodes
|
||||
git multipull .
|
||||
}
|
||||
|
||||
def --env path-add [pth] {
|
||||
$env.PATH = ($env.PATH | append ($pth | path expand))
|
||||
|
||||
}
|
||||
|
||||
|
||||
export-env {
|
||||
$env.COMFY_MTB = ("." | path expand)
|
||||
$env.CUDA_ROOT = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v12.1\'
|
||||
|
||||
$env.CUDA_HOME = $env.CUDA_ROOT
|
||||
|
||||
$env.COMFY_ROOT = ("../.." | path expand)
|
||||
$env.COMFY_CLEAN_ROOT = ($env.COMFY_ROOT | path dirname | path join ComfyClean)
|
||||
|
||||
path-add 'C:/Portable/TensorRT-8.6.0.12/lib'
|
||||
path-add ($env.CUDA_ROOT | path join bin)
|
||||
overlay use ../../.venv/Scripts/activate.nu
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -36,7 +36,7 @@ class Formatter(logging.Formatter):
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
def mklog(name, level=base_log_level):
|
||||
def mklog(name: str, level: int = base_log_level):
|
||||
logger = logging.getLogger(name)
|
||||
logger.setLevel(level)
|
||||
|
||||
@@ -58,24 +58,30 @@ def mklog(name, level=base_log_level):
|
||||
log = mklog(__package__, base_log_level)
|
||||
|
||||
|
||||
def log_user(arg):
|
||||
print("\033[34mComfy MTB Utils:\033[0m {arg}")
|
||||
def log_user(arg: str):
|
||||
print(f"\033[34mComfy MTB Utils:\033[0m {arg}")
|
||||
|
||||
|
||||
def get_summary(docstring):
|
||||
def get_summary(docstring: str):
|
||||
return docstring.strip().split("\n\n", 1)[0]
|
||||
|
||||
|
||||
def blue_text(text):
|
||||
def blue_text(text: str):
|
||||
return f"\033[94m{text}\033[0m"
|
||||
|
||||
|
||||
def cyan_text(text):
|
||||
def cyan_text(text: str):
|
||||
return f"\033[96m{text}\033[0m"
|
||||
|
||||
|
||||
def get_label(label):
|
||||
def get_label(label: str):
|
||||
if label.startswith("MTB_"):
|
||||
label = label[4:]
|
||||
words = re.findall(r"(?:^|[A-Z])[a-z]*", label)
|
||||
|
||||
words = re.findall(
|
||||
r"(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[A-Za-z])(?=[0-9])|(?<=[0-9])(?=[A-Za-z]))",
|
||||
label,
|
||||
)
|
||||
reformatted_label = re.sub(r"([A-Z]+)", r" \1", label).strip()
|
||||
words = reformatted_label.split()
|
||||
return " ".join(words).strip()
|
||||
|
||||
+235
@@ -0,0 +1,235 @@
|
||||
from typing import TypedDict
|
||||
|
||||
import torch
|
||||
import torchaudio
|
||||
|
||||
|
||||
class AudioDict(TypedDict):
|
||||
"""Comfy's representation of AUDIO data."""
|
||||
|
||||
sample_rate: int
|
||||
waveform: torch.Tensor
|
||||
|
||||
|
||||
AudioData = AudioDict | list[AudioDict]
|
||||
|
||||
|
||||
class MtbAudio:
|
||||
"""Base class for audio processing."""
|
||||
|
||||
@classmethod
|
||||
def is_stereo(
|
||||
cls,
|
||||
audios: AudioData,
|
||||
) -> bool:
|
||||
if isinstance(audios, list):
|
||||
return any(cls.is_stereo(audio) for audio in audios)
|
||||
else:
|
||||
return audios["waveform"].shape[1] == 2
|
||||
|
||||
@staticmethod
|
||||
def resample(audio: AudioDict, common_sample_rate: int) -> AudioDict:
|
||||
if audio["sample_rate"] != common_sample_rate:
|
||||
resampler = torchaudio.transforms.Resample(
|
||||
orig_freq=audio["sample_rate"], new_freq=common_sample_rate
|
||||
)
|
||||
return {
|
||||
"sample_rate": common_sample_rate,
|
||||
"waveform": resampler(audio["waveform"]),
|
||||
}
|
||||
else:
|
||||
return audio
|
||||
|
||||
@staticmethod
|
||||
def to_stereo(audio: AudioDict) -> AudioDict:
|
||||
if audio["waveform"].shape[1] == 1:
|
||||
return {
|
||||
"sample_rate": audio["sample_rate"],
|
||||
"waveform": torch.cat(
|
||||
[audio["waveform"], audio["waveform"]], dim=1
|
||||
),
|
||||
}
|
||||
else:
|
||||
return audio
|
||||
|
||||
@classmethod
|
||||
def preprocess_audios(
|
||||
cls, audios: list[AudioDict]
|
||||
) -> tuple[list[AudioDict], bool, int]:
|
||||
max_sample_rate = max([audio["sample_rate"] for audio in audios])
|
||||
|
||||
resampled_audios = [
|
||||
cls.resample(audio, max_sample_rate) for audio in audios
|
||||
]
|
||||
|
||||
is_stereo = cls.is_stereo(audios)
|
||||
if is_stereo:
|
||||
audios = [cls.to_stereo(audio) for audio in resampled_audios]
|
||||
|
||||
return (audios, is_stereo, max_sample_rate)
|
||||
|
||||
|
||||
class MTB_AudioCut(MtbAudio):
|
||||
"""Basic audio cutter, values are in ms."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": ("AUDIO",),
|
||||
"length": (
|
||||
("FLOAT"),
|
||||
{
|
||||
"default": 1000.0,
|
||||
"min": 0.0,
|
||||
"max": 999999.0,
|
||||
"step": 1,
|
||||
},
|
||||
),
|
||||
"offset": (
|
||||
("FLOAT"),
|
||||
{"default": 0.0, "min": 0.0, "max": 999999.0, "step": 1},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("cut_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "cut"
|
||||
|
||||
def cut(self, audio: AudioDict, length: float, offset: float):
|
||||
sample_rate = audio["sample_rate"]
|
||||
start_idx = int(offset * sample_rate / 1000)
|
||||
end_idx = min(
|
||||
start_idx + int(length * sample_rate / 1000),
|
||||
audio["waveform"].shape[-1],
|
||||
)
|
||||
cut_waveform = audio["waveform"][:, :, start_idx:end_idx]
|
||||
|
||||
return (
|
||||
{
|
||||
"sample_rate": sample_rate,
|
||||
"waveform": cut_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class MTB_AudioStack(MtbAudio):
|
||||
"""Stack/Overlay audio inputs (dynamic inputs).
|
||||
|
||||
- pad audios to the longest inputs.
|
||||
- resample audios to the highest sample rate in the inputs.
|
||||
- convert them all to stereo if one of the inputs is.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {}}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("stacked_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "stack"
|
||||
|
||||
def stack(self, **kwargs: AudioDict) -> tuple[AudioDict]:
|
||||
audios, is_stereo, max_rate = self.preprocess_audios(
|
||||
list(kwargs.values())
|
||||
)
|
||||
|
||||
max_length = max([audio["waveform"].shape[-1] for audio in audios])
|
||||
|
||||
padded_audios: list[torch.Tensor] = []
|
||||
for audio in audios:
|
||||
padding = torch.zeros(
|
||||
(
|
||||
1,
|
||||
2 if is_stereo else 1,
|
||||
max_length - audio["waveform"].shape[-1],
|
||||
)
|
||||
)
|
||||
padded_audio = torch.cat([audio["waveform"], padding], dim=-1)
|
||||
padded_audios.append(padded_audio)
|
||||
|
||||
stacked_waveform = torch.stack(padded_audios, dim=0).sum(dim=0)
|
||||
|
||||
return (
|
||||
{
|
||||
"sample_rate": max_rate,
|
||||
"waveform": stacked_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class MTB_AudioSequence(MtbAudio):
|
||||
"""Sequence audio inputs (dynamic inputs).
|
||||
|
||||
- adding silence_duration between each segment
|
||||
can now also be negative to overlap the clips, safely bound
|
||||
to the the input length.
|
||||
- resample audios to the highest sample rate in the inputs.
|
||||
- convert them all to stereo if one of the inputs is.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"silence_duration": (
|
||||
("FLOAT"),
|
||||
{"default": 0.0, "min": -999.0, "max": 999, "step": 0.01},
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
RETURN_NAMES = ("sequenced_audio",)
|
||||
CATEGORY = "mtb/audio"
|
||||
FUNCTION = "sequence"
|
||||
|
||||
def sequence(self, silence_duration: float, **kwargs: AudioDict):
|
||||
audios, is_stereo, max_rate = self.preprocess_audios(
|
||||
list(kwargs.values())
|
||||
)
|
||||
|
||||
sequence: list[torch.Tensor] = []
|
||||
for i, audio in enumerate(audios):
|
||||
if i > 0:
|
||||
if silence_duration > 0:
|
||||
silence = torch.zeros(
|
||||
(
|
||||
1,
|
||||
2 if is_stereo else 1,
|
||||
int(silence_duration * max_rate),
|
||||
)
|
||||
)
|
||||
sequence.append(silence)
|
||||
elif silence_duration < 0:
|
||||
overlap = int(abs(silence_duration) * max_rate)
|
||||
previous_audio = sequence[-1]
|
||||
overlap = min(
|
||||
overlap,
|
||||
previous_audio.shape[-1],
|
||||
audio["waveform"].shape[-1],
|
||||
)
|
||||
if overlap > 0:
|
||||
overlap_part = (
|
||||
previous_audio[:, :, -overlap:]
|
||||
+ audio["waveform"][:, :, :overlap]
|
||||
)
|
||||
sequence[-1] = previous_audio[:, :, :-overlap]
|
||||
sequence.append(overlap_part)
|
||||
audio["waveform"] = audio["waveform"][:, :, overlap:]
|
||||
|
||||
sequence.append(audio["waveform"])
|
||||
|
||||
sequenced_waveform = torch.cat(sequence, dim=-1)
|
||||
return (
|
||||
{
|
||||
"sample_rate": max_rate,
|
||||
"waveform": sequenced_waveform,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
__nodes__ = [MTB_AudioSequence, MTB_AudioStack, MTB_AudioCut]
|
||||
+262
-24
@@ -6,11 +6,11 @@ import torch
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
from ..utils import apply_easing, pil2tensor
|
||||
from .transform import TransformImage
|
||||
from ..utils import EASINGS, apply_easing, pil2tensor
|
||||
from .transform import MTB_TransformImage
|
||||
|
||||
|
||||
def hex_to_rgb(hex_color, bgr=False):
|
||||
def hex_to_rgb(hex_color: str, bgr: bool = False):
|
||||
hex_color = hex_color.lstrip("#")
|
||||
if bgr:
|
||||
return tuple(int(hex_color[i : i + 2], 16) for i in (4, 2, 0))
|
||||
@@ -18,6 +18,157 @@ def hex_to_rgb(hex_color, bgr=False):
|
||||
return tuple(int(hex_color[i : i + 2], 16) for i in (0, 2, 4))
|
||||
|
||||
|
||||
class MTB_BatchFloatMath:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"reverse": ("BOOLEAN", {"default": False}),
|
||||
"operation": (
|
||||
["add", "sub", "mul", "div", "pow", "abs"],
|
||||
{"default": "add"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
CATEGORY = "mtb/utils"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(self, reverse: bool, operation: str, **kwargs: list[float]):
|
||||
res: list[float] = []
|
||||
vals = list(kwargs.values())
|
||||
|
||||
if reverse:
|
||||
vals = vals[::-1]
|
||||
|
||||
ref_count = len(vals[0])
|
||||
for v in vals:
|
||||
if len(v) != ref_count:
|
||||
raise ValueError(
|
||||
f"All values must have the same length (current: {len(v)}, ref: {ref_count}"
|
||||
)
|
||||
|
||||
match operation:
|
||||
case "add":
|
||||
for i in range(ref_count):
|
||||
result = sum(v[i] for v in vals)
|
||||
res.append(result)
|
||||
case "sub":
|
||||
for i in range(ref_count):
|
||||
result = vals[0][i] - sum(v[i] for v in vals[1:])
|
||||
res.append(result)
|
||||
case "mul":
|
||||
for i in range(ref_count):
|
||||
result = vals[0][i] * vals[1][i]
|
||||
res.append(result)
|
||||
case "div":
|
||||
for i in range(ref_count):
|
||||
result = vals[0][i] / vals[1][i]
|
||||
res.append(result)
|
||||
case "pow":
|
||||
for i in range(ref_count):
|
||||
result: float = vals[0][i] ** vals[1][i]
|
||||
res.append(result)
|
||||
case "abs":
|
||||
for i in range(ref_count):
|
||||
result = abs(vals[0][i])
|
||||
res.append(result)
|
||||
case _:
|
||||
log.info(f"For now this mode ({operation}) is not implemented")
|
||||
|
||||
return (res,)
|
||||
|
||||
|
||||
class MTB_BatchFloatNormalize:
|
||||
"""Normalize the values in the list of floats"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"floats": ("FLOATS",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
RETURN_NAMES = ("normalized_floats",)
|
||||
CATEGORY = "mtb/batch"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(
|
||||
self,
|
||||
floats: list[float],
|
||||
):
|
||||
min_value = min(floats)
|
||||
max_value = max(floats)
|
||||
|
||||
normalized_floats = [
|
||||
(x - min_value) / (max_value - min_value) for x in floats
|
||||
]
|
||||
log.debug(f"Floats: {floats}")
|
||||
log.debug(f"Normalized Floats: {normalized_floats}")
|
||||
|
||||
return (normalized_floats,)
|
||||
|
||||
|
||||
class MTB_BatchTimeWrap:
|
||||
"""Remap a batch using a time curve (FLOATS)"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"target_count": ("INT", {"default": 25, "min": 2}),
|
||||
"frames": ("IMAGE",),
|
||||
"curve": ("FLOATS",),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "FLOATS")
|
||||
RETURN_NAMES = ("image", "interpolated_floats")
|
||||
CATEGORY = "mtb/batch"
|
||||
FUNCTION = "execute"
|
||||
|
||||
def execute(
|
||||
self, target_count: int, frames: torch.Tensor, curve: list[float]
|
||||
):
|
||||
"""Apply time warping to a list of video frames based on a curve."""
|
||||
log.debug(f"Input frames shape: {frames.shape}")
|
||||
log.debug(f"Curve: {curve}")
|
||||
|
||||
total_duration = sum(curve)
|
||||
|
||||
log.debug(f"Total duration: {total_duration}")
|
||||
|
||||
B, H, W, C = frames.shape
|
||||
|
||||
log.debug(f"Batch Size: {B}")
|
||||
|
||||
normalized_times = np.linspace(0, 1, target_count)
|
||||
interpolated_curve = np.interp(
|
||||
normalized_times, np.linspace(0, 1, len(curve)), curve
|
||||
).tolist()
|
||||
log.debug(f"Interpolated curve: {interpolated_curve}")
|
||||
|
||||
interpolated_frame_indices = [
|
||||
(B - 1) * value for value in interpolated_curve
|
||||
]
|
||||
log.debug(f"Interpolated frame indices: {interpolated_frame_indices}")
|
||||
|
||||
rounded_indices = [
|
||||
int(round(idx)) for idx in interpolated_frame_indices
|
||||
]
|
||||
rounded_indices = np.clip(rounded_indices, 0, B - 1)
|
||||
|
||||
# Gather frames based on interpolated indices
|
||||
warped_frames = []
|
||||
for index in rounded_indices:
|
||||
warped_frames.append(frames[index].unsqueeze(0))
|
||||
|
||||
warped_tensor = torch.cat(warped_frames, dim=0)
|
||||
log.debug(f"Warped frames shape: {warped_tensor.shape}")
|
||||
return (warped_tensor, interpolated_curve)
|
||||
|
||||
|
||||
class MTB_BatchMake:
|
||||
"""Simply duplicates the input frame as a batch"""
|
||||
|
||||
@@ -192,18 +343,21 @@ class MTB_BatchFloatAssemble:
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {"reverse": ("BOOLEAN", {"default": False})}}
|
||||
|
||||
FUNCTION = "assemble_floats"
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
CATEGORY = "mtb/batch"
|
||||
FUNCTION = "assemble_floats"
|
||||
|
||||
def assemble_floats(self, reverse: bool, **kwargs: list[float]):
|
||||
res: list[float] = []
|
||||
|
||||
def assemble_floats(self, reverse, **kwargs):
|
||||
res = []
|
||||
if reverse:
|
||||
for x in reversed(kwargs.values()):
|
||||
res += x
|
||||
if x:
|
||||
res += x
|
||||
else:
|
||||
for x in kwargs.values():
|
||||
res += x
|
||||
if x:
|
||||
res += x
|
||||
|
||||
return (res,)
|
||||
|
||||
@@ -219,7 +373,7 @@ class MTB_BatchFloat:
|
||||
["Single", "Steps"],
|
||||
{"default": "Steps"},
|
||||
),
|
||||
"count": ("INT", {"default": 1}),
|
||||
"count": ("INT", {"default": 2}),
|
||||
"min": ("FLOAT", {"default": 0.0, "step": 0.001}),
|
||||
"max": ("FLOAT", {"default": 1.0, "step": 0.001}),
|
||||
"easing": (
|
||||
@@ -257,6 +411,10 @@ class MTB_BatchFloat:
|
||||
CATEGORY = "mtb/batch"
|
||||
|
||||
def set_floats(self, mode, count, min, max, easing):
|
||||
if mode == "Steps" and count == 1:
|
||||
raise ValueError(
|
||||
"Steps mode requires at least a count of 2 values"
|
||||
)
|
||||
keyframes = []
|
||||
if mode == "Single":
|
||||
keyframes = [min] * count
|
||||
@@ -415,7 +573,7 @@ class MTB_Batch2dTransform:
|
||||
if count == 0:
|
||||
keyframes[name] = [default_vals[name]] * image.shape[0]
|
||||
|
||||
transformer = TransformImage()
|
||||
transformer = MTB_TransformImage()
|
||||
res = [
|
||||
transformer.transform(
|
||||
image[i].unsqueeze(0),
|
||||
@@ -432,6 +590,66 @@ class MTB_Batch2dTransform:
|
||||
return (torch.cat(res, dim=0),)
|
||||
|
||||
|
||||
class MTB_BatchFloatFit:
|
||||
"""Fit a list of floats using a source and target range"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"values": ("FLOATS", {"forceInput": True}),
|
||||
"clamp": ("BOOLEAN", {"default": False}),
|
||||
"auto_compute_source": ("BOOLEAN", {"default": False}),
|
||||
"source_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"source_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"target_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"target_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"easing": (
|
||||
EASINGS,
|
||||
{"default": "Linear"},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
FUNCTION = "fit_range"
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
CATEGORY = "mtb/batch"
|
||||
DESCRIPTION = "Fit a list of floats using a source and target range"
|
||||
|
||||
def fit_range(
|
||||
self,
|
||||
values: list[float],
|
||||
clamp: bool,
|
||||
auto_compute_source: bool,
|
||||
source_min: float,
|
||||
source_max: float,
|
||||
target_min: float,
|
||||
target_max: float,
|
||||
easing: str,
|
||||
):
|
||||
if auto_compute_source:
|
||||
source_min = min(values)
|
||||
source_max = max(values)
|
||||
|
||||
from .graph_utils import MTB_FitNumber
|
||||
|
||||
res = []
|
||||
fit_number = MTB_FitNumber()
|
||||
for value in values:
|
||||
(transformed_value,) = fit_number.set_range(
|
||||
value,
|
||||
clamp,
|
||||
source_min,
|
||||
source_max,
|
||||
target_min,
|
||||
target_max,
|
||||
easing,
|
||||
)
|
||||
res.append(transformed_value)
|
||||
|
||||
return (res,)
|
||||
|
||||
|
||||
class MTB_PlotBatchFloat:
|
||||
"""Plot floats"""
|
||||
|
||||
@@ -443,6 +661,7 @@ class MTB_PlotBatchFloat:
|
||||
"height": ("INT", {"default": 768}),
|
||||
"point_size": ("INT", {"default": 4}),
|
||||
"seed": ("INT", {"default": 1}),
|
||||
"start_at_zero": ("BOOLEAN", {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,10 +670,21 @@ class MTB_PlotBatchFloat:
|
||||
FUNCTION = "plot"
|
||||
CATEGORY = "mtb/batch"
|
||||
|
||||
def plot(self, width, height, point_size, seed, **kwargs):
|
||||
def plot(
|
||||
self,
|
||||
width: int,
|
||||
height: int,
|
||||
point_size: int,
|
||||
seed: int,
|
||||
start_at_zero: bool,
|
||||
interactive_backend: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use("Agg")
|
||||
# NOTE: This is for notebook usage or tests, i.e not exposed to comfy that should always use Agg
|
||||
if not interactive_backend:
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
fig, ax = plt.subplots(figsize=(width / 100, height / 100), dpi=100)
|
||||
@@ -465,26 +695,30 @@ class MTB_PlotBatchFloat:
|
||||
ax.grid(color="gray", linestyle="-", linewidth=0.5, alpha=0.5)
|
||||
|
||||
# Finding global min and max across all lists for scaling the plot
|
||||
global_min = min(min(values) for values in kwargs.values())
|
||||
global_max = max(max(values) for values in kwargs.values())
|
||||
all_values = [value for values in kwargs.values() for value in values]
|
||||
global_min = min(all_values)
|
||||
global_max = max(all_values)
|
||||
|
||||
# Color cycle to ensure each plot has a distinct color
|
||||
colormap = plt.cm.get_cmap("viridis", len(kwargs))
|
||||
color_normalization_factor = (
|
||||
0.5 if len(kwargs) == 1 else (len(kwargs) - 1)
|
||||
)
|
||||
y_padding = 0.05 * (global_max - global_min)
|
||||
ax.set_ylim(global_min - y_padding, global_max + y_padding)
|
||||
|
||||
# Plotting each list with a unique color
|
||||
for i, (label, values) in enumerate(kwargs.items()):
|
||||
color_value = i / color_normalization_factor
|
||||
ax.plot(values, label=label, color=colormap(color_value))
|
||||
max_length = max(len(values) for values in kwargs.values())
|
||||
if start_at_zero:
|
||||
x_values = np.linspace(0, max_length - 1, max_length)
|
||||
else:
|
||||
x_values = np.linspace(1, max_length, max_length)
|
||||
|
||||
ax.set_ylim(global_min, global_max) # Scaling the y-axis
|
||||
ax.set_xlim(1, max_length) # Set X-axis limits
|
||||
np.random.seed(seed)
|
||||
colors = np.random.rand(len(kwargs), 3) # Generate random RGB values
|
||||
for color, (label, values) in zip(colors, kwargs.items()):
|
||||
ax.plot(x_values[: len(values)], values, label=label, color=color)
|
||||
ax.legend(
|
||||
title="Legend",
|
||||
title_fontsize="large",
|
||||
fontsize="medium",
|
||||
edgecolor="black",
|
||||
loc="best",
|
||||
)
|
||||
|
||||
# Setting labels and title
|
||||
@@ -798,7 +1032,11 @@ __nodes__ = [
|
||||
MTB_BatchMake,
|
||||
MTB_BatchFloatAssemble,
|
||||
MTB_BatchFloatFill,
|
||||
MTB_BatchFloatNormalize,
|
||||
MTB_BatchMerge,
|
||||
MTB_BatchShake,
|
||||
MTB_PlotBatchFloat,
|
||||
MTB_BatchTimeWrap,
|
||||
MTB_BatchFloatFit,
|
||||
MTB_BatchFloatMath,
|
||||
]
|
||||
|
||||
+35
-15
@@ -1,4 +1,5 @@
|
||||
import csv, shutil
|
||||
import csv
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import folder_paths
|
||||
@@ -7,7 +8,7 @@ from ..log import log
|
||||
from ..utils import here
|
||||
|
||||
|
||||
class InterpolateClipSequential:
|
||||
class MTB_InterpolateClipSequential:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
@@ -28,7 +29,12 @@ class InterpolateClipSequential:
|
||||
CATEGORY = "mtb/conditioning"
|
||||
|
||||
def interpolate_encodings_sequential(
|
||||
self, base_text, text_to_replace, clip, interpolation_strength, **replacements
|
||||
self,
|
||||
base_text,
|
||||
text_to_replace,
|
||||
clip,
|
||||
interpolation_strength,
|
||||
**replacements,
|
||||
):
|
||||
log.debug(f"Received interpolation_strength: {interpolation_strength}")
|
||||
|
||||
@@ -63,20 +69,30 @@ class InterpolateClipSequential:
|
||||
log.debug("Using the base text a the base blend")
|
||||
# - Start with the base_text condition
|
||||
tokens = clip.tokenize(base_text)
|
||||
cond_from, pooled_from = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||
cond_from, pooled_from = clip.encode_from_tokens(
|
||||
tokens, return_pooled=True
|
||||
)
|
||||
else:
|
||||
base_replace = list(replacements.values())[segment_index - 1]
|
||||
log.debug(f"Using {base_replace} a the base blend")
|
||||
|
||||
# - Start with the base_text condition replaced by the closest replacement
|
||||
tokens = clip.tokenize(base_text.replace(text_to_replace, base_replace))
|
||||
cond_from, pooled_from = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||
tokens = clip.tokenize(
|
||||
base_text.replace(text_to_replace, base_replace)
|
||||
)
|
||||
cond_from, pooled_from = clip.encode_from_tokens(
|
||||
tokens, return_pooled=True
|
||||
)
|
||||
|
||||
replacement_text = list(replacements.values())[segment_index]
|
||||
|
||||
interpolated_text = base_text.replace(text_to_replace, replacement_text)
|
||||
interpolated_text = base_text.replace(
|
||||
text_to_replace, replacement_text
|
||||
)
|
||||
tokens = clip.tokenize(interpolated_text)
|
||||
cond_to, pooled_to = clip.encode_from_tokens(tokens, return_pooled=True)
|
||||
cond_to, pooled_to = clip.encode_from_tokens(
|
||||
tokens, return_pooled=True
|
||||
)
|
||||
|
||||
# - Linearly interpolate between the two conditions
|
||||
interpolated_condition = (
|
||||
@@ -86,10 +102,12 @@ class InterpolateClipSequential:
|
||||
1.0 - local_strength
|
||||
) * pooled_from + local_strength * pooled_to
|
||||
|
||||
return ([[interpolated_condition, {"pooled_output": interpolated_pooled}]],)
|
||||
return (
|
||||
[[interpolated_condition, {"pooled_output": interpolated_pooled}]],
|
||||
)
|
||||
|
||||
|
||||
class SmartStep:
|
||||
class MTB_SmartStep:
|
||||
"""Utils to control the steps start/stop of the KAdvancedSampler in percentage"""
|
||||
|
||||
@classmethod
|
||||
@@ -136,7 +154,7 @@ def install_default_styles(force=False):
|
||||
return dest_style
|
||||
|
||||
|
||||
class StylesLoader:
|
||||
class MTB_StylesLoader:
|
||||
"""Load csv files and populate a dropdown from the rows (à la A111)"""
|
||||
|
||||
options = {}
|
||||
@@ -148,16 +166,18 @@ class StylesLoader:
|
||||
if not input_dir.exists():
|
||||
install_default_styles()
|
||||
|
||||
if not (files := [f for f in input_dir.iterdir() if f.suffix == ".csv"]):
|
||||
if not (
|
||||
files := [f for f in input_dir.iterdir() if f.suffix == ".csv"]
|
||||
):
|
||||
log.warn(
|
||||
"No styles found in the styles folder, place at least one csv file in the styles folder at the root of ComfyUI (for instance ComfyUI/styles/mystyle.csv)"
|
||||
)
|
||||
|
||||
for file in files:
|
||||
with open(file, "r", encoding="utf8") as f:
|
||||
with open(file, encoding="utf8") as f:
|
||||
parsed = csv.reader(f)
|
||||
for i, row in enumerate(parsed):
|
||||
log.debug(f"Adding style {row[0]}")
|
||||
# log.debug(f"Adding style {row[0]}")
|
||||
try:
|
||||
name, positive, negative = (row + [None] * 3)[:3]
|
||||
positive = positive or ""
|
||||
@@ -193,4 +213,4 @@ class StylesLoader:
|
||||
return (self.options[style_name][0], self.options[style_name][1])
|
||||
|
||||
|
||||
__nodes__ = [SmartStep, StylesLoader, InterpolateClipSequential]
|
||||
__nodes__ = [MTB_SmartStep, MTB_StylesLoader, MTB_InterpolateClipSequential]
|
||||
|
||||
+1
-1
@@ -24,4 +24,4 @@ class MTB_Constant:
|
||||
return (kwargs.get("Value"),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_Constant]
|
||||
# __nodes__ = [MTB_Constant]
|
||||
|
||||
+23
-5
@@ -6,7 +6,7 @@ from ..log import log
|
||||
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
|
||||
|
||||
|
||||
class Bbox:
|
||||
class MTB_Bbox:
|
||||
"""The bounding box (BBOX) custom type used by other nodes"""
|
||||
|
||||
@classmethod
|
||||
@@ -41,7 +41,25 @@ class Bbox:
|
||||
return ((x, y, width, height),)
|
||||
|
||||
|
||||
class BboxFromMask:
|
||||
class MTB_SplitBbox:
|
||||
"""Split the components of a bbox"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"bbox": ("BBOX",)},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/crop"
|
||||
FUNCTION = "split_bbox"
|
||||
RETURN_TYPES = ("INT", "INT", "INT", "INT")
|
||||
RETURN_NAMES = ("x", "y", "width", "height")
|
||||
|
||||
def split_bbox(self, bbox):
|
||||
return (bbox[0], bbox[1], bbox[2], bbox[3])
|
||||
|
||||
|
||||
class MTB_BboxFromMask:
|
||||
"""From a mask extract the bounding box"""
|
||||
|
||||
@classmethod
|
||||
@@ -110,7 +128,7 @@ class BboxFromMask:
|
||||
)
|
||||
|
||||
|
||||
class Crop:
|
||||
class MTB_Crop:
|
||||
"""Crops an image and an optional mask to a given bounding box
|
||||
|
||||
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
|
||||
@@ -218,7 +236,7 @@ def bbox_to_region(bbox, target_size=None):
|
||||
return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
|
||||
|
||||
|
||||
class Uncrop:
|
||||
class MTB_Uncrop:
|
||||
"""Uncrops an image to a given bounding box
|
||||
|
||||
The bounding box can be given as a tuple of (x, y, width, height) or as a BBOX type
|
||||
@@ -324,4 +342,4 @@ class Uncrop:
|
||||
return (pil2tensor(out_images),)
|
||||
|
||||
|
||||
__nodes__ = [BboxFromMask, Bbox, Crop, Uncrop]
|
||||
__nodes__ = [MTB_BboxFromMask, MTB_Bbox, MTB_Crop, MTB_Uncrop, MTB_SplitBbox]
|
||||
|
||||
+58
-1
@@ -1,5 +1,7 @@
|
||||
import json
|
||||
|
||||
from ..log import log
|
||||
|
||||
|
||||
def deserialize_curve(curve):
|
||||
if isinstance(curve, str):
|
||||
@@ -30,7 +32,62 @@ class MTB_Curve:
|
||||
CATEGORY = "mtb/curve"
|
||||
|
||||
def do_curve(self, curve):
|
||||
log.debug(f"Curve: {curve}")
|
||||
return (curve,)
|
||||
|
||||
|
||||
__nodes__ = [MTB_Curve]
|
||||
class MTB_CurveToFloat:
|
||||
"""Convert a FLOAT_CURVE to a FLOAT or FLOATS"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"curve": ("FLOAT_CURVE", {"forceInput": True}),
|
||||
"steps": ("INT", {"default": 10, "min": 2}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOATS", "FLOAT")
|
||||
FUNCTION = "do_curve"
|
||||
|
||||
CATEGORY = "mtb/curve"
|
||||
|
||||
def do_curve(self, curve, steps):
|
||||
log.debug(f"Curve: {curve}")
|
||||
|
||||
# sort by x (should be handled by the widget)
|
||||
sorted_points = sorted(curve.items(), key=lambda item: item[1]["x"])
|
||||
# Extract X and Y values
|
||||
x_values = [point[1]["x"] for point in sorted_points]
|
||||
y_values = [point[1]["y"] for point in sorted_points]
|
||||
# Calculate step size
|
||||
step_size = (max(x_values) - min(x_values)) / (steps - 1)
|
||||
|
||||
# Interpolate Y values for each step
|
||||
interpolated_y_values = []
|
||||
for step in range(steps):
|
||||
current_x = min(x_values) + step_size * step
|
||||
|
||||
# Find the indices of the two points between which the current_x falls
|
||||
idx1 = max(idx for idx, x in enumerate(x_values) if x <= current_x)
|
||||
idx2 = min(idx for idx, x in enumerate(x_values) if x >= current_x)
|
||||
|
||||
# If the current_x matches one of the points, no interpolation is needed
|
||||
if current_x == x_values[idx1]:
|
||||
interpolated_y_values.append(y_values[idx1])
|
||||
elif current_x == x_values[idx2]:
|
||||
interpolated_y_values.append(y_values[idx2])
|
||||
else:
|
||||
# Interpolate Y value using linear interpolation
|
||||
y1 = y_values[idx1]
|
||||
y2 = y_values[idx2]
|
||||
x1 = x_values[idx1]
|
||||
x2 = x_values[idx2]
|
||||
interpolated_y = y1 + (y2 - y1) * (current_x - x1) / (x2 - x1)
|
||||
interpolated_y_values.append(interpolated_y)
|
||||
|
||||
return (interpolated_y_values, interpolated_y_values)
|
||||
|
||||
|
||||
__nodes__ = [MTB_Curve, MTB_CurveToFloat]
|
||||
|
||||
+7
-2
@@ -1,5 +1,6 @@
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
@@ -48,7 +49,7 @@ def process_list(anything):
|
||||
f"List of Tensors: {first_element.shape} (x{len(anything)})"
|
||||
)
|
||||
else:
|
||||
text.append(f"Array: {anything}")
|
||||
text.append(f"Array ({len(anything)}): {anything}")
|
||||
|
||||
return {"text": text}
|
||||
|
||||
@@ -61,6 +62,9 @@ def process_dict(anything):
|
||||
)
|
||||
text.append(f"Latent Samples: {anything['samples'].shape} {is_empty}")
|
||||
|
||||
else:
|
||||
text.append(json.dumps(anything, indent=2))
|
||||
|
||||
return {"text": text}
|
||||
|
||||
|
||||
@@ -106,10 +110,11 @@ class MTB_Debug:
|
||||
}
|
||||
if output_to_console:
|
||||
for k, v in kwargs.items():
|
||||
print(f"{k}: {v}")
|
||||
log.info(f"{k}: {v}")
|
||||
|
||||
for anything in kwargs.values():
|
||||
processor = processors.get(type(anything), process_text)
|
||||
|
||||
processed_data = processor(anything)
|
||||
|
||||
for ui_key, ui_value in processed_data.items():
|
||||
|
||||
+22
-3
@@ -69,7 +69,26 @@ def color_to_normals(
|
||||
if not model or not model.exists():
|
||||
raise ModelNotFound(f"deepbump ({model})")
|
||||
|
||||
ort_session = ort.InferenceSession(model)
|
||||
providers = [
|
||||
"TensorrtExecutionProvider",
|
||||
"CUDAExecutionProvider",
|
||||
"CoreMLProvider",
|
||||
"CPUExecutionProvider",
|
||||
]
|
||||
available_providers = [
|
||||
provider
|
||||
for provider in providers
|
||||
if provider in ort.get_available_providers()
|
||||
]
|
||||
|
||||
if not available_providers:
|
||||
raise RuntimeError(
|
||||
"No valid ONNX Runtime providers available on this machine."
|
||||
)
|
||||
log.debug(f"Using ONNX providers: {available_providers}")
|
||||
ort_session = ort.InferenceSession(
|
||||
model.as_posix(), providers=available_providers
|
||||
)
|
||||
|
||||
# Predict normal map for each tile
|
||||
log.debug("DeepBump Color → Normals : generating")
|
||||
@@ -303,7 +322,7 @@ def normals_to_height(normals_img, seamless, progress_callback):
|
||||
|
||||
|
||||
# - ADDON
|
||||
class DeepBump:
|
||||
class MTB_DeepBump:
|
||||
"""Normal & height maps generation from single pictures"""
|
||||
|
||||
@classmethod
|
||||
@@ -386,4 +405,4 @@ class DeepBump:
|
||||
return (torch.cat(out_images, dim=0),)
|
||||
|
||||
|
||||
__nodes__ = [DeepBump]
|
||||
__nodes__ = [MTB_DeepBump]
|
||||
|
||||
+34
-15
@@ -1,6 +1,4 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Tuple
|
||||
|
||||
import comfy
|
||||
import comfy.utils
|
||||
@@ -9,14 +7,13 @@ import folder_paths
|
||||
import numpy as np
|
||||
import torch
|
||||
from comfy import model_management
|
||||
from gfpgan import GFPGANer
|
||||
from PIL import Image
|
||||
|
||||
from ..log import NullWriter, log
|
||||
from ..utils import get_model_path, np2tensor, pil2tensor, tensor2np
|
||||
|
||||
|
||||
class LoadFaceEnhanceModel:
|
||||
class MTB_LoadFaceEnhanceModel:
|
||||
"""Loads a GFPGan or RestoreFormer model for face enhancement."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
@@ -37,7 +34,9 @@ class LoadFaceEnhanceModel:
|
||||
fr_models_path, um_models_path = cls.get_models_root()
|
||||
|
||||
if fr_models_path is None and um_models_path is None:
|
||||
log.warning("Face restoration models not found.")
|
||||
if not hasattr(cls, "_warned"):
|
||||
log.warning("Face restoration models not found.")
|
||||
cls._warned = True
|
||||
return []
|
||||
if not fr_models_path.exists():
|
||||
# log.warning(
|
||||
@@ -81,6 +80,8 @@ class LoadFaceEnhanceModel:
|
||||
CATEGORY = "mtb/facetools"
|
||||
|
||||
def load_model(self, model_name, upscale=2, bg_upsampler=None):
|
||||
from gfpgan import GFPGANer
|
||||
|
||||
basic = "RestoreFormer" not in model_name
|
||||
|
||||
fr_root, um_root = self.get_models_root()
|
||||
@@ -153,7 +154,7 @@ class BGUpscaleWrapper:
|
||||
import sys
|
||||
|
||||
|
||||
class RestoreFace:
|
||||
class MTB_RestoreFace:
|
||||
"""Uses GFPGan to restore faces"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
@@ -176,22 +177,33 @@ class RestoreFace:
|
||||
# Adjustable weights
|
||||
"weight": ("FLOAT", {"default": 0.5}),
|
||||
"save_tmp_steps": ("BOOLEAN", {"default": True}),
|
||||
}
|
||||
},
|
||||
"optional": {
|
||||
"preserve_alpha": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
def do_restore(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
model: GFPGANer,
|
||||
model,
|
||||
aligned,
|
||||
only_center_face,
|
||||
weight,
|
||||
save_tmp_steps,
|
||||
preserve_alpha: bool = False,
|
||||
) -> torch.Tensor:
|
||||
pimage = tensor2np(image)[0]
|
||||
width, height = pimage.shape[1], pimage.shape[0]
|
||||
source_img = cv2.cvtColor(np.array(pimage), cv2.COLOR_RGB2BGR)
|
||||
|
||||
alpha_channel = None
|
||||
if (
|
||||
preserve_alpha and image.size(-1) == 4
|
||||
): # Check if the image has an alpha channel
|
||||
alpha_channel = pimage[:, :, 3]
|
||||
pimage = pimage[:, :, :3] # Remove alpha channel for processing
|
||||
|
||||
sys.stdout = NullWriter()
|
||||
cropped_faces, restored_faces, restored_img = model.enhance(
|
||||
source_img,
|
||||
@@ -210,9 +222,14 @@ class 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)
|
||||
@@ -220,12 +237,13 @@ class RestoreFace:
|
||||
def restore(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
model: GFPGANer,
|
||||
model,
|
||||
aligned=False,
|
||||
only_center_face=False,
|
||||
weight=0.5,
|
||||
save_tmp_steps=True,
|
||||
) -> Tuple[torch.Tensor]:
|
||||
preserve_alpha: bool = False,
|
||||
) -> tuple[torch.Tensor]:
|
||||
out = [
|
||||
self.do_restore(
|
||||
image[i],
|
||||
@@ -234,6 +252,7 @@ class RestoreFace:
|
||||
only_center_face,
|
||||
weight,
|
||||
save_tmp_steps,
|
||||
preserve_alpha,
|
||||
)
|
||||
for i in range(image.size(0))
|
||||
]
|
||||
@@ -259,7 +278,7 @@ class RestoreFace:
|
||||
self, cropped_faces, restored_faces, height, width
|
||||
):
|
||||
for idx, (cropped_face, restored_face) in enumerate(
|
||||
zip(cropped_faces, restored_faces)
|
||||
zip(cropped_faces, restored_faces, strict=False)
|
||||
):
|
||||
face_id = idx + 1
|
||||
file = self.get_step_image_path("cropped_faces", face_id)
|
||||
@@ -275,4 +294,4 @@ class RestoreFace:
|
||||
cv2.imwrite(file, cmp_img)
|
||||
|
||||
|
||||
__nodes__ = [RestoreFace, LoadFaceEnhanceModel]
|
||||
__nodes__ = [MTB_RestoreFace, MTB_LoadFaceEnhanceModel]
|
||||
|
||||
+19
-9
@@ -2,7 +2,6 @@
|
||||
# region imports
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Set, Union
|
||||
|
||||
import comfy.model_management as model_management
|
||||
import cv2
|
||||
@@ -22,7 +21,7 @@ from ..utils import download_antelopev2, get_model_path, pil2tensor, tensor2pil
|
||||
log = mklog(__name__)
|
||||
|
||||
|
||||
class LoadFaceAnalysisModel:
|
||||
class MTB_LoadFaceAnalysisModel:
|
||||
"""Loads a face analysis model"""
|
||||
|
||||
models = []
|
||||
@@ -53,7 +52,7 @@ class LoadFaceAnalysisModel:
|
||||
return (face_analyser,)
|
||||
|
||||
|
||||
class LoadFaceSwapModel:
|
||||
class MTB_LoadFaceSwapModel:
|
||||
"""Loads a faceswap model"""
|
||||
|
||||
@staticmethod
|
||||
@@ -97,7 +96,7 @@ class LoadFaceSwapModel:
|
||||
|
||||
|
||||
# region roop node
|
||||
class FaceSwap:
|
||||
class MTB_FaceSwap:
|
||||
"""Face swap using deepinsight/insightface models"""
|
||||
|
||||
model = None
|
||||
@@ -119,7 +118,9 @@ class FaceSwap:
|
||||
),
|
||||
"faceswap_model": ("FACESWAP_MODEL", {"default": "None"}),
|
||||
},
|
||||
"optional": {},
|
||||
"optional": {
|
||||
"preserve_alpha": ("BOOLEAN", {"default": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
@@ -133,11 +134,18 @@ class FaceSwap:
|
||||
faces_index: str,
|
||||
faceanalysis_model,
|
||||
faceswap_model,
|
||||
preserve_alpha=False,
|
||||
):
|
||||
def do_swap(img):
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
img = tensor2pil(img)[0]
|
||||
ref = tensor2pil(reference)[0]
|
||||
|
||||
alpha_channel = None
|
||||
if preserve_alpha and img.mode == "RGBA":
|
||||
alpha_channel = img.getchannel("A")
|
||||
img = img.convert("RGB")
|
||||
|
||||
face_ids = {
|
||||
int(x)
|
||||
for x in faces_index.strip(",").split(",")
|
||||
@@ -148,6 +156,8 @@ class FaceSwap:
|
||||
faceanalysis_model, ref, img, faceswap_model, face_ids
|
||||
)
|
||||
sys.stdout = sys.__stdout__
|
||||
if alpha_channel:
|
||||
swapped.putalpha(alpha_channel)
|
||||
return pil2tensor(swapped)
|
||||
|
||||
batch_count = image.size(0)
|
||||
@@ -194,10 +204,10 @@ def get_face_single(
|
||||
|
||||
def swap_face(
|
||||
face_analyser,
|
||||
source_img: Union[Image.Image, List[Image.Image]],
|
||||
target_img: Union[Image.Image, List[Image.Image]],
|
||||
source_img: Image.Image | list[Image.Image],
|
||||
target_img: Image.Image | list[Image.Image],
|
||||
face_swapper_model,
|
||||
faces_index: Optional[Set[int]] = None,
|
||||
faces_index: set[int] | None = None,
|
||||
) -> Image.Image:
|
||||
if faces_index is None:
|
||||
faces_index = {0}
|
||||
@@ -239,4 +249,4 @@ def swap_face(
|
||||
# endregion face swap utils
|
||||
|
||||
|
||||
__nodes__ = [FaceSwap, LoadFaceSwapModel, LoadFaceAnalysisModel]
|
||||
__nodes__ = [MTB_FaceSwap, MTB_LoadFaceSwapModel, MTB_LoadFaceAnalysisModel]
|
||||
|
||||
+3
-75
@@ -1,4 +1,3 @@
|
||||
import qrcode
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
@@ -52,7 +51,7 @@ from ..utils import comfy_dir, font_path, pil2tensor
|
||||
# return m.digest().hex()
|
||||
|
||||
|
||||
class UnsplashImage:
|
||||
class MTB_UnsplashImage:
|
||||
"""Unsplash Image given a keyword and a size"""
|
||||
|
||||
@classmethod
|
||||
@@ -113,76 +112,6 @@ class UnsplashImage:
|
||||
return (None,)
|
||||
|
||||
|
||||
class QrCode:
|
||||
"""Basic QR Code generator"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"url": ("STRING", {"default": "https://www.github.com"}),
|
||||
"width": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
|
||||
"box_size": (
|
||||
"INT",
|
||||
{"default": 10, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"border": (
|
||||
"INT",
|
||||
{"default": 4, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"invert": (("BOOLEAN",), {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "do_qr"
|
||||
CATEGORY = "mtb/generate"
|
||||
|
||||
def do_qr(
|
||||
self, url, width, height, error_correct, box_size, border, invert
|
||||
):
|
||||
log.warning(
|
||||
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
|
||||
)
|
||||
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_L
|
||||
elif error_correct == "M":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_M
|
||||
elif error_correct == "Q":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_Q
|
||||
else:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_H
|
||||
|
||||
qr = qrcode.QRCode(
|
||||
version=1,
|
||||
error_correction=error_correct,
|
||||
box_size=box_size,
|
||||
border=border,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
back_color = (255, 255, 255) if invert else (0, 0, 0)
|
||||
fill_color = (0, 0, 0) if invert else (255, 255, 255)
|
||||
|
||||
code = img = qr.make_image(
|
||||
back_color=back_color, fill_color=fill_color
|
||||
)
|
||||
|
||||
# that we now resize without filtering
|
||||
code = code.resize((width, height), Image.NEAREST)
|
||||
|
||||
return (pil2tensor(code),)
|
||||
|
||||
|
||||
def bbox_dim(bbox):
|
||||
left, upper, right, lower = bbox
|
||||
width = right - left
|
||||
@@ -202,7 +131,7 @@ class MTB_TextToImage:
|
||||
fonts = {}
|
||||
DESCRIPTION = """# Text to Image
|
||||
|
||||
This node look for any font files in comfy_dir/fonts.
|
||||
This node look for any font files in comfy_dir/fonts.
|
||||
by default it fallsback to a default font.
|
||||
|
||||

|
||||
@@ -364,8 +293,7 @@ by default it fallsback to a default font.
|
||||
|
||||
|
||||
__nodes__ = [
|
||||
QrCode,
|
||||
UnsplashImage,
|
||||
MTB_UnsplashImage,
|
||||
MTB_TextToImage,
|
||||
# MtbExamples,
|
||||
]
|
||||
|
||||
+129
-58
@@ -3,17 +3,16 @@ import json
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from math import pi
|
||||
from typing import Optional
|
||||
|
||||
import comfy.model_management as model_management
|
||||
import comfy.utils
|
||||
import numpy as np
|
||||
import torch
|
||||
import torchvision.transforms.functional as F
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
from ..utils import (
|
||||
EASINGS,
|
||||
apply_easing,
|
||||
get_server_info,
|
||||
numpy_NFOV,
|
||||
@@ -70,8 +69,8 @@ class MTB_ToDevice:
|
||||
*,
|
||||
ignore_errors=False,
|
||||
device="cuda",
|
||||
image: Optional[torch.Tensor] = None,
|
||||
mask: Optional[torch.Tensor] = None,
|
||||
image: torch.Tensor | None = None,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
if not ignore_errors and image is None and mask is None:
|
||||
raise ValueError(
|
||||
@@ -137,6 +136,8 @@ class MTB_MatchDimensions:
|
||||
def execute(
|
||||
self, source: torch.Tensor, reference: torch.Tensor, match: str
|
||||
):
|
||||
import torchvision.transforms.functional as VF
|
||||
|
||||
_batch_size, height, width, _channels = source.shape
|
||||
_rbatch_size, rheight, rwidth, _rchannels = reference.shape
|
||||
|
||||
@@ -154,7 +155,7 @@ class MTB_MatchDimensions:
|
||||
new_height = int(rwidth / source_aspect_ratio)
|
||||
|
||||
resized_images = [
|
||||
F.resize(
|
||||
VF.resize(
|
||||
source[i],
|
||||
(new_height, new_width),
|
||||
antialias=True,
|
||||
@@ -168,11 +169,48 @@ class MTB_MatchDimensions:
|
||||
return (resized_source, new_width, new_height)
|
||||
|
||||
|
||||
class MTB_FloatsToFloat:
|
||||
"""AD, IPA, Fitz etc have commonly choose to mistype float lists as FLOAT.
|
||||
class MTB_FloatToFloats:
|
||||
"""Conversion utility for compatibility with other extensions (AD, IPA, Fitz are using FLOAT to represent list of floats.)"""
|
||||
|
||||
This is just a hack to be compatible with these
|
||||
"""
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"float": ("FLOAT", {"default": 0.0, "forceInput": True}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOATS",)
|
||||
RETURN_NAMES = ("floats",)
|
||||
CATEGORY = "mtb/utils"
|
||||
FUNCTION = "convert"
|
||||
|
||||
def convert(self, float: float):
|
||||
return (float,)
|
||||
|
||||
|
||||
class MTB_FloatsToInts:
|
||||
"""Conversion utility for compatibility with frame interpolation."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"floats": ("FLOATS", {"forceInput": True}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("INTS", "INT")
|
||||
CATEGORY = "mtb/utils"
|
||||
FUNCTION = "convert"
|
||||
|
||||
def convert(self, floats: list[float]):
|
||||
vals = [int(x) for x in floats]
|
||||
return (vals, vals)
|
||||
|
||||
|
||||
class MTB_FloatsToFloat:
|
||||
"""Conversion utility for compatibility with other extensions (AD, IPA, Fitz are using FLOAT to represent list of floats.)"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -379,7 +417,7 @@ class MTB_AnyToString:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"input": ("*")},
|
||||
"required": {"input": ("*",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
@@ -453,14 +491,14 @@ class MTB_MathExpression:
|
||||
RETURN_NAMES = ("result (float)", "result (int)")
|
||||
CATEGORY = "mtb/math"
|
||||
DESCRIPTION = (
|
||||
"evaluate a simple math expression string (!! Fallsback to eval)"
|
||||
"evaluate a simple math expression string, only supports literal_eval"
|
||||
)
|
||||
|
||||
def eval_expression(self, expression, **kwargs):
|
||||
def eval_expression(self, expression: str, **kwargs):
|
||||
from ast import literal_eval
|
||||
|
||||
for key, value in kwargs.items():
|
||||
print(f"Replacing placeholder <{key}> with value {value}")
|
||||
log.debug(f"Replacing placeholder <{key}> with value {value}")
|
||||
expression = expression.replace(f"<{key}>", str(value))
|
||||
|
||||
result = -1
|
||||
@@ -471,15 +509,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))
|
||||
|
||||
@@ -493,35 +526,24 @@ class MTB_FitNumber:
|
||||
"required": {
|
||||
"value": ("FLOAT", {"default": 0, "forceInput": True}),
|
||||
"clamp": ("BOOLEAN", {"default": False}),
|
||||
"source_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"source_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"target_min": ("FLOAT", {"default": 0.0, "step": 0.01}),
|
||||
"target_max": ("FLOAT", {"default": 1.0, "step": 0.01}),
|
||||
"source_min": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"source_max": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"target_min": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"target_max": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.01, "min": -1e5},
|
||||
),
|
||||
"easing": (
|
||||
[
|
||||
"Linear",
|
||||
"Sine In",
|
||||
"Sine Out",
|
||||
"Sine In/Out",
|
||||
"Quart In",
|
||||
"Quart Out",
|
||||
"Quart In/Out",
|
||||
"Cubic In",
|
||||
"Cubic Out",
|
||||
"Cubic In/Out",
|
||||
"Circ In",
|
||||
"Circ Out",
|
||||
"Circ In/Out",
|
||||
"Back In",
|
||||
"Back Out",
|
||||
"Back In/Out",
|
||||
"Elastic In",
|
||||
"Elastic Out",
|
||||
"Elastic In/Out",
|
||||
"Bounce In",
|
||||
"Bounce Out",
|
||||
"Bounce In/Out",
|
||||
],
|
||||
EASINGS,
|
||||
{"default": "Linear"},
|
||||
),
|
||||
}
|
||||
@@ -568,19 +590,66 @@ class MTB_ConcatImages:
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {"reverse": ("BOOLEAN", {"default": False})},
|
||||
"optional": {
|
||||
"on_mismatch": (
|
||||
["Error", "Smallest", "Largest"],
|
||||
{"default": "Smallest"},
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
def concatenate_tensors(self, reverse, **kwargs):
|
||||
tensors = tuple(kwargs.values())
|
||||
batch_sizes = [tensor.size(0) for tensor in tensors]
|
||||
def concatenate_tensors(
|
||||
self,
|
||||
reverse: bool,
|
||||
on_mismatch: str = "Smallest",
|
||||
**kwargs: torch.Tensor,
|
||||
) -> tuple[torch.Tensor]:
|
||||
tensors = list(kwargs.values())
|
||||
|
||||
if on_mismatch == "Error":
|
||||
shapes = [tensor.shape for tensor in tensors]
|
||||
if not all(shape == shapes[0] for shape in shapes):
|
||||
raise ValueError(
|
||||
"All input tensors must have the same shape when on_mismatch is 'Error'."
|
||||
)
|
||||
|
||||
else:
|
||||
import torch.nn.functional as F
|
||||
|
||||
if on_mismatch == "Smallest":
|
||||
target_shape = min(
|
||||
(tensor.shape for tensor in tensors),
|
||||
key=lambda s: (s[1], s[2]),
|
||||
)
|
||||
else: # on_mismatch == "Largest"
|
||||
target_shape = max(
|
||||
(tensor.shape for tensor in tensors),
|
||||
key=lambda s: (s[1], s[2]),
|
||||
)
|
||||
|
||||
target_height, target_width = target_shape[1], target_shape[2]
|
||||
|
||||
resized_tensors = []
|
||||
for tensor in tensors:
|
||||
if (
|
||||
tensor.shape[1] != target_height
|
||||
or tensor.shape[2] != target_width
|
||||
):
|
||||
resized_tensor = F.interpolate(
|
||||
tensor.permute(0, 3, 1, 2),
|
||||
size=(target_height, target_width),
|
||||
mode="bilinear",
|
||||
align_corners=False,
|
||||
)
|
||||
resized_tensor = resized_tensor.permute(0, 2, 3, 1)
|
||||
resized_tensors.append(resized_tensor)
|
||||
else:
|
||||
resized_tensors.append(tensor)
|
||||
|
||||
tensors = resized_tensors
|
||||
|
||||
concatenated = torch.cat(tensors, dim=0)
|
||||
|
||||
# Update the batch size in the concatenated tensor
|
||||
concatenated_size = list(concatenated.size())
|
||||
concatenated_size[0] = sum(batch_sizes)
|
||||
concatenated = concatenated.view(*concatenated_size)
|
||||
|
||||
return (concatenated,)
|
||||
|
||||
|
||||
@@ -596,4 +665,6 @@ __nodes__ = [
|
||||
MTB_MatchDimensions,
|
||||
MTB_AutoPanEquilateral,
|
||||
MTB_FloatsToFloat,
|
||||
MTB_FloatToFloats,
|
||||
MTB_FloatsToInts,
|
||||
]
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import glob
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
import comfy
|
||||
import comfy.model_management as model_management
|
||||
import comfy.utils
|
||||
import folder_paths
|
||||
import numpy as np
|
||||
import tensorflow as tf
|
||||
import torch
|
||||
@@ -17,7 +14,7 @@ from ..log import log
|
||||
from ..utils import get_model_path
|
||||
|
||||
|
||||
class LoadFilmModel:
|
||||
class MTB_LoadFilmModel:
|
||||
"""Loads a FILM model"""
|
||||
|
||||
@staticmethod
|
||||
@@ -58,7 +55,7 @@ class LoadFilmModel:
|
||||
return (interpolator.Interpolator(model_path.as_posix(), None),)
|
||||
|
||||
|
||||
class FilmInterpolation:
|
||||
class MTB_FilmInterpolation:
|
||||
"""Google Research FILM frame interpolation for large motion"""
|
||||
|
||||
@classmethod
|
||||
@@ -107,12 +104,16 @@ class FilmInterpolation:
|
||||
in_frames, interpolate, film_model
|
||||
):
|
||||
out_tensors.append(
|
||||
torch.from_numpy(frame) if isinstance(frame, np.ndarray) else frame
|
||||
torch.from_numpy(frame)
|
||||
if isinstance(frame, np.ndarray)
|
||||
else frame
|
||||
)
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
pbar.update(1)
|
||||
|
||||
out_tensors = torch.cat([tens.unsqueeze(0) for tens in out_tensors], dim=0)
|
||||
out_tensors = torch.cat(
|
||||
[tens.unsqueeze(0) for tens in out_tensors], dim=0
|
||||
)
|
||||
|
||||
log.debug(f"Returning {len(out_tensors)} tensors")
|
||||
log.debug(f"Output shape {out_tensors.shape}")
|
||||
@@ -120,4 +121,4 @@ class FilmInterpolation:
|
||||
return (out_tensors,)
|
||||
|
||||
|
||||
__nodes__ = [LoadFilmModel, FilmInterpolation]
|
||||
__nodes__ = [MTB_LoadFilmModel, MTB_FilmInterpolation]
|
||||
|
||||
+496
-93
@@ -3,6 +3,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
|
||||
import comfy.model_management as model_management
|
||||
import folder_paths
|
||||
import numpy as np
|
||||
import torch
|
||||
@@ -13,7 +14,7 @@ from skimage.filters import gaussian
|
||||
from skimage.util import compare_images
|
||||
|
||||
from ..log import log
|
||||
from ..utils import np2tensor, pil2tensor, tensor2np, tensor2pil
|
||||
from ..utils import np2tensor, pil2tensor, tensor2pil
|
||||
|
||||
# try:
|
||||
# from cv2.ximgproc import guidedFilter
|
||||
@@ -35,6 +36,343 @@ def gaussian_kernel(
|
||||
return g / g.sum()
|
||||
|
||||
|
||||
class MTB_CoordinatesToString:
|
||||
RETURN_TYPES = ("STRING",)
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "mtb/coordinates"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"coordinates": ("BATCH_COORDINATES",),
|
||||
"frame": ("INT",),
|
||||
}
|
||||
}
|
||||
|
||||
def convert(
|
||||
self, coordinates: list[list[tuple[int, int]]], frame: int
|
||||
) -> tuple[str]:
|
||||
frame = max(frame, len(coordinates) - 1)
|
||||
coords = coordinates[frame]
|
||||
output: list[dict[str, int]] = []
|
||||
|
||||
for x, y in coords:
|
||||
output.append({"x": x, "y": y})
|
||||
|
||||
return (json.dumps(output),)
|
||||
|
||||
|
||||
class MTB_ExtractCoordinatesFromImage:
|
||||
"""Extract 2D points from a batch of images based on a threshold."""
|
||||
|
||||
RETURN_TYPES = ("BATCH_COORDINATES", "IMAGE")
|
||||
FUNCTION = "extract"
|
||||
CATEGORY = "mtb/coordinates"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"threshold": ("FLOAT",),
|
||||
"max_points": ("INT", {"default": 50, "min": 0}),
|
||||
},
|
||||
"optional": {"image": ("IMAGE",), "mask": ("MASK",)},
|
||||
}
|
||||
|
||||
def extract(
|
||||
self,
|
||||
threshold: float,
|
||||
max_points: int,
|
||||
image: torch.Tensor | None = None,
|
||||
mask: torch.Tensor | None = None,
|
||||
) -> tuple[list[list[tuple[int, int]]], torch.Tensor]:
|
||||
if image is not None:
|
||||
batch_count, height, width, channel_count = image.shape
|
||||
imgs = image
|
||||
else:
|
||||
if mask is None:
|
||||
raise ValueError("Must provide either image or mask")
|
||||
batch_count, height, width = mask.shape
|
||||
channel_count = 1
|
||||
imgs = mask
|
||||
|
||||
if channel_count not in [1, 2, 3, 4]:
|
||||
raise ValueError(f"Incorrect channel count: {channel_count}")
|
||||
|
||||
all_points: list[list[tuple[int, int]]] = []
|
||||
debug_images = torch.zeros(
|
||||
(batch_count, height, width, 3),
|
||||
dtype=torch.uint8,
|
||||
device=imgs.device,
|
||||
)
|
||||
|
||||
for i, img in enumerate(imgs):
|
||||
if channel_count == 1:
|
||||
alpha_channel = img if len(img.shape) == 2 else img[:, :, 0]
|
||||
elif channel_count == 2:
|
||||
alpha_channel = img[:, :, 1]
|
||||
elif channel_count == 4:
|
||||
alpha_channel = img[:, :, 3]
|
||||
else:
|
||||
# get intensity
|
||||
alpha_channel = img[:, :, :3].max(dim=2)[0]
|
||||
|
||||
points = (alpha_channel > threshold).nonzero(as_tuple=False)
|
||||
|
||||
if len(points) > max_points:
|
||||
indices = torch.randperm(points.size(0), device=img.device)[
|
||||
:max_points
|
||||
]
|
||||
points = points[indices]
|
||||
|
||||
points = [(int(y.item()), int(x.item())) for x, y in points]
|
||||
all_points.append(points)
|
||||
|
||||
for x, y in points:
|
||||
self._draw_circle(debug_images[i], (x, y), 5)
|
||||
|
||||
return (all_points, debug_images)
|
||||
|
||||
@staticmethod
|
||||
def _draw_circle(
|
||||
image: torch.Tensor, center: tuple[int, int], radius: int
|
||||
):
|
||||
"""Draw a 5px circle on the image."""
|
||||
x0, y0 = center
|
||||
for x in range(-radius, radius + 1):
|
||||
for y in range(-radius, radius + 1):
|
||||
in_radius = x**2 + y**2 <= radius**2
|
||||
in_bounds = (
|
||||
0 <= x0 + x < image.shape[1]
|
||||
and 0 <= y0 + y < image.shape[0]
|
||||
)
|
||||
if in_radius and in_bounds:
|
||||
image[y0 + y, x0 + x] = torch.tensor(
|
||||
[255, 255, 255],
|
||||
dtype=torch.uint8,
|
||||
device=image.device,
|
||||
)
|
||||
|
||||
|
||||
class MTB_ColorCorrectGPU:
|
||||
"""Various color correction methods using only Torch."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"force_gpu": ("BOOLEAN", {"default": True}),
|
||||
"clamp": ([True, False], {"default": True}),
|
||||
"gamma": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"contrast": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"exposure": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"offset": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -5.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"hue": (
|
||||
"FLOAT",
|
||||
{"default": 0.0, "min": -0.5, "max": 0.5, "step": 0.01},
|
||||
),
|
||||
"saturation": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
"value": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
},
|
||||
"optional": {"mask": ("MASK",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "correct"
|
||||
CATEGORY = "mtb/image processing"
|
||||
|
||||
@staticmethod
|
||||
def get_device(tensor: torch.Tensor, force_gpu: bool):
|
||||
if force_gpu:
|
||||
if torch.cuda.is_available():
|
||||
return torch.device("cuda")
|
||||
elif (
|
||||
hasattr(torch.backends, "mps")
|
||||
and torch.backends.mps.is_available()
|
||||
):
|
||||
return torch.device("mps")
|
||||
elif hasattr(torch, "hip") and torch.hip.is_available():
|
||||
return torch.device("hip")
|
||||
return (
|
||||
tensor.device
|
||||
) # model_management.get_torch_device() # torch.device("cpu")
|
||||
|
||||
@staticmethod
|
||||
def rgb_to_hsv(image: torch.Tensor):
|
||||
r, g, b = image.unbind(-1)
|
||||
max_rgb, argmax_rgb = image.max(-1)
|
||||
min_rgb, _ = image.min(-1)
|
||||
|
||||
diff = max_rgb - min_rgb
|
||||
|
||||
h = torch.empty_like(max_rgb)
|
||||
s = diff / (max_rgb + 1e-7)
|
||||
v = max_rgb
|
||||
|
||||
h[argmax_rgb == 0] = (g - b)[argmax_rgb == 0] / (diff + 1e-7)[
|
||||
argmax_rgb == 0
|
||||
]
|
||||
h[argmax_rgb == 1] = (
|
||||
2.0 + (b - r)[argmax_rgb == 1] / (diff + 1e-7)[argmax_rgb == 1]
|
||||
)
|
||||
h[argmax_rgb == 2] = (
|
||||
4.0 + (r - g)[argmax_rgb == 2] / (diff + 1e-7)[argmax_rgb == 2]
|
||||
)
|
||||
h = (h / 6.0) % 1.0
|
||||
|
||||
h = h.unsqueeze(-1)
|
||||
s = s.unsqueeze(-1)
|
||||
v = v.unsqueeze(-1)
|
||||
|
||||
return torch.cat((h, s, v), dim=-1)
|
||||
|
||||
@staticmethod
|
||||
def hsv_to_rgb(hsv: torch.Tensor):
|
||||
h, s, v = hsv.unbind(-1)
|
||||
h = h * 6.0
|
||||
|
||||
i = torch.floor(h)
|
||||
f = h - i
|
||||
p = v * (1.0 - s)
|
||||
q = v * (1.0 - s * f)
|
||||
t = v * (1.0 - s * (1.0 - f))
|
||||
|
||||
i = i.long() % 6
|
||||
|
||||
mask = torch.stack(
|
||||
(i == 0, i == 1, i == 2, i == 3, i == 4, i == 5), -1
|
||||
)
|
||||
|
||||
rgb = torch.stack(
|
||||
(
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
q,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
p,
|
||||
torch.where(mask[..., 4], t, v),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
t,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
v,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
q,
|
||||
torch.where(mask[..., 4], p, p),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
torch.where(
|
||||
mask[..., 0],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 1],
|
||||
p,
|
||||
torch.where(
|
||||
mask[..., 2],
|
||||
t,
|
||||
torch.where(
|
||||
mask[..., 3],
|
||||
v,
|
||||
torch.where(mask[..., 4], v, q),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
return rgb
|
||||
|
||||
def correct(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
force_gpu: bool,
|
||||
clamp: bool,
|
||||
gamma: float = 1.0,
|
||||
contrast: float = 1.0,
|
||||
exposure: float = 0.0,
|
||||
offset: float = 0.0,
|
||||
hue: float = 0.0,
|
||||
saturation: float = 1.0,
|
||||
value: float = 1.0,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
device = self.get_device(image, force_gpu)
|
||||
image = image.to(device)
|
||||
|
||||
if mask is not None:
|
||||
if mask.shape[0] != image.shape[0]:
|
||||
mask = mask.expand(image.shape[0], -1, -1)
|
||||
|
||||
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
|
||||
mask = mask.to(device)
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
adjusted = image.pow(1 / gamma) * (2.0**exposure) * contrast + offset
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
hsv = self.rgb_to_hsv(adjusted)
|
||||
hsv[..., 0] = (hsv[..., 0] + hue) % 1.0 # Hue
|
||||
hsv[..., 1] = hsv[..., 1] * saturation # Saturation
|
||||
hsv[..., 2] = hsv[..., 2] * value # Value
|
||||
adjusted = self.hsv_to_rgb(hsv)
|
||||
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
if clamp:
|
||||
adjusted = torch.clamp(adjusted, 0.0, 1.0)
|
||||
|
||||
# apply mask
|
||||
result = (
|
||||
adjusted
|
||||
if mask is None
|
||||
else torch.where(mask > 0, adjusted, image)
|
||||
)
|
||||
|
||||
if not force_gpu:
|
||||
result = result.cpu()
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
class MTB_ColorCorrect:
|
||||
"""Various color correction methods"""
|
||||
|
||||
@@ -72,7 +410,8 @@ class MTB_ColorCorrect:
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.0, "max": 5.0, "step": 0.01},
|
||||
),
|
||||
}
|
||||
},
|
||||
"optional": {"mask": ("MASK",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
@@ -86,7 +425,14 @@ class MTB_ColorCorrect:
|
||||
|
||||
@staticmethod
|
||||
def contrast_adjustment_tensor(image, contrast):
|
||||
contrasted = (image - 0.5) * contrast + 0.5
|
||||
r, g, b = image.unbind(-1)
|
||||
|
||||
# Using Adobe RGB luminance weights.
|
||||
luminance_image = 0.33 * r + 0.71 * g + 0.06 * b
|
||||
luminance_mean = torch.mean(luminance_image.unsqueeze(-1))
|
||||
|
||||
# Blend original with mean luminance using contrast factor as blend ratio.
|
||||
contrasted = image * contrast + (1.0 - contrast) * luminance_mean
|
||||
return torch.clamp(contrasted, 0.0, 1.0)
|
||||
|
||||
@staticmethod
|
||||
@@ -181,18 +527,31 @@ class MTB_ColorCorrect:
|
||||
hue: float = 0.0,
|
||||
saturation: float = 1.0,
|
||||
value: float = 1.0,
|
||||
mask: torch.Tensor | None = None,
|
||||
):
|
||||
if mask is not None:
|
||||
if mask.shape[0] != image.shape[0]:
|
||||
mask = mask.expand(image.shape[0], -1, -1)
|
||||
|
||||
mask = mask.unsqueeze(-1).expand(-1, -1, -1, 3)
|
||||
|
||||
# Apply color correction operations
|
||||
image = self.gamma_correction_tensor(image, gamma)
|
||||
image = self.contrast_adjustment_tensor(image, contrast)
|
||||
image = self.exposure_adjustment_tensor(image, exposure)
|
||||
image = self.offset_adjustment_tensor(image, offset)
|
||||
image = self.hsv_adjustment(image, hue, saturation, value)
|
||||
adjusted = self.gamma_correction_tensor(image, gamma)
|
||||
adjusted = self.contrast_adjustment_tensor(adjusted, contrast)
|
||||
adjusted = self.exposure_adjustment_tensor(adjusted, exposure)
|
||||
adjusted = self.offset_adjustment_tensor(adjusted, offset)
|
||||
adjusted = self.hsv_adjustment(adjusted, hue, saturation, value)
|
||||
|
||||
if clamp:
|
||||
image = torch.clamp(image, 0.0, 1.0)
|
||||
adjusted = torch.clamp(image, 0.0, 1.0)
|
||||
|
||||
return (image,)
|
||||
result = (
|
||||
adjusted
|
||||
if mask is None
|
||||
else torch.where(mask > 0, adjusted, image)
|
||||
)
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
class MTB_ImageCompare:
|
||||
@@ -216,16 +575,55 @@ class MTB_ImageCompare:
|
||||
CATEGORY = "mtb/image"
|
||||
|
||||
def compare(self, imageA: torch.Tensor, imageB: torch.Tensor, mode):
|
||||
imageA = imageA.numpy()
|
||||
imageB = imageB.numpy()
|
||||
if imageA.dim() == 4:
|
||||
batch_count = imageA.size(0)
|
||||
return (
|
||||
torch.cat(
|
||||
tuple(
|
||||
self.compare(imageA[i], imageB[i], mode)[0]
|
||||
for i in range(batch_count)
|
||||
),
|
||||
dim=0,
|
||||
),
|
||||
)
|
||||
|
||||
imageA = imageA.squeeze()
|
||||
imageB = imageB.squeeze()
|
||||
num_channels_A = imageA.size(2)
|
||||
num_channels_B = imageB.size(2)
|
||||
|
||||
image = compare_images(imageA, imageB, method=mode)
|
||||
# handle RGBA/RGB mismatch
|
||||
if num_channels_A == 3 and num_channels_B == 4:
|
||||
imageA = torch.cat(
|
||||
(imageA, torch.ones_like(imageA[:, :, 0:1])), dim=2
|
||||
)
|
||||
elif num_channels_B == 3 and num_channels_A == 4:
|
||||
imageB = torch.cat(
|
||||
(imageB, torch.ones_like(imageB[:, :, 0:1])), dim=2
|
||||
)
|
||||
match mode:
|
||||
case "diff":
|
||||
compare_image = torch.abs(imageA - imageB)
|
||||
case "blend":
|
||||
compare_image = 0.5 * (imageA + imageB)
|
||||
case "checkerboard":
|
||||
imageA = imageA.numpy()
|
||||
imageB = imageB.numpy()
|
||||
compared_channels = [
|
||||
torch.from_numpy(
|
||||
compare_images(
|
||||
imageA[:, :, i], imageB[:, :, i], method=mode
|
||||
)
|
||||
)
|
||||
for i in range(imageA.shape[2])
|
||||
]
|
||||
|
||||
image = np.expand_dims(image, axis=0)
|
||||
return (torch.from_numpy(image),)
|
||||
compare_image = torch.stack(compared_channels, dim=2)
|
||||
case _:
|
||||
compare_image = None
|
||||
raise ValueError(f"Unknown mode {mode}")
|
||||
|
||||
compare_image = compare_image.unsqueeze(0)
|
||||
|
||||
return (compare_image,)
|
||||
|
||||
|
||||
import requests
|
||||
@@ -429,7 +827,10 @@ class MTB_MaskToImage:
|
||||
"mask": ("MASK",),
|
||||
"color": ("COLOR",),
|
||||
"background": ("COLOR", {"default": "#000000"}),
|
||||
}
|
||||
},
|
||||
"optional": {
|
||||
"invert": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/generate"
|
||||
@@ -438,11 +839,12 @@ class MTB_MaskToImage:
|
||||
|
||||
FUNCTION = "render_mask"
|
||||
|
||||
def render_mask(self, mask, color, background):
|
||||
masks = tensor2np(mask)[0]
|
||||
def render_mask(self, mask, color, background, invert=False):
|
||||
masks = tensor2pil(1.0 - mask) if invert else tensor2pil(mask)
|
||||
images = []
|
||||
|
||||
for m in masks:
|
||||
_mask = Image.fromarray(m).convert("L")
|
||||
_mask = m.convert("L")
|
||||
|
||||
log.debug(
|
||||
f"Converted mask to PIL Image format, size: {_mask.size}"
|
||||
@@ -480,6 +882,11 @@ class MTB_ColoredImage:
|
||||
"optional": {
|
||||
"foreground_image": ("IMAGE",),
|
||||
"foreground_mask": ("MASK",),
|
||||
"invert": ("BOOLEAN", {"default": False}),
|
||||
"mask_opacity": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "step": 0.1, "min": 0},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -489,28 +896,19 @@ class MTB_ColoredImage:
|
||||
|
||||
FUNCTION = "render_img"
|
||||
|
||||
def resize_and_crop(self, img, target_size):
|
||||
# Calculate scaling factors for both dimensions
|
||||
scale_x = target_size[0] / img.width
|
||||
scale_y = target_size[1] / img.height
|
||||
|
||||
# Use the smaller scaling factor to maintain aspect ratio
|
||||
scale = max(scale_x, scale_y)
|
||||
|
||||
# Resize the image based on calculated scale
|
||||
def resize_and_crop(self, img: Image.Image, target_size: tuple[int, int]):
|
||||
scale = max(target_size[0] / img.width, target_size[1] / img.height)
|
||||
new_size = (int(img.width * scale), int(img.height * scale))
|
||||
img = img.resize(new_size, Image.LANCZOS)
|
||||
left = (img.width - target_size[0]) // 2
|
||||
top = (img.height - target_size[1]) // 2
|
||||
return img.crop(
|
||||
(left, top, left + target_size[0], top + target_size[1])
|
||||
)
|
||||
|
||||
# Calculate cropping coordinates
|
||||
left = (img.width - target_size[0]) / 2
|
||||
top = (img.height - target_size[1]) / 2
|
||||
right = (img.width + target_size[0]) / 2
|
||||
bottom = (img.height + target_size[1]) / 2
|
||||
|
||||
# Crop and return the image
|
||||
return img.crop((left, top, right, bottom))
|
||||
|
||||
def resize_and_crop_thumbnails(self, img, target_size):
|
||||
def resize_and_crop_thumbnails(
|
||||
self, img: Image.Image, target_size: tuple[int, int]
|
||||
):
|
||||
img.thumbnail(target_size, Image.LANCZOS)
|
||||
left = (img.width - target_size[0]) / 2
|
||||
top = (img.height - target_size[1]) / 2
|
||||
@@ -518,69 +916,71 @@ class MTB_ColoredImage:
|
||||
bottom = (img.height + target_size[1]) / 2
|
||||
return img.crop((left, top, right, bottom))
|
||||
|
||||
@staticmethod
|
||||
def process_mask(
|
||||
mask: torch.Tensor | None,
|
||||
invert: bool,
|
||||
# opacity: float,
|
||||
batch_size: int,
|
||||
) -> list[Image.Image] | None:
|
||||
if mask is None:
|
||||
return [None] * batch_size
|
||||
|
||||
masks = tensor2pil(mask if not invert else 1.0 - mask)
|
||||
|
||||
if len(masks) == 1 and batch_size > 1:
|
||||
masks = masks * batch_size
|
||||
|
||||
if len(masks) != batch_size:
|
||||
raise ValueError(
|
||||
"Foreground image and mask must have the same batch size"
|
||||
)
|
||||
|
||||
return masks
|
||||
|
||||
def render_img(
|
||||
self,
|
||||
color,
|
||||
width,
|
||||
height,
|
||||
color: str,
|
||||
width: int,
|
||||
height: int,
|
||||
foreground_image: torch.Tensor | None = None,
|
||||
foreground_mask: torch.Tensor | None = None,
|
||||
):
|
||||
image = Image.new("RGBA", (width, height), color=color)
|
||||
output = []
|
||||
if foreground_image is not None:
|
||||
fg_masks = [None] * foreground_image.size()[0]
|
||||
invert: bool = False,
|
||||
mask_opacity: float = 1.0,
|
||||
) -> tuple[torch.Tensor]:
|
||||
background = Image.new("RGBA", (width, height), color=color)
|
||||
|
||||
if foreground_mask is not None:
|
||||
fg_size = foreground_image.size()[0]
|
||||
mask_size = foreground_mask.size()[0]
|
||||
if foreground_image is None:
|
||||
return (pil2tensor([background.convert("RGB")]),)
|
||||
|
||||
if fg_size == 1 and mask_size > fg_size:
|
||||
foreground_image = foreground_image.repeat(
|
||||
mask_size, 1, 1, 1
|
||||
)
|
||||
fg_images = tensor2pil(foreground_image)
|
||||
fg_masks = self.process_mask(foreground_mask, invert, len(fg_images))
|
||||
|
||||
if foreground_image.size()[0] != foreground_mask.size()[0]:
|
||||
output: list[Image.Image] = []
|
||||
for fg_image, fg_mask in zip(fg_images, fg_masks, strict=False):
|
||||
fg_image = self.resize_and_crop(fg_image, background.size)
|
||||
|
||||
if fg_mask:
|
||||
fg_mask = self.resize_and_crop(fg_mask, background.size)
|
||||
|
||||
fg_mask_array = np.array(fg_mask)
|
||||
fg_mask_array = (fg_mask_array * mask_opacity).astype(np.uint8)
|
||||
fg_mask = Image.fromarray(fg_mask_array)
|
||||
output.append(
|
||||
Image.composite(
|
||||
fg_image.convert("RGBA"), background, fg_mask
|
||||
).convert("RGB")
|
||||
)
|
||||
else:
|
||||
if fg_image.mode != "RGBA":
|
||||
raise ValueError(
|
||||
"Foreground image and mask must have same batch size"
|
||||
f"Foreground image must be in 'RGBA' mode when no mask is provided, got {fg_image.mode}"
|
||||
)
|
||||
fg_masks = tensor2pil(foreground_mask.unsqueeze(-1))
|
||||
output.append(
|
||||
Image.alpha_composite(background, fg_image).convert("RGB")
|
||||
)
|
||||
|
||||
fg_images = tensor2pil(foreground_image)
|
||||
|
||||
for fg_image, fg_mask in zip(fg_images, fg_masks):
|
||||
# Resize and crop if dimensions mismatch
|
||||
if fg_image.size != image.size:
|
||||
fg_image = self.resize_and_crop(fg_image, image.size)
|
||||
if fg_mask:
|
||||
fg_mask = self.resize_and_crop(fg_mask, image.size)
|
||||
|
||||
if fg_mask:
|
||||
output.append(
|
||||
Image.composite(
|
||||
fg_image.convert("RGBA"),
|
||||
image,
|
||||
fg_mask,
|
||||
).convert("RGB")
|
||||
)
|
||||
else:
|
||||
if fg_image.mode != "RGBA":
|
||||
raise ValueError(
|
||||
"Foreground image must be in 'RGBA' mode "
|
||||
f"when no mask is provided, got {fg_image.mode}"
|
||||
)
|
||||
output.append(
|
||||
Image.alpha_composite(image, fg_image).convert("RGB")
|
||||
)
|
||||
|
||||
else:
|
||||
if foreground_mask is not None:
|
||||
log.warn("Mask ignored because no foreground image is given")
|
||||
output.append(image.convert("RGB"))
|
||||
|
||||
output = pil2tensor(output)
|
||||
|
||||
return (output,)
|
||||
return (pil2tensor(output),)
|
||||
|
||||
|
||||
class MTB_ImagePremultiply:
|
||||
@@ -878,6 +1278,7 @@ class MTB_ImageTileOffset:
|
||||
|
||||
__nodes__ = [
|
||||
MTB_ColorCorrect,
|
||||
MTB_ColorCorrectGPU,
|
||||
MTB_ImageCompare,
|
||||
MTB_ImageTileOffset,
|
||||
MTB_Blur,
|
||||
@@ -889,4 +1290,6 @@ __nodes__ = [
|
||||
MTB_SaveImageGrid,
|
||||
MTB_LoadImageFromUrl,
|
||||
MTB_Sharpen,
|
||||
MTB_ExtractCoordinatesFromImage,
|
||||
MTB_CoordinatesToString,
|
||||
]
|
||||
|
||||
@@ -27,6 +27,11 @@ class MTB_StackImages:
|
||||
normalized_tensors = [
|
||||
self.normalize_to_rgba(tensor) for tensor in tensors
|
||||
]
|
||||
max_batch_size = max(tensor.shape[0] for tensor in normalized_tensors)
|
||||
normalized_tensors = [
|
||||
self.duplicate_frames(tensor, max_batch_size)
|
||||
for tensor in normalized_tensors
|
||||
]
|
||||
|
||||
if vertical:
|
||||
width = normalized_tensors[0].shape[2]
|
||||
@@ -67,6 +72,21 @@ class MTB_StackImages:
|
||||
"expected 3 (RGB) or 4 (RGBA)."
|
||||
)
|
||||
|
||||
def duplicate_frames(self, tensor, target_batch_size):
|
||||
"""Duplicate frames in tensor to match the target batch size."""
|
||||
current_batch_size = tensor.shape[0]
|
||||
if current_batch_size < target_batch_size:
|
||||
duplication_factors: int = target_batch_size // current_batch_size
|
||||
duplicated_tensor = tensor.repeat(duplication_factors, 1, 1, 1)
|
||||
remaining_frames = target_batch_size % current_batch_size
|
||||
if remaining_frames > 0:
|
||||
duplicated_tensor = torch.cat(
|
||||
(duplicated_tensor, tensor[:remaining_frames]), dim=0
|
||||
)
|
||||
return duplicated_tensor
|
||||
else:
|
||||
return tensor
|
||||
|
||||
|
||||
class MTB_PickFromBatch:
|
||||
"""Pick a specific number of images from a batch.
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ def get_playlist_path(playlist_name: str, persistant_playlist=False):
|
||||
return output_dir / "playlists" / session_id / f"{playlist_name}.json"
|
||||
|
||||
|
||||
class ReadPlaylist:
|
||||
class MTB_ReadPlaylist:
|
||||
"""Read a playlist"""
|
||||
|
||||
@classmethod
|
||||
@@ -399,5 +399,5 @@ __nodes__ = [
|
||||
MTB_SaveGif,
|
||||
MTB_ExportWithFfmpeg,
|
||||
MTB_AddToPlaylist,
|
||||
ReadPlaylist,
|
||||
MTB_ReadPlaylist,
|
||||
]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import torch
|
||||
|
||||
|
||||
class LatentLerp:
|
||||
class MTB_LatentLerp:
|
||||
"""Linear interpolation (blend) between two latent vectors"""
|
||||
|
||||
@classmethod
|
||||
@@ -10,7 +10,10 @@ class LatentLerp:
|
||||
"required": {
|
||||
"A": ("LATENT",),
|
||||
"B": ("LATENT",),
|
||||
"t": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"t": (
|
||||
"FLOAT",
|
||||
{"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,5 +32,5 @@ class LatentLerp:
|
||||
|
||||
|
||||
__nodes__ = [
|
||||
LatentLerp,
|
||||
MTB_LatentLerp,
|
||||
]
|
||||
|
||||
+2
-2
@@ -80,7 +80,7 @@ def conv_forward(lyr, tensor, weight, bias):
|
||||
)
|
||||
|
||||
|
||||
class ModelPatchSeamless:
|
||||
class MTB_ModelPatchSeamless:
|
||||
"""Uses the stable diffusion 'hack' to infer seamless images by setting the model layers padding mode to circular (experimental)"""
|
||||
|
||||
@classmethod
|
||||
@@ -152,4 +152,4 @@ class ModelPatchSeamless:
|
||||
return (model, hacked_model)
|
||||
|
||||
|
||||
__nodes__ = [ModelPatchSeamless, MTB_VaeDecode]
|
||||
__nodes__ = [MTB_ModelPatchSeamless, MTB_VaeDecode]
|
||||
|
||||
@@ -77,8 +77,6 @@ class MTB_FloatToNumber:
|
||||
def float_to_number(self, float):
|
||||
return (float,)
|
||||
|
||||
return (int,)
|
||||
|
||||
|
||||
__nodes__ = [
|
||||
MTB_FloatToNumber,
|
||||
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
from pathlib import Path
|
||||
|
||||
import safetensors.torch
|
||||
import torch
|
||||
import tqdm
|
||||
|
||||
from ..log import log
|
||||
from ..utils import Operation, Precision
|
||||
from ..utils import output_dir as comfy_out_dir
|
||||
|
||||
PRUNE_DATA = {
|
||||
"known_junk_prefix": [
|
||||
"embedding_manager.embedder.",
|
||||
"lora_te_text_model",
|
||||
"control_model.",
|
||||
],
|
||||
"nai_keys": {
|
||||
"cond_stage_model.transformer.embeddings.": "cond_stage_model.transformer.text_model.embeddings.",
|
||||
"cond_stage_model.transformer.encoder.": "cond_stage_model.transformer.text_model.encoder.",
|
||||
"cond_stage_model.transformer.final_layer_norm.": "cond_stage_model.transformer.text_model.final_layer_norm.",
|
||||
},
|
||||
}
|
||||
|
||||
# position_ids in clip is int64. model_ema.num_updates is int32
|
||||
dtypes_to_fp16 = {torch.float32, torch.float64, torch.bfloat16}
|
||||
dtypes_to_bf16 = {torch.float32, torch.float64, torch.float16}
|
||||
dtypes_to_fp8 = {torch.float32, torch.float64, torch.bfloat16, torch.float16}
|
||||
|
||||
|
||||
class MTB_ModelPruner:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"optional": {
|
||||
"unet": ("MODEL",),
|
||||
"clip": ("CLIP",),
|
||||
"vae": ("VAE",),
|
||||
},
|
||||
"required": {
|
||||
"save_separately": ("BOOLEAN", {"default": False}),
|
||||
"save_folder": ("STRING", {"default": "checkpoints/ComfyUI"}),
|
||||
"fix_clip": ("BOOLEAN", {"default": True}),
|
||||
"remove_junk": ("BOOLEAN", {"default": True}),
|
||||
"ema_mode": (
|
||||
("disabled", "remove_ema", "ema_only"),
|
||||
{"default": "remove_ema"},
|
||||
),
|
||||
"precision_unet": (
|
||||
Precision.list_members(),
|
||||
{"default": Precision.FULL.value},
|
||||
),
|
||||
"operation_unet": (
|
||||
Operation.list_members(),
|
||||
{"default": Operation.CONVERT.value},
|
||||
),
|
||||
"precision_clip": (
|
||||
Precision.list_members(),
|
||||
{"default": Precision.FULL.value},
|
||||
),
|
||||
"operation_clip": (
|
||||
Operation.list_members(),
|
||||
{"default": Operation.CONVERT.value},
|
||||
),
|
||||
"precision_vae": (
|
||||
Precision.list_members(),
|
||||
{"default": Precision.FULL.value},
|
||||
),
|
||||
"operation_vae": (
|
||||
Operation.list_members(),
|
||||
{"default": Operation.CONVERT.value},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
OUTPUT_NODE = True
|
||||
RETURN_TYPES = ()
|
||||
CATEGORY = "mtb/prune"
|
||||
FUNCTION = "prune"
|
||||
|
||||
def convert_precision(self, tensor: torch.Tensor, precision: Precision):
|
||||
precision = Precision.from_str(precision)
|
||||
log.debug(f"Converting to {precision}")
|
||||
match precision:
|
||||
case Precision.FP8:
|
||||
if tensor.dtype in dtypes_to_fp8:
|
||||
return tensor.to(torch.float8_e4m3fn)
|
||||
log.error(f"Cannot convert {tensor.dtype} to fp8")
|
||||
return tensor
|
||||
case Precision.FP16:
|
||||
if tensor.dtype in dtypes_to_fp16:
|
||||
return tensor.half()
|
||||
log.error(f"Cannot convert {tensor.dtype} to f16")
|
||||
return tensor
|
||||
case Precision.BF16:
|
||||
if tensor.dtype in dtypes_to_bf16:
|
||||
return tensor.bfloat16()
|
||||
log.error(f"Cannot convert {tensor.dtype} to bf16")
|
||||
return tensor
|
||||
case Precision.FULL | Precision.FP32:
|
||||
return tensor
|
||||
|
||||
def is_sdxl_model(self, clip: dict[str, torch.Tensor] | None):
|
||||
if clip:
|
||||
return (any(k.startswith("conditioner.embedders") for k in clip),)
|
||||
return False
|
||||
|
||||
def has_ema(self, unet: dict[str, torch.Tensor]):
|
||||
return any(k.startswith("model_ema") for k in unet)
|
||||
|
||||
def fix_clip(self, clip: dict[str, torch.Tensor] | None):
|
||||
if self.is_sdxl_model(clip):
|
||||
log.warn("[fix clip] SDXL not supported")
|
||||
return
|
||||
|
||||
if clip is None:
|
||||
return
|
||||
|
||||
position_id_key = (
|
||||
"cond_stage_model.transformer.text_model.embeddings.position_ids"
|
||||
)
|
||||
if position_id_key in clip:
|
||||
correct = torch.Tensor([list(range(77))]).to(torch.int64)
|
||||
now = clip[position_id_key].to(torch.int64)
|
||||
|
||||
broken = correct.ne(now)
|
||||
broken = [i for i in range(77) if broken[0][i]]
|
||||
|
||||
if len(broken) != 0:
|
||||
clip[position_id_key] = correct
|
||||
log.info(f"[Converter] Fixed broken clip\n{broken}")
|
||||
else:
|
||||
log.info(
|
||||
"[Converter] Clip in this model is fine, skip fixing..."
|
||||
)
|
||||
|
||||
else:
|
||||
log.info("[Converter] Missing position id in model, try fixing...")
|
||||
clip[position_id_key] = torch.Tensor([list(range(77))]).to(
|
||||
torch.int64
|
||||
)
|
||||
return clip
|
||||
|
||||
def get_dicts(self, unet, clip, vae):
|
||||
clip_sd = clip.get_sd()
|
||||
state_dict = unet.model.state_dict_for_saving(
|
||||
clip_sd, vae.get_sd(), None
|
||||
)
|
||||
|
||||
unet = {
|
||||
k: v
|
||||
for k, v in state_dict.items()
|
||||
if k.startswith("model.diffusion_model")
|
||||
}
|
||||
clip = {
|
||||
k: v
|
||||
for k, v in state_dict.items()
|
||||
if k.startswith("cond_stage_model")
|
||||
or k.startswith("conditioner.embedders")
|
||||
}
|
||||
vae = {
|
||||
k: v
|
||||
for k, v in state_dict.items()
|
||||
if k.startswith("first_stage_model")
|
||||
}
|
||||
|
||||
other = {
|
||||
k: v
|
||||
for k, v in state_dict.items()
|
||||
if k not in unet and k not in vae and k not in clip
|
||||
}
|
||||
|
||||
return (unet, clip, vae, other)
|
||||
|
||||
def do_remove_junk(self, tensors: dict[str, dict[str, torch.Tensor]]):
|
||||
need_delete: list[str] = []
|
||||
for layer in tensors:
|
||||
for key in layer:
|
||||
for jk in PRUNE_DATA["known_junk_prefix"]:
|
||||
if key.startswith(jk):
|
||||
need_delete.append(".".join([layer, key]))
|
||||
|
||||
for k in need_delete:
|
||||
log.info(f"Removing junk data: {k}")
|
||||
del tensors[k]
|
||||
|
||||
return tensors
|
||||
|
||||
def prune(
|
||||
self,
|
||||
*,
|
||||
save_separately: bool,
|
||||
save_folder: str,
|
||||
fix_clip: bool,
|
||||
remove_junk: bool,
|
||||
ema_mode: str,
|
||||
precision_unet: Precision,
|
||||
precision_clip: Precision,
|
||||
precision_vae: Precision,
|
||||
operation_unet: str,
|
||||
operation_clip: str,
|
||||
operation_vae: str,
|
||||
unet: dict[str, torch.Tensor] | None = None,
|
||||
clip: dict[str, torch.Tensor] | None = None,
|
||||
vae: dict[str, torch.Tensor] | None = None,
|
||||
):
|
||||
operation = {
|
||||
"unet": Operation.from_str(operation_unet),
|
||||
"clip": Operation.from_str(operation_clip),
|
||||
"vae": Operation.from_str(operation_vae),
|
||||
}
|
||||
precision = {
|
||||
"unet": Precision.from_str(precision_unet),
|
||||
"clip": Precision.from_str(precision_clip),
|
||||
"vae": Precision.from_str(precision_vae),
|
||||
}
|
||||
|
||||
unet, clip, vae, _other = self.get_dicts(unet, clip, vae)
|
||||
|
||||
out_dir = Path(save_folder)
|
||||
folder = out_dir.parent
|
||||
if not out_dir.is_absolute():
|
||||
folder = (comfy_out_dir / save_folder).parent
|
||||
|
||||
if not folder.exists():
|
||||
if folder.parent.exists():
|
||||
folder.mkdir()
|
||||
else:
|
||||
raise FileNotFoundError(
|
||||
f"Folder {folder.parent} does not exist"
|
||||
)
|
||||
|
||||
name = out_dir.name
|
||||
save_name = f"{name}-{precision_unet}"
|
||||
if ema_mode != "disabled":
|
||||
save_name += f"-{ema_mode}"
|
||||
if fix_clip:
|
||||
save_name += "-clip-fix"
|
||||
|
||||
if (
|
||||
any(o == Operation.CONVERT for o in operation.values())
|
||||
and any(p == Precision.FP8 for p in precision.values())
|
||||
and torch.__version__ < "2.1.0"
|
||||
):
|
||||
raise NotImplementedError(
|
||||
"PyTorch 2.1.0 or newer is required for fp8 conversion"
|
||||
)
|
||||
|
||||
if not self.is_sdxl_model(clip):
|
||||
for part in [unet, vae, clip]:
|
||||
if part:
|
||||
nai_keys = PRUNE_DATA["nai_keys"]
|
||||
for k in list(part.keys()):
|
||||
for r in nai_keys:
|
||||
if isinstance(k, str) and k.startswith(r):
|
||||
new_key = k.replace(r, nai_keys[r])
|
||||
part[new_key] = part[k]
|
||||
del part[k]
|
||||
log.info(
|
||||
f"[Converter] Fixed novelai error key {k}"
|
||||
)
|
||||
break
|
||||
|
||||
if fix_clip:
|
||||
clip = self.fix_clip(clip)
|
||||
|
||||
ok: dict[str, dict[str, torch.Tensor]] = {
|
||||
"unet": {},
|
||||
"clip": {},
|
||||
"vae": {},
|
||||
}
|
||||
|
||||
def _hf(part: str, wk: str, t: torch.Tensor):
|
||||
if not isinstance(t, torch.Tensor):
|
||||
log.debug("Not a torch tensor, skipping key")
|
||||
return
|
||||
|
||||
log.debug(f"Operation {operation[part]}")
|
||||
if operation[part] == Operation.CONVERT:
|
||||
ok[part][wk] = self.convert_precision(
|
||||
t, precision[part]
|
||||
) # conv_func(t)
|
||||
elif operation[part] == Operation.COPY:
|
||||
ok[part][wk] = t
|
||||
elif operation[part] == Operation.DELETE:
|
||||
return
|
||||
|
||||
log.info("[Converter] Converting model...")
|
||||
|
||||
for part_name, part in zip(
|
||||
["unet", "vae", "clip", "other"],
|
||||
[unet, vae, clip],
|
||||
strict=False,
|
||||
):
|
||||
if part:
|
||||
match ema_mode:
|
||||
case "remove_ema":
|
||||
for k, v in tqdm.tqdm(part.items()):
|
||||
if "model_ema." not in k:
|
||||
_hf(part_name, k, v)
|
||||
case "ema_only":
|
||||
if not self.has_ema(part):
|
||||
log.warn("No EMA to extract")
|
||||
return
|
||||
for k in tqdm.tqdm(part):
|
||||
ema_k = "___"
|
||||
try:
|
||||
ema_k = "model_ema." + k[6:].replace(".", "")
|
||||
except Exception:
|
||||
pass
|
||||
if ema_k in part:
|
||||
_hf(part_name, k, part[ema_k])
|
||||
elif not k.startswith("model_ema.") or k in [
|
||||
"model_ema.num_updates",
|
||||
"model_ema.decay",
|
||||
]:
|
||||
_hf(part_name, k, part[k])
|
||||
case "disabled" | _:
|
||||
for k, v in tqdm.tqdm(part.items()):
|
||||
_hf(part_name, k, v)
|
||||
|
||||
if save_separately:
|
||||
if remove_junk:
|
||||
ok = self.do_remove_junk(ok)
|
||||
|
||||
flat_ok = {
|
||||
k: v
|
||||
for _, subdict in ok.items()
|
||||
for k, v in subdict.items()
|
||||
}
|
||||
save_path = (
|
||||
folder / f"{part_name}-{save_name}.safetensors"
|
||||
).as_posix()
|
||||
safetensors.torch.save_file(flat_ok, save_path)
|
||||
ok: dict[str, dict[str, torch.Tensor]] = {
|
||||
"unet": {},
|
||||
"clip": {},
|
||||
"vae": {},
|
||||
}
|
||||
|
||||
if save_separately:
|
||||
return ()
|
||||
|
||||
if remove_junk:
|
||||
ok = self.do_remove_junk(ok)
|
||||
|
||||
flat_ok = {
|
||||
k: v for _, subdict in ok.items() for k, v in subdict.items()
|
||||
}
|
||||
|
||||
try:
|
||||
safetensors.torch.save_file(
|
||||
flat_ok, (folder / f"{save_name}.safetensors").as_posix()
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(e)
|
||||
|
||||
return ()
|
||||
|
||||
|
||||
__nodes__ = [MTB_ModelPruner]
|
||||
@@ -0,0 +1,85 @@
|
||||
import qrcode
|
||||
import torch
|
||||
from PIL import Image
|
||||
|
||||
from ..log import log
|
||||
from ..utils import pil2tensor
|
||||
|
||||
|
||||
class MTB_QrCode:
|
||||
"""Basic QR Code generator."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"url": ("STRING", {"default": "https://www.github.com"}),
|
||||
"width": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{"default": 256, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"error_correct": (("L", "M", "Q", "H"), {"default": "L"}),
|
||||
"box_size": (
|
||||
"INT",
|
||||
{"default": 10, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"border": (
|
||||
"INT",
|
||||
{"default": 4, "max": 8096, "min": 0, "step": 1},
|
||||
),
|
||||
"invert": (("BOOLEAN",), {"default": False}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "do_qr"
|
||||
CATEGORY = "mtb/generate"
|
||||
|
||||
def do_qr(
|
||||
self,
|
||||
*,
|
||||
url: str,
|
||||
width: int,
|
||||
height: int,
|
||||
error_correct: str,
|
||||
box_size: int,
|
||||
border: int,
|
||||
invert: bool,
|
||||
) -> tuple[torch.Tensor]:
|
||||
log.warning(
|
||||
"This node will soon be deprecated, there are much better alternatives like https://github.com/coreyryanhanson/comfy-qr"
|
||||
)
|
||||
if error_correct == "L" or error_correct not in ["M", "Q", "H"]:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_L
|
||||
elif error_correct == "M":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_M
|
||||
elif error_correct == "Q":
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_Q
|
||||
else:
|
||||
error_correct = qrcode.constants.ERROR_CORRECT_H
|
||||
|
||||
qr = qrcode.QRCode(
|
||||
version=1,
|
||||
error_correction=error_correct,
|
||||
box_size=box_size,
|
||||
border=border,
|
||||
)
|
||||
qr.add_data(url)
|
||||
qr.make(fit=True)
|
||||
|
||||
back_color = (255, 255, 255) if invert else (0, 0, 0)
|
||||
fill_color = (0, 0, 0) if invert else (255, 255, 255)
|
||||
|
||||
code = qr.make_image(back_color=back_color, fill_color=fill_color)
|
||||
|
||||
# that we now resize without filtering
|
||||
code = code.resize((width, height), Image.NEAREST)
|
||||
|
||||
return (pil2tensor(code),)
|
||||
|
||||
|
||||
__nodes__ = [MTB_QrCode]
|
||||
+42
-15
@@ -1,15 +1,16 @@
|
||||
from math import ceil, sqrt
|
||||
from typing import cast
|
||||
|
||||
import torch
|
||||
import torchvision.transforms.functional as TF
|
||||
from ..utils import log, hex_to_rgb, tensor2pil, pil2tensor
|
||||
from math import sqrt, ceil
|
||||
from typing import cast
|
||||
from PIL import Image
|
||||
|
||||
from ..utils import hex_to_rgb, log, pil2tensor, tensor2pil
|
||||
|
||||
class TransformImage:
|
||||
|
||||
class MTB_TransformImage:
|
||||
"""Save torch tensors (image, mask or latent) to disk, useful to debug things outside comfy
|
||||
|
||||
|
||||
it return a tensor representing the transformed images with the same shape as the input tensor
|
||||
"""
|
||||
|
||||
@@ -18,10 +19,22 @@ class TransformImage:
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"x": ("FLOAT", {"default": 0, "step": 1, "min": -4096, "max": 4096}),
|
||||
"y": ("FLOAT", {"default": 0, "step": 1, "min": -4096, "max": 4096}),
|
||||
"zoom": ("FLOAT", {"default": 1.0, "min": 0.001, "step": 0.01}),
|
||||
"angle": ("FLOAT", {"default": 0, "step": 1, "min": -360, "max": 360}),
|
||||
"x": (
|
||||
"FLOAT",
|
||||
{"default": 0, "step": 1, "min": -4096, "max": 4096},
|
||||
),
|
||||
"y": (
|
||||
"FLOAT",
|
||||
{"default": 0, "step": 1, "min": -4096, "max": 4096},
|
||||
),
|
||||
"zoom": (
|
||||
"FLOAT",
|
||||
{"default": 1.0, "min": 0.001, "step": 0.01},
|
||||
),
|
||||
"angle": (
|
||||
"FLOAT",
|
||||
{"default": 0, "step": 1, "min": -360, "max": 360},
|
||||
),
|
||||
"shear": (
|
||||
"FLOAT",
|
||||
{"default": 0, "step": 1, "min": -4096, "max": 4096},
|
||||
@@ -53,14 +66,21 @@ class TransformImage:
|
||||
y = int(y)
|
||||
angle = int(angle)
|
||||
|
||||
log.debug(f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}")
|
||||
log.debug(
|
||||
f"Zoom: {zoom} | x: {x}, y: {y}, angle: {angle}, shear: {shear}"
|
||||
)
|
||||
|
||||
if image.size(0) == 0:
|
||||
return (torch.zeros(0),)
|
||||
transformed_images = []
|
||||
frames_count, frame_height, frame_width, frame_channel_count = image.size()
|
||||
frames_count, frame_height, frame_width, frame_channel_count = (
|
||||
image.size()
|
||||
)
|
||||
|
||||
new_height, new_width = int(frame_height * zoom), int(frame_width * zoom)
|
||||
new_height, new_width = (
|
||||
int(frame_height * zoom),
|
||||
int(frame_width * zoom),
|
||||
)
|
||||
|
||||
log.debug(f"New height: {new_height}, New width: {new_width}")
|
||||
|
||||
@@ -74,7 +94,12 @@ class TransformImage:
|
||||
pw += abs(max_padding)
|
||||
ph += abs(max_padding)
|
||||
|
||||
padding = [max(0, pw + x), max(0, ph + y), max(0, pw - x), max(0, ph - y)]
|
||||
padding = [
|
||||
max(0, pw + x),
|
||||
max(0, ph + y),
|
||||
max(0, pw - x),
|
||||
max(0, ph - y),
|
||||
]
|
||||
|
||||
constant_color = hex_to_rgb(constant_color)
|
||||
log.debug(f"Fill Tuple: {constant_color}")
|
||||
@@ -89,7 +114,9 @@ class TransformImage:
|
||||
|
||||
img = cast(
|
||||
Image.Image,
|
||||
TF.affine(img, angle=angle, scale=zoom, translate=[x, y], shear=shear),
|
||||
TF.affine(
|
||||
img, angle=angle, scale=zoom, translate=[x, y], shear=shear
|
||||
),
|
||||
)
|
||||
|
||||
left = abs(padding[0])
|
||||
@@ -107,4 +134,4 @@ class TransformImage:
|
||||
return (pil2tensor(transformed_images),)
|
||||
|
||||
|
||||
__nodes__ = [TransformImage]
|
||||
__nodes__ = [MTB_TransformImage]
|
||||
|
||||
+99
-25
@@ -1,4 +1,7 @@
|
||||
import hashlib, json, os, re
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import folder_paths
|
||||
@@ -10,11 +13,12 @@ from PIL.PngImagePlugin import PngInfo
|
||||
from ..log import log
|
||||
|
||||
|
||||
class LoadImageSequence:
|
||||
class MTB_LoadImageSequence:
|
||||
"""Load an image sequence from a folder. The current frame is used to determine which image to load.
|
||||
|
||||
Usually used in conjunction with the `Primitive` node set to increment to load a sequence of images from a folder.
|
||||
Use -1 to load all matching frames as a batch.
|
||||
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
@@ -26,7 +30,10 @@ class LoadImageSequence:
|
||||
"INT",
|
||||
{"default": 0, "min": -1, "max": 9999999},
|
||||
),
|
||||
}
|
||||
},
|
||||
"optional": {
|
||||
"range": ("STRING", {"default": ""}),
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "mtb/IO"
|
||||
@@ -35,17 +42,28 @@ class LoadImageSequence:
|
||||
"IMAGE",
|
||||
"MASK",
|
||||
"INT",
|
||||
"INT",
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"image",
|
||||
"mask",
|
||||
"current_frame",
|
||||
"total_frames",
|
||||
)
|
||||
|
||||
def load_image(self, path=None, current_frame=0):
|
||||
def load_image(self, path=None, current_frame=0, range=""):
|
||||
load_all = current_frame == -1
|
||||
total_frames = 1
|
||||
|
||||
if load_all:
|
||||
if range:
|
||||
frames = self.get_frames_from_range(path, range)
|
||||
imgs, masks = zip(*(img_from_path(frame) for frame in frames))
|
||||
out_img = torch.cat(imgs, dim=0)
|
||||
out_mask = torch.cat(masks, dim=0)
|
||||
total_frames = len(imgs)
|
||||
return (out_img, out_mask, -1, total_frames)
|
||||
|
||||
elif load_all:
|
||||
log.debug(f"Loading all frames from {path}")
|
||||
frames = resolve_all_frames(path)
|
||||
log.debug(f"Found {len(frames)} frames")
|
||||
@@ -53,33 +71,72 @@ class LoadImageSequence:
|
||||
imgs = []
|
||||
masks = []
|
||||
|
||||
for frame in frames:
|
||||
img, mask = img_from_path(frame)
|
||||
imgs.append(img)
|
||||
masks.append(mask)
|
||||
imgs, masks = zip(*(img_from_path(frame) for frame in frames))
|
||||
|
||||
out_img = torch.cat(imgs, dim=0)
|
||||
out_mask = torch.cat(masks, dim=0)
|
||||
total_frames = len(imgs)
|
||||
|
||||
return (
|
||||
out_img,
|
||||
out_mask,
|
||||
)
|
||||
return (out_img, out_mask, -1, total_frames)
|
||||
|
||||
log.debug(f"Loading image: {path}, {current_frame}")
|
||||
print(f"Loading image: {path}, {current_frame}")
|
||||
resolved_path = resolve_path(path, current_frame)
|
||||
image_path = folder_paths.get_annotated_filepath(resolved_path)
|
||||
image, mask = img_from_path(image_path)
|
||||
return (
|
||||
image,
|
||||
mask,
|
||||
current_frame,
|
||||
)
|
||||
return (image, mask, current_frame, total_frames)
|
||||
|
||||
def get_frames_from_range(self, path, range_str):
|
||||
try:
|
||||
start, end = map(int, range_str.split("-"))
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
f"Invalid range format: {range_str}. Expected format is 'start-end'."
|
||||
)
|
||||
|
||||
frames = resolve_all_frames(path)
|
||||
total_frames = len(frames)
|
||||
|
||||
if start < 0 or end >= total_frames:
|
||||
raise ValueError(
|
||||
f"Range {range_str} is out of bounds. Total frames available: {total_frames}"
|
||||
)
|
||||
|
||||
if "#" in path:
|
||||
frame_regex = re.escape(path).replace(r"\#", r"(\d+)")
|
||||
frame_number_regex = re.compile(frame_regex)
|
||||
|
||||
matching_frames = []
|
||||
for frame in frames:
|
||||
match = frame_number_regex.search(frame)
|
||||
|
||||
if match:
|
||||
frame_number = int(match.group(1))
|
||||
if start <= frame_number <= end:
|
||||
matching_frames.append(frame)
|
||||
|
||||
return matching_frames
|
||||
else:
|
||||
log.warning(
|
||||
f"Wildcard pattern or directory will use indexes instead of frame numbers for : {path}"
|
||||
)
|
||||
|
||||
selected_frames = frames[start : end + 1]
|
||||
|
||||
return selected_frames
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(path="", current_frame=0):
|
||||
def IS_CHANGED(path="", current_frame=0, range=""):
|
||||
print(f"Checking if changed: {path}, {current_frame}")
|
||||
if range or current_frame == -1:
|
||||
resolved_paths = resolve_all_frames(path)
|
||||
timestamps = [
|
||||
os.path.getmtime(folder_paths.get_annotated_filepath(p))
|
||||
for p in resolved_paths
|
||||
]
|
||||
combined_hash = hashlib.sha256(
|
||||
"".join(map(str, timestamps)).encode()
|
||||
)
|
||||
return combined_hash.hexdigest()
|
||||
resolved_path = resolve_path(path, current_frame)
|
||||
image_path = folder_paths.get_annotated_filepath(resolved_path)
|
||||
if os.path.exists(image_path):
|
||||
@@ -119,11 +176,28 @@ def img_from_path(path):
|
||||
)
|
||||
|
||||
|
||||
def resolve_all_frames(pattern):
|
||||
def resolve_all_frames(path: str):
|
||||
frames: list[str] = []
|
||||
if "#" not in path:
|
||||
pth = Path(path)
|
||||
if pth.is_dir():
|
||||
for f in pth.iterdir():
|
||||
if f.suffix in [".jpg", ".png"]:
|
||||
frames.append(f.as_posix())
|
||||
elif "*" in path:
|
||||
frames = glob.glob(path)
|
||||
else:
|
||||
raise ValueError(
|
||||
"The path doesn't contain a # or a * or is not a directory"
|
||||
)
|
||||
frames.sort()
|
||||
|
||||
return frames
|
||||
|
||||
pattern = path
|
||||
folder_path, file_pattern = os.path.split(pattern)
|
||||
|
||||
log.debug(f"Resolving all frames in {folder_path}")
|
||||
frames = []
|
||||
hash_count = file_pattern.count("#")
|
||||
frame_pattern = re.sub(r"#+", "*", file_pattern)
|
||||
|
||||
@@ -155,7 +229,7 @@ def resolve_path(path, frame):
|
||||
return re.sub("#+", padded_number, path)
|
||||
|
||||
|
||||
class SaveImageSequence:
|
||||
class MTB_SaveImageSequence:
|
||||
"""Save an image sequence to a folder. The current frame is used to determine which image to save.
|
||||
|
||||
This is merely a wrapper around the `save_images` function with formatting for the output folder and filename.
|
||||
@@ -251,6 +325,6 @@ class SaveImageSequence:
|
||||
|
||||
|
||||
__nodes__ = [
|
||||
LoadImageSequence,
|
||||
SaveImageSequence,
|
||||
MTB_LoadImageSequence,
|
||||
MTB_SaveImageSequence,
|
||||
]
|
||||
|
||||
@@ -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]
|
||||
+179
-114
@@ -1,114 +1,179 @@
|
||||
[tool.poetry]
|
||||
name = "comfy-mtb"
|
||||
version = "0.4.0"
|
||||
description = "Animation oriented nodes pack for ComfyUI."
|
||||
license = "MIT"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/melMass/comfy_mtb"
|
||||
authors = ["Mel Massadian"]
|
||||
packages = [{ include = "comfy-mtb" }]
|
||||
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",
|
||||
]
|
||||
|
||||
[tool.poetry.urls]
|
||||
"Bug Tracker" = "https://github.com/melMass/comfy_mtb/issues"
|
||||
"Changelog" = "https://github.com/melMass/comfy_mtb/releases"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = "^3.10"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
black = { extras = ["jupyter"], version = "^23.7.0" }
|
||||
codespell = "^2.2.5"
|
||||
mypy = "^1.5.1"
|
||||
pre-commit = "^3.3.3"
|
||||
pytest = "^7.4.0"
|
||||
pytest-cov = "^4.1.0"
|
||||
pytest-random-order = "^1.1.0"
|
||||
ruff = "^0.0.285"
|
||||
|
||||
[tool.poetry.group.docs]
|
||||
optional = true
|
||||
|
||||
[tool.poetry.group.docs.dependencies]
|
||||
docutils = "0.17.1"
|
||||
jupyter-book = "^0.15.1"
|
||||
sphinx-autobuild = "^2021.3.14"
|
||||
|
||||
[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
|
||||
|
||||
[tool.poetry-version-plugin]
|
||||
source = "git-tag"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
[build-system]
|
||||
requires = ["setuptools", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "comfy-mtb"
|
||||
version = "0.1.6"
|
||||
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.6"
|
||||
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
|
||||
|
||||
Vendored
+79
-5
@@ -1,9 +1,28 @@
|
||||
// Some manual types I use to facilitate developing on top of
|
||||
// Comfy's Litegraph implementation.
|
||||
|
||||
import type { ContextMenuItem, LGraphNode } from '../web/types/litegraph'
|
||||
import type {
|
||||
ContextMenuItem,
|
||||
LGraphNode,
|
||||
IWidget,
|
||||
LGraph,
|
||||
} from '../../../web/types/litegraph'
|
||||
|
||||
export type { ContextMenuItem } from '../web/types/litegraph'
|
||||
export type {
|
||||
ComfyExtension,
|
||||
ComfyObjectInfo,
|
||||
ComfyObjectInfoConfig,
|
||||
} from '../../../web/types/comfy'
|
||||
|
||||
export type {
|
||||
ContextMenuItem,
|
||||
IWidget,
|
||||
LLink,
|
||||
INodeInputSlot,
|
||||
INodeOutputSlot,
|
||||
} from '../../../web/types/litegraph'
|
||||
|
||||
export type VectorWidget = IWidget<number[], { default: number[] }>
|
||||
export interface NodeData {
|
||||
category: str
|
||||
description: str
|
||||
@@ -16,18 +35,72 @@ export interface NodeData {
|
||||
output_node: boolean
|
||||
}
|
||||
|
||||
export interface ExtendedLGraphNode {
|
||||
export interface ComfyDialog {
|
||||
element: Element
|
||||
close: () => void
|
||||
show: (html: str) => void
|
||||
}
|
||||
|
||||
export interface ComfySettingsDialog {
|
||||
app: ComfyApp
|
||||
element: Element
|
||||
settingsValues: Record<string, unknown>
|
||||
settingsLookup: Record<string, unknown>
|
||||
load: () => Promise<void>
|
||||
setSettingValueAsync: (id: string, value: unknown) => Promise<void>
|
||||
}
|
||||
|
||||
export interface ComfyUI {
|
||||
app: ComfyApp
|
||||
dialog: ComfyDialog
|
||||
settings: ComfySettingsDialog
|
||||
autoQueueMode: 'instant' | 'change'
|
||||
batchCount: number
|
||||
lastQueueSize: number
|
||||
graphHasChanged: boolean
|
||||
queue: ComfyList
|
||||
history: ComfyList
|
||||
}
|
||||
|
||||
/**Very incomplete Comfy App definition*/
|
||||
interface ComfyApp {
|
||||
graph: LGraph
|
||||
queueItems: { number: number; batchCount: number }[]
|
||||
processingQueue: boolean
|
||||
ui: ComfyUI
|
||||
extensions: ComfyExtension[]
|
||||
nodeOutputs: Record<string, unknown>
|
||||
nodePreviewImages: Record<string, Image>
|
||||
shiftDown: boolean
|
||||
isImageNode: (node: LGraphNodeExtended) => boolean
|
||||
queuePrompt: (number: number, batchCount: number) => Promise<void>
|
||||
/** Loads workflow data from the specified file*/
|
||||
handleFile: (file: File) => Promise<void>
|
||||
}
|
||||
|
||||
export type { ComfyApp as App }
|
||||
|
||||
export interface LGraphNodeExtension {
|
||||
addDOMWidget: (
|
||||
name: string,
|
||||
type: string,
|
||||
element: Element,
|
||||
options: Record<string, unknown>,
|
||||
) => IWidget
|
||||
onNodeCreated: () => void
|
||||
getExtraMenuOptions: () => ContextMenuItem[]
|
||||
prototype: LGraphNodeExtended
|
||||
}
|
||||
|
||||
export type LGraphNodeExtended = LGraphNode & LGraphNodeExtension
|
||||
|
||||
export interface NodeType /*extends LGraphNode*/ {
|
||||
category: str
|
||||
comfyClass: str
|
||||
length: 0
|
||||
name: str
|
||||
nodeData: NodeData
|
||||
prototype: LGraphNode & ExtendedLGraphNode
|
||||
prototype: LGraphNodeExtended
|
||||
title: str
|
||||
type: str
|
||||
}
|
||||
@@ -37,13 +110,14 @@ export interface NodeInput {
|
||||
}
|
||||
|
||||
// NOTE: for prototype overriding
|
||||
export type OnDrawWidgetParams = Parameters<IWidget['draw']>
|
||||
export type OnDrawForegroundParams = Parameters<LGraphNode['onDrawForeground']>
|
||||
export type OnMouseDownParams = Parameters<LGraphNode['onMouseDown']>
|
||||
export type OnConnectionsChangeParams = Parameters<
|
||||
LGraphNode['onConnectionsChange']
|
||||
>
|
||||
export type OnNodeCreatedParams = Parameters<
|
||||
ExtendedLGraphNode['onNodeCreated']
|
||||
LGraphNodeExtension['onNodeCreated']
|
||||
>
|
||||
|
||||
export interface DocumentationOptions {
|
||||
|
||||
+10
-1
@@ -5,5 +5,14 @@
|
||||
* @typedef {import("./shared.d.ts").OnDrawForegroundParams} OnDrawForegroundParams
|
||||
* @typedef {import("./shared.d.ts").OnMouseDownParams} OnMouseDownParams
|
||||
* @typedef {import("./shared.d.ts").OnConnectionsChangeParams} OnConnectionsChangeParams
|
||||
* @typedef {import("./shared.d.ts").getExtraMenuOptionsParams} getExtraMenuOptionsParams
|
||||
* @typedef {import("./shared.d.ts").ContextMenuItem} ContextMenuItem
|
||||
* @typedef {import("./shared.d.ts").IWidget} IWidget
|
||||
* @typedef {import("./shared.d.ts").VectorWidget} VectorWidget
|
||||
* @typedef {import("./shared.d.ts").LGraphNodeExtended} LGraphNode
|
||||
* @typedef {import("./shared.d.ts").LLink} LLink
|
||||
* @typedef {import("./shared.d.ts").App} App
|
||||
* @typedef {import("./shared.d.ts").OnDrawWidgetParams} OnDrawWidgetParams
|
||||
* @typedef {import("./shared.d.ts").INodeInputSlot} INodeInputSlot
|
||||
* @typedef {import("./shared.d.ts").INodeOutputSlot} INodeOutputSlot
|
||||
*/
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import contextlib
|
||||
import functools
|
||||
import importlib
|
||||
import math
|
||||
import os
|
||||
import shlex
|
||||
@@ -8,11 +9,14 @@ import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import uuid
|
||||
from collections.abc import Callable, Sequence
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
from typing import TypeVar
|
||||
|
||||
import folder_paths
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
import requests
|
||||
import torch
|
||||
from PIL import Image
|
||||
@@ -208,12 +212,120 @@ def get_server_info():
|
||||
|
||||
|
||||
# region MISC Utilities
|
||||
|
||||
|
||||
# TODO: use mtb.core directly instead of copying parts here
|
||||
T = TypeVar("T", bound="StringConvertibleEnum")
|
||||
|
||||
|
||||
class StringConvertibleEnum(Enum):
|
||||
"""Base class for enums with utility methods for string conversion and member listing."""
|
||||
|
||||
@classmethod
|
||||
def from_str(cls: type[T], label: str | T) -> T:
|
||||
"""
|
||||
Convert a string to the corresponding enum value (case sensitive).
|
||||
|
||||
Args:
|
||||
label (Union[str, T]): The string or enum value to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
T: The corresponding enum value.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError: If the label does not correspond to any enum member.
|
||||
"""
|
||||
if isinstance(label, cls):
|
||||
return label
|
||||
if isinstance(label, str):
|
||||
# from key
|
||||
if label in cls.__members__:
|
||||
return cls[label]
|
||||
|
||||
for member in cls:
|
||||
if member.value == label:
|
||||
return member
|
||||
|
||||
raise ValueError(
|
||||
f"Unknown label: '{label}'. Valid members: {list(cls.__members__.keys())}, "
|
||||
f"valid values: {cls.list_members()}"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def to_str(cls: type[T], enum_value: T) -> str:
|
||||
"""
|
||||
Convert an enum value to its string representation.
|
||||
|
||||
Args:
|
||||
enum_value (T): The enum value to convert.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str: The string representation of the enum value.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError: If the enum value is invalid.
|
||||
"""
|
||||
if isinstance(enum_value, cls):
|
||||
return enum_value.value
|
||||
raise ValueError(f"Invalid Enum: {enum_value}")
|
||||
|
||||
@classmethod
|
||||
def list_members(cls: type[T]) -> list[str]:
|
||||
"""
|
||||
Return a list of string representations of all enum members.
|
||||
|
||||
Returns
|
||||
-------
|
||||
List[str]: List of all enum member values.
|
||||
"""
|
||||
return [enum.value for enum in cls]
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""
|
||||
Returns the string representation of the enum value.
|
||||
|
||||
Returns
|
||||
-------
|
||||
str: The string representation of the enum value.
|
||||
"""
|
||||
return self.value
|
||||
|
||||
|
||||
class Precision(StringConvertibleEnum):
|
||||
FULL = "full"
|
||||
FP32 = "fp32"
|
||||
FP16 = "fp16"
|
||||
BF16 = "bf16"
|
||||
FP8 = "fp8"
|
||||
|
||||
def to_dtype(self):
|
||||
match self:
|
||||
case Precision.FP32 | Precision.FULL:
|
||||
return torch.float32
|
||||
case Precision.FP16:
|
||||
return torch.float16
|
||||
case Precision.BF16:
|
||||
return torch.bfloat16
|
||||
case Precision.FP8:
|
||||
return torch.float8_e4m3fn
|
||||
|
||||
|
||||
class Operation(StringConvertibleEnum):
|
||||
COPY = "copy"
|
||||
CONVERT = "convert"
|
||||
DELETE = "delete"
|
||||
|
||||
|
||||
def backup_file(
|
||||
fp: Path,
|
||||
target: Optional[Path] = None,
|
||||
target: Path | None = None,
|
||||
backup_dir: str = ".bak",
|
||||
suffix: Optional[str] = None,
|
||||
prefix: Optional[str] = None,
|
||||
suffix: str | None = None,
|
||||
prefix: str | None = None,
|
||||
):
|
||||
if not fp.exists():
|
||||
raise FileNotFoundError(f"No file found at {fp}")
|
||||
@@ -315,12 +427,6 @@ def _run_command(shell_cmd, ignored_lines_start):
|
||||
print("Command executed successfully!")
|
||||
|
||||
|
||||
# todo use the requirements library
|
||||
reqs_map = {value: key for key, value in pip_map.items()}
|
||||
|
||||
import importlib
|
||||
|
||||
|
||||
def import_install(package_name):
|
||||
package_spec = reqs_map.get(package_name, package_name)
|
||||
|
||||
@@ -360,6 +466,7 @@ here = Path(__file__).parent.absolute()
|
||||
comfy_dir = Path(folder_paths.base_path)
|
||||
models_dir = Path(folder_paths.models_dir)
|
||||
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
|
||||
@@ -368,6 +475,7 @@ font_path = here / "data" / "font.ttf"
|
||||
# - Add extern folder to path
|
||||
extern_root = here / "extern"
|
||||
add_path(extern_root)
|
||||
|
||||
for pth in extern_root.iterdir():
|
||||
if pth.is_dir():
|
||||
add_path(pth)
|
||||
@@ -376,6 +484,14 @@ for pth in extern_root.iterdir():
|
||||
add_path(comfy_dir)
|
||||
add_path(comfy_dir / "custom_nodes")
|
||||
|
||||
|
||||
# TODO: use the requirements library
|
||||
reqs_map = {value: key for key, value in pip_map.items()}
|
||||
|
||||
# NOTE: store already logged warnings to only alert once.
|
||||
warned_messages: set[str] = set()
|
||||
|
||||
|
||||
PIL_FILTER_MAP = {
|
||||
"nearest": Image.Resampling.NEAREST,
|
||||
"box": Image.Resampling.BOX,
|
||||
@@ -388,52 +504,92 @@ 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
|
||||
)
|
||||
)
|
||||
]
|
||||
def to_numpy(image: torch.Tensor) -> npt.NDArray[np.uint8]:
|
||||
"""Converts a tensor to a ndarray with proper scaling and type conversion."""
|
||||
log.debug(f"Converting tensor to numpy array with shape {image.shape}")
|
||||
np_array = np.clip(255.0 * image.cpu().numpy(), 0, 255).astype(np.uint8)
|
||||
log.debug(f"Numpy array shape after conversion: {np_array.shape}")
|
||||
return np_array
|
||||
|
||||
|
||||
def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
|
||||
if isinstance(image, list):
|
||||
return torch.cat([pil2tensor(img) for img in image], dim=0)
|
||||
|
||||
return torch.from_numpy(
|
||||
np.array(image).astype(np.float32) / 255.0
|
||||
).unsqueeze(0)
|
||||
def handle_batch(
|
||||
tensor: torch.Tensor,
|
||||
func: Callable[[torch.Tensor], Image.Image | npt.NDArray[np.uint8]],
|
||||
) -> list[Image.Image] | list[npt.NDArray[np.uint8]]:
|
||||
"""Handles batch processing for a given tensor and conversion function."""
|
||||
return [func(tensor[i]) for i in range(tensor.shape[0])]
|
||||
|
||||
|
||||
def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor:
|
||||
if isinstance(img_np, list):
|
||||
return torch.cat([np2tensor(img) for img in img_np], dim=0)
|
||||
def tensor2pil(tensor: torch.Tensor) -> list[Image.Image]:
|
||||
"""Converts a batch of tensors to a list of PIL Images."""
|
||||
|
||||
return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
|
||||
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 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 pil2tensor(images: Image.Image | list[Image.Image]) -> torch.Tensor:
|
||||
"""Converts a PIL Image or a list of PIL Images to a tensor."""
|
||||
|
||||
return [
|
||||
np.clip(255.0 * tensor.cpu().numpy().squeeze(), 0, 255).astype(
|
||||
np.uint8
|
||||
)
|
||||
]
|
||||
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 pad(img, left, right, top, bottom):
|
||||
@@ -683,10 +839,11 @@ def get_model_path(fam, model=None):
|
||||
if res:
|
||||
if isinstance(res, list):
|
||||
if len(res) > 1:
|
||||
log.warning(
|
||||
f"Found multiple match, we will pick the first {res[0]}\n{res}"
|
||||
)
|
||||
res = res[0]
|
||||
warn_msg = f"Found multiple match, we will pick the last {res[-1]}\n{res}"
|
||||
if warn_msg not in warned_messages:
|
||||
log.info(warn_msg)
|
||||
warned_messages.add(warn_msg)
|
||||
res = res[-1]
|
||||
res = Path(res)
|
||||
log.debug(f"Resolved model path from folder_paths: {res}")
|
||||
else:
|
||||
@@ -720,6 +877,32 @@ def create_uv_map_tensor(width=512, height=512):
|
||||
|
||||
|
||||
# region ANIMATION Utilities
|
||||
EASINGS = [
|
||||
"Linear",
|
||||
"Sine In",
|
||||
"Sine Out",
|
||||
"Sine In/Out",
|
||||
"Quart In",
|
||||
"Quart Out",
|
||||
"Quart In/Out",
|
||||
"Cubic In",
|
||||
"Cubic Out",
|
||||
"Cubic In/Out",
|
||||
"Circ In",
|
||||
"Circ Out",
|
||||
"Circ In/Out",
|
||||
"Back In",
|
||||
"Back Out",
|
||||
"Back In/Out",
|
||||
"Elastic In",
|
||||
"Elastic Out",
|
||||
"Elastic In/Out",
|
||||
"Bounce In",
|
||||
"Bounce Out",
|
||||
"Bounce In/Out",
|
||||
]
|
||||
|
||||
|
||||
def apply_easing(value, easing_type):
|
||||
if easing_type == "Linear":
|
||||
return value
|
||||
|
||||
+659
-296
File diff suppressed because it is too large
Load Diff
+356
-122
@@ -1,62 +1,225 @@
|
||||
import { app } from '../../scripts/app.js'
|
||||
import * as shared from './comfy_shared.js'
|
||||
import { infoLogger } from './comfy_shared.js'
|
||||
import { MtbWidgets } from './mtb_widgets.js'
|
||||
import { ComfyWidgets } from '../../scripts/widgets.js'
|
||||
import * as mtb_widgets from './mtb_widgets.js'
|
||||
|
||||
export class Constant extends LiteGraph.LGraphNode {
|
||||
constructor() {
|
||||
super()
|
||||
this.uuid = shared.makeUUID()
|
||||
this.collapsable = true
|
||||
/**
|
||||
* @typedef {'number'|'string'|'vector2'|'vector3'|'vector4'|'color'} ConstantType
|
||||
* @typedef {import ("../../../web/types/litegraph.d.ts").LGraphNode} Node
|
||||
* @typedef {{x:number,y:number,z?:number,w?:number}} VectorValue
|
||||
* @typedef {}
|
||||
*
|
||||
*/
|
||||
|
||||
// this avoid serializing the node when converting to prompt
|
||||
this.isVirtualNode = true
|
||||
|
||||
this.shape = LiteGraph.BOX_SHAPE
|
||||
this.serialize_widgets = true
|
||||
|
||||
// Properties
|
||||
this.addProperty('type', 'number')
|
||||
this.addProperty('value', 0)
|
||||
|
||||
// Inputs and outputs
|
||||
this.addOutput('Output', '*')
|
||||
|
||||
// Widget for selecting the type
|
||||
this.addWidget(
|
||||
'combo',
|
||||
'Type',
|
||||
this.properties.type,
|
||||
(value) => {
|
||||
this.properties.type = value
|
||||
this.updateWidgets()
|
||||
this.updateOutputType()
|
||||
},
|
||||
{
|
||||
values: ['number', 'string', 'vector2', 'vector3', 'vector4', 'color'],
|
||||
},
|
||||
)
|
||||
|
||||
// Initialize the node
|
||||
this.updateWidgets()
|
||||
this.updateOutputType()
|
||||
/**
|
||||
* @param {number} size - The number of axis of the vector (2,3 or 4)
|
||||
* @param {number} val - The default scalar value to fill the vector with
|
||||
* @returns {VectorValue} vector
|
||||
* */
|
||||
const initVector = (size, val = 0.0) => {
|
||||
const res = {}
|
||||
for (let i = 0; i < size; i++) {
|
||||
const axis = mtb_widgets.VECTOR_AXIS[i]
|
||||
res[axis] = val
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @extends {Node}
|
||||
* @classdesc Wrapper for the python node
|
||||
*/
|
||||
export class ConstantJs {
|
||||
constructor(python_node) {
|
||||
// this.uuid = shared.makeUUID()
|
||||
const wrapper = this
|
||||
|
||||
python_node.shape = LiteGraph.BOX_SHAPE
|
||||
python_node.serialize_widgets = true
|
||||
|
||||
const onNodeCreated = python_node.prototype.onNodeCreated
|
||||
python_node.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated ? onNodeCreated.apply(this) : undefined
|
||||
|
||||
this.addProperty('type', 'number')
|
||||
this.addProperty('value', 0)
|
||||
|
||||
this.removeInput(0)
|
||||
this.removeOutput(0)
|
||||
|
||||
this.addOutput('Output', '*')
|
||||
|
||||
// bind our wrapper
|
||||
this.configure = wrapper.configure.bind(this)
|
||||
// this.applyToGraph = wrapper.applyToGraph.bind(this)
|
||||
this.updateWidgets = wrapper.updateWidgets.bind(this)
|
||||
this.convertValue = wrapper.convertValue.bind(this)
|
||||
// this.updateOutput = wrapper.updateOutput.bind(this)
|
||||
this.updateOutputType = wrapper.updateOutputType.bind(this)
|
||||
// this.updateTargetWidgets = wrapper.updateTargetWidgets.bind(this)
|
||||
|
||||
this.addWidget(
|
||||
'combo',
|
||||
'Type',
|
||||
this.properties.type,
|
||||
(value) => {
|
||||
this.properties.type = value
|
||||
this.updateWidgets()
|
||||
this.updateOutputType()
|
||||
},
|
||||
{
|
||||
values: [
|
||||
// 'number',
|
||||
'float',
|
||||
'int',
|
||||
'string',
|
||||
'vector2',
|
||||
'vector3',
|
||||
'vector4',
|
||||
'color',
|
||||
],
|
||||
},
|
||||
)
|
||||
this.updateWidgets()
|
||||
this.updateOutputType()
|
||||
|
||||
for (let n = 0; n < this.inputs.length; n++) {
|
||||
this.removeInput(n)
|
||||
}
|
||||
this.inputs = []
|
||||
return r
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// NOTE: this is called onPrompt
|
||||
applyToGraph() {
|
||||
this.updateTargetWidgets()
|
||||
}
|
||||
// applyToGraph() {
|
||||
// infoLogger('Updating values for backend')
|
||||
// this.updateTargetWidgets()
|
||||
// }
|
||||
|
||||
// NOTE: deserialization happens here
|
||||
configure(info) {
|
||||
super.configure(info)
|
||||
// super.configure(info)
|
||||
infoLogger('Configure Constant', { info, node: this })
|
||||
|
||||
this.properties.type = info.properties.type
|
||||
this.properties.value = info.properties.value
|
||||
|
||||
shared.infoLogger('Configure Constant', { info, node: this })
|
||||
this.pos = info.pos
|
||||
this.order = info.order
|
||||
|
||||
this.updateWidgets()
|
||||
this.updateOutputType()
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert the old value type to the new one, falling back to some default
|
||||
* @param {ConstantType} propType - The target type
|
||||
*/
|
||||
convertValue(propType) {
|
||||
switch (propType) {
|
||||
case 'color': {
|
||||
if (typeof this.properties.value !== 'string') {
|
||||
this.properties.value = '#ffffff'
|
||||
} else if (this.properties.value[0] !== '#') {
|
||||
this.properties.value = '#ff0000'
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'int': {
|
||||
if (typeof this.properties.value === 'object') {
|
||||
this.properties.value = Number.parseInt(this.properties.value.x)
|
||||
} else {
|
||||
this.properties.value = Number.parseInt(this.properties.value) || 0
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'float': {
|
||||
if (typeof this.properties.value === 'object') {
|
||||
this.properties.value = Number.parseFloat(this.properties.value.x)
|
||||
} else {
|
||||
this.properties.value =
|
||||
Number.parseFloat(this.properties.value) || 0.0
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'string': {
|
||||
if (typeof this.properties.value !== 'string') {
|
||||
this.properties.value = JSON.stringify(this.properties.value)
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'vector2':
|
||||
case 'vector3':
|
||||
case 'vector4': {
|
||||
const numInputs = Number.parseInt(propType.charAt(6))
|
||||
if (!this.properties.value) {
|
||||
this.properties.value = initVector(numInputs) // Array.from({ length: numInputs }, () => 0.0)
|
||||
} else if (typeof this.properties.value === 'string') {
|
||||
try {
|
||||
const parsed = JSON.parse(this.properties.value)
|
||||
const newVec = {}
|
||||
for (
|
||||
let i = 0;
|
||||
i < Object.keys(mtb_widgets.VECTOR_AXIS).length;
|
||||
i++
|
||||
) {
|
||||
const axis = mtb_widgets.VECTOR_AXIS[i]
|
||||
if (Object.keys(parsed).includes(axis)) {
|
||||
newVec[axis] = parsed[axis]
|
||||
}
|
||||
}
|
||||
this.properties.value = newVec
|
||||
} catch (e) {
|
||||
shared.errorLogger(e)
|
||||
infoLogger(
|
||||
`Couldn't parse string to vec (${this.properties.value})`,
|
||||
)
|
||||
this.properties.value = initVector(numInputs)
|
||||
}
|
||||
} else if (typeof this.properties.value === 'number') {
|
||||
const newVec = initVector(numInputs)
|
||||
newVec.x = Number.parseFloat(this.properties.value)
|
||||
this.properties.value = newVec
|
||||
}
|
||||
|
||||
if (
|
||||
typeof this.properties.value === 'object' &&
|
||||
Object.keys(this.properties.value).length !== numInputs
|
||||
) {
|
||||
const current = Object.keys(this.properties.value)
|
||||
if (current.length < numInputs) {
|
||||
infoLogger('current value smaller than target, adjusting')
|
||||
for (let index = current.length; index < numInputs; index++) {
|
||||
this.properties.value[mtb_widgets.VECTOR_AXIS[index]] = 0.0
|
||||
}
|
||||
} else {
|
||||
infoLogger('current value greater than target, adjusting')
|
||||
const newVal = {}
|
||||
for (let index = 0; index < numInputs; index++) {
|
||||
newVal[mtb_widgets.VECTOR_AXIS[index]] =
|
||||
this.properties.value[mtb_widgets.VECTOR_AXIS[index]]
|
||||
}
|
||||
this.properties.value = newVal
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all widgets but the comboBox for selecting the type
|
||||
* then recreate the appropriate widget from scratch
|
||||
*/
|
||||
updateWidgets() {
|
||||
// Remove existing widgets
|
||||
// NOTE: Remove existing widgets
|
||||
for (let i = 1; i < this.widgets.length; i++) {
|
||||
const element = this.widgets[i]
|
||||
if (element.onRemove) {
|
||||
@@ -66,28 +229,113 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
}
|
||||
|
||||
this.widgets.splice(1)
|
||||
this.widgets[0].value = this.properties.type
|
||||
|
||||
this.convertValue(this.properties.type)
|
||||
|
||||
switch (this.properties.type) {
|
||||
case 'color': {
|
||||
if (typeof this.properties.value !== 'string') {
|
||||
this.properties.value = '#ffffff'
|
||||
}
|
||||
const col_widget = this.addCustomWidget(
|
||||
MtbWidgets.COLOR('Value', this.properties.value || '#ff0000'),
|
||||
MtbWidgets.COLOR('Value', this.properties.value),
|
||||
)
|
||||
col_widget.callback = (col) => {
|
||||
this.properties.value = col
|
||||
this.updateOutput()
|
||||
// this.updateOutput()
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'number':
|
||||
case 'int': {
|
||||
const f_widget = this.addCustomWidget(
|
||||
ComfyWidgets.INT(
|
||||
this,
|
||||
'Value',
|
||||
[
|
||||
'',
|
||||
{
|
||||
default: this.properties.value,
|
||||
callback: (val) => console.log('VALUE', val),
|
||||
},
|
||||
],
|
||||
app,
|
||||
),
|
||||
)
|
||||
|
||||
f_widget.widget.callback = (val) => {
|
||||
this.properties.value = val
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
case 'float': {
|
||||
this.addWidget('number', 'Value', this.properties.value, (val) => {
|
||||
this.properties.value = val
|
||||
})
|
||||
break
|
||||
}
|
||||
case 'string': {
|
||||
mtb_widgets.addMultilineWidget(
|
||||
this,
|
||||
'Value',
|
||||
{
|
||||
defaultVal: this.properties.value,
|
||||
},
|
||||
(v) => {
|
||||
this.properties.value = v
|
||||
// this.updateOutput()
|
||||
},
|
||||
)
|
||||
break
|
||||
}
|
||||
case 'vector2':
|
||||
case 'vector3':
|
||||
case 'vector4': {
|
||||
const numInputs = Number.parseInt(this.properties.type.charAt(6))
|
||||
const node = this
|
||||
const v_widget = mtb_widgets.addVectorWidget(
|
||||
this,
|
||||
'Value',
|
||||
this.properties.value, // value
|
||||
numInputs, // vector_size
|
||||
function (v) {
|
||||
node.properties.value = v
|
||||
// this.updateOutput()
|
||||
},
|
||||
)
|
||||
break
|
||||
}
|
||||
|
||||
// NOTE: this is not reached anymore, kept for reference
|
||||
case 'number': {
|
||||
if (typeof this.properties.value !== 'number') {
|
||||
this.properties.value = 0.0
|
||||
}
|
||||
this.addWidget('number', 'Value', this.properties.value, (value) => {
|
||||
this.properties.value = value
|
||||
this.updateOutput()
|
||||
})
|
||||
const n_widget = this.addWidget(
|
||||
'number',
|
||||
'Value',
|
||||
this.properties.force_int
|
||||
? Number.parseInt(this.properties.value)
|
||||
: this.properties.value,
|
||||
(value) => {
|
||||
this.properties.value = this.properties.force_int
|
||||
? Number.parseInt(value)
|
||||
: value
|
||||
// this.updateOutput()
|
||||
},
|
||||
)
|
||||
//override the callback
|
||||
const origCallback = n_widget.callback
|
||||
const node = this
|
||||
n_widget.callback = function (val) {
|
||||
const r = origCallback ? origCallback.apply(this, [val]) : undefined
|
||||
if (node.properties.force_int) {
|
||||
// TODO: rework this, a it makes it harder to manipulate
|
||||
this.value = Number.parseInt(this.value)
|
||||
node.properties.value = Number.parseInt(this.value)
|
||||
}
|
||||
infoLogger('NEW NUMBER', this.value)
|
||||
return r
|
||||
}
|
||||
|
||||
this.addWidget(
|
||||
'toggle',
|
||||
'Convert to Integer',
|
||||
@@ -98,51 +346,6 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
},
|
||||
)
|
||||
break
|
||||
case 'string': {
|
||||
if (typeof this.properties.value !== 'string') {
|
||||
this.properties.value = `${this.properties.value}`
|
||||
}
|
||||
shared.addMultilineWidget(
|
||||
this,
|
||||
'Value',
|
||||
{
|
||||
defaultVal: this.properties.value,
|
||||
},
|
||||
(v) => {
|
||||
this.properties.value = v
|
||||
this.updateOutput()
|
||||
},
|
||||
)
|
||||
break
|
||||
}
|
||||
case 'vector2':
|
||||
case 'vector3':
|
||||
case 'vector4': {
|
||||
const numInputs = Number.parseInt(this.properties.type.charAt(6))
|
||||
|
||||
if (['string', 'number'].includes(typeof this.properties.value)) {
|
||||
this.properties.value = Array.from({ length: numInputs }, () => 0.0)
|
||||
} else if (this.properties.value.length !== numInputs) {
|
||||
if (this.properties.value.length > numInputs) {
|
||||
this.properties.value = this.properties.value.slice(0, numInputs)
|
||||
} else {
|
||||
this.properties.value = this.properties.value.concat(
|
||||
new Array(numInputs - this.properties.value.length).fill(0.0),
|
||||
)
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < numInputs; i++) {
|
||||
this.addWidget(
|
||||
'number',
|
||||
`Value ${i + 1}`,
|
||||
this.properties.value[i] || 0,
|
||||
(value) => {
|
||||
this.properties.value[i] = value
|
||||
this.updateOutput()
|
||||
},
|
||||
)
|
||||
}
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
@@ -154,20 +357,28 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
this.updateTargetWidgets([link.id])
|
||||
}
|
||||
}
|
||||
|
||||
updateOutputType() {
|
||||
const cur_type = this.outputs[0].type
|
||||
infoLogger('Updating output type')
|
||||
const rm_if_mismatch = (type) => {
|
||||
if (cur_type !== type) {
|
||||
if (this.outputs[0].type !== type) {
|
||||
for (let i = 0; i < this.outputs.length; i++) {
|
||||
this.removeOutput(i)
|
||||
}
|
||||
this.addOutput('output', type)
|
||||
// this.setOutputDataType(0, type)
|
||||
}
|
||||
}
|
||||
switch (this.properties.type) {
|
||||
case 'color':
|
||||
rm_if_mismatch('COLOR')
|
||||
break
|
||||
case 'float':
|
||||
rm_if_mismatch('FLOAT')
|
||||
break
|
||||
case 'int':
|
||||
rm_if_mismatch('INT')
|
||||
break
|
||||
case 'number':
|
||||
if (this.properties.force_int) {
|
||||
rm_if_mismatch('INT')
|
||||
@@ -178,6 +389,11 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
case 'string':
|
||||
rm_if_mismatch('STRING')
|
||||
break
|
||||
// case 'vector2':
|
||||
// case 'vector3':
|
||||
// case 'vector4':
|
||||
// rm_if_mismatch('FLOAT')
|
||||
// break
|
||||
case 'vector2':
|
||||
rm_if_mismatch('VECTOR2')
|
||||
break
|
||||
@@ -190,7 +406,7 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
default:
|
||||
break
|
||||
}
|
||||
this.updateOutput()
|
||||
// this.updateOutput()
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -198,6 +414,7 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
* since Constant is a virtual node.
|
||||
*/
|
||||
updateTargetWidgets(u_links) {
|
||||
infoLogger('Updating target widgets')
|
||||
if (!app.graph.links) return
|
||||
const links = u_links || this.outputs[0].links
|
||||
if (!links) return
|
||||
@@ -210,12 +427,16 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
const tgt_widget = tgt_node.widgets.filter(
|
||||
(w) => w.name === tgt_input.name,
|
||||
)
|
||||
if (!tgt_widget) return
|
||||
// infoLogger('Constant Target Node', tgt_node)
|
||||
// infoLogger('Constant Target Input', tgt_input)
|
||||
if (!tgt_widget || tgt_widget.length === 0) return
|
||||
|
||||
tgt_widget[0].value = this.properties.value
|
||||
}
|
||||
}
|
||||
|
||||
updateOutput() {
|
||||
infoLogger('Updating output value')
|
||||
const value = this.properties.value
|
||||
|
||||
switch (this.properties.type) {
|
||||
@@ -223,40 +444,53 @@ export class Constant extends LiteGraph.LGraphNode {
|
||||
this.setOutputData(0, value)
|
||||
break
|
||||
case 'number':
|
||||
this.setOutputData(0, Number.parseFloat(value))
|
||||
if (this.properties.force_int) {
|
||||
this.setOutputData(0, Number.parseInt(value))
|
||||
} else {
|
||||
this.setOutputData(0, Number.parseFloat(value))
|
||||
}
|
||||
break
|
||||
case 'string':
|
||||
this.setOutputData(0, value.toString())
|
||||
break
|
||||
case 'vector2':
|
||||
if (value.length >= 2) {
|
||||
this.setOutputData(0, value.slice(0, 2))
|
||||
}
|
||||
break
|
||||
case 'vector3':
|
||||
if (value.length >= 3) {
|
||||
this.setOutputData(0, value.slice(0, 3))
|
||||
}
|
||||
break
|
||||
case 'vector4':
|
||||
if (value.length >= 4) {
|
||||
this.setOutputData(0, value.slice(0, 4))
|
||||
}
|
||||
this.setOutputData(0, value)
|
||||
break
|
||||
|
||||
// case 'vector2':
|
||||
// this.setOutputData(0, value.slice(0, 2))
|
||||
// break
|
||||
// case 'vector3':
|
||||
// this.setOutputData(0, value.slice(0, 3))
|
||||
// break
|
||||
// case 'vector4':
|
||||
// this.setOutputData(0, value.slice(0, 4))
|
||||
// break
|
||||
default:
|
||||
break
|
||||
}
|
||||
|
||||
infoLogger('New Value', this.value)
|
||||
|
||||
this.updateTargetWidgets()
|
||||
}
|
||||
}
|
||||
app.registerExtension({
|
||||
name: 'mtb.constant',
|
||||
|
||||
// app.registerExtension({
|
||||
// name: 'mtb.constant',
|
||||
// registerCustomNodes() {
|
||||
// LiteGraph.registerNodeType('Constant (mtb)', Constant)
|
||||
//
|
||||
// Constant.category = 'mtb/utils'
|
||||
// Constant.title = 'Constant (mtb)'
|
||||
// },
|
||||
// })
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, _app) {
|
||||
if (nodeData.name === 'Constant (mtb)') {
|
||||
new ConstantJs(nodeType)
|
||||
}
|
||||
},
|
||||
// NOTE: old js only registration
|
||||
//
|
||||
// registerCustomNodes() {
|
||||
// LiteGraph.registerNodeType('Constant (mtb)', Constant)
|
||||
//
|
||||
// Constant.category = 'mtb/utils'
|
||||
// Constant.title = 'Constant (mtb)'
|
||||
// },
|
||||
})
|
||||
|
||||
+200
-166
@@ -1,187 +1,221 @@
|
||||
|
||||
// Reference the shared typedefs file
|
||||
/// <reference path="../types/typedefs.js" />
|
||||
import { app } from '../../scripts/app.js'
|
||||
import { infoLogger } from './comfy_shared.js'
|
||||
|
||||
function B0(t) { return (1 - t) ** 3 / 6; }
|
||||
function B1(t) { return (3 * t ** 3 - 6 * t ** 2 + 4) / 6; }
|
||||
function B2(t) { return (-3 * t ** 3 + 3 * t ** 2 + 3 * t + 1) / 6; }
|
||||
function B3(t) { return t ** 3 / 6; }
|
||||
|
||||
function B0(t) {
|
||||
return (1 - t) ** 3 / 6
|
||||
}
|
||||
function B1(t) {
|
||||
return (3 * t ** 3 - 6 * t ** 2 + 4) / 6
|
||||
}
|
||||
function B2(t) {
|
||||
return (-3 * t ** 3 + 3 * t ** 2 + 3 * t + 1) / 6
|
||||
}
|
||||
function B3(t) {
|
||||
return t ** 3 / 6
|
||||
}
|
||||
class CurveWidget {
|
||||
constructor(inputName, defaultValue) {
|
||||
this.name = inputName || "Curve";
|
||||
this._value = defaultValue || [{ x: 0, y: 0 }, { x: 1, y: 1 }];
|
||||
this.type = "FLOAT_CURVE";
|
||||
this.selectedPointIndex = null;
|
||||
this.resize
|
||||
}
|
||||
constructor(...args) {
|
||||
const [inputName, opts] = args
|
||||
|
||||
drawBSpline(ctx, width, height, posY) {
|
||||
const n = this._value.length - 1;
|
||||
const numSegments = n - 2;
|
||||
const numPoints = this._value.length;
|
||||
if (numPoints < 4) {
|
||||
this.drawLinear(ctx, width, height, posY);
|
||||
} else {
|
||||
for (let j = 0; j <= numSegments; j++) {
|
||||
for (let t = 0; t <= 1; t += 0.01) {
|
||||
let pt = this.getBSplinePoint(j, t);
|
||||
let x = pt.x * width;
|
||||
let y = posY + height - pt.y * height;
|
||||
this.name = inputName || 'Curve'
|
||||
|
||||
if (t === 0) ctx.moveTo(x, y);
|
||||
else ctx.lineTo(x, y);
|
||||
}
|
||||
}
|
||||
ctx.stroke();
|
||||
this.type = 'FLOAT_CURVE'
|
||||
this.selectedPointIndex = null
|
||||
this.options = opts
|
||||
this.value = this.value || { 0: { x: 0, y: 0 }, 1: { x: 1, y: 1 } }
|
||||
}
|
||||
|
||||
drawBSpline(ctx, width, height, posY) {
|
||||
const n = this.value.length - 1
|
||||
const numSegments = n - 2
|
||||
const numPoints = this.value.length
|
||||
if (numPoints < 4) {
|
||||
this.drawLinear(ctx, width, height, posY)
|
||||
} else {
|
||||
for (let j = 0; j <= numSegments; j++) {
|
||||
for (let t = 0; t <= 1; t += 0.01) {
|
||||
let pt = this.getBSplinePoint(j, t)
|
||||
let x = pt.x * width
|
||||
let y = posY + height - pt.y * height
|
||||
|
||||
if (t === 0) ctx.moveTo(x, y)
|
||||
else ctx.lineTo(x, y)
|
||||
}
|
||||
}
|
||||
ctx.stroke()
|
||||
}
|
||||
}
|
||||
|
||||
drawLinear(ctx, width, height, posY) {
|
||||
for (let i = 0; i < Object.keys(this.value).length - 1; i++) {
|
||||
let p1 = this.value[i]
|
||||
let p2 = this.value[i + 1]
|
||||
ctx.moveTo(p1.x * width, posY + height - p1.y * height)
|
||||
ctx.lineTo(p2.x * width, posY + height - p2.y * height)
|
||||
}
|
||||
ctx.stroke()
|
||||
}
|
||||
getBSplinePoint(i, t) {
|
||||
// Control points for this segment
|
||||
const p0 = this.value[i]
|
||||
const p1 = this.value[i + 1]
|
||||
const p2 = this.value[i + 2]
|
||||
const p3 = this.value[i + 3]
|
||||
|
||||
const x = B0(t) * p0.x + B1(t) * p1.x + B2(t) * p2.x + B3(t) * p3.x
|
||||
const y = B0(t) * p0.y + B1(t) * p1.y + B2(t) * p2.y + B3(t) * p3.y
|
||||
|
||||
return { x, y }
|
||||
}
|
||||
/**
|
||||
* @param {OnDrawWidgetParams} args
|
||||
*/
|
||||
draw(...args) {
|
||||
const hide = this.type !== 'FLOAT_CURVE'
|
||||
if (hide) {
|
||||
return
|
||||
}
|
||||
|
||||
drawLinear(ctx, width, height, posY) {
|
||||
for (let i = 0; i < this._value.length - 1; i++) {
|
||||
let p1 = this._value[i];
|
||||
let p2 = this._value[i + 1];
|
||||
ctx.moveTo(p1.x * width, posY + height - p1.y * height);
|
||||
ctx.lineTo(p2.x * width, posY + height - p2.y * height);
|
||||
}
|
||||
ctx.stroke();
|
||||
const [ctx, node, width, posY, height] = args
|
||||
const [cw, ch] = this.computeSize(width)
|
||||
|
||||
ctx.beginPath()
|
||||
ctx.fillStyle = '#000'
|
||||
ctx.strokeStyle = '#fff'
|
||||
ctx.lineWidth = 2
|
||||
|
||||
// normalized coordinates -> canvas coordinates
|
||||
for (let i = 0; i < Object.keys(this.value || {}).length - 1; i++) {
|
||||
let p1 = this.value[i]
|
||||
let p2 = this.value[i + 1]
|
||||
ctx.moveTo(p1.x * cw, posY + ch - p1.y * ch)
|
||||
ctx.lineTo(p2.x * cw, posY + ch - p2.y * ch)
|
||||
}
|
||||
ctx.stroke()
|
||||
|
||||
// points
|
||||
Object.values(this.value || {}).forEach((point) => {
|
||||
ctx.beginPath()
|
||||
ctx.arc(point.x * cw, posY + ch - point.y * ch, 5, 0, 2 * Math.PI)
|
||||
ctx.fill()
|
||||
})
|
||||
}
|
||||
|
||||
mouse(event, pos, node) {
|
||||
let x = pos[0] - node.pos[0]
|
||||
let y = pos[1] - node.pos[1]
|
||||
const width = node.size[0]
|
||||
const height = 300 // TODO: compute
|
||||
const posY = node.pos[1]
|
||||
const localPos = { x: pos[0], y: pos[1] - LiteGraph.NODE_WIDGET_HEIGHT }
|
||||
|
||||
if (event.type === LiteGraph.pointerevents_method + 'down') {
|
||||
console.debug('Checking if a point was clicked')
|
||||
const clickedPointIndex = this.detectPoint(localPos, width, height)
|
||||
if (clickedPointIndex !== null) {
|
||||
this.selectedPointIndex = clickedPointIndex
|
||||
} else {
|
||||
this.addPoint(localPos, width, height)
|
||||
}
|
||||
return true
|
||||
} else if (
|
||||
event.type === LiteGraph.pointerevents_method + 'move' &&
|
||||
this.selectedPointIndex !== null
|
||||
) {
|
||||
this.movePoint(this.selectedPointIndex, localPos, width, height)
|
||||
return true
|
||||
} else if (
|
||||
event.type === LiteGraph.pointerevents_method + 'up' &&
|
||||
this.selectedPointIndex !== null
|
||||
) {
|
||||
this.selectedPointIndex = null
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
callback(...args) {
|
||||
//value, that, node, pos, event) {
|
||||
|
||||
}
|
||||
|
||||
detectPoint(localPos, width, height) {
|
||||
const threshold = 20 // TODO: extract
|
||||
const keys = Object.keys(this.value)
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i]
|
||||
const p = this.value[key]
|
||||
const px = p.x * width
|
||||
const py = height - p.y * height
|
||||
if (
|
||||
Math.abs(localPos.x - px) < threshold &&
|
||||
Math.abs(localPos.y - py) < threshold
|
||||
) {
|
||||
return key
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
addPoint(localPos, width, height) {
|
||||
// add a new point based on click position
|
||||
const normalizedPoint = {
|
||||
x: localPos.x / width,
|
||||
y: 1 - localPos.y / height,
|
||||
}
|
||||
|
||||
getBSplinePoint(i, t) {
|
||||
// Control points for this segment
|
||||
const p0 = this._value[i];
|
||||
const p1 = this._value[i + 1];
|
||||
const p2 = this._value[i + 2];
|
||||
const p3 = this._value[i + 3];
|
||||
|
||||
const x = B0(t) * p0.x + B1(t) * p1.x + B2(t) * p2.x + B3(t) * p3.x;
|
||||
const y = B0(t) * p0.y + B1(t) * p1.y + B2(t) * p2.y + B3(t) * p3.y;
|
||||
|
||||
return { x, y };
|
||||
const keys = Object.keys(this.value)
|
||||
let insertIndex = keys.length
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
if (normalizedPoint.x < this.value[keys[i]].x) {
|
||||
insertIndex = i
|
||||
break
|
||||
}
|
||||
}
|
||||
// shift
|
||||
for (let i = keys.length; i > insertIndex; i--) {
|
||||
this.value[i] = this.value[i - 1]
|
||||
}
|
||||
|
||||
draw(ctx, node, width, posY, height) {
|
||||
const [cw, ch] = this.computeSize(width)
|
||||
this.value[insertIndex] = normalizedPoint
|
||||
}
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = "#000";
|
||||
//ctx.fillRect(0, posY, cw, ch);
|
||||
ctx.strokeStyle = "#fff";
|
||||
ctx.lineWidth = 2;
|
||||
movePoint(index, localPos, width, height) {
|
||||
const point = this.value[index]
|
||||
point.x = Math.max(0, Math.min(1, localPos.x / width))
|
||||
point.y = Math.max(0, Math.min(1, 1 - localPos.y / height))
|
||||
|
||||
// normalized coordinates -> canvas coordinates
|
||||
for (let i = 0; i < this._value.length - 1; i++) {
|
||||
let p1 = this._value[i];
|
||||
let p2 = this._value[i + 1];
|
||||
ctx.moveTo(p1.x * cw, posY + ch - p1.y * ch);
|
||||
ctx.lineTo(p2.x * cw, posY + ch - p2.y * ch);
|
||||
}
|
||||
ctx.stroke();
|
||||
// this.drawBSpline(ctx, width, height, posY);
|
||||
this.value[index] = point
|
||||
}
|
||||
computeSize(width) {
|
||||
return [width, 300]
|
||||
}
|
||||
|
||||
// points
|
||||
this._value.forEach(point => {
|
||||
ctx.beginPath();
|
||||
ctx.arc(point.x * cw, posY + ch - point.y * ch, 5, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
});
|
||||
}
|
||||
|
||||
mouse(event, pos, node) {
|
||||
// console.debug(event.type, pos, node)
|
||||
let x = pos[0] - node.pos[0]
|
||||
let y = pos[1] - node.pos[1]
|
||||
let width = node.size[0]
|
||||
const height = 300; // TODO: compute
|
||||
const posY = node.pos[1];
|
||||
|
||||
const localPos = { x: pos[0], y: pos[1] - LiteGraph.NODE_WIDGET_HEIGHT };
|
||||
|
||||
if (event.type === LiteGraph.pointerevents_method + "down") {
|
||||
console.debug("Checking if a point was clicked");
|
||||
const clickedPointIndex = this.detectPoint(localPos, width, height);
|
||||
if (clickedPointIndex !== null) {
|
||||
this.selectedPointIndex = clickedPointIndex;
|
||||
} else {
|
||||
this.addPoint(localPos, width, height);
|
||||
}
|
||||
return true;
|
||||
} else if (event.type === LiteGraph.pointerevents_method + "move" && this.selectedPointIndex !== null) {
|
||||
this.movePoint(this.selectedPointIndex, localPos, width, height);
|
||||
return true;
|
||||
} else if (event.type === LiteGraph.pointerevents_method + "up" && this.selectedPointIndex !== null) {
|
||||
this.selectedPointIndex = null;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
detectPoint(localPos, width, height) {
|
||||
const threshold = 20; // TODO: extract
|
||||
for (let i = 0; i < this._value.length; i++) {
|
||||
const p = this._value[i];
|
||||
const px = p.x * width;
|
||||
const py = height - p.y * height;
|
||||
if (Math.abs(localPos.x - px) < threshold && Math.abs(localPos.y - py) < threshold) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
addPoint(localPos, width, height) {
|
||||
// add a new point based on click position
|
||||
const normalizedPoint = { x: localPos.x / width, y: 1 - localPos.y / height };
|
||||
this._value.push(normalizedPoint);
|
||||
this._value.sort((a, b) => a.x - b.x);
|
||||
this.value = JSON.stringify(this._value);
|
||||
}
|
||||
|
||||
movePoint(index, localPos, width, height) {
|
||||
const point = this._value[index];
|
||||
point.x = Math.max(0, Math.min(1, localPos.x / width));
|
||||
point.y = Math.max(0, Math.min(1, 1 - localPos.y / height));
|
||||
|
||||
this._value[index] = point;
|
||||
this.value = JSON.stringify(this._value);
|
||||
}
|
||||
|
||||
computeSize(width) {
|
||||
return [width, 300];
|
||||
}
|
||||
|
||||
configure(data) {
|
||||
console.log(data)
|
||||
}
|
||||
|
||||
value() {
|
||||
console.debug('Returning value', this._value)
|
||||
return this._value
|
||||
}
|
||||
setValue(value) {
|
||||
console.debug('Setting value', value)
|
||||
this._value = value
|
||||
}
|
||||
configure(data) {
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: 'mtb.curves',
|
||||
getCustomWidgets: function () {
|
||||
name: 'mtb.curves',
|
||||
getCustomWidgets: () => {
|
||||
return {
|
||||
/**
|
||||
* @param {LGraphNode} node
|
||||
* @param {str} inputName
|
||||
* @param {[str,*]} inputData
|
||||
* @param {*} app
|
||||
*
|
||||
*/
|
||||
FLOAT_CURVE: (node, inputName, inputData, app) => {
|
||||
// const c = node.widgets.find((w) => w.type === "FLOAT_CURVE")
|
||||
const wid = node.addCustomWidget(new CurveWidget(inputName, inputData))
|
||||
|
||||
return {
|
||||
FLOAT_CURVE: (node, inputName, inputData, app) => {
|
||||
console.debug('Registering float curve widget');
|
||||
|
||||
return {
|
||||
widget: node.addCustomWidget(
|
||||
new CurveWidget(inputName, inputData[1]?.default)
|
||||
),
|
||||
minWidth: 150,
|
||||
minHeight: 30,
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
widget: wid,
|
||||
minWidth: 150,
|
||||
minHeight: 30,
|
||||
}
|
||||
},
|
||||
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
+34
-23
@@ -7,10 +7,12 @@
|
||||
*
|
||||
*/
|
||||
|
||||
// Reference the shared typedefs file
|
||||
/// <reference path="../types/typedefs.js" />
|
||||
|
||||
import { app } from '../../scripts/app.js'
|
||||
|
||||
import * as shared from './comfy_shared.js'
|
||||
import { log } from './comfy_shared.js'
|
||||
import { MtbWidgets } from './mtb_widgets.js'
|
||||
|
||||
// TODO: respect inputs order...
|
||||
@@ -25,10 +27,17 @@ function escapeHtml(unsafe) {
|
||||
}
|
||||
app.registerExtension({
|
||||
name: 'mtb.Debug',
|
||||
|
||||
/**
|
||||
* @param {NodeType} nodeType
|
||||
* @param {NodeData} nodeData
|
||||
* @param {*} app
|
||||
*/
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name === 'Debug (mtb)') {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
this.options = {}
|
||||
const r = onNodeCreated
|
||||
? onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
@@ -37,24 +46,29 @@ app.registerExtension({
|
||||
}
|
||||
|
||||
const onConnectionsChange = nodeType.prototype.onConnectionsChange
|
||||
nodeType.prototype.onConnectionsChange = function (
|
||||
type,
|
||||
index,
|
||||
connected,
|
||||
link_info,
|
||||
) {
|
||||
/**
|
||||
* @param {OnConnectionsChangeParams} args
|
||||
*/
|
||||
nodeType.prototype.onConnectionsChange = function (...args) {
|
||||
const [_type, index, connected, link_info, ioSlot] = args
|
||||
const r = onConnectionsChange
|
||||
? onConnectionsChange.apply(this, arguments)
|
||||
? onConnectionsChange.apply(this, args)
|
||||
: undefined
|
||||
// TODO: remove all widgets on disconnect once computed
|
||||
shared.dynamic_connection(this, index, connected, 'anything_', '*')
|
||||
shared.dynamic_connection(this, index, connected, 'anything_', '*', {
|
||||
link: link_info,
|
||||
ioSlot: ioSlot,
|
||||
})
|
||||
|
||||
//- infer type
|
||||
if (link_info) {
|
||||
const fromNode = this.graph._nodes.find(
|
||||
(otherNode) => otherNode.id === link_info.origin_id,
|
||||
)
|
||||
const type = fromNode.outputs[link_info.origin_slot].type
|
||||
// const fromNode = this.graph._nodes.find(
|
||||
// (otherNode) => otherNode.id === link_info.origin_id,
|
||||
// )
|
||||
// const fromNode = app.graph.getNodeById(link_info.origin_id)
|
||||
const { from } = shared.nodesFromLink(this, link_info)
|
||||
if (!from || this.inputs.length === 0) return
|
||||
const type = from.outputs[link_info.origin_slot].type
|
||||
this.inputs[index].type = type
|
||||
// this.inputs[index].label = type.toLowerCase()
|
||||
}
|
||||
@@ -67,14 +81,12 @@ app.registerExtension({
|
||||
}
|
||||
|
||||
const onExecuted = nodeType.prototype.onExecuted
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
nodeType.prototype.onExecuted = function (data) {
|
||||
onExecuted?.apply(this, arguments)
|
||||
|
||||
const prefix = 'anything_'
|
||||
|
||||
if (this.widgets) {
|
||||
// const pos = this.widgets.findIndex((w) => w.name === "anything_1");
|
||||
// if (pos !== -1) {
|
||||
for (let i = 0; i < this.widgets.length; i++) {
|
||||
if (this.widgets[i].name !== 'output_to_console') {
|
||||
this.widgets[i].onRemoved?.()
|
||||
@@ -83,8 +95,9 @@ app.registerExtension({
|
||||
this.widgets.length = 1
|
||||
}
|
||||
let widgetI = 1
|
||||
if (message.text) {
|
||||
for (const txt of message.text) {
|
||||
// console.log(message)
|
||||
if (data.text) {
|
||||
for (const txt of data.text) {
|
||||
const w = this.addCustomWidget(
|
||||
MtbWidgets.DEBUG_STRING(`${prefix}_${widgetI}`, escapeHtml(txt)),
|
||||
)
|
||||
@@ -92,19 +105,17 @@ app.registerExtension({
|
||||
widgetI++
|
||||
}
|
||||
}
|
||||
if (message.b64_images) {
|
||||
for (const img of message.b64_images) {
|
||||
if (data.b64_images) {
|
||||
for (const img of data.b64_images) {
|
||||
const w = this.addCustomWidget(
|
||||
MtbWidgets.DEBUG_IMG(`${prefix}_${widgetI}`, img),
|
||||
)
|
||||
w.parent = this
|
||||
widgetI++
|
||||
}
|
||||
// this.onResize?.(this.size);
|
||||
// this.resize?.(this.size)
|
||||
}
|
||||
|
||||
this.setSize(this.computeSize())
|
||||
// this.setSize(this.computeSize())
|
||||
|
||||
this.onRemoved = function () {
|
||||
// When removing this node we need to remove the input from the DOM
|
||||
|
||||
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
+1128
-861
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,246 @@
|
||||
// web/note_plus.constants.js
|
||||
|
||||
export const DEFAULT_CSS = ''
|
||||
export const DEFAULT_HTML = `<p style='color:red;font-family:monospace'>
|
||||
Note+
|
||||
</p>`
|
||||
export const DEFAULT_MD = '## Note+'
|
||||
export const DEFAULT_MODE = 'markdown'
|
||||
export const DEFAULT_THEME = 'one_dark'
|
||||
|
||||
export const DEMO_CONTENT = `
|
||||
# @mtb/svelte-markdown.
|
||||
## This is a subheader
|
||||
|
||||
[](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 = `
|
||||
* {
|
||||
font-family: monospace;
|
||||
line-height: 1.25em;
|
||||
}
|
||||
.shiki{
|
||||
padding: 1em;
|
||||
width: 100%;
|
||||
}
|
||||
.markdown-callout-title {
|
||||
.octicon{
|
||||
fill:white;
|
||||
}
|
||||
/* background: var(--current-color); */
|
||||
color: var(--current-color);
|
||||
font-weight: bold;
|
||||
/* border-start-end-radius: var(--radius); */
|
||||
/* border-start-start-radius: var(--radius); */
|
||||
padding: 0.5em;
|
||||
padding-inline-start: 1em;
|
||||
}
|
||||
.markdown-callout-content {
|
||||
padding: 1em;
|
||||
}
|
||||
.markdown-callout {
|
||||
--radius: 8px;
|
||||
--current-color: purple;
|
||||
/* border-start-end-radius: var(--radius); */
|
||||
/* border-start-start-radius: var(--radius); */
|
||||
border-left: 3px solid var(--current-color);
|
||||
margin-bottom: 1em;
|
||||
margin-top: 1em;
|
||||
}
|
||||
|
||||
.markdown-callout-tip {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #50e3c2;
|
||||
}
|
||||
|
||||
.markdown-callout-note {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #0070f3;
|
||||
}
|
||||
.markdown-callout-important {
|
||||
--text-color: whitesmoke;
|
||||
--current-color: #7928ca;
|
||||
}
|
||||
.markdown-callout-warning {
|
||||
--current-color: #f5a623;
|
||||
}
|
||||
.markdown-callout-caution {
|
||||
--current-color: #e60000;
|
||||
}
|
||||
|
||||
|
||||
.note-plus-preview {
|
||||
display:flex;
|
||||
flex-direction:column;
|
||||
align-items: flex-start;
|
||||
width:95%;
|
||||
margin-left: 20px;
|
||||
margin-top:20px;
|
||||
/*background-color: rgba(255,0,0,0.5)!important;*/
|
||||
}
|
||||
|
||||
/* allowed to be selected*/
|
||||
h1, h2, h3, h4, h5, h6,a, p, ul, ol, dl, blockquote,details,summary {
|
||||
pointer-events:auto;
|
||||
user-select:text;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
display:inline-block;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
p, ul, ol, dl, blockquote {
|
||||
margin: 0.3em;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
ul, ol {
|
||||
padding-left: 1em;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
pointer-events: all;
|
||||
color: cyan;
|
||||
}
|
||||
|
||||
img {
|
||||
padding: 1em 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
iframe {
|
||||
max-width: 100%;
|
||||
height: auto;
|
||||
border:none;
|
||||
pointer-events:all;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #ccc;
|
||||
padding-left: 1em;
|
||||
margin-left: 0;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
pre, code {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #000;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
th, td {
|
||||
border-left: 1px solid #000;
|
||||
border-right: 1px solid #000;
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
border: 1px solid #000;
|
||||
background-color: rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-right: 10px;
|
||||
}
|
||||
`
|
||||
+390
-253
@@ -1,155 +1,122 @@
|
||||
/// <reference path="../types/typedefs.js" />
|
||||
|
||||
import { app } from '../../scripts/app.js'
|
||||
|
||||
import * as shared from './comfy_shared.js'
|
||||
import { infoLogger, successLogger, errorLogger } from './comfy_shared.js'
|
||||
import {
|
||||
DEFAULT_CSS,
|
||||
DEFAULT_HTML,
|
||||
DEFAULT_MD,
|
||||
DEFAULT_MODE,
|
||||
DEFAULT_THEME,
|
||||
THEMES,
|
||||
CSS_RESET,
|
||||
DEMO_CONTENT,
|
||||
} from './note_plus.constants.js'
|
||||
import { LocalStorageManager } from './comfy_shared.js'
|
||||
|
||||
const DEFAULT_CSS = ''
|
||||
const DEFAULT_HTML = `<p style='color:red;font-family:monospace'>
|
||||
Note+
|
||||
</p>`
|
||||
const DEFAULT_MD = '## Note+'
|
||||
const DEFAULT_MODE = 'markdown'
|
||||
const DEFAULT_THEME = 'one_dark'
|
||||
const storage = new LocalStorageManager('mtb')
|
||||
|
||||
const CSS_RESET = `
|
||||
* {
|
||||
font-family: monospace;
|
||||
line-height: 1.25em;
|
||||
/**
|
||||
* Uses `@mtb/markdown-parser` (a fork of marked)
|
||||
* It is statically stored to avoid having
|
||||
* more than 1 instance ever.
|
||||
* The size difference between both libraries...
|
||||
* ╭───┬────────────────────────────────┬──────────╮
|
||||
* │ # │ name │ size │
|
||||
* ├───┼────────────────────────────────┼──────────┤
|
||||
* │ 0 │ web-dist/mtb_markdown_plus.mjs │ 1.2 MB │ <- with shiki
|
||||
* │ 1 │ web-dist/mtb_markdown.mjs │ 44.7 KB │
|
||||
* ╰───┴────────────────────────────────┴──────────╯
|
||||
*/
|
||||
let useShiki = storage.get('np-use-shiki', false)
|
||||
|
||||
const makeResizable = (dialog) => {
|
||||
dialog.style.resize = 'both'
|
||||
dialog.style.transformOrigin = 'top left'
|
||||
dialog.style.overflow = 'auto'
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-weight: normal;
|
||||
const makeDraggable = (dialog, handle) => {
|
||||
let offsetX = 0
|
||||
let offsetY = 0
|
||||
let isDragging = false
|
||||
|
||||
const onMouseMove = (e) => {
|
||||
if (isDragging) {
|
||||
dialog.style.left = `${e.clientX - offsetX}px`
|
||||
dialog.style.top = `${e.clientY - offsetY}px`
|
||||
}
|
||||
}
|
||||
|
||||
const onMouseUp = () => {
|
||||
isDragging = false
|
||||
document.removeEventListener('mousemove', onMouseMove)
|
||||
document.removeEventListener('mouseup', onMouseUp)
|
||||
}
|
||||
|
||||
handle.addEventListener('mousedown', (e) => {
|
||||
isDragging = true
|
||||
offsetX = e.clientX - dialog.offsetLeft
|
||||
offsetY = e.clientY - dialog.offsetTop
|
||||
document.addEventListener('mousemove', onMouseMove)
|
||||
document.addEventListener('mouseup', onMouseUp)
|
||||
})
|
||||
}
|
||||
|
||||
p, ul, ol, dl, blockquote {
|
||||
margin: 0.3em;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
|
||||
ul, ol {
|
||||
|
||||
padding-left: 1em;
|
||||
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
pointer-events: all;
|
||||
color: cyan;
|
||||
}
|
||||
|
||||
img {
|
||||
padding: 1em 0;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
iframe {
|
||||
width: 100%;
|
||||
height: auto;
|
||||
border:none;
|
||||
pointer-events:all;
|
||||
}
|
||||
|
||||
blockquote {
|
||||
border-left: 4px solid #ccc;
|
||||
padding-left: 1em;
|
||||
margin-left: 0;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
pre, code {
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #000;
|
||||
margin: 1em 0;
|
||||
}
|
||||
|
||||
th, td {
|
||||
border-left: 1px solid #000;
|
||||
border-right: 1px solid #000;
|
||||
padding: 8px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
th {
|
||||
border: 1px solid #000;
|
||||
|
||||
background-color: rgba(0,0,0,0.5);
|
||||
}
|
||||
|
||||
input[type="checkbox"] {
|
||||
margin-right: 10px;
|
||||
}
|
||||
|
||||
`
|
||||
|
||||
const themes = [
|
||||
'ambiance',
|
||||
'chaos',
|
||||
'chrome',
|
||||
'cloud9_day',
|
||||
'cloud9_night',
|
||||
'cloud9_night_low_color',
|
||||
'cloud_editor',
|
||||
'cloud_editor_dark',
|
||||
'clouds',
|
||||
'clouds_midnight',
|
||||
'cobalt',
|
||||
'crimson_editor',
|
||||
'dawn',
|
||||
'dracula',
|
||||
'dreamweaver',
|
||||
'eclipse',
|
||||
'github',
|
||||
'github_dark',
|
||||
'gob',
|
||||
'gruvbox',
|
||||
'gruvbox_dark_hard',
|
||||
'gruvbox_light_hard',
|
||||
'idle_fingers',
|
||||
'iplastic',
|
||||
'katzenmilch',
|
||||
'kr_theme',
|
||||
'kuroir',
|
||||
'merbivore',
|
||||
'merbivore_soft',
|
||||
'mono_industrial',
|
||||
'monokai',
|
||||
'nord_dark',
|
||||
'one_dark',
|
||||
'pastel_on_dark',
|
||||
'solarized_dark',
|
||||
'solarized_light',
|
||||
'sqlserver',
|
||||
'terminal',
|
||||
'textmate',
|
||||
'tomorrow',
|
||||
'tomorrow_night',
|
||||
'tomorrow_night_blue',
|
||||
'tomorrow_night_bright',
|
||||
'tomorrow_night_eighties',
|
||||
'twilight',
|
||||
'vibrant_ink',
|
||||
'vscode',
|
||||
]
|
||||
/** @extends {LGraphNode} */
|
||||
class NotePlus extends LiteGraph.LGraphNode {
|
||||
// same values as the comfy note
|
||||
color = LGraphCanvas.node_colors.yellow.color
|
||||
bgcolor = LGraphCanvas.node_colors.yellow.bgcolor
|
||||
groupcolor = LGraphCanvas.node_colors.yellow.groupcolor
|
||||
|
||||
/* NOTE: this is not serialized and only there to make multiple
|
||||
* note+ nodes in the same graph unique.
|
||||
*/
|
||||
uuid
|
||||
|
||||
/** Stores the dialog observer*/
|
||||
resizeObserver
|
||||
|
||||
/** Live update the preview*/
|
||||
live = true
|
||||
/** DOM height by adding child size together*/
|
||||
calculated_height = 0
|
||||
|
||||
/** ????*/
|
||||
_raw_html
|
||||
|
||||
/** might not be needed anymore */
|
||||
inner
|
||||
|
||||
/** the dialog DOM widget*/
|
||||
dialog
|
||||
|
||||
/** widgets*/
|
||||
|
||||
/** used to store the raw value and display the parsed html at the same time*/
|
||||
html_widget
|
||||
|
||||
/** hidden widgets for serialization*/
|
||||
css_widget
|
||||
edit_mode_widget
|
||||
theme_widget
|
||||
|
||||
editorsContainer
|
||||
/** ACE editors instances*/
|
||||
html_editor
|
||||
css_editor
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.uuid = shared.makeUUID()
|
||||
|
||||
infoLogger('Constructing Note+ instance')
|
||||
shared.ensureMarkdownParser((_p) => {
|
||||
this.updateHTML()
|
||||
})
|
||||
// - litegraph settings
|
||||
this.collapsable = true
|
||||
this.isVirtualNode = true
|
||||
@@ -159,35 +126,30 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
// - default values, serialization is done through widgets
|
||||
this._raw_html = DEFAULT_MODE === 'html' ? DEFAULT_HTML : DEFAULT_MD
|
||||
|
||||
// - mardown converter
|
||||
this.markdownConverter = new showdown.Converter({
|
||||
tables: true,
|
||||
strikethrough: true,
|
||||
emoji: true,
|
||||
ghCodeBlocks: true,
|
||||
tasklists: true,
|
||||
ghMentions: true,
|
||||
smoothLivePreview: true,
|
||||
simplifiedAutoLink: true,
|
||||
parseImgDimensions: true,
|
||||
openLinksInNewWindow: true,
|
||||
})
|
||||
|
||||
// - state
|
||||
this.live = true
|
||||
this.calculated_height = 0
|
||||
|
||||
// - add widgets
|
||||
const inner = document.createElement('div')
|
||||
inner.style.margin = '0'
|
||||
inner.style.padding = '0'
|
||||
inner.style.pointerEvents = 'none'
|
||||
this.html_widget = this.addDOMWidget('HTML', 'html', inner, {
|
||||
const cinner = document.createElement('div')
|
||||
this.inner = document.createElement('div')
|
||||
|
||||
cinner.append(this.inner)
|
||||
this.inner.classList.add('note-plus-preview')
|
||||
cinner.style.margin = '0'
|
||||
cinner.style.padding = '0'
|
||||
this.html_widget = this.addDOMWidget('HTML', 'html', cinner, {
|
||||
setValue: (val) => {
|
||||
this._raw_html = val
|
||||
},
|
||||
getValue: () => this._raw_html,
|
||||
getMinHeight: () => this.calculated_height, // (the edit button),
|
||||
onDraw: () => {
|
||||
// HACK: dirty hack for now until it's addressed upstream...
|
||||
this.html_widget.element.style.pointerEvents = 'none'
|
||||
// NOTE: not sure about this, it avoid the visual "bugs" but scrolling over the wrong area will affect zoom...
|
||||
// this.html_widget.element.style.overflow = 'scroll'
|
||||
},
|
||||
hideOnZoom: false,
|
||||
})
|
||||
|
||||
@@ -197,22 +159,48 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {CanvasRenderingContext2D} ctx
|
||||
* @param {LGraphCanvas} graphcanvas
|
||||
* @returns
|
||||
* @param {CanvasRenderingContext2D} ctx canvas context
|
||||
* @param {any} _graphcanvas
|
||||
*/
|
||||
|
||||
onDrawForeground(ctx, _graphcanvas) {
|
||||
if (this.flags.collapsed) return
|
||||
this.drawEditIcon(ctx)
|
||||
this.drawSideHandle(ctx)
|
||||
|
||||
// Define the size and position of the icon
|
||||
const iconSize = 14 // Size of the icon
|
||||
const iconMargin = 8 // Margin from the edges
|
||||
const x = this.size[0] - iconSize - iconMargin
|
||||
const y = iconMargin * 1.5
|
||||
// DEBUG BACKGROUND
|
||||
// ctx.fillStyle = 'rgba(0, 255, 0, 0.3)'
|
||||
// const rect = this.rect
|
||||
// ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
|
||||
}
|
||||
drawSideHandle(ctx) {
|
||||
const handleRect = this.sideHandleRect
|
||||
const chamfer = 20
|
||||
ctx.beginPath()
|
||||
|
||||
// top left
|
||||
ctx.moveTo(handleRect.x, handleRect.y + chamfer)
|
||||
// top right
|
||||
ctx.lineTo(handleRect.x + handleRect.width, handleRect.y)
|
||||
|
||||
// bottom right
|
||||
ctx.lineTo(
|
||||
handleRect.x + handleRect.width,
|
||||
handleRect.y + handleRect.height,
|
||||
)
|
||||
// bottom left
|
||||
ctx.lineTo(handleRect.x, handleRect.y + handleRect.height - chamfer)
|
||||
ctx.closePath()
|
||||
|
||||
ctx.fillStyle = 'rgba(255, 255, 255, 0.05)'
|
||||
ctx.fill()
|
||||
}
|
||||
|
||||
drawEditIcon(ctx) {
|
||||
const rect = this.iconRect
|
||||
// DEBUG ICON POSITION
|
||||
// ctx.fillStyle = 'rgba(0, 255, 0, 0.3)'
|
||||
// ctx.fillRect(rect.x, rect.y, rect.width, rect.height)
|
||||
|
||||
// Create a new Path2D object from SVG path data
|
||||
const pencilPath = new Path2D(
|
||||
'M21.28 6.4l-9.54 9.54c-.95.95-3.77 1.39-4.4.76-.63-.63-.2-3.45.75-4.4l9.55-9.55a2.58 2.58 0 1 1 3.64 3.65z',
|
||||
)
|
||||
@@ -220,41 +208,73 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
'M11 4H6a4 4 0 0 0-4 4v10a4 4 0 0 0 4 4h11c2.21 0 3-1.8 3-4v-5',
|
||||
)
|
||||
|
||||
// Draw the paths
|
||||
ctx.save()
|
||||
ctx.translate(x, y) // Position the icon on the canvas
|
||||
ctx.scale(iconSize / 32, iconSize / 32) // Scale the icon to the desired size
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.3)'
|
||||
|
||||
ctx.translate(rect.x, rect.y)
|
||||
ctx.scale(rect.width / 32, rect.height / 32)
|
||||
ctx.strokeStyle = 'rgba(255,255,255,0.4)'
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
|
||||
ctx.lineWidth = 2.4
|
||||
ctx.stroke(pencilPath)
|
||||
ctx.stroke(folderPath)
|
||||
ctx.restore()
|
||||
}
|
||||
onMouseDown(_e, localPos, _graphcanvas) {
|
||||
// Check if the click is within the pencil icon bounds
|
||||
const iconSize = 14
|
||||
const iconMargin = 8
|
||||
const iconX = this.size[0] - iconSize - iconMargin
|
||||
const iconY = iconMargin * 1.5
|
||||
|
||||
if (
|
||||
localPos[0] > iconX &&
|
||||
localPos[0] < iconX + iconSize &&
|
||||
localPos[1] > iconY &&
|
||||
localPos[1] < iconY + iconSize
|
||||
) {
|
||||
// Pencil icon was clicked, open the editor
|
||||
this.openEditorDialog()
|
||||
return true // Return true to indicate the event was handled
|
||||
/**
|
||||
* @param {number} x
|
||||
* @param {number} y
|
||||
* @param {{x:number,y:number,width:number,height:number}} rect
|
||||
* @returns {}
|
||||
*/
|
||||
inRect(x, y, rect) {
|
||||
rect = rect || this.iconRect
|
||||
return (
|
||||
x >= rect.x &&
|
||||
x <= rect.x + rect.width &&
|
||||
y >= rect.y &&
|
||||
y <= rect.y + rect.height
|
||||
)
|
||||
}
|
||||
get rect() {
|
||||
return {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: this.size[0],
|
||||
height: this.size[1],
|
||||
}
|
||||
}
|
||||
get sideHandleRect() {
|
||||
const w = this.size[0]
|
||||
const h = this.size[1]
|
||||
|
||||
return false // Return false to let the event propagate
|
||||
const bw = 32
|
||||
const bho = 64
|
||||
|
||||
return {
|
||||
x: w - bw,
|
||||
y: bho,
|
||||
width: bw,
|
||||
height: h - bho * 1.5,
|
||||
}
|
||||
}
|
||||
get iconRect() {
|
||||
const iconSize = 32
|
||||
const iconMargin = 16
|
||||
return {
|
||||
x: this.size[0] - iconSize - iconMargin,
|
||||
y: iconMargin * 1.5,
|
||||
width: iconSize,
|
||||
height: iconSize,
|
||||
}
|
||||
}
|
||||
onMouseDown(_e, localPos, _graphcanvas) {
|
||||
if (this.inRect(localPos[0], localPos[1])) {
|
||||
this.openEditorDialog()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/* Hidden widgets to store note+ settings in the workflow (stripped in API)*/
|
||||
setupSerializationWidgets() {
|
||||
infoLogger('Setup Serializing widgets')
|
||||
|
||||
@@ -283,15 +303,36 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
shared.hideWidgetForGood(this, this.css_widget)
|
||||
shared.hideWidgetForGood(this, this.theme_widget)
|
||||
}
|
||||
|
||||
setupDialog() {
|
||||
infoLogger('Setup dialog')
|
||||
// this.addWidget('button', 'Edit', 'Edit', this.openEditorDialog.bind(this))
|
||||
|
||||
this.dialog = new app.ui.dialog.constructor()
|
||||
this.dialog.element.classList.add('comfy-settings')
|
||||
|
||||
Object.assign(this.dialog.element.style, {
|
||||
position: 'absolute',
|
||||
boxShadow: 'none',
|
||||
})
|
||||
|
||||
const subcontainer = this.dialog.textElement.parentElement
|
||||
|
||||
if (subcontainer) {
|
||||
Object.assign(subcontainer.style, {
|
||||
width: '100%',
|
||||
})
|
||||
}
|
||||
const closeButton = this.dialog.element.querySelector('button')
|
||||
closeButton.textContent = 'CANCEL'
|
||||
closeButton.id = 'cancel-editor-dialog'
|
||||
closeButton.title =
|
||||
"Cancel the changes since last opened (doesn't support live mode)"
|
||||
closeButton.disabled = this.live
|
||||
|
||||
closeButton.style.background = this.live
|
||||
? 'repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px)'
|
||||
: ''
|
||||
|
||||
const saveButton = document.createElement('button')
|
||||
saveButton.textContent = 'SAVE'
|
||||
saveButton.onclick = () => {
|
||||
@@ -313,32 +354,54 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
|
||||
closeEditorDialog(accept) {
|
||||
infoLogger('Closing editor dialog', accept)
|
||||
if (accept) {
|
||||
if (accept && !this.live) {
|
||||
this.updateHTML(this.html_editor.getValue())
|
||||
this.updateCSS(this.css_editor.getValue())
|
||||
}
|
||||
if (this.resizeObserver) {
|
||||
this.resizeObserver.disconnect()
|
||||
this.resizeObserver = null
|
||||
}
|
||||
this.teardownEditors()
|
||||
this.dialog.close()
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} elem
|
||||
*/
|
||||
hookResize(elem) {
|
||||
if (!this.resizeObserver) {
|
||||
const observer = () => {
|
||||
this.html_editor.resize()
|
||||
this.css_editor.resize()
|
||||
Object.assign(this.editorsContainer.style, {
|
||||
minHeight: `${(this.dialog.element.clientHeight / 100) * 50}px`, //'200px',
|
||||
})
|
||||
}
|
||||
this.resizeObserver = new ResizeObserver(observer).observe(elem)
|
||||
}
|
||||
}
|
||||
openEditorDialog() {
|
||||
infoLogger(`Current edit mode ${this.edit_mode_widget.value}`)
|
||||
this.hookResize(this.dialog.element)
|
||||
const container = document.createElement('div')
|
||||
|
||||
Object.assign(container.style, {
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
flexDirection: 'column',
|
||||
})
|
||||
|
||||
const editorsContainer = document.createElement('div')
|
||||
Object.assign(editorsContainer.style, {
|
||||
this.editorsContainer = document.createElement('div')
|
||||
|
||||
Object.assign(this.editorsContainer.style, {
|
||||
display: 'flex',
|
||||
gap: '10px',
|
||||
flexDirection: 'row',
|
||||
minHeight: this.dialog.element.offsetHeight, //'200px',
|
||||
width: '100%',
|
||||
})
|
||||
|
||||
container.append(editorsContainer)
|
||||
container.append(this.editorsContainer)
|
||||
|
||||
this.dialog.show('')
|
||||
this.dialog.textElement.append(container)
|
||||
@@ -346,30 +409,39 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
const aceHTML = document.createElement('div')
|
||||
aceHTML.id = 'noteplus-html-editor'
|
||||
Object.assign(aceHTML.style, {
|
||||
width: '300px',
|
||||
height: '300px',
|
||||
// backgroundColor: 'rgb(30,30,30)',
|
||||
// color: 'whitesmoke',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
|
||||
minWidth: '300px',
|
||||
minHeight: 'inherit',
|
||||
})
|
||||
|
||||
editorsContainer.append(aceHTML)
|
||||
this.editorsContainer.append(aceHTML)
|
||||
|
||||
const aceCSS = document.createElement('div')
|
||||
aceCSS.id = 'noteplus-css-editor'
|
||||
Object.assign(aceCSS.style, {
|
||||
width: '300px',
|
||||
height: '300px',
|
||||
// backgroundColor: 'rgb(30,30,30)',
|
||||
// color: 'whitesmoke',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
minHeight: 'inherit',
|
||||
})
|
||||
|
||||
editorsContainer.append(aceCSS)
|
||||
this.editorsContainer.append(aceCSS)
|
||||
|
||||
const live_edit = document.createElement('input')
|
||||
live_edit.type = 'checkbox'
|
||||
live_edit.checked = this.live
|
||||
live_edit.onchange = () => {
|
||||
this.live = live_edit.checked
|
||||
const cancel_button = this.dialog.element.querySelector(
|
||||
'#cancel-editor-dialog',
|
||||
)
|
||||
if (cancel_button) {
|
||||
cancel_button.disabled = this.live
|
||||
cancel_button.style.background = this.live
|
||||
? 'repeating-linear-gradient(45deg,#606dbc,#606dbc 10px,#465298 10px,#465298 20px)'
|
||||
: ''
|
||||
}
|
||||
}
|
||||
|
||||
//- "Dynamic" elements
|
||||
@@ -388,15 +460,14 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
const md = this.html_editor.getValue()
|
||||
this.edit_mode_widget.value = 'html'
|
||||
select_mode.value = 'html'
|
||||
const html = this.markdownConverter.makeHtml(md)
|
||||
this.html_widget.value = html
|
||||
this.html_editor.setValue(html)
|
||||
this.html_editor.session.setMode('ace/mode/html')
|
||||
this.updateHTML(this.html_widget.value)
|
||||
|
||||
convert_to_html.remove()
|
||||
MTB.mdParser.parse(md).then((content) => {
|
||||
this.html_widget.value = content
|
||||
this.html_editor.setValue(content)
|
||||
this.html_editor.session.setMode('ace/mode/html')
|
||||
this.updateHTML(this.html_widget.value)
|
||||
convert_to_html.remove()
|
||||
})
|
||||
}
|
||||
|
||||
firstButton.before(convert_to_html)
|
||||
}
|
||||
} else {
|
||||
@@ -406,6 +477,19 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
}
|
||||
}
|
||||
select_mode.value = this.edit_mode_widget.value
|
||||
|
||||
// the header for dragging the dialog
|
||||
const header = document.createElement('div')
|
||||
header.style.padding = '8px'
|
||||
header.style.cursor = 'move'
|
||||
header.style.backgroundColor = 'rgba(0,0,0,0.5)'
|
||||
header.style.userSelect = 'none'
|
||||
|
||||
header.style.borderBottom = '1px solid #ddd'
|
||||
header.textContent = 'MTB Note+ Editor'
|
||||
container.prepend(header)
|
||||
makeDraggable(this.dialog.element, header)
|
||||
makeResizable(this.dialog.element)
|
||||
}
|
||||
//- combobox
|
||||
let theme_select = this.dialog.element.querySelector('#theme_select')
|
||||
@@ -421,7 +505,7 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
option.textContent = label
|
||||
theme_select.append(option)
|
||||
}
|
||||
for (const t of themes) {
|
||||
for (const t of THEMES) {
|
||||
addOption(t)
|
||||
}
|
||||
|
||||
@@ -491,54 +575,59 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
onCreate() {
|
||||
errorLogger('NotePlus onCreate')
|
||||
}
|
||||
configure(info) {
|
||||
super.configure(info)
|
||||
infoLogger('Restoring serialized values', info)
|
||||
// - update view from serialzed data
|
||||
restoreNodeState(info) {
|
||||
this.html_widget.element.id = `note-plus-${this.uuid}`
|
||||
this.setMode(this.edit_mode_widget.value)
|
||||
this.setTheme(this.theme_widget.value)
|
||||
this.updateHTML(this.html_widget.value)
|
||||
this.updateCSS(this.css_widget.value)
|
||||
this.setSize(info.size)
|
||||
if (info?.size) {
|
||||
this.setSize(info.size)
|
||||
}
|
||||
}
|
||||
configure(info) {
|
||||
super.configure(info)
|
||||
infoLogger('Restoring serialized values', info)
|
||||
this.restoreNodeState(info)
|
||||
// - update view from serialzed data
|
||||
}
|
||||
onNodeCreated() {
|
||||
infoLogger('Node created', this.uuid)
|
||||
this.html_widget.element.id = `note-plus-${this.uuid}`
|
||||
this.setMode(this.edit_mode_widget.value)
|
||||
this.setTheme(this.theme_widget.value)
|
||||
this.updateHTML(this.html_widget.value) // widget is populated here since we called super
|
||||
this.updateCSS(this.css_widget.value)
|
||||
this.restoreNodeState({})
|
||||
// this.html_widget.element.id = `note-plus-${this.uuid}`
|
||||
// this.setMode(this.edit_mode_widget.value)
|
||||
// this.setTheme(this.theme_widget.value)
|
||||
// this.updateHTML(this.html_widget.value) // widget is populated here since we called super
|
||||
// this.updateCSS(this.css_widget.value)
|
||||
}
|
||||
onRemoved() {
|
||||
infoLogger('Node removed', this.uuid)
|
||||
}
|
||||
getExtraMenuOptions() {
|
||||
const options = []
|
||||
// {
|
||||
// content: string;
|
||||
// callback?: ContextMenuEventListener;
|
||||
// /** Used as innerHTML for extra child element */
|
||||
// title?: string;
|
||||
// disabled?: boolean;
|
||||
// has_submenu?: boolean;
|
||||
// submenu?: {
|
||||
// options: ContextMenuItem[];
|
||||
// } & IContextMenuOptions;
|
||||
// className?: string;
|
||||
// }
|
||||
options.push({
|
||||
content: `Set to ${
|
||||
this.edit_mode_widget.value === 'html' ? 'markdown' : 'html'
|
||||
}`,
|
||||
callback: () => {
|
||||
this.edit_mode_widget.value =
|
||||
this.edit_mode_widget.value === 'html' ? 'markdown' : 'html'
|
||||
this.updateHTML(this.html_widget.value)
|
||||
},
|
||||
})
|
||||
const currentMode = this.edit_mode_widget.value
|
||||
const newMode = currentMode === 'html' ? 'markdown' : 'html'
|
||||
|
||||
return options
|
||||
const debugItems = window.MTB?.DEBUG
|
||||
? [
|
||||
{
|
||||
content: 'Replace with demo content (debug)',
|
||||
callback: () => {
|
||||
this.html_widget.value = DEMO_CONTENT
|
||||
},
|
||||
},
|
||||
]
|
||||
: []
|
||||
|
||||
return [
|
||||
...debugItems,
|
||||
{
|
||||
content: `Set to ${newMode}`,
|
||||
callback: () => {
|
||||
this.edit_mode_widget.value = newMode
|
||||
this.updateHTML(this.html_widget.value)
|
||||
},
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
_setupEditor(editor) {
|
||||
@@ -663,17 +752,44 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
// this.setSize(this.computeSize())
|
||||
}
|
||||
|
||||
updateHTML(val) {
|
||||
const cleanHTML = DOMPurify.sanitize(val, { ADD_TAGS: ['iframe'] })
|
||||
this.html_widget.value = cleanHTML
|
||||
parserInitiated() {
|
||||
if (window.MTB?.mdParser) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// update our widget preview
|
||||
if (this.edit_mode_widget.value === 'html') {
|
||||
this.html_widget.element.innerHTML = cleanHTML
|
||||
} else if (this.edit_mode_widget.value === 'markdown') {
|
||||
this.html_widget.element.innerHTML =
|
||||
this.markdownConverter.makeHtml(cleanHTML)
|
||||
/** to easilty swap purification methods*/
|
||||
purify(content) {
|
||||
return DOMPurify.sanitize(content, {
|
||||
ADD_TAGS: ['iframe', 'detail', 'summary'],
|
||||
})
|
||||
}
|
||||
|
||||
updateHTML(val) {
|
||||
if (!this.parserInitiated()) {
|
||||
return
|
||||
}
|
||||
val = val || this.html_widget.value
|
||||
const isHTML = this.edit_mode_widget.value === 'html'
|
||||
|
||||
const cleanHTML = this.purify(val)
|
||||
|
||||
const value = isHTML
|
||||
? cleanHTML
|
||||
: cleanHTML.replaceAll('>', '>').replaceAll('<', '<')
|
||||
// .replaceAll('&', '&')
|
||||
// .replaceAll('"', '"')
|
||||
// .replaceAll(''', "'")
|
||||
|
||||
this.html_widget.value = value
|
||||
|
||||
if (isHTML) {
|
||||
this.inner.innerHTML = value
|
||||
} else {
|
||||
MTB.mdParser.parse(value).then((e) => {
|
||||
this.inner.innerHTML = e
|
||||
})
|
||||
}
|
||||
// this.html_widget.element.innerHTML = `<div id="note-plus-spacer"></div>${value}`
|
||||
this.calculateHeight()
|
||||
// this.setSize(this.computeSize())
|
||||
}
|
||||
@@ -681,6 +797,27 @@ class NotePlus extends LiteGraph.LGraphNode {
|
||||
|
||||
app.registerExtension({
|
||||
name: 'mtb.noteplus',
|
||||
setup: () => {
|
||||
app.ui.settings.addSetting({
|
||||
id: 'mtb.noteplus.use-shiki',
|
||||
category: ['mtb', 'Note+', 'use-shiki'],
|
||||
name: 'Use shiki to highlight code',
|
||||
tooltip:
|
||||
'This will load a larger version of @mtb/markdown-parser that bundles shiki, it supports all shiki transformers (supported langs: html,css,python,markdown)',
|
||||
|
||||
type: 'boolean',
|
||||
defaultValue: false,
|
||||
attrs: {
|
||||
style: {
|
||||
// fontFamily: 'monospace',
|
||||
},
|
||||
},
|
||||
async onChange(value) {
|
||||
storage.set('np-use-shiki', value)
|
||||
useShiki = value
|
||||
},
|
||||
})
|
||||
},
|
||||
|
||||
registerCustomNodes() {
|
||||
LiteGraph.registerNodeType('Note Plus (mtb)', NotePlus)
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
// This is a vanillajs implementation of Houdini's number input widgets.
|
||||
// It basically popup a visual sensitivity slider of steps to use as incr/decr
|
||||
// TODO: Convert it to IWidget
|
||||
|
||||
// import styles from "./style.module.css";
|
||||
|
||||
function getValidNumber(numberInput) {
|
||||
let num =
|
||||
isNaN(numberInput.value) || numberInput.value === ''
|
||||
? 0
|
||||
: parseFloat(numberInput.value)
|
||||
return num
|
||||
}
|
||||
/**
|
||||
* Number input widgets
|
||||
*/
|
||||
export class NumberInputWidget {
|
||||
constructor(containerId, numberOfInputs = 1, isDebug = false) {
|
||||
this.container = document.getElementById(containerId)
|
||||
this.numberOfInputs = numberOfInputs
|
||||
this.currentInput = null // Store the currently active input
|
||||
|
||||
this.threshold = 30
|
||||
this.mouseSensitivityMultiplier = 0.05
|
||||
this.debug = isDebug
|
||||
|
||||
//- states
|
||||
this.initialMouseX
|
||||
this.lastMouseX
|
||||
this.activeStep = 1
|
||||
this.accumulatedDelta = 0
|
||||
this.stepLocked = false
|
||||
this.thresholdExceeded = false
|
||||
this.isDragging = false
|
||||
|
||||
const styleTagId = 'mtb-constant-style'
|
||||
|
||||
let styleTag = document.head.querySelector(`#${styleTagId}`)
|
||||
|
||||
if (!styleTag) {
|
||||
styleTag = document.createElement('style')
|
||||
styleTag.type = 'text/css'
|
||||
styleTag.id = styleTagId
|
||||
|
||||
styleTag.innerHTML = `
|
||||
|
||||
.${containerId}{
|
||||
margin-top: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.sensitivity-menu {
|
||||
display: none;
|
||||
position: absolute;
|
||||
/* Additional styling */
|
||||
}
|
||||
|
||||
.sensitivity-menu .step {
|
||||
cursor: pointer;
|
||||
padding: 0.5em;
|
||||
/* Add more styling as needed */
|
||||
}
|
||||
|
||||
.sensitivity-menu {
|
||||
font-family: monospace;
|
||||
|
||||
background: var(--bg-color);
|
||||
border: 1px solid var(--fg-color);
|
||||
/* Highlight for the active step */
|
||||
}
|
||||
.number-input {
|
||||
background: var(--bg-color);
|
||||
color: var(--fg-color)
|
||||
}
|
||||
|
||||
.sensitivity-menu .step.active {
|
||||
background-color:var(--drag-text);
|
||||
/* Highlight for the active step */
|
||||
}
|
||||
|
||||
.sensitivity-menu .step.locked {
|
||||
background-color: #f00;
|
||||
/* Change to your preferred color for the locked state */
|
||||
}
|
||||
#debug-container {
|
||||
transform: translateX(50%);
|
||||
width: 50%;
|
||||
text-align: center;
|
||||
font-family: monospace;
|
||||
}
|
||||
`
|
||||
document.head.appendChild(styleTag)
|
||||
}
|
||||
|
||||
this.createWidgetElements()
|
||||
this.initializeEventListeners()
|
||||
}
|
||||
|
||||
setLabel(str) {
|
||||
this.label.textContent = str
|
||||
}
|
||||
setValue(...values) {
|
||||
if (values.length !== this.numberInputs.length) {
|
||||
console.error('Number of values does not match the number of inputs.')
|
||||
console.error(
|
||||
`You provided ${values.length} but the input want ${this.numberInputs.length}`,
|
||||
{ values },
|
||||
)
|
||||
return
|
||||
}
|
||||
// Set each input value
|
||||
this.numberInputs.forEach((input, index) => {
|
||||
input.value = values[index]
|
||||
})
|
||||
}
|
||||
getValue() {
|
||||
const value = []
|
||||
this.numberInputs.forEach((input, index) => {
|
||||
value.push(Number.parseFloat(input.value) || 0.0)
|
||||
})
|
||||
return value
|
||||
}
|
||||
resetValues() {
|
||||
for (const input of numberInputs) {
|
||||
input.value = 0
|
||||
}
|
||||
this.onChange?.(this.getValue())
|
||||
}
|
||||
|
||||
createWidgetElements() {
|
||||
this.label = document.createElement('label')
|
||||
this.label.textContent = 'Control All:'
|
||||
this.label.className = 'widget-label'
|
||||
this.container.appendChild(this.label)
|
||||
|
||||
this.label.addEventListener('mousedown', (event) => {
|
||||
if (event.button === 1) {
|
||||
this.currentInput = null
|
||||
this.handleMouseDown(event)
|
||||
}
|
||||
})
|
||||
|
||||
this.label.addEventListener('contextmenu', (event) => {
|
||||
event.preventDefault()
|
||||
this.resetValues()
|
||||
})
|
||||
|
||||
this.numberInputs = []
|
||||
|
||||
// create linked inputs
|
||||
for (let i = 0; i < this.numberOfInputs; i++) {
|
||||
const numberInput = document.createElement('input')
|
||||
numberInput.type = 'number'
|
||||
numberInput.className = 'number-input' //styles.numberInput; //"number-input";
|
||||
numberInput.step = 'any'
|
||||
this.container.appendChild(numberInput)
|
||||
this.numberInputs.push(numberInput)
|
||||
|
||||
numberInput.addEventListener('mousedown', (event) => {
|
||||
if (event.button === 1) {
|
||||
this.currentInput = numberInput
|
||||
this.handleMouseDown(event)
|
||||
}
|
||||
})
|
||||
}
|
||||
this.sensitivityMenu = document.createElement('div')
|
||||
this.sensitivityMenu.className = 'sensitivity-menu' //styles.sensitivityMenu; //"sensitivity-menu";
|
||||
this.container.appendChild(this.sensitivityMenu)
|
||||
|
||||
// create steps
|
||||
const stepsValues = [0.001, 0.01, 0.1, 1, 10, 100]
|
||||
stepsValues.forEach((value) => {
|
||||
const step = document.createElement('div')
|
||||
step.className = 'step' //styles.step //"step";
|
||||
step.dataset.step = value
|
||||
step.textContent = value.toString()
|
||||
this.sensitivityMenu.appendChild(step)
|
||||
})
|
||||
|
||||
this.steps = this.sensitivityMenu.getElementsByClassName('step') //styles.step)
|
||||
|
||||
if (this.debug) {
|
||||
this.debugContainer = document.createElement('div')
|
||||
this.debugContainer.id = 'debug-container' //styles.debugContainer //"debugContainer";
|
||||
document.body.appendChild(this.debugContainer)
|
||||
}
|
||||
}
|
||||
showSensitivityMenu(pageX, pageY) {
|
||||
this.sensitivityMenu.style.display = 'block'
|
||||
this.sensitivityMenu.style.left = `${pageX}px`
|
||||
this.sensitivityMenu.style.top = `${pageY}px`
|
||||
this.initialMouseX = pageX
|
||||
this.lastMouseX = pageX
|
||||
this.isDragging = true
|
||||
this.thresholdExceeded = false
|
||||
this.stepLocked = false
|
||||
this.updateDebugInfo()
|
||||
}
|
||||
updateDebugInfo() {
|
||||
if (this.debug) {
|
||||
this.debugContainer.innerHTML = `
|
||||
<div>Active Step: ${this.activeStep}</div>
|
||||
<div>Initial Mouse X: ${this.initialMouseX}</div>
|
||||
<div>Last Mouse X: ${this.lastMouseX}</div>
|
||||
<div>Accumulated Delta: ${this.accumulatedDelta}</div>
|
||||
<div>Threshold Exceeded: ${this.thresholdExceeded}</div>
|
||||
<div>Step Locked: ${this.stepLocked}</div>
|
||||
<div>Number Input Value: ${this.currentInput?.value}</div>
|
||||
`
|
||||
}
|
||||
}
|
||||
handleMouseDown(event) {
|
||||
if (event.button === 1) {
|
||||
this.showSensitivityMenu(
|
||||
event.target.offsetWidth,
|
||||
event.target.offsetHeight,
|
||||
)
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
handleMouseUp(event) {
|
||||
if (event.button === 1) {
|
||||
this.resetWidgetState()
|
||||
}
|
||||
}
|
||||
handleClickOutside(event) {
|
||||
if (event.target !== this.numberInput) {
|
||||
this.resetWidgetState()
|
||||
}
|
||||
}
|
||||
handleMouseMove(event) {
|
||||
if (this.sensitivityMenu.style.display === 'block') {
|
||||
const relativeY = event.pageY - 300 // this.sensitivityMenu.offsetTop
|
||||
|
||||
const horizontalDistanceFromInitial = Math.abs(
|
||||
event.target.offsetWidth - this.initialMouseX,
|
||||
)
|
||||
|
||||
// Unlock if the mouse moves back towards the initial position
|
||||
if (horizontalDistanceFromInitial < this.threshold) {
|
||||
this.thresholdExceeded = false
|
||||
this.stepLocked = false
|
||||
this.accumulatedDelta = 0
|
||||
}
|
||||
|
||||
// Update step only if it is not locked
|
||||
if (!this.stepLocked) {
|
||||
for (let step of this.steps) {
|
||||
step.classList.remove('active') //styles.active)
|
||||
step.classList.remove('locked') //styles.locked)
|
||||
if (
|
||||
relativeY >= step.offsetTop &&
|
||||
relativeY <= step.offsetTop + step.offsetHeight
|
||||
) {
|
||||
step.classList.add('active') //styles.active)
|
||||
this.setActiveStep(parseFloat(step.dataset.step))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.stepLocked) {
|
||||
this.sensitivityMenu
|
||||
.querySelector('.step.active')
|
||||
?.classList.add('locked')
|
||||
}
|
||||
|
||||
this.updateStepValue(event.pageX)
|
||||
}
|
||||
}
|
||||
|
||||
initializeEventListeners() {
|
||||
document.addEventListener('mousemove', (event) =>
|
||||
this.handleMouseMove(event),
|
||||
)
|
||||
document.addEventListener('mouseup', (event) => this.handleMouseUp(event))
|
||||
|
||||
document.addEventListener('click', (event) =>
|
||||
this.handleClickOutside(event),
|
||||
)
|
||||
}
|
||||
|
||||
setActiveStep(val) {
|
||||
if (this.activeStep !== val) {
|
||||
this.activeStep = val
|
||||
this.stepLocked = false
|
||||
this.accumulatedDelta = 0
|
||||
this.thresholdExceeded = false
|
||||
}
|
||||
}
|
||||
resetWidgetState() {
|
||||
this.sensitivityMenu.style.display = 'none'
|
||||
this.isDragging = false
|
||||
this.lastMouseX = undefined
|
||||
this.thresholdExceeded = false
|
||||
this.stepLocked = false
|
||||
this.updateDebugInfo()
|
||||
}
|
||||
updateStepValue(mouseX) {
|
||||
if (this.isDragging && this.lastMouseX !== undefined) {
|
||||
const deltaX = mouseX - this.lastMouseX
|
||||
this.accumulatedDelta += deltaX
|
||||
|
||||
if (
|
||||
!this.thresholdExceeded &&
|
||||
Math.abs(this.accumulatedDelta) > this.threshold
|
||||
) {
|
||||
this.thresholdExceeded = true
|
||||
this.stepLocked = true
|
||||
}
|
||||
|
||||
if (this.thresholdExceeded && this.stepLocked) {
|
||||
// frequency of value changes
|
||||
if (
|
||||
Math.abs(this.accumulatedDelta) * this.mouseSensitivityMultiplier >=
|
||||
1
|
||||
) {
|
||||
const valueChange = Math.sign(this.accumulatedDelta) * this.activeStep
|
||||
if (this.currentInput) {
|
||||
this.currentInput.value =
|
||||
getValidNumber(this.currentInput) + valueChange
|
||||
this.onChange?.(this.getValue())
|
||||
} else {
|
||||
this.numberInputs.forEach((input) => {
|
||||
input.value = getValidNumber(input) + valueChange
|
||||
})
|
||||
}
|
||||
this.accumulatedDelta = 0
|
||||
}
|
||||
}
|
||||
|
||||
this.lastMouseX = mouseX
|
||||
}
|
||||
this.updateDebugInfo()
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1
-1
Submodule wiki updated: a3327c786b...4db733ae92
Reference in New Issue
Block a user