├── .github └── workflows │ └── publish_action.yml ├── .gitignore ├── LICENSE ├── README-CN.md ├── README.md ├── __init__.py ├── docker-compose-lite.yml ├── heygem_node.py ├── heygem_utils.py ├── images └── 2025-05-22_22-41-52.png ├── pyproject.toml └── requirements.txt /.github/workflows/publish_action.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - master 7 | - main 8 | paths: 9 | - "pyproject.toml" 10 | 11 | jobs: 12 | publish-node: 13 | name: Publish Custom Node to registry 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out code 17 | uses: actions/checkout@v4 18 | - name: Publish Custom Node 19 | uses: Comfy-Org/publish-node-action@main 20 | with: 21 | ## Add your own personal access token to your Github Repository secrets and reference it here. 22 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # Ruff stuff: 171 | .ruff_cache/ 172 | 173 | # PyPI configuration file 174 | .pypirc 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README-CN.md: -------------------------------------------------------------------------------- 1 | [中文](README-CN.md) | [English](README.md) 2 | 3 | # ComfyUI 的 HeyGem 数字人节点 4 | 5 | 目前 (2025.05.22) 最好的开源数字人, 没有之一. 基本可生成全身, 动态, 任意分辨率数字人. **输入视频帧率要与合成帧率保持一致.** 6 | 7 | ![image](https://github.com/billwuhao/Comfyui_HeyGem/blob/main/images/2025-05-22_22-41-52.png) 8 | 9 | ## 📣 更新 10 | 11 | [2025-05-25]⚒️: 修复 bug, 长视频自动截取匹配音频时长. 12 | 13 | [2025-05-23]⚒️: 优化长视频 cpu 占用, 短视频可重复或 pingpong 到音频时长. 长视频自动截取匹配音频时长. 14 | 15 | [2025-05-22]⚒️: 发布 v1.0.0. 16 | 17 | ## 节点安装 18 | 19 | ``` 20 | cd ComfyUI/custom_nodes 21 | git clone https://github.com/billwuhao/Comfyui_HeyGem.git 22 | ``` 23 | 24 | ## WSL 和 Docker 安装 25 | 26 | - Windows (以 X64 为例): 27 | 28 | 1, 安装 Windows 的 Linux 子系统: https://github.com/microsoft/WSL/releases (`wsl.2.5.7.0.x64.msi`). 已经安装的, 管理员权限执行 `wsl --update` 更新. 29 | 30 | 2, 安装 Docker: https://www.docker.com/ (下载 `AMD64` 版本). 安装完成后, 启动它: 31 | 32 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/8.png) 33 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/13.png) 34 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/3.png) 35 | 36 | 镜像默认下载到 C 盘 **(大概需要 14g 空间)**, 可以在设置里修改为其他盘: 37 | 38 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/7.png) 39 | 40 | OK! 准备就绪, 每次运行节点, 先启动 docker 即可. 第一次运行节点, 需要下载镜像, 大概 30 分钟左右, 看网速. 安装不复杂, 就点击几下安装完软件即可, docker 是独立镜像环境, 不担心兼容问题, 还很少报错, 比其他插件安装还简单. 41 | 42 | - Linux (以 Ubuntu 为例): 43 | 44 | 1, 安装 Docker: 执行 `docker --version` 查看是否安装, 没有安装的, 执行下列命令安装. 45 | ``` 46 | sudo apt update 47 | sudo apt install docker.io 48 | sudo apt install docker-compose 49 | ``` 50 | 51 | 2, 安装驱动: 执行 `nvidia-smi` 查看是否安装, 没有安装的, 参考官方文档安装 (https://www.nvidia.cn/drivers/lookup/). 52 | 53 | 3, 安装 NVIDIA 容器工具包: 54 | - 添加 NVIDIA 软件包存储库: 55 | ``` 56 | distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ 57 | && curl -s -L https://nvidia.github.io/libnvidia-container/gpgkey | sudo apt-key add - \ 58 | && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list 59 | ``` 60 | 61 | - 安装 NVIDIA 容器工具包: 62 | ``` 63 | sudo apt-get update 64 | sudo apt-get install -y nvidia-container-toolkit 65 | ``` 66 | 67 | - 配置 NVIDIA 容器运行时: 68 | ``` 69 | sudo nvidia-ctk runtime configure --runtime=docker 70 | ``` 71 | 72 | - 重启 Docker 守护进程以应用更改: 73 | ``` 74 | sudo systemctl restart docker 75 | ``` 76 | 77 | OK! 准备就绪, 第一次运行节点, 需要下载镜像, 大概 30 分钟左右, 看网速. 78 | 79 | ## 鸣谢 80 | 81 | - [Duix.Heygem](https://github.com/duixcom/Duix.Heygem) 82 | - https://github.com/duixcom/Duix.Heygem/blob/main/LICENSE -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [中文](README-CN.md) | [English](README.md) 2 | 3 | # HeyGem Digital Human Node for ComfyUI 4 | 5 | Currently (2025.05.22) the best open-source digital human, bar none. Basically capable of generating full-body, dynamic, and arbitrary resolution digital humans. **The input video frame rate should be consistent with the synthesized frame rate.** 6 | 7 | ![image](https://github.com/billwuhao/Comfyui_HeyGem/blob/main/images/2025-05-22_22-41-52.png) 8 | 9 | ## 📣 Updates 10 | 11 | [2025-05-25]⚒️: Fixed bugs, automatically capture long videos to match audio duration. 12 | 13 | [2025-05-23]⚒️: Optimize CPU usage for long videos, allowing short videos to be repeated or pingPong to audio duration. 14 | 15 | [2025-05-22]⚒️: Released v1.0.0. 16 | 17 | ## Node Installation 18 | 19 | ``` 20 | cd ComfyUI/custom_nodes 21 | git clone https://github.com/billwuhao/Comfyui_HeyGem.git 22 | ``` 23 | 24 | ## WSL and Docker Installation 25 | 26 | - Windows (taking X64 as an example): 27 | 28 | 1, Install Windows Subsystem for Linux: https://github.com/microsoft/WSL/releases (`wsl.2.5.7.0.x64.msi`). If already installed, run `wsl --update` with administrator privileges to update. 29 | 30 | 2, Install Docker: https://www.docker.com/ (download `AMD64` version). After installation, start it: 31 | 32 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/8.png) 33 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/13.png) 34 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/3.png) 35 | 36 | The image is downloaded to drive C by default **(requires about 14GB of space)**. You can change it to another drive in the settings: 37 | 38 | ![](https://github.com/duixcom/Duix.Heygem/raw/main/README.assets/7.png) 39 | 40 | OK! You are ready. Start Docker before running the node each time. The first time you run the node, it needs to download the image, which takes about 30 minutes, depending on your network speed. The installation is not complicated; just click a few times to install the software. Docker is an isolated image environment, so you don't need to worry about compatibility issues, and it rarely reports errors, making it simpler than installing other plugins. 41 | 42 | - Linux (taking Ubuntu as an example): 43 | 44 | 1, Install Docker: Run `docker --version` to check if it is installed. If not installed, run the following commands to install it. 45 | ``` 46 | sudo apt update 47 | sudo apt install docker.io 48 | sudo apt install docker-compose 49 | ``` 50 | 51 | 2, Install Drivers: Run `nvidia-smi` to check if they are installed. If not installed, refer to the official documentation (https://www.nvidia.cn/drivers/lookup/) for installation. 52 | 53 | 3, Install NVIDIA Container Toolkit: 54 | - Add the NVIDIA package repository: 55 | ``` 56 | distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \ 57 | && curl -s -L https://nvidia.github.io/libnvidia-container/gpgkey | sudo apt-key add - \ 58 | && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list 59 | ``` 60 | 61 | - Install the NVIDIA Container Toolkit: 62 | ``` 63 | sudo apt-get update 64 | sudo apt-get install -y nvidia-container-toolkit 65 | ``` 66 | 67 | - Configure the NVIDIA container runtime: 68 | ``` 69 | sudo nvidia-ctk runtime configure --runtime=docker 70 | ``` 71 | 72 | - Restart the Docker daemon to apply changes: 73 | ``` 74 | sudo systemctl restart docker 75 | ``` 76 | 77 | OK! You are ready. The first time you run the node, it needs to download the image, which takes about 30 minutes, depending on your network speed. 78 | 79 | ## Acknowledgements 80 | 81 | - [Duix.Heygem](https://github.com/duixcom/Duix.Heygem) 82 | - https://github.com/duixcom/Duix.Heygem/blob/main/LICENSE -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .heygem_node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 2 | 3 | __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS'] 4 | -------------------------------------------------------------------------------- /docker-compose-lite.yml: -------------------------------------------------------------------------------- 1 | networks: 2 | ai_network: 3 | driver: bridge 4 | 5 | services: 6 | heygem-gen-video: 7 | image: guiji2025/heygem.ai 8 | container_name: heygem-gen-video 9 | restart: always 10 | runtime: nvidia 11 | privileged: true 12 | volumes: 13 | - ${HEGEM_FACE2FACE_DATA_PATH}:/code/data 14 | environment: 15 | - PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:512 16 | deploy: 17 | resources: 18 | reservations: 19 | devices: 20 | - capabilities: [gpu] 21 | shm_size: '8g' 22 | ports: 23 | - '8383:8383' 24 | command: python /code/app_local.py 25 | networks: 26 | - ai_network 27 | -------------------------------------------------------------------------------- /heygem_node.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import uuid 4 | import torchaudio 5 | import tempfile 6 | from typing import Optional 7 | import torch 8 | import requests 9 | import json 10 | from tqdm import tqdm 11 | 12 | from .heygem_utils import ( 13 | start_heygem_service, 14 | stop_heygem_service, 15 | process_tensor_by_duration, 16 | save_tensor_as_video, 17 | video_to_tensor 18 | ) 19 | import folder_paths 20 | temp_dir = folder_paths.get_temp_directory() 21 | 22 | TEMP_DIR = os.path.join(temp_dir, 'heygem') 23 | os.makedirs(os.path.join(TEMP_DIR, 'temp'), exist_ok=True) 24 | 25 | 26 | def cache_audio_tensor( 27 | cache_dir, 28 | audio_tensor: torch.Tensor, 29 | sample_rate: int, 30 | filename_prefix: str = "cached_audio_", 31 | audio_format: Optional[str] = ".wav" 32 | ) -> str: 33 | try: 34 | with tempfile.NamedTemporaryFile( 35 | prefix=filename_prefix, 36 | suffix=audio_format, 37 | dir=cache_dir, 38 | delete=False 39 | ) as tmp_file: 40 | temp_filepath = tmp_file.name 41 | 42 | torchaudio.save(temp_filepath, audio_tensor, sample_rate) 43 | 44 | return temp_filepath 45 | except Exception as e: 46 | raise Exception(f"Error caching audio tensor: {e}") 47 | 48 | 49 | SERVICE_DICT = { 50 | 9999: 'System abnormality', 51 | 10000: 'Succeeded', 52 | 10001: 'Engaged in another task', 53 | 10002: 'Parameter exception', 54 | 10003: 'Get lock exception', 55 | 10004: 'Task does not exist', 56 | 10005: 'Task processing timeout', 57 | 10006: 'Unable to submit task, please check service status', 58 | } 59 | 60 | class HeyGemRun: 61 | @classmethod 62 | def INPUT_TYPES(s): 63 | return {"required": 64 | { 65 | "audio": ("AUDIO",), 66 | "video": ("IMAGE", ), 67 | "mode": (['pingpong', 'repeat'], {"default": "pingpong"}), 68 | }, 69 | "optional": { 70 | "stop_heygem": ("BOOLEAN", {"default": False}), 71 | "fps": ("FLOAT", {"default": 24.0, "min": 1.0, "max": 60.0, "step": 1.0}), 72 | }, 73 | } 74 | 75 | CATEGORY = "🎤MW/MW-HeyGem" 76 | RETURN_TYPES = ("IMAGE",) 77 | RETURN_NAMES = ("VIDEO",) 78 | 79 | FUNCTION = "run" 80 | 81 | def run(self, video, audio, mode, fps, stop_heygem=False): 82 | start_heygem_service(TEMP_DIR) 83 | 84 | audio_path = cache_audio_tensor( 85 | cache_dir=os.path.join(TEMP_DIR, "temp"), 86 | audio_tensor=audio["waveform"].squeeze(0), 87 | sample_rate=audio["sample_rate"] 88 | ) 89 | 90 | duration = audio["waveform"].shape[-1] / audio["sample_rate"] 91 | 92 | taskcode = f"{uuid.uuid4()}" 93 | video_path = os.path.join(TEMP_DIR, "temp", f"{taskcode}.mkv") 94 | 95 | processed_tensor = process_tensor_by_duration(video, duration, mode, fps) 96 | save_tensor_as_video(processed_tensor, video_path, fps) 97 | 98 | docker_video_path = os.path.join("/code/data/temp/", f"{taskcode}.mkv") 99 | docker_audio_path = os.path.join("/code/data/temp/", os.path.basename(audio_path)) 100 | data = { 101 | "audio_url": docker_audio_path, 102 | "video_url": docker_video_path, 103 | "code": taskcode, 104 | 'watermark_switch': 0, 105 | 'digital_auth': 0, 106 | 'chaofen': 0, 107 | 'pn': 0 108 | } 109 | 110 | data = json.dumps(data) 111 | waite_sec = 0 112 | while waite_sec < 120: 113 | try: 114 | post_response = requests.post(url="http://127.0.0.1:8383/easy/submit",data=data) 115 | if post_response.status_code == 200: 116 | result = post_response.json() 117 | if result['code'] != 10000: 118 | raise ValueError(SERVICE_DICT[result['code']]) 119 | break 120 | else: 121 | raise Exception(f"Request failed, status code: {post_response.status_code}") 122 | except requests.exceptions.RequestException as e: 123 | print(f"Request failed: {e}... \nWait a moment... The service is not ready, try again...") 124 | 125 | time.sleep(3) 126 | waite_sec += 3 127 | 128 | tq_bar = tqdm(desc="\nHeyGem...") 129 | 130 | while True: 131 | try: 132 | get_response = requests.get(url=f"http://127.0.0.1:8383/easy/query?code={taskcode}") 133 | if get_response.status_code == 200: 134 | result = get_response.json() 135 | print(result) 136 | if result['code'] != 10000: 137 | raise ValueError(SERVICE_DICT[result['code']]) 138 | try: 139 | if result['data']['status'] == 2: 140 | break 141 | except: 142 | pass 143 | 144 | else: 145 | raise Exception(f"Request failed, status code: {get_response.status_code}") 146 | except requests.exceptions.RequestException as e: 147 | raise Exception(f"Request failed: {e}") 148 | 149 | time.sleep(3) 150 | tq_bar.update(1) 151 | 152 | res_viedo = os.path.join(TEMP_DIR, "temp", f"{taskcode}-r.mp4") 153 | 154 | images_tensor = video_to_tensor(res_viedo) 155 | if stop_heygem: 156 | stop_heygem_service() 157 | return (images_tensor,) 158 | 159 | 160 | 161 | NODE_CLASS_MAPPINGS = { 162 | "HeyGemRun": HeyGemRun, 163 | } 164 | 165 | NODE_DISPLAY_NAME_MAPPINGS = { 166 | "HeyGemRun": "HeyGem AI Avatar", 167 | } -------------------------------------------------------------------------------- /heygem_utils.py: -------------------------------------------------------------------------------- 1 | import imageio 2 | import numpy as np 3 | import torch 4 | import subprocess 5 | import os 6 | import sys 7 | import time 8 | 9 | 10 | BASE_DIR = os.path.dirname(os.path.abspath(__file__)) 11 | DOCKER_COMPOSE_FILE = os.path.join(BASE_DIR, "docker-compose-lite.yml") 12 | CONTAINER_NAME = "heygem-gen-video" 13 | VOLUME_ENV_VAR = "HEGEM_FACE2FACE_DATA_PATH" 14 | 15 | os.environ['NO_PROXY'] = 'localhost,127.0.0.1,::1' 16 | os.environ['no_proxy'] = 'localhost,127.0.0.1,::1' 17 | 18 | def _run_docker_command(command_parts, check_result=False, capture_output=True, text_output=True, env=None): 19 | try: 20 | result = subprocess.run( 21 | command_parts, 22 | capture_output=capture_output, 23 | text=text_output, 24 | check=check_result, 25 | env=env 26 | ) 27 | return result 28 | except FileNotFoundError: 29 | print(f"Error: '{command_parts[0]}' command not found.", file=sys.stderr) 30 | print(f"Please ensure Docker or Docker Compose is installed and in your system's PATH.", file=sys.stderr) 31 | raise 32 | except subprocess.CalledProcessError as e: 33 | print(f"Error executing command: {' '.join(e.cmd)}", file=sys.stderr) 34 | print(f"Exit Code: {e.returncode}", file=sys.stderr) 35 | if e.stdout: print(f"Stdout:\n{e.stdout}", file=sys.stderr) 36 | if e.stderr: print(f"Stderr:\n{e.stderr}", file=sys.stderr) 37 | raise 38 | except Exception as e: 39 | print(f"An unexpected error occurred: {e}", file=sys.stderr) 40 | raise 41 | 42 | def is_docker_container_running(container_name): 43 | command = [ 44 | "docker", "ps", 45 | "-q", 46 | "--filter", f"name={container_name}" 47 | ] 48 | try: 49 | result = _run_docker_command(command) 50 | if result.stdout.strip(): 51 | print(f"Container '{container_name}' is running (ID: {result.stdout.strip()}).") 52 | return True 53 | else: 54 | return False 55 | except Exception: 56 | raise 57 | 58 | 59 | def docker_container_exists(container_name): 60 | command = [ 61 | "docker", "ps", 62 | "-aq", 63 | "--filter", f"name={container_name}" 64 | ] 65 | try: 66 | result = _run_docker_command(command) 67 | if result.stdout.strip(): 68 | print(f"Container '{container_name}' exists (ID: {result.stdout.strip()}).") 69 | return True 70 | else: 71 | print(f"Container '{container_name}' does not exist.") 72 | return False 73 | except Exception: 74 | return False 75 | 76 | def start_heygem_service(volume_host_path): 77 | if is_docker_container_running(CONTAINER_NAME): 78 | print(f"\nContainer '{CONTAINER_NAME}' is already running. No action needed.") 79 | return True 80 | 81 | if docker_container_exists(CONTAINER_NAME): 82 | start_command = ["docker", "start", CONTAINER_NAME] 83 | try: 84 | _run_docker_command(start_command, check_result=True) 85 | print(f"Successfully sent 'docker start {CONTAINER_NAME}' command.") 86 | 87 | time.sleep(5) 88 | if is_docker_container_running(CONTAINER_NAME): 89 | print(f"Container '{CONTAINER_NAME}' confirmed as running after direct start.") 90 | return True 91 | else: 92 | print(f"Container '{CONTAINER_NAME}' did not become ready after direct start.") 93 | return False 94 | 95 | except Exception: 96 | print(f"Failed to directly start container '{CONTAINER_NAME}'. Falling back to docker-compose.", file=sys.stderr) 97 | pass 98 | 99 | docker_daemon_running = False 100 | try: 101 | _run_docker_command(["docker", "info"], check_result=True) 102 | docker_daemon_running = True 103 | print("Docker daemon is running and reachable.") 104 | except (subprocess.CalledProcessError, FileNotFoundError) as e: 105 | print("\n--- Docker Daemon Not Running ---", file=sys.stderr) 106 | print("Error: Could not connect to the Docker daemon.", file=sys.stderr) 107 | print("Cannot proceed with docker-compose without a running Docker daemon.", file=sys.stderr) 108 | print("\nPlease ensure the Docker daemon is running:", file=sys.stderr) 109 | 110 | if sys.platform.startswith('linux'): 111 | print(" - On Linux, try: 'sudo systemctl start docker' or 'sudo service docker start'", file=sys.stderr) 112 | elif sys.platform == 'win32': 113 | print(" - On Windows with Docker Desktop: Ensure Docker Desktop application is running.", file=sys.stderr) 114 | print(" - If running within WSL: Ensure Docker Desktop on Windows is running and WSL integration is enabled.", file=sys.stderr) 115 | elif sys.platform == 'darwin': 116 | print(" - On macOS: Ensure Docker Desktop application is running.", file=sys.stderr) 117 | else: 118 | print(" - Please consult your operating system documentation for starting the Docker service.", file=sys.stderr) 119 | 120 | print("-----------------------------------", file=sys.stderr) 121 | raise 122 | 123 | if docker_daemon_running: 124 | env_for_subprocess = os.environ.copy() 125 | env_for_subprocess[VOLUME_ENV_VAR] = volume_host_path 126 | env_for_subprocess['PWD'] = os.getcwd() 127 | 128 | compose_up_command = [ 129 | "docker-compose", 130 | "-f", 131 | DOCKER_COMPOSE_FILE, 132 | "up", 133 | "-d" 134 | ] 135 | 136 | try: 137 | subprocess.run( 138 | compose_up_command, 139 | check=True, 140 | env=env_for_subprocess, 141 | stdout=sys.stdout, 142 | stderr=sys.stderr 143 | ) 144 | print(f"\nSuccessfully executed 'docker-compose up -d' for '{CONTAINER_NAME}'.") 145 | 146 | wait_sec = 0 147 | max_wait_sec = 60 148 | wait_interval_sec = 3 149 | 150 | while wait_sec < max_wait_sec: 151 | if is_docker_container_running(CONTAINER_NAME): 152 | print(f"Container '{CONTAINER_NAME}' confirmed as running after docker-compose up.") 153 | return True 154 | 155 | try: 156 | status_command = ["docker", "inspect", "-f", "{{.State.Status}}", CONTAINER_NAME] 157 | status_result = _run_docker_command(status_command) 158 | status = status_result.stdout.strip() 159 | except Exception: 160 | pass 161 | 162 | time.sleep(wait_interval_sec) 163 | wait_sec += wait_interval_sec 164 | 165 | print(f"\nError: Timed out waiting for container '{CONTAINER_NAME}' to start after docker-compose up ({max_wait_sec}s).", file=sys.stderr) 166 | print("Please check container logs for details (e.g., 'docker logs {}').".format(CONTAINER_NAME), file=sys.stderr) 167 | return False 168 | 169 | except Exception: 170 | print(f"\nFailed to start '{CONTAINER_NAME}' using docker-compose. The command output above should provide details.", file=sys.stderr) 171 | return False 172 | 173 | else: 174 | print("Skipping docker-compose up because Docker daemon is not running.", file=sys.stderr) 175 | return False 176 | 177 | def _get_container_id(container_name): 178 | command = [ 179 | "docker", "ps", 180 | "-q", 181 | "--filter", f"name={container_name}" 182 | ] 183 | try: 184 | result = _run_docker_command(command) 185 | container_id = result.stdout.strip() 186 | if container_id: 187 | return container_id 188 | return None 189 | except Exception as e: 190 | print(f"Error getting container ID for '{container_name}': {e}", file=sys.stderr) 191 | return None 192 | 193 | def stop_heygem_service(): 194 | current_container_id = _get_container_id(CONTAINER_NAME) 195 | if not current_container_id: 196 | print(f"\nContainer '{CONTAINER_NAME}' is not running. No need to stop.") 197 | return True 198 | 199 | stop_command = ["docker", "stop", current_container_id] 200 | 201 | try: 202 | _run_docker_command(stop_command, check_result=True) 203 | print(f"\nSuccessfully sent 'docker stop {CONTAINER_NAME}' command.") 204 | 205 | except Exception as e: 206 | print(f"\nFailed to stop '{CONTAINER_NAME}' using 'docker stop': {e}. Please check the logs above.", file=sys.stderr) 207 | 208 | def process_tensor_by_duration(image_tensor, duration, mode='normal', fps=24): 209 | original_frames_count = image_tensor.shape[0] 210 | target_frames_count = int(duration * fps) 211 | 212 | if mode == 'normal': 213 | if target_frames_count <= original_frames_count: 214 | return image_tensor[:target_frames_count] 215 | else: 216 | return image_tensor 217 | 218 | frame_indices_to_write = [] 219 | original_indices = np.arange(original_frames_count) 220 | 221 | if mode == 'repeat': 222 | if target_frames_count <= original_frames_count: 223 | return image_tensor[:target_frames_count] 224 | 225 | while len(frame_indices_to_write) < target_frames_count: 226 | frame_indices_to_write.extend(original_indices) 227 | frame_indices_to_write = frame_indices_to_write[:target_frames_count] 228 | 229 | elif mode == 'pingpong': 230 | if target_frames_count <= original_frames_count: 231 | return image_tensor[:target_frames_count] 232 | 233 | forward_indices = original_indices 234 | backward_indices = original_indices[::-1] 235 | 236 | while len(frame_indices_to_write) < target_frames_count: 237 | frame_indices_to_write.extend(forward_indices) 238 | if len(frame_indices_to_write) < target_frames_count: 239 | frame_indices_to_write.extend(backward_indices) 240 | frame_indices_to_write = frame_indices_to_write[:target_frames_count] 241 | 242 | return image_tensor[frame_indices_to_write] 243 | 244 | def save_tensor_as_video(image_tensor, output_path, fps=24): 245 | if image_tensor.is_cuda: 246 | tensor_np = image_tensor.cpu().numpy() 247 | else: 248 | tensor_np = image_tensor.numpy() 249 | 250 | tensor_np = np.clip(np.round(tensor_np * 255), 0, 255).astype(np.uint8) 251 | 252 | try: 253 | writer_params = {'codec': 'ffv1'} 254 | with imageio.get_writer(output_path, fps=fps, **writer_params) as writer: 255 | for frame in tensor_np: 256 | writer.append_data(frame) 257 | print(f"Successfully saved video to {output_path} using FFV1 (lossless).") 258 | 259 | except Exception as e: 260 | print(f"Failed to use FFV1 codec: {e}. Trying libx264 with crf=0 (lossless, but might have YUV conversion).") 261 | try: 262 | ffmpeg_params = ['-crf', '0', '-pix_fmt', 'yuv444p'] 263 | 264 | with imageio.get_writer(output_path, fps=fps, codec='libx264', ffmpeg_params=ffmpeg_params) as writer: 265 | for frame in tensor_np: 266 | writer.append_data(frame) 267 | 268 | print(f"Successfully saved video to {output_path} using libx264 (crf=0, lossless).") 269 | 270 | except Exception as e_h264: 271 | print(f"Failed to use libx264 crf=0: {e_h264}. Falling back to default (potentially lossy).") 272 | try: 273 | with imageio.get_writer(output_path, fps=fps) as writer: 274 | for frame in tensor_np: 275 | writer.append_data(frame) 276 | print(f"Saved video to {output_path} using default imageio settings (potentially lossy).") 277 | except Exception as e_default: 278 | print(f"Failed even with default settings: {e_default}") 279 | print("Video saving failed.") 280 | 281 | def video_to_tensor(video_path): 282 | if not os.path.exists(video_path): 283 | raise FileNotFoundError(f"Video file not found: {video_path}") 284 | 285 | reader = None 286 | try: 287 | reader = imageio.get_reader(video_path) 288 | meta = reader.get_meta_data() 289 | 290 | width, height = meta['size'] 291 | channels = 3 292 | 293 | def frame_processor_generator(imgio_reader, expected_shape): 294 | for i, frame in enumerate(imgio_reader): 295 | if frame.shape[-1] == 4 and expected_shape[-1] == 3: 296 | frame = frame[:, :, :3] 297 | if frame.shape != expected_shape: 298 | print(f"Warning: Frame {i} has unexpected shape {frame.shape}. Expected {expected_shape}. Skipping.") 299 | continue 300 | 301 | frame_processed = (frame.astype(np.float32) / 255.0) 302 | 303 | yield frame_processed 304 | 305 | frame_shape = (height, width, channels) 306 | gen_instance = frame_processor_generator(reader, frame_shape) 307 | 308 | frames_np_flat = np.fromiter( 309 | gen_instance, 310 | np.dtype((np.float32, frame_shape)) 311 | ) 312 | 313 | num_loaded_frames = len(frames_np_flat) 314 | 315 | if num_loaded_frames == 0: 316 | reader.close() 317 | raise RuntimeError(f"Failed to load any frames from video '{video_path}'. Check video file.") 318 | 319 | frame_shape = (height, width, channels) 320 | gen_instance = frame_processor_generator(reader, frame_shape) 321 | 322 | frames_structured_np = np.fromiter( 323 | gen_instance, 324 | dtype=np.dtype((np.float32, frame_shape)) 325 | ) 326 | print(f"Finished reading frames. Structured numpy array shape: {frames_structured_np.shape}, dtype: {frames_structured_np.dtype}") 327 | 328 | num_loaded_frames = len(frames_structured_np) 329 | 330 | if num_loaded_frames == 0: 331 | reader.close() 332 | raise RuntimeError(f"Failed to load any frames from video '{video_path}'. Check video file or its content.") 333 | 334 | total_scalars = num_loaded_frames * height * width * channels 335 | try: 336 | if frames_structured_np.size * frames_structured_np.dtype.itemsize != total_scalars * np.dtype(np.float32).itemsize: 337 | pass 338 | 339 | frames_np = frames_structured_np.view(np.float32).reshape(-1, height, width, channels) 340 | print(f"Reshaped numpy array shape: {frames_np.shape}, dtype: {frames_np.dtype}") 341 | 342 | except Exception as reshape_e: 343 | print(f"Error reshaping numpy array after fromiter: {reshape_e}") 344 | reader.close() 345 | raise RuntimeError(f"Failed to reshape frame data loaded from '{video_path}'. Likely mismatch in expected frame dimensions or data.") from reshape_e 346 | 347 | try: 348 | tensor = torch.from_numpy(frames_np) 349 | print("Tensor conversion successful.") 350 | except Exception as tensor_e: 351 | print(f"Error converting numpy array to torch tensor: {tensor_e}") 352 | reader.close() 353 | raise RuntimeError(f"Failed to convert numpy array to torch tensor for '{video_path}'. Likely out of memory.") from tensor_e 354 | 355 | reader.close() 356 | 357 | print(f"Successfully loaded video '{video_path}' into tensor with shape {tensor.shape}.") 358 | return tensor 359 | 360 | except Exception as e: 361 | print(f"An error occurred during video loading for '{video_path}': {e}") 362 | if reader is not None: 363 | try: 364 | reader.close() 365 | except Exception: 366 | pass 367 | raise -------------------------------------------------------------------------------- /images/2025-05-22_22-41-52.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billwuhao/Comfyui_HeyGem/95a9e534babd68984bb70297ce67355d49642f1d/images/2025-05-22_22-41-52.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "heygem-mw" 3 | description = "HeyGem AI avatar." 4 | version = "1.0.3" 5 | license = {file = "LICENSE"} 6 | dependencies = [] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/billwuhao/Comfyui_HeyGem" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "mw" 14 | DisplayName = "Comfyui_HeyGem" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/billwuhao/Comfyui_HeyGem/95a9e534babd68984bb70297ce67355d49642f1d/requirements.txt --------------------------------------------------------------------------------