Spaces:
Running on Zero
Running on Zero
copia del Space que funciona
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +8 -0
- .gitignore +18 -0
- LICENSE +674 -0
- README.md +21 -13
- app.py +94 -0
- chain_injectors/__init__.py +50 -0
- chain_injectors/h3_controlnet_injector.py +115 -0
- chain_injectors/h3_guide_injector.py +152 -0
- chain_injectors/h3_ref_audio_injector.py +27 -0
- chain_injectors/h3_ref_img_injector.py +35 -0
- chain_injectors/h3_ref_video_injector.py +32 -0
- chain_injectors/lora_injector.py +76 -0
- comfy_integration/__init__.py +0 -0
- comfy_integration/nodes.py +57 -0
- comfy_integration/setup.py +95 -0
- core/__init__.py +0 -0
- core/generation_logic.py +131 -0
- core/model_manager.py +32 -0
- core/pipelines/__init__.py +0 -0
- core/pipelines/base_pipeline.py +55 -0
- core/pipelines/pipeline_input_processor.py +36 -0
- core/pipelines/workflow_executor.py +125 -0
- core/settings.py +134 -0
- core/shared_state.py +1 -0
- core/workflow_assembler.py +202 -0
- mcp_tools/__init__.py +42 -0
- mcp_tools/common.py +610 -0
- mcp_tools/error_schema.py +85 -0
- mcp_tools/get_task_list.py +11 -0
- mcp_tools/get_task_status.py +21 -0
- mcp_tools/hf_private.py +66 -0
- mcp_tools/mcp_gradio_integration.py +122 -0
- mcp_tools/run.py +94 -0
- mcp_tools/tool_handlers.py +19 -0
- requirements.txt +42 -0
- tests/test_h3_guide.py +373 -0
- ui/__init__.py +0 -0
- ui/events/__init__.py +1 -0
- ui/events/chain_handlers.py +222 -0
- ui/events/main.py +22 -0
- ui/h3_logic.py +198 -0
- ui/h3_ui.py +443 -0
- ui/layout.py +42 -0
- ui/shared/h3_fl2va_logic.py +138 -0
- ui/shared/h3_fl2va_recipe.yaml +157 -0
- ui/shared/h3_fl2va_ui.py +235 -0
- ui/shared/h3_ref2va_logic.py +137 -0
- ui/shared/h3_ref2va_recipe.yaml +172 -0
- ui/shared/h3_ref2va_ui.py +423 -0
- ui/shared/ui_components.py +203 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
refs/andres_voz_01.wav filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
refs/ficha_ramiro_A.webp filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
refs/ficha_wilson_A.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
refs/prueba_andres_base_v3.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
refs/ref_camioneta.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
refs/ref_clavo.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
refs/ref_patio_amanecer.png filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
refs/ref_patio_manana.png filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
*$py.class
|
| 4 |
+
|
| 5 |
+
# Environments & IDE
|
| 6 |
+
.env
|
| 7 |
+
.venv/
|
| 8 |
+
env/
|
| 9 |
+
venv/
|
| 10 |
+
.idea/
|
| 11 |
+
.vscode/
|
| 12 |
+
|
| 13 |
+
# Temporary files
|
| 14 |
+
*.tmp
|
| 15 |
+
*.temp
|
| 16 |
+
input/
|
| 17 |
+
output/
|
| 18 |
+
|
LICENSE
ADDED
|
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 29 June 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works.
|
| 12 |
+
|
| 13 |
+
The licenses for most software and other practical works are designed
|
| 14 |
+
to take away your freedom to share and change the works. By contrast,
|
| 15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
| 16 |
+
share and change all versions of a program--to make sure it remains free
|
| 17 |
+
software for all its users. We, the Free Software Foundation, use the
|
| 18 |
+
GNU General Public License for most of our software; it applies also to
|
| 19 |
+
any other work released this way by its authors. You can apply it to
|
| 20 |
+
your programs, too.
|
| 21 |
+
|
| 22 |
+
When we speak of free software, we are referring to freedom, not
|
| 23 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 24 |
+
have the freedom to distribute copies of free software (and charge for
|
| 25 |
+
them if you wish), that you receive source code or can get it if you
|
| 26 |
+
want it, that you can change the software or use pieces of it in new
|
| 27 |
+
free programs, and that you know you can do these things.
|
| 28 |
+
|
| 29 |
+
To protect your rights, we need to prevent others from denying you
|
| 30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
| 31 |
+
certain responsibilities if you distribute copies of the software, or if
|
| 32 |
+
you modify it: responsibilities to respect the freedom of others.
|
| 33 |
+
|
| 34 |
+
For example, if you distribute copies of such a program, whether
|
| 35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
| 36 |
+
freedoms that you received. You must make sure that they, too, receive
|
| 37 |
+
or can get the source code. And you must show them these terms so they
|
| 38 |
+
know their rights.
|
| 39 |
+
|
| 40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
| 41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
| 42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
| 43 |
+
|
| 44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
| 45 |
+
that there is no warranty for this free software. For both users' and
|
| 46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
| 47 |
+
changed, so that their problems will not be attributed erroneously to
|
| 48 |
+
authors of previous versions.
|
| 49 |
+
|
| 50 |
+
Some devices are designed to deny users access to install or run
|
| 51 |
+
modified versions of the software inside them, although the manufacturer
|
| 52 |
+
can do so. This is fundamentally incompatible with the aim of
|
| 53 |
+
protecting users' freedom to change the software. The systematic
|
| 54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
| 55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
| 56 |
+
have designed this version of the GPL to prohibit the practice for those
|
| 57 |
+
products. If such problems arise substantially in other domains, we
|
| 58 |
+
stand ready to extend this provision to those domains in future versions
|
| 59 |
+
of the GPL, as needed to protect the freedom of users.
|
| 60 |
+
|
| 61 |
+
Finally, every program is threatened constantly by software patents.
|
| 62 |
+
States should not allow patents to restrict development and use of
|
| 63 |
+
software on general-purpose computers, but in those that do, we wish to
|
| 64 |
+
avoid the special danger that patents applied to a free program could
|
| 65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
| 66 |
+
patents cannot be used to render the program non-free.
|
| 67 |
+
|
| 68 |
+
The precise terms and conditions for copying, distribution and
|
| 69 |
+
modification follow.
|
| 70 |
+
|
| 71 |
+
TERMS AND CONDITIONS
|
| 72 |
+
|
| 73 |
+
0. Definitions.
|
| 74 |
+
|
| 75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
| 76 |
+
|
| 77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 78 |
+
works, such as semiconductor masks.
|
| 79 |
+
|
| 80 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 82 |
+
"recipients" may be individuals or organizations.
|
| 83 |
+
|
| 84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 85 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 86 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 87 |
+
earlier work or a work "based on" the earlier work.
|
| 88 |
+
|
| 89 |
+
A "covered work" means either the unmodified Program or a work based
|
| 90 |
+
on the Program.
|
| 91 |
+
|
| 92 |
+
To "propagate" a work means to do anything with it that, without
|
| 93 |
+
permission, would make you directly or secondarily liable for
|
| 94 |
+
infringement under applicable copyright law, except executing it on a
|
| 95 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 96 |
+
distribution (with or without modification), making available to the
|
| 97 |
+
public, and in some countries other activities as well.
|
| 98 |
+
|
| 99 |
+
To "convey" a work means any kind of propagation that enables other
|
| 100 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 102 |
+
|
| 103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 104 |
+
to the extent that it includes a convenient and prominently visible
|
| 105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 106 |
+
tells the user that there is no warranty for the work (except to the
|
| 107 |
+
extent that warranties are provided), that licensees may convey the
|
| 108 |
+
work under this License, and how to view a copy of this License. If
|
| 109 |
+
the interface presents a list of user commands or options, such as a
|
| 110 |
+
menu, a prominent item in the list meets this criterion.
|
| 111 |
+
|
| 112 |
+
1. Source Code.
|
| 113 |
+
|
| 114 |
+
The "source code" for a work means the preferred form of the work
|
| 115 |
+
for making modifications to it. "Object code" means any non-source
|
| 116 |
+
form of a work.
|
| 117 |
+
|
| 118 |
+
A "Standard Interface" means an interface that either is an official
|
| 119 |
+
standard defined by a recognized standards body, or, in the case of
|
| 120 |
+
interfaces specified for a particular programming language, one that
|
| 121 |
+
is widely used among developers working in that language.
|
| 122 |
+
|
| 123 |
+
The "System Libraries" of an executable work include anything, other
|
| 124 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 125 |
+
packaging a Major Component, but which is not part of that Major
|
| 126 |
+
Component, and (b) serves only to enable use of the work with that
|
| 127 |
+
Major Component, or to implement a Standard Interface for which an
|
| 128 |
+
implementation is available to the public in source code form. A
|
| 129 |
+
"Major Component", in this context, means a major essential component
|
| 130 |
+
(kernel, window system, and so on) of the specific operating system
|
| 131 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 132 |
+
produce the work, or an object code interpreter used to run it.
|
| 133 |
+
|
| 134 |
+
The "Corresponding Source" for a work in object code form means all
|
| 135 |
+
the source code needed to generate, install, and (for an executable
|
| 136 |
+
work) run the object code and to modify the work, including scripts to
|
| 137 |
+
control those activities. However, it does not include the work's
|
| 138 |
+
System Libraries, or general-purpose tools or generally available free
|
| 139 |
+
programs which are used unmodified in performing those activities but
|
| 140 |
+
which are not part of the work. For example, Corresponding Source
|
| 141 |
+
includes interface definition files associated with source files for
|
| 142 |
+
the work, and the source code for shared libraries and dynamically
|
| 143 |
+
linked subprograms that the work is specifically designed to require,
|
| 144 |
+
such as by intimate data communication or control flow between those
|
| 145 |
+
subprograms and other parts of the work.
|
| 146 |
+
|
| 147 |
+
The Corresponding Source need not include anything that users
|
| 148 |
+
can regenerate automatically from other parts of the Corresponding
|
| 149 |
+
Source.
|
| 150 |
+
|
| 151 |
+
The Corresponding Source for a work in source code form is that
|
| 152 |
+
same work.
|
| 153 |
+
|
| 154 |
+
2. Basic Permissions.
|
| 155 |
+
|
| 156 |
+
All rights granted under this License are granted for the term of
|
| 157 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 158 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 159 |
+
permission to run the unmodified Program. The output from running a
|
| 160 |
+
covered work is covered by this License only if the output, given its
|
| 161 |
+
content, constitutes a covered work. This License acknowledges your
|
| 162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 163 |
+
|
| 164 |
+
You may make, run and propagate covered works that you do not
|
| 165 |
+
convey, without conditions so long as your license otherwise remains
|
| 166 |
+
in force. You may convey covered works to others for the sole purpose
|
| 167 |
+
of having them make modifications exclusively for you, or provide you
|
| 168 |
+
with facilities for running those works, provided that you comply with
|
| 169 |
+
the terms of this License in conveying all material for which you do
|
| 170 |
+
not control copyright. Those thus making or running the covered works
|
| 171 |
+
for you must do so exclusively on your behalf, under your direction
|
| 172 |
+
and control, on terms that prohibit them from making any copies of
|
| 173 |
+
your copyrighted material outside their relationship with you.
|
| 174 |
+
|
| 175 |
+
Conveying under any other circumstances is permitted solely under
|
| 176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 177 |
+
makes it unnecessary.
|
| 178 |
+
|
| 179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 180 |
+
|
| 181 |
+
No covered work shall be deemed part of an effective technological
|
| 182 |
+
measure under any applicable law fulfilling obligations under article
|
| 183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 184 |
+
similar laws prohibiting or restricting circumvention of such
|
| 185 |
+
measures.
|
| 186 |
+
|
| 187 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 188 |
+
circumvention of technological measures to the extent such circumvention
|
| 189 |
+
is effected by exercising rights under this License with respect to
|
| 190 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 191 |
+
modification of the work as a means of enforcing, against the work's
|
| 192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 193 |
+
technological measures.
|
| 194 |
+
|
| 195 |
+
4. Conveying Verbatim Copies.
|
| 196 |
+
|
| 197 |
+
You may convey verbatim copies of the Program's source code as you
|
| 198 |
+
receive it, in any medium, provided that you conspicuously and
|
| 199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 200 |
+
keep intact all notices stating that this License and any
|
| 201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 202 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 203 |
+
recipients a copy of this License along with the Program.
|
| 204 |
+
|
| 205 |
+
You may charge any price or no price for each copy that you convey,
|
| 206 |
+
and you may offer support or warranty protection for a fee.
|
| 207 |
+
|
| 208 |
+
5. Conveying Modified Source Versions.
|
| 209 |
+
|
| 210 |
+
You may convey a work based on the Program, or the modifications to
|
| 211 |
+
produce it from the Program, in the form of source code under the
|
| 212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 213 |
+
|
| 214 |
+
a) The work must carry prominent notices stating that you modified
|
| 215 |
+
it, and giving a relevant date.
|
| 216 |
+
|
| 217 |
+
b) The work must carry prominent notices stating that it is
|
| 218 |
+
released under this License and any conditions added under section
|
| 219 |
+
7. This requirement modifies the requirement in section 4 to
|
| 220 |
+
"keep intact all notices".
|
| 221 |
+
|
| 222 |
+
c) You must license the entire work, as a whole, under this
|
| 223 |
+
License to anyone who comes into possession of a copy. This
|
| 224 |
+
License will therefore apply, along with any applicable section 7
|
| 225 |
+
additional terms, to the whole of the work, and all its parts,
|
| 226 |
+
regardless of how they are packaged. This License gives no
|
| 227 |
+
permission to license the work in any other way, but it does not
|
| 228 |
+
invalidate such permission if you have separately received it.
|
| 229 |
+
|
| 230 |
+
d) If the work has interactive user interfaces, each must display
|
| 231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 233 |
+
work need not make them do so.
|
| 234 |
+
|
| 235 |
+
A compilation of a covered work with other separate and independent
|
| 236 |
+
works, which are not by their nature extensions of the covered work,
|
| 237 |
+
and which are not combined with it such as to form a larger program,
|
| 238 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 240 |
+
used to limit the access or legal rights of the compilation's users
|
| 241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 242 |
+
in an aggregate does not cause this License to apply to the other
|
| 243 |
+
parts of the aggregate.
|
| 244 |
+
|
| 245 |
+
6. Conveying Non-Source Forms.
|
| 246 |
+
|
| 247 |
+
You may convey a covered work in object code form under the terms
|
| 248 |
+
of sections 4 and 5, provided that you also convey the
|
| 249 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 250 |
+
in one of these ways:
|
| 251 |
+
|
| 252 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 253 |
+
(including a physical distribution medium), accompanied by the
|
| 254 |
+
Corresponding Source fixed on a durable physical medium
|
| 255 |
+
customarily used for software interchange.
|
| 256 |
+
|
| 257 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 258 |
+
(including a physical distribution medium), accompanied by a
|
| 259 |
+
written offer, valid for at least three years and valid for as
|
| 260 |
+
long as you offer spare parts or customer support for that product
|
| 261 |
+
model, to give anyone who possesses the object code either (1) a
|
| 262 |
+
copy of the Corresponding Source for all the software in the
|
| 263 |
+
product that is covered by this License, on a durable physical
|
| 264 |
+
medium customarily used for software interchange, for a price no
|
| 265 |
+
more than your reasonable cost of physically performing this
|
| 266 |
+
conveying of source, or (2) access to copy the
|
| 267 |
+
Corresponding Source from a network server at no charge.
|
| 268 |
+
|
| 269 |
+
c) Convey individual copies of the object code with a copy of the
|
| 270 |
+
written offer to provide the Corresponding Source. This
|
| 271 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 272 |
+
only if you received the object code with such an offer, in accord
|
| 273 |
+
with subsection 6b.
|
| 274 |
+
|
| 275 |
+
d) Convey the object code by offering access from a designated
|
| 276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 277 |
+
Corresponding Source in the same way through the same place at no
|
| 278 |
+
further charge. You need not require recipients to copy the
|
| 279 |
+
Corresponding Source along with the object code. If the place to
|
| 280 |
+
copy the object code is a network server, the Corresponding Source
|
| 281 |
+
may be on a different server (operated by you or a third party)
|
| 282 |
+
that supports equivalent copying facilities, provided you maintain
|
| 283 |
+
clear directions next to the object code saying where to find the
|
| 284 |
+
Corresponding Source. Regardless of what server hosts the
|
| 285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 286 |
+
available for as long as needed to satisfy these requirements.
|
| 287 |
+
|
| 288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 289 |
+
you inform other peers where the object code and Corresponding
|
| 290 |
+
Source of the work are being offered to the general public at no
|
| 291 |
+
charge under subsection 6d.
|
| 292 |
+
|
| 293 |
+
A separable portion of the object code, whose source code is excluded
|
| 294 |
+
from the Corresponding Source as a System Library, need not be
|
| 295 |
+
included in conveying the object code work.
|
| 296 |
+
|
| 297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 298 |
+
tangible personal property which is normally used for personal, family,
|
| 299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 302 |
+
product received by a particular user, "normally used" refers to a
|
| 303 |
+
typical or common use of that class of product, regardless of the status
|
| 304 |
+
of the particular user or of the way in which the particular user
|
| 305 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 306 |
+
is a consumer product regardless of whether the product has substantial
|
| 307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 308 |
+
the only significant mode of use of the product.
|
| 309 |
+
|
| 310 |
+
"Installation Information" for a User Product means any methods,
|
| 311 |
+
procedures, authorization keys, or other information required to install
|
| 312 |
+
and execute modified versions of a covered work in that User Product from
|
| 313 |
+
a modified version of its Corresponding Source. The information must
|
| 314 |
+
suffice to ensure that the continued functioning of the modified object
|
| 315 |
+
code is in no case prevented or interfered with solely because
|
| 316 |
+
modification has been made.
|
| 317 |
+
|
| 318 |
+
If you convey an object code work under this section in, or with, or
|
| 319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 320 |
+
part of a transaction in which the right of possession and use of the
|
| 321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 322 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 323 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 324 |
+
by the Installation Information. But this requirement does not apply
|
| 325 |
+
if neither you nor any third party retains the ability to install
|
| 326 |
+
modified object code on the User Product (for example, the work has
|
| 327 |
+
been installed in ROM).
|
| 328 |
+
|
| 329 |
+
The requirement to provide Installation Information does not include a
|
| 330 |
+
requirement to continue to provide support service, warranty, or updates
|
| 331 |
+
for a work that has been modified or installed by the recipient, or for
|
| 332 |
+
the User Product in which it has been modified or installed. Access to a
|
| 333 |
+
network may be denied when the modification itself materially and
|
| 334 |
+
adversely affects the operation of the network or violates the rules and
|
| 335 |
+
protocols for communication across the network.
|
| 336 |
+
|
| 337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 338 |
+
in accord with this section must be in a format that is publicly
|
| 339 |
+
documented (and with an implementation available to the public in
|
| 340 |
+
source code form), and must require no special password or key for
|
| 341 |
+
unpacking, reading or copying.
|
| 342 |
+
|
| 343 |
+
7. Additional Terms.
|
| 344 |
+
|
| 345 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 346 |
+
License by making exceptions from one or more of its conditions.
|
| 347 |
+
Additional permissions that are applicable to the entire Program shall
|
| 348 |
+
be treated as though they were included in this License, to the extent
|
| 349 |
+
that they are valid under applicable law. If additional permissions
|
| 350 |
+
apply only to part of the Program, that part may be used separately
|
| 351 |
+
under those permissions, but the entire Program remains governed by
|
| 352 |
+
this License without regard to the additional permissions.
|
| 353 |
+
|
| 354 |
+
When you convey a copy of a covered work, you may at your option
|
| 355 |
+
remove any additional permissions from that copy, or from any part of
|
| 356 |
+
it. (Additional permissions may be written to require their own
|
| 357 |
+
removal in certain cases when you modify the work.) You may place
|
| 358 |
+
additional permissions on material, added by you to a covered work,
|
| 359 |
+
for which you have or can give appropriate copyright permission.
|
| 360 |
+
|
| 361 |
+
Notwithstanding any other provision of this License, for material you
|
| 362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 363 |
+
that material) supplement the terms of this License with terms:
|
| 364 |
+
|
| 365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 366 |
+
terms of sections 15 and 16 of this License; or
|
| 367 |
+
|
| 368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 369 |
+
author attributions in that material or in the Appropriate Legal
|
| 370 |
+
Notices displayed by works containing it; or
|
| 371 |
+
|
| 372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 373 |
+
requiring that modified versions of such material be marked in
|
| 374 |
+
reasonable ways as different from the original version; or
|
| 375 |
+
|
| 376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 377 |
+
authors of the material; or
|
| 378 |
+
|
| 379 |
+
e) Declining to grant rights under trademark law for use of some
|
| 380 |
+
trade names, trademarks, or service marks; or
|
| 381 |
+
|
| 382 |
+
f) Requiring indemnification of licensors and authors of that
|
| 383 |
+
material by anyone who conveys the material (or modified versions of
|
| 384 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 385 |
+
any liability that these contractual assumptions directly impose on
|
| 386 |
+
those licensors and authors.
|
| 387 |
+
|
| 388 |
+
All other non-permissive additional terms are considered "further
|
| 389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 390 |
+
received it, or any part of it, contains a notice stating that it is
|
| 391 |
+
governed by this License along with a term that is a further
|
| 392 |
+
restriction, you may remove that term. If a license document contains
|
| 393 |
+
a further restriction but permits relicensing or conveying under this
|
| 394 |
+
License, you may add to a covered work material governed by the terms
|
| 395 |
+
of that license document, provided that the further restriction does
|
| 396 |
+
not survive such relicensing or conveying.
|
| 397 |
+
|
| 398 |
+
If you add terms to a covered work in accord with this section, you
|
| 399 |
+
must place, in the relevant source files, a statement of the
|
| 400 |
+
additional terms that apply to those files, or a notice indicating
|
| 401 |
+
where to find the applicable terms.
|
| 402 |
+
|
| 403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 404 |
+
form of a separately written license, or stated as exceptions;
|
| 405 |
+
the above requirements apply either way.
|
| 406 |
+
|
| 407 |
+
8. Termination.
|
| 408 |
+
|
| 409 |
+
You may not propagate or modify a covered work except as expressly
|
| 410 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 411 |
+
modify it is void, and will automatically terminate your rights under
|
| 412 |
+
this License (including any patent licenses granted under the third
|
| 413 |
+
paragraph of section 11).
|
| 414 |
+
|
| 415 |
+
However, if you cease all violation of this License, then your
|
| 416 |
+
license from a particular copyright holder is reinstated (a)
|
| 417 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 419 |
+
holder fails to notify you of the violation by some reasonable means
|
| 420 |
+
prior to 60 days after the cessation.
|
| 421 |
+
|
| 422 |
+
Moreover, your license from a particular copyright holder is
|
| 423 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 424 |
+
violation by some reasonable means, this is the first time you have
|
| 425 |
+
received notice of violation of this License (for any work) from that
|
| 426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 427 |
+
your receipt of the notice.
|
| 428 |
+
|
| 429 |
+
Termination of your rights under this section does not terminate the
|
| 430 |
+
licenses of parties who have received copies or rights from you under
|
| 431 |
+
this License. If your rights have been terminated and not permanently
|
| 432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 433 |
+
material under section 10.
|
| 434 |
+
|
| 435 |
+
9. Acceptance Not Required for Having Copies.
|
| 436 |
+
|
| 437 |
+
You are not required to accept this License in order to receive or
|
| 438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 440 |
+
to receive a copy likewise does not require acceptance. However,
|
| 441 |
+
nothing other than this License grants you permission to propagate or
|
| 442 |
+
modify any covered work. These actions infringe copyright if you do
|
| 443 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 444 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 445 |
+
|
| 446 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 447 |
+
|
| 448 |
+
Each time you convey a covered work, the recipient automatically
|
| 449 |
+
receives a license from the original licensors, to run, modify and
|
| 450 |
+
propagate that work, subject to this License. You are not responsible
|
| 451 |
+
for enforcing compliance by third parties with this License.
|
| 452 |
+
|
| 453 |
+
An "entity transaction" is a transaction transferring control of an
|
| 454 |
+
organization, or substantially all assets of one, or subdividing an
|
| 455 |
+
organization, or merging organizations. If propagation of a covered
|
| 456 |
+
work results from an entity transaction, each party to that
|
| 457 |
+
transaction who receives a copy of the work also receives whatever
|
| 458 |
+
licenses to the work the party's predecessor in interest had or could
|
| 459 |
+
give under the previous paragraph, plus a right to possession of the
|
| 460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 461 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 462 |
+
|
| 463 |
+
You may not impose any further restrictions on the exercise of the
|
| 464 |
+
rights granted or affirmed under this License. For example, you may
|
| 465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 466 |
+
rights granted under this License, and you may not initiate litigation
|
| 467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 468 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 469 |
+
sale, or importing the Program or any portion of it.
|
| 470 |
+
|
| 471 |
+
11. Patents.
|
| 472 |
+
|
| 473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 474 |
+
License of the Program or a work on which the Program is based. The
|
| 475 |
+
work thus licensed is called the contributor's "contributor version".
|
| 476 |
+
|
| 477 |
+
A contributor's "essential patent claims" are all patent claims
|
| 478 |
+
owned or controlled by the contributor, whether already acquired or
|
| 479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 480 |
+
by this License, of making, using, or selling its contributor version,
|
| 481 |
+
but do not include claims that would be infringed only as a
|
| 482 |
+
consequence of further modification of the contributor version. For
|
| 483 |
+
purposes of this definition, "control" includes the right to grant
|
| 484 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 485 |
+
this License.
|
| 486 |
+
|
| 487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 488 |
+
patent license under the contributor's essential patent claims, to
|
| 489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 490 |
+
propagate the contents of its contributor version.
|
| 491 |
+
|
| 492 |
+
In the following three paragraphs, a "patent license" is any express
|
| 493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 494 |
+
(such as an express permission to practice a patent or covenant not to
|
| 495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 496 |
+
party means to make such an agreement or commitment not to enforce a
|
| 497 |
+
patent against the party.
|
| 498 |
+
|
| 499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 500 |
+
and the Corresponding Source of the work is not available for anyone
|
| 501 |
+
to copy, free of charge and under the terms of this License, through a
|
| 502 |
+
publicly available network server or other readily accessible means,
|
| 503 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 506 |
+
consistent with the requirements of this License, to extend the patent
|
| 507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 508 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 509 |
+
covered work in a country, or your recipient's use of the covered work
|
| 510 |
+
in a country, would infringe one or more identifiable patents in that
|
| 511 |
+
country that you have reason to believe are valid.
|
| 512 |
+
|
| 513 |
+
If, pursuant to or in connection with a single transaction or
|
| 514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 515 |
+
covered work, and grant a patent license to some of the parties
|
| 516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 517 |
+
or convey a specific copy of the covered work, then the patent license
|
| 518 |
+
you grant is automatically extended to all recipients of the covered
|
| 519 |
+
work and works based on it.
|
| 520 |
+
|
| 521 |
+
A patent license is "discriminatory" if it does not include within
|
| 522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 524 |
+
specifically granted under this License. You may not convey a covered
|
| 525 |
+
work if you are a party to an arrangement with a third party that is
|
| 526 |
+
in the business of distributing software, under which you make payment
|
| 527 |
+
to the third party based on the extent of your activity of conveying
|
| 528 |
+
the work, and under which the third party grants, to any of the
|
| 529 |
+
parties who would receive the covered work from you, a discriminatory
|
| 530 |
+
patent license (a) in connection with copies of the covered work
|
| 531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 532 |
+
for and in connection with specific products or compilations that
|
| 533 |
+
contain the covered work, unless you entered into that arrangement,
|
| 534 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 535 |
+
|
| 536 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 537 |
+
any implied license or other defenses to infringement that may
|
| 538 |
+
otherwise be available to you under applicable patent law.
|
| 539 |
+
|
| 540 |
+
12. No Surrender of Others' Freedom.
|
| 541 |
+
|
| 542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 543 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 546 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 548 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 549 |
+
the Program, the only way you could satisfy both those terms and this
|
| 550 |
+
License would be to refrain entirely from conveying the Program.
|
| 551 |
+
|
| 552 |
+
13. Use with the GNU Affero General Public License.
|
| 553 |
+
|
| 554 |
+
Notwithstanding any other provision of this License, you have
|
| 555 |
+
permission to link or combine any covered work with a work licensed
|
| 556 |
+
under version 3 of the GNU Affero General Public License into a single
|
| 557 |
+
combined work, and to convey the resulting work. The terms of this
|
| 558 |
+
License will continue to apply to the part which is the covered work,
|
| 559 |
+
but the special requirements of the GNU Affero General Public License,
|
| 560 |
+
section 13, concerning interaction through a network will apply to the
|
| 561 |
+
combination as such.
|
| 562 |
+
|
| 563 |
+
14. Revised Versions of this License.
|
| 564 |
+
|
| 565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 566 |
+
the GNU General Public License from time to time. Such new versions will
|
| 567 |
+
be similar in spirit to the present version, but may differ in detail to
|
| 568 |
+
address new problems or concerns.
|
| 569 |
+
|
| 570 |
+
Each version is given a distinguishing version number. If the
|
| 571 |
+
Program specifies that a certain numbered version of the GNU General
|
| 572 |
+
Public License "or any later version" applies to it, you have the
|
| 573 |
+
option of following the terms and conditions either of that numbered
|
| 574 |
+
version or of any later version published by the Free Software
|
| 575 |
+
Foundation. If the Program does not specify a version number of the
|
| 576 |
+
GNU General Public License, you may choose any version ever published
|
| 577 |
+
by the Free Software Foundation.
|
| 578 |
+
|
| 579 |
+
If the Program specifies that a proxy can decide which future
|
| 580 |
+
versions of the GNU General Public License can be used, that proxy's
|
| 581 |
+
public statement of acceptance of a version permanently authorizes you
|
| 582 |
+
to choose that version for the Program.
|
| 583 |
+
|
| 584 |
+
Later license versions may give you additional or different
|
| 585 |
+
permissions. However, no additional obligations are imposed on any
|
| 586 |
+
author or copyright holder as a result of your choosing to follow a
|
| 587 |
+
later version.
|
| 588 |
+
|
| 589 |
+
15. Disclaimer of Warranty.
|
| 590 |
+
|
| 591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 599 |
+
|
| 600 |
+
16. Limitation of Liability.
|
| 601 |
+
|
| 602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 610 |
+
SUCH DAMAGES.
|
| 611 |
+
|
| 612 |
+
17. Interpretation of Sections 15 and 16.
|
| 613 |
+
|
| 614 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 615 |
+
above cannot be given local legal effect according to their terms,
|
| 616 |
+
reviewing courts shall apply local law that most closely approximates
|
| 617 |
+
an absolute waiver of all civil liability in connection with the
|
| 618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 619 |
+
copy of the Program in return for a fee.
|
| 620 |
+
|
| 621 |
+
END OF TERMS AND CONDITIONS
|
| 622 |
+
|
| 623 |
+
How to Apply These Terms to Your New Programs
|
| 624 |
+
|
| 625 |
+
If you develop a new program, and you want it to be of the greatest
|
| 626 |
+
possible use to the public, the best way to achieve this is to make it
|
| 627 |
+
free software which everyone can redistribute and change under these terms.
|
| 628 |
+
|
| 629 |
+
To do so, attach the following notices to the program. It is safest
|
| 630 |
+
to attach them to the start of each source file to most effectively
|
| 631 |
+
state the exclusion of warranty; and each file should have at least
|
| 632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 633 |
+
|
| 634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 635 |
+
Copyright (C) <year> <name of author>
|
| 636 |
+
|
| 637 |
+
This program is free software: you can redistribute it and/or modify
|
| 638 |
+
it under the terms of the GNU General Public License as published by
|
| 639 |
+
the Free Software Foundation, either version 3 of the License, or
|
| 640 |
+
(at your option) any later version.
|
| 641 |
+
|
| 642 |
+
This program is distributed in the hope that it will be useful,
|
| 643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 645 |
+
GNU General Public License for more details.
|
| 646 |
+
|
| 647 |
+
You should have received a copy of the GNU General Public License
|
| 648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 649 |
+
|
| 650 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 651 |
+
|
| 652 |
+
If the program does terminal interaction, make it output a short
|
| 653 |
+
notice like this when it starts in an interactive mode:
|
| 654 |
+
|
| 655 |
+
<program> Copyright (C) <year> <name of author>
|
| 656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
| 657 |
+
This is free software, and you are welcome to redistribute it
|
| 658 |
+
under certain conditions; type `show c' for details.
|
| 659 |
+
|
| 660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
| 661 |
+
parts of the General Public License. Of course, your program's commands
|
| 662 |
+
might be different; for a GUI interface, you would use an "about box".
|
| 663 |
+
|
| 664 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
| 667 |
+
<https://www.gnu.org/licenses/>.
|
| 668 |
+
|
| 669 |
+
The GNU General Public License does not permit incorporating your program
|
| 670 |
+
into proprietary programs. If your program is a subroutine library, you
|
| 671 |
+
may consider it more useful to permit linking proprietary applications with
|
| 672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
| 673 |
+
Public License instead of this License. But first, please read
|
| 674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
CHANGED
|
@@ -1,13 +1,21 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: MiniMax
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk: gradio
|
| 7 |
-
|
| 8 |
-
python_version:
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: MiniMax-H3
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
app_file: app.py
|
| 8 |
+
python_version: 3.12
|
| 9 |
+
short_description: Multi-task video generator with dynamic, chainable workflows
|
| 10 |
+
models:
|
| 11 |
+
# This Space supports a wide variety of image generation pipelines. To maintain transparency, credit the original creators, and help users explore the Hugging Face ecosystem, we list and link several types of models in our metadata:
|
| 12 |
+
# 1. **Directly Run Models:** Models and checkpoints actively loaded by our pipelines (configured via `yaml/file_list.yaml`).
|
| 13 |
+
# 2. **Upstream Base Models:** The original foundation architectures from which our optimized ports, quantized versions, or wrappers are derived.
|
| 14 |
+
# Directly Run Models
|
| 15 |
+
- Comfy-Org/MiniMax-H3
|
| 16 |
+
- Kijai/MiniMax-H3-experimental
|
| 17 |
+
# Upstream Base Models
|
| 18 |
+
- alibaba-pai/MiniMax-H3-Fun-Controlnet-Union
|
| 19 |
+
- alibaba-pai/MiniMax-H3-Fun-Controlnet-Union-2.0
|
| 20 |
+
- MiniMaxAI/MiniMax-H3
|
| 21 |
+
---
|
app.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import spaces
|
| 2 |
+
import os
|
| 3 |
+
import sys
|
| 4 |
+
import site
|
| 5 |
+
|
| 6 |
+
if "--use-sage-attention" not in sys.argv:
|
| 7 |
+
sys.argv.append("--use-sage-attention")
|
| 8 |
+
print("🚀 [SageAttention] Injected '--use-sage-attention' into sys.argv.")
|
| 9 |
+
|
| 10 |
+
APP_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 11 |
+
if APP_DIR not in sys.path:
|
| 12 |
+
sys.path.insert(0, APP_DIR)
|
| 13 |
+
print(f"✅ Added project root '{APP_DIR}' to sys.path.")
|
| 14 |
+
|
| 15 |
+
SAGE_PATCH_APPLIED = False
|
| 16 |
+
|
| 17 |
+
def apply_sage_attention_patch():
|
| 18 |
+
global SAGE_PATCH_APPLIED
|
| 19 |
+
if SAGE_PATCH_APPLIED:
|
| 20 |
+
return "SageAttention patch already applied."
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
from comfy import model_management
|
| 24 |
+
import sageattention
|
| 25 |
+
|
| 26 |
+
print("--- [Runtime Patch] sageattention package found. Applying patch... ---")
|
| 27 |
+
model_management.sage_attention_enabled = lambda: True
|
| 28 |
+
model_management.pytorch_attention_enabled = lambda: False
|
| 29 |
+
|
| 30 |
+
SAGE_PATCH_APPLIED = True
|
| 31 |
+
return "✅ Successfully enabled SageAttention."
|
| 32 |
+
except ImportError:
|
| 33 |
+
SAGE_PATCH_APPLIED = False
|
| 34 |
+
msg = "--- [Runtime Patch] ⚠️ sageattention package not found. Continuing with default attention. ---"
|
| 35 |
+
print(msg)
|
| 36 |
+
return msg
|
| 37 |
+
except Exception as e:
|
| 38 |
+
SAGE_PATCH_APPLIED = False
|
| 39 |
+
msg = f"--- [Runtime Patch] ❌ An error occurred while applying SageAttention patch: {e} ---"
|
| 40 |
+
print(msg)
|
| 41 |
+
return msg
|
| 42 |
+
|
| 43 |
+
@spaces.GPU
|
| 44 |
+
def dummy_gpu_for_startup():
|
| 45 |
+
print("--- [GPU Startup] Dummy function for startup check initiated. ---")
|
| 46 |
+
patch_result = apply_sage_attention_patch()
|
| 47 |
+
print(f"--- [GPU Startup] {patch_result} ---")
|
| 48 |
+
print("--- [GPU Startup] Startup check passed. ---")
|
| 49 |
+
return "Startup check passed."
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def create_app():
|
| 53 |
+
from comfy_integration import setup as setup_comfyui
|
| 54 |
+
|
| 55 |
+
print("--- [Setup] Starting ComfyUI initialization ---")
|
| 56 |
+
setup_comfyui.initialize_comfyui()
|
| 57 |
+
|
| 58 |
+
print("--- [Setup] Applying SageAttention Runtime Patch ---")
|
| 59 |
+
patch_result = apply_sage_attention_patch()
|
| 60 |
+
print(f"--- [Setup] {patch_result} ---")
|
| 61 |
+
|
| 62 |
+
print("--- [Setup] Reloading site-packages to detect newly installed packages... ---")
|
| 63 |
+
try:
|
| 64 |
+
site.main()
|
| 65 |
+
print("--- [Setup] ✅ Site-packages reloaded. ---")
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"--- [Setup] ⚠️ Warning: Could not fully reload site-packages: {e} ---")
|
| 68 |
+
|
| 69 |
+
print("--- Initiating GPU Startup Check & SageAttention Patch Verification ---")
|
| 70 |
+
try:
|
| 71 |
+
dummy_gpu_for_startup()
|
| 72 |
+
except BaseException as e:
|
| 73 |
+
err_msg = f"{type(e).__name__}: {str(e)}"
|
| 74 |
+
print(f"--- [GPU Startup] ⚠️ Warning: Startup check failed: {err_msg} ---")
|
| 75 |
+
|
| 76 |
+
print("--- Starting Application Setup ---")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
print("--- Environment configured. Proceeding with module imports. ---")
|
| 80 |
+
from ui.layout import build_ui
|
| 81 |
+
from ui.events import attach_event_handlers
|
| 82 |
+
import mcp_tools as mcp
|
| 83 |
+
print(f"✅ Loaded MCP module with tools: {[fn.__name__ for fn in mcp.MCP_FUNCTIONS]}")
|
| 84 |
+
|
| 85 |
+
print(f"✅ Working directory is stable: {os.getcwd()}")
|
| 86 |
+
|
| 87 |
+
demo = build_ui(attach_event_handlers)
|
| 88 |
+
return demo
|
| 89 |
+
|
| 90 |
+
demo = create_app()
|
| 91 |
+
|
| 92 |
+
if __name__ == "__main__":
|
| 93 |
+
print("--- Launching Gradio Interface ---")
|
| 94 |
+
demo.queue().launch(mcp_server=True, footer_links=["api", "gradio", "settings"])
|
chain_injectors/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import importlib
|
| 3 |
+
import pkgutil
|
| 4 |
+
|
| 5 |
+
def discover_injectors():
|
| 6 |
+
injectors = {}
|
| 7 |
+
package_dir = os.path.dirname(__file__)
|
| 8 |
+
|
| 9 |
+
for _, module_name, is_pkg in pkgutil.iter_modules([package_dir]):
|
| 10 |
+
if is_pkg or module_name.startswith('_'):
|
| 11 |
+
continue
|
| 12 |
+
|
| 13 |
+
full_module_name = f"chain_injectors.{module_name}"
|
| 14 |
+
try:
|
| 15 |
+
module = importlib.import_module(full_module_name)
|
| 16 |
+
if hasattr(module, 'inject') and callable(module.inject):
|
| 17 |
+
feature_name = getattr(module, 'FEATURE_NAME', None)
|
| 18 |
+
if not feature_name:
|
| 19 |
+
feature_name = module_name[:-9] if module_name.endswith('_injector') else module_name
|
| 20 |
+
|
| 21 |
+
chain_type = getattr(module, 'CHAIN_TYPE', None)
|
| 22 |
+
if not chain_type:
|
| 23 |
+
chain_type = f"dynamic_{feature_name}_chains"
|
| 24 |
+
|
| 25 |
+
injectors[chain_type] = module.inject
|
| 26 |
+
else:
|
| 27 |
+
print(f"Warning: Module '{full_module_name}' does not have a callable 'inject' function.")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"Error importing injector module '{full_module_name}': {e}")
|
| 30 |
+
|
| 31 |
+
return injectors
|
| 32 |
+
|
| 33 |
+
def get_registered_features():
|
| 34 |
+
features = {}
|
| 35 |
+
package_dir = os.path.dirname(__file__)
|
| 36 |
+
|
| 37 |
+
for _, module_name, is_pkg in pkgutil.iter_modules([package_dir]):
|
| 38 |
+
if is_pkg or module_name.startswith('_'):
|
| 39 |
+
continue
|
| 40 |
+
|
| 41 |
+
feature_name = module_name[:-9] if module_name.endswith('_injector') else module_name
|
| 42 |
+
full_module_name = f"chain_injectors.{module_name}"
|
| 43 |
+
chain_type = f"dynamic_{feature_name}_chains"
|
| 44 |
+
|
| 45 |
+
features[feature_name] = {
|
| 46 |
+
'module': full_module_name,
|
| 47 |
+
'chain_type': chain_type
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
return features
|
chain_injectors/h3_controlnet_injector.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def inject(assembler, chain_definition, chain_items):
|
| 2 |
+
"""
|
| 3 |
+
Dynamically injects H3 Fun ControlNet into the model pipeline.
|
| 4 |
+
Connects:
|
| 5 |
+
LoadVideo -> GetVideoComponents -> MiniMaxH3FunControlNetApply (control_video)
|
| 6 |
+
ModelPatchLoader (name) -> MiniMaxH3FunControlNetApply (model_patch)
|
| 7 |
+
Video VAE -> MiniMaxH3FunControlNetApply (vae)
|
| 8 |
+
Current Model -> MiniMaxH3FunControlNetApply (model) -> Target Nodes (basic_guider, basic_scheduler)
|
| 9 |
+
"""
|
| 10 |
+
if not chain_items:
|
| 11 |
+
return
|
| 12 |
+
|
| 13 |
+
# 1. Determine target nodes to receive the modified model output
|
| 14 |
+
target_nodes_def = chain_definition.get('target_nodes', [
|
| 15 |
+
'basic_guider:model',
|
| 16 |
+
'basic_scheduler:model'
|
| 17 |
+
])
|
| 18 |
+
|
| 19 |
+
# Locate current model connection from the first available target node
|
| 20 |
+
current_model_connection = None
|
| 21 |
+
for target_str in target_nodes_def:
|
| 22 |
+
if ':' in target_str:
|
| 23 |
+
node_name, input_name = target_str.split(':')
|
| 24 |
+
node_id = assembler.node_map.get(node_name)
|
| 25 |
+
if node_id and input_name in assembler.workflow.get(node_id, {}).get('inputs', {}):
|
| 26 |
+
current_model_connection = assembler.workflow[node_id]['inputs'][input_name]
|
| 27 |
+
break
|
| 28 |
+
|
| 29 |
+
if not current_model_connection:
|
| 30 |
+
# Fallback to unet_loader:0
|
| 31 |
+
unet_node_id = assembler.node_map.get('unet_loader')
|
| 32 |
+
if unet_node_id:
|
| 33 |
+
current_model_connection = [unet_node_id, 0]
|
| 34 |
+
else:
|
| 35 |
+
print("[H3 ControlNet Injector] Warning: Could not determine initial model connection. Skipping.")
|
| 36 |
+
return
|
| 37 |
+
|
| 38 |
+
# 2. Resolve VAE connection
|
| 39 |
+
vae_source_str = chain_definition.get('vae_source', 'video_vae_loader:0')
|
| 40 |
+
vae_connection = None
|
| 41 |
+
if vae_source_str and ':' in vae_source_str:
|
| 42 |
+
vae_node_name, vae_idx_str = vae_source_str.split(':')
|
| 43 |
+
vae_node_id = assembler.node_map.get(vae_node_name)
|
| 44 |
+
if vae_node_id:
|
| 45 |
+
vae_connection = [vae_node_id, int(vae_idx_str)]
|
| 46 |
+
else:
|
| 47 |
+
print(f"[H3 ControlNet Injector] Warning: VAE source '{vae_node_name}' not found in node_map.")
|
| 48 |
+
|
| 49 |
+
# 3. Iterate through active controlnet items and chain them
|
| 50 |
+
applied_count = 0
|
| 51 |
+
for item_data in chain_items:
|
| 52 |
+
video_file = item_data.get('video') or item_data.get('control_video') or item_data.get('file')
|
| 53 |
+
if not video_file:
|
| 54 |
+
continue
|
| 55 |
+
|
| 56 |
+
control_net_name = (
|
| 57 |
+
item_data.get('control_net_name') or
|
| 58 |
+
item_data.get('filepath') or
|
| 59 |
+
item_data.get('name') or
|
| 60 |
+
'minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors'
|
| 61 |
+
)
|
| 62 |
+
strength = float(item_data.get('strength', 1.0))
|
| 63 |
+
start_percent = 0
|
| 64 |
+
end_percent = 1
|
| 65 |
+
|
| 66 |
+
# Node: LoadVideo
|
| 67 |
+
load_vid_id = assembler._get_unique_id()
|
| 68 |
+
load_vid_node = assembler._get_node_template("LoadVideo")
|
| 69 |
+
load_vid_node['inputs']['file'] = video_file
|
| 70 |
+
if 'video-preview' in load_vid_node['inputs']:
|
| 71 |
+
load_vid_node['inputs']['video-preview'] = ""
|
| 72 |
+
load_vid_node['_meta'] = {"title": "Load Video"}
|
| 73 |
+
assembler.workflow[load_vid_id] = load_vid_node
|
| 74 |
+
|
| 75 |
+
# Node: GetVideoComponents
|
| 76 |
+
comp_id = assembler._get_unique_id()
|
| 77 |
+
comp_node = assembler._get_node_template("GetVideoComponents")
|
| 78 |
+
comp_node['inputs']['video'] = [load_vid_id, 0]
|
| 79 |
+
comp_node['_meta'] = {"title": "Extract Control Frames"}
|
| 80 |
+
assembler.workflow[comp_id] = comp_node
|
| 81 |
+
|
| 82 |
+
# Node: ModelPatchLoader
|
| 83 |
+
patch_id = assembler._get_unique_id()
|
| 84 |
+
patch_node = assembler._get_node_template("ModelPatchLoader")
|
| 85 |
+
patch_node['inputs']['name'] = control_net_name
|
| 86 |
+
patch_node['_meta'] = {"title": "Load Model Patch"}
|
| 87 |
+
assembler.workflow[patch_id] = patch_node
|
| 88 |
+
|
| 89 |
+
# Node: MiniMaxH3FunControlNetApply
|
| 90 |
+
apply_template_name = chain_definition.get('template', 'MiniMaxH3FunControlNetApply')
|
| 91 |
+
apply_id = assembler._get_unique_id()
|
| 92 |
+
apply_node = assembler._get_node_template(apply_template_name)
|
| 93 |
+
apply_node['inputs']['strength'] = strength
|
| 94 |
+
apply_node['inputs']['start_percent'] = 0
|
| 95 |
+
apply_node['inputs']['end_percent'] = 1
|
| 96 |
+
apply_node['inputs']['model'] = current_model_connection
|
| 97 |
+
apply_node['inputs']['model_patch'] = [patch_id, 0]
|
| 98 |
+
if vae_connection:
|
| 99 |
+
apply_node['inputs']['vae'] = vae_connection
|
| 100 |
+
apply_node['inputs']['control_video'] = [comp_id, 0]
|
| 101 |
+
apply_node['_meta'] = {"title": "Apply MiniMax H3 Fun ControlNet"}
|
| 102 |
+
assembler.workflow[apply_id] = apply_node
|
| 103 |
+
|
| 104 |
+
current_model_connection = [apply_id, 0]
|
| 105 |
+
applied_count += 1
|
| 106 |
+
|
| 107 |
+
# 4. Reconnect target nodes to the final model connection
|
| 108 |
+
if applied_count > 0:
|
| 109 |
+
for target_str in target_nodes_def:
|
| 110 |
+
if ':' in target_str:
|
| 111 |
+
node_name, input_name = target_str.split(':')
|
| 112 |
+
node_id = assembler.node_map.get(node_name)
|
| 113 |
+
if node_id and node_id in assembler.workflow:
|
| 114 |
+
assembler.workflow[node_id]['inputs'][input_name] = current_model_connection
|
| 115 |
+
print(f"[H3 ControlNet Injector] Successfully applied {applied_count} H3 ControlNet patch(es).")
|
chain_injectors/h3_guide_injector.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FEATURE_NAME = 'h3_guide'
|
| 2 |
+
CHAIN_TYPE = 'dynamic_h3_guide_chains'
|
| 3 |
+
|
| 4 |
+
def inject(assembler, chain_definition, chain_items):
|
| 5 |
+
"""
|
| 6 |
+
Dynamically injects MiniMaxH3AddGuide nodes into the conditioning pipeline.
|
| 7 |
+
Connects:
|
| 8 |
+
Initial:
|
| 9 |
+
positive: minimax_h3:0
|
| 10 |
+
latent: minimax_h3:1
|
| 11 |
+
vae: video_vae_loader:0
|
| 12 |
+
audio_vae: audio_vae_loader:0
|
| 13 |
+
Each guide item:
|
| 14 |
+
- Creates LoadImage (if item has image) or LoadVideo+GetVideoComponents (if video) or LoadAudio (if audio)
|
| 15 |
+
- Creates MiniMaxH3AddGuide with:
|
| 16 |
+
frame_idx: int(item['frame_idx'])
|
| 17 |
+
positive: current_positive
|
| 18 |
+
latent: latent_connection
|
| 19 |
+
vae: vae_connection
|
| 20 |
+
audio_vae: audio_vae_connection
|
| 21 |
+
image: [load_img_id, 0] or [comp_id, 0] (if present)
|
| 22 |
+
audio: [load_aud_id, 0] or [comp_id, 1] (if present)
|
| 23 |
+
- Updates current_positive = [guide_id, 0]
|
| 24 |
+
Finally:
|
| 25 |
+
Connects final current_positive to target_nodes (e.g. basic_guider:conditioning)
|
| 26 |
+
"""
|
| 27 |
+
if not chain_items or not isinstance(chain_items, list):
|
| 28 |
+
return
|
| 29 |
+
|
| 30 |
+
source_node_name = chain_definition.get('source_node', 'minimax_h3')
|
| 31 |
+
source_node_id = assembler.node_map.get(source_node_name)
|
| 32 |
+
if not source_node_id:
|
| 33 |
+
print(f"[H3 Guide Injector] Error: Source node '{source_node_name}' not found in node_map.")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
# 1. Resolve initial positive and latent connections from source node
|
| 37 |
+
current_positive = [source_node_id, int(chain_definition.get('source_output', 0))]
|
| 38 |
+
latent_conn = [source_node_id, 1]
|
| 39 |
+
|
| 40 |
+
# 2. Resolve VAE connections
|
| 41 |
+
vae_source_str = chain_definition.get('vae_source', 'video_vae_loader:0')
|
| 42 |
+
vae_conn = None
|
| 43 |
+
if vae_source_str and ':' in vae_source_str:
|
| 44 |
+
vae_node_name, vae_idx_str = vae_source_str.split(':')
|
| 45 |
+
vae_node_id = assembler.node_map.get(vae_node_name)
|
| 46 |
+
if vae_node_id:
|
| 47 |
+
vae_conn = [vae_node_id, int(vae_idx_str)]
|
| 48 |
+
else:
|
| 49 |
+
print(f"[H3 Guide Injector] Warning: VAE source '{vae_node_name}' not found in node_map.")
|
| 50 |
+
|
| 51 |
+
audio_vae_source_str = chain_definition.get('audio_vae_source', 'audio_vae_loader:0')
|
| 52 |
+
audio_vae_conn = None
|
| 53 |
+
if audio_vae_source_str and ':' in audio_vae_source_str:
|
| 54 |
+
a_vae_name, a_vae_idx_str = audio_vae_source_str.split(':')
|
| 55 |
+
a_vae_id = assembler.node_map.get(a_vae_name)
|
| 56 |
+
if a_vae_id:
|
| 57 |
+
audio_vae_conn = [a_vae_id, int(a_vae_idx_str)]
|
| 58 |
+
else:
|
| 59 |
+
print(f"[H3 Guide Injector] Warning: Audio VAE source '{a_vae_name}' not found in node_map.")
|
| 60 |
+
|
| 61 |
+
# 3. Filter valid guide items and sort by frame_idx
|
| 62 |
+
valid_items = []
|
| 63 |
+
for item in chain_items:
|
| 64 |
+
if not isinstance(item, dict):
|
| 65 |
+
continue
|
| 66 |
+
has_media = bool(item.get('image') or item.get('video') or item.get('audio'))
|
| 67 |
+
if has_media and item.get('frame_idx') is not None:
|
| 68 |
+
valid_items.append(item)
|
| 69 |
+
|
| 70 |
+
if not valid_items:
|
| 71 |
+
return
|
| 72 |
+
|
| 73 |
+
valid_items.sort(key=lambda x: int(x['frame_idx']))
|
| 74 |
+
|
| 75 |
+
target_nodes_def = chain_definition.get('target_nodes', ['basic_guider:conditioning'])
|
| 76 |
+
guide_template_name = chain_definition.get('template', 'MiniMaxH3AddGuide')
|
| 77 |
+
|
| 78 |
+
applied_count = 0
|
| 79 |
+
for idx, item in enumerate(valid_items):
|
| 80 |
+
frame_idx = int(item['frame_idx'])
|
| 81 |
+
image_conn = None
|
| 82 |
+
audio_conn = None
|
| 83 |
+
|
| 84 |
+
# Handle Image
|
| 85 |
+
if item.get('image'):
|
| 86 |
+
load_img_id = assembler._get_unique_id()
|
| 87 |
+
load_img_node = assembler._get_node_template("LoadImage")
|
| 88 |
+
load_img_node['inputs']['image'] = item['image']
|
| 89 |
+
load_img_node['_meta'] = {"title": f"Load Guide Image {idx+1}"}
|
| 90 |
+
assembler.workflow[load_img_id] = load_img_node
|
| 91 |
+
image_conn = [load_img_id, 0]
|
| 92 |
+
|
| 93 |
+
# Handle Video
|
| 94 |
+
if item.get('video'):
|
| 95 |
+
load_vid_id = assembler._get_unique_id()
|
| 96 |
+
load_vid_node = assembler._get_node_template("LoadVideo")
|
| 97 |
+
load_vid_node['inputs']['file'] = item['video']
|
| 98 |
+
if 'video-preview' in load_vid_node['inputs']:
|
| 99 |
+
load_vid_node['inputs']['video-preview'] = ""
|
| 100 |
+
load_vid_node['_meta'] = {"title": f"Load Guide Video {idx+1}"}
|
| 101 |
+
assembler.workflow[load_vid_id] = load_vid_node
|
| 102 |
+
|
| 103 |
+
comp_id = assembler._get_unique_id()
|
| 104 |
+
comp_node = assembler._get_node_template("GetVideoComponents")
|
| 105 |
+
comp_node['inputs']['video'] = [load_vid_id, 0]
|
| 106 |
+
comp_node['_meta'] = {"title": f"Extract Guide Components {idx+1}"}
|
| 107 |
+
assembler.workflow[comp_id] = comp_node
|
| 108 |
+
|
| 109 |
+
image_conn = [comp_id, 0]
|
| 110 |
+
if not item.get('audio'):
|
| 111 |
+
audio_conn = [comp_id, 1]
|
| 112 |
+
|
| 113 |
+
# Handle Audio
|
| 114 |
+
if item.get('audio'):
|
| 115 |
+
load_aud_id = assembler._get_unique_id()
|
| 116 |
+
load_aud_node = assembler._get_node_template("LoadAudio")
|
| 117 |
+
load_aud_node['inputs']['audio'] = item['audio']
|
| 118 |
+
load_aud_node['_meta'] = {"title": f"Load Guide Audio {idx+1}"}
|
| 119 |
+
assembler.workflow[load_aud_id] = load_aud_node
|
| 120 |
+
audio_conn = [load_aud_id, 0]
|
| 121 |
+
|
| 122 |
+
# Create MiniMaxH3AddGuide
|
| 123 |
+
guide_id = assembler._get_unique_id()
|
| 124 |
+
guide_node = assembler._get_node_template(guide_template_name)
|
| 125 |
+
guide_node['inputs']['frame_idx'] = frame_idx
|
| 126 |
+
guide_node['inputs']['positive'] = current_positive
|
| 127 |
+
guide_node['inputs']['latent'] = latent_conn
|
| 128 |
+
if vae_conn:
|
| 129 |
+
guide_node['inputs']['vae'] = vae_conn
|
| 130 |
+
if audio_vae_conn:
|
| 131 |
+
guide_node['inputs']['audio_vae'] = audio_vae_conn
|
| 132 |
+
if image_conn:
|
| 133 |
+
guide_node['inputs']['image'] = image_conn
|
| 134 |
+
if audio_conn:
|
| 135 |
+
guide_node['inputs']['audio'] = audio_conn
|
| 136 |
+
guide_node['_meta'] = {"title": f"Add Guide for MiniMax H3 (frame {frame_idx})"}
|
| 137 |
+
assembler.workflow[guide_id] = guide_node
|
| 138 |
+
|
| 139 |
+
# Update chain positive output
|
| 140 |
+
current_positive = [guide_id, 0]
|
| 141 |
+
applied_count += 1
|
| 142 |
+
|
| 143 |
+
# 4. Reconnect target conditioning nodes to the end of the guide chain
|
| 144 |
+
if applied_count > 0:
|
| 145 |
+
for target_str in target_nodes_def:
|
| 146 |
+
if ':' in target_str:
|
| 147 |
+
node_name, input_name = target_str.split(':')
|
| 148 |
+
node_id = assembler.node_map.get(node_name)
|
| 149 |
+
if node_id and node_id in assembler.workflow:
|
| 150 |
+
assembler.workflow[node_id]['inputs'][input_name] = current_positive
|
| 151 |
+
|
| 152 |
+
print(f"[H3 Guide Injector] Successfully chained {applied_count} MiniMax H3 guide(s).")
|
chain_injectors/h3_ref_audio_injector.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def inject(assembler, chain_definition, chain_items):
|
| 2 |
+
"""
|
| 3 |
+
Dynamically injects uploaded reference audios into MiniMaxH3ReferenceToVideo node.
|
| 4 |
+
chain_items is a list of saved audio filenames.
|
| 5 |
+
"""
|
| 6 |
+
if not chain_items or not isinstance(chain_items, list):
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
target_node_name = chain_definition.get('target_node', 'minimax_h3')
|
| 10 |
+
target_node_id = assembler.node_map.get(target_node_name)
|
| 11 |
+
if not target_node_id:
|
| 12 |
+
print(f"[H3 RefAudio Injector] Error: Target node '{target_node_name}' not found in node_map.")
|
| 13 |
+
return
|
| 14 |
+
|
| 15 |
+
minimax_h3_node = assembler.workflow[target_node_id]
|
| 16 |
+
|
| 17 |
+
valid_audios = [aud for aud in chain_items if aud]
|
| 18 |
+
for idx, audio_file in enumerate(valid_audios):
|
| 19 |
+
load_id = assembler._get_unique_id()
|
| 20 |
+
load_node = assembler._get_node_template("LoadAudio")
|
| 21 |
+
load_node['inputs']['audio'] = audio_file
|
| 22 |
+
assembler.workflow[load_id] = load_node
|
| 23 |
+
|
| 24 |
+
param_name = f"ref_audios.ref_audio_{idx}"
|
| 25 |
+
minimax_h3_node['inputs'][param_name] = [load_id, 0]
|
| 26 |
+
|
| 27 |
+
print(f"[H3 RefAudio Injector] Successfully injected {len(valid_audios)} reference audio(s).")
|
chain_injectors/h3_ref_img_injector.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def inject(assembler, chain_definition, chain_items):
|
| 2 |
+
"""
|
| 3 |
+
Dynamically injects uploaded reference images into MiniMaxH3ReferenceToVideo node.
|
| 4 |
+
chain_items is a list of saved image filenames.
|
| 5 |
+
"""
|
| 6 |
+
if not chain_items or not isinstance(chain_items, list):
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
target_node_name = chain_definition.get('target_node', 'minimax_h3')
|
| 10 |
+
target_node_id = assembler.node_map.get(target_node_name)
|
| 11 |
+
if not target_node_id:
|
| 12 |
+
print(f"[H3 RefImg Injector] Error: Target node '{target_node_name}' not found in node_map.")
|
| 13 |
+
return
|
| 14 |
+
|
| 15 |
+
minimax_h3_node = assembler.workflow[target_node_id]
|
| 16 |
+
|
| 17 |
+
valid_images = [img for img in chain_items if img]
|
| 18 |
+
for idx, img_file in enumerate(valid_images):
|
| 19 |
+
load_id = assembler._get_unique_id()
|
| 20 |
+
load_node = assembler._get_node_template("LoadImage")
|
| 21 |
+
load_node['inputs']['image'] = img_file
|
| 22 |
+
assembler.workflow[load_id] = load_node
|
| 23 |
+
|
| 24 |
+
scale_id = assembler._get_unique_id()
|
| 25 |
+
scale_node = assembler._get_node_template("ImageScaleToTotalPixels")
|
| 26 |
+
scale_node['inputs']['image'] = [load_id, 0]
|
| 27 |
+
scale_node['inputs']['upscale_method'] = "nearest-exact"
|
| 28 |
+
scale_node['inputs']['megapixels'] = 1
|
| 29 |
+
scale_node['inputs']['resolution_steps'] = 1
|
| 30 |
+
assembler.workflow[scale_id] = scale_node
|
| 31 |
+
|
| 32 |
+
param_name = f"ref_images.ref_image_{idx}"
|
| 33 |
+
minimax_h3_node['inputs'][param_name] = [scale_id, 0]
|
| 34 |
+
|
| 35 |
+
print(f"[H3 RefImg Injector] Successfully injected {len(valid_images)} reference image(s).")
|
chain_injectors/h3_ref_video_injector.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def inject(assembler, chain_definition, chain_items):
|
| 2 |
+
"""
|
| 3 |
+
Dynamically injects uploaded reference videos into MiniMaxH3ReferenceToVideo node.
|
| 4 |
+
chain_items is a list of saved video filenames.
|
| 5 |
+
"""
|
| 6 |
+
if not chain_items or not isinstance(chain_items, list):
|
| 7 |
+
return
|
| 8 |
+
|
| 9 |
+
target_node_name = chain_definition.get('target_node', 'minimax_h3')
|
| 10 |
+
target_node_id = assembler.node_map.get(target_node_name)
|
| 11 |
+
if not target_node_id:
|
| 12 |
+
print(f"[H3 RefVideo Injector] Error: Target node '{target_node_name}' not found in node_map.")
|
| 13 |
+
return
|
| 14 |
+
|
| 15 |
+
minimax_h3_node = assembler.workflow[target_node_id]
|
| 16 |
+
|
| 17 |
+
valid_videos = [vid for vid in chain_items if vid]
|
| 18 |
+
for idx, video_file in enumerate(valid_videos):
|
| 19 |
+
load_id = assembler._get_unique_id()
|
| 20 |
+
load_node = assembler._get_node_template("LoadVideo")
|
| 21 |
+
load_node['inputs']['file'] = video_file
|
| 22 |
+
assembler.workflow[load_id] = load_node
|
| 23 |
+
|
| 24 |
+
comp_id = assembler._get_unique_id()
|
| 25 |
+
comp_node = assembler._get_node_template("GetVideoComponents")
|
| 26 |
+
comp_node['inputs']['video'] = [load_id, 0]
|
| 27 |
+
assembler.workflow[comp_id] = comp_node
|
| 28 |
+
|
| 29 |
+
minimax_h3_node['inputs'][f"ref_videos.ref_video_{idx}"] = [comp_id, 0]
|
| 30 |
+
minimax_h3_node['inputs'][f"ref_video_audios.ref_video_audio_{idx}"] = [comp_id, 1]
|
| 31 |
+
|
| 32 |
+
print(f"[H3 RefVideo Injector] Successfully injected {len(valid_videos)} reference video(s).")
|
chain_injectors/lora_injector.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
|
| 3 |
+
def inject(assembler, chain_definition, chain_items):
|
| 4 |
+
if not chain_items:
|
| 5 |
+
return
|
| 6 |
+
|
| 7 |
+
start_node_name = chain_definition.get('start')
|
| 8 |
+
start_node_id = None
|
| 9 |
+
if start_node_name:
|
| 10 |
+
if start_node_name not in assembler.node_map:
|
| 11 |
+
print(f"Warning: Start node '{start_node_name}' for dynamic LoRA chain not found. Skipping chain.")
|
| 12 |
+
return
|
| 13 |
+
start_node_id = assembler.node_map[start_node_name]
|
| 14 |
+
|
| 15 |
+
output_map = chain_definition.get('output_map', {})
|
| 16 |
+
current_connections = {}
|
| 17 |
+
for key, type_name in output_map.items():
|
| 18 |
+
if ':' in str(key):
|
| 19 |
+
node_name, idx_str = key.split(':')
|
| 20 |
+
if node_name not in assembler.node_map:
|
| 21 |
+
print(f"Warning: Node '{node_name}' in chain's output_map not found. Skipping.")
|
| 22 |
+
continue
|
| 23 |
+
node_id = assembler.node_map[node_name]
|
| 24 |
+
start_output_idx = int(idx_str)
|
| 25 |
+
current_connections[type_name] = [node_id, start_output_idx]
|
| 26 |
+
elif start_node_id:
|
| 27 |
+
start_output_idx = int(key)
|
| 28 |
+
current_connections[type_name] = [start_node_id, start_output_idx]
|
| 29 |
+
else:
|
| 30 |
+
print(f"Warning: LoRA chain has no 'start' node defined, and an output_map key '{key}' is not in 'node:index' format. Skipping this connection.")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
input_map = chain_definition.get('input_map', {})
|
| 34 |
+
chain_output_map = chain_definition.get('template_output_map', { "0": "model", "1": "clip" })
|
| 35 |
+
|
| 36 |
+
for item_data in chain_items:
|
| 37 |
+
template_name = chain_definition['template']
|
| 38 |
+
template = assembler._get_node_template(template_name)
|
| 39 |
+
node_data = deepcopy(template)
|
| 40 |
+
|
| 41 |
+
for param_name, value in item_data.items():
|
| 42 |
+
if param_name in node_data['inputs']:
|
| 43 |
+
node_data['inputs'][param_name] = value
|
| 44 |
+
|
| 45 |
+
if 'scale' in item_data:
|
| 46 |
+
scale_val = item_data['scale']
|
| 47 |
+
if 'strength_model' in node_data['inputs'] and (node_data['inputs']['strength_model'] is None or node_data['inputs']['strength_model'] == 1.0):
|
| 48 |
+
node_data['inputs']['strength_model'] = scale_val
|
| 49 |
+
if 'strength_clip' in node_data['inputs'] and (node_data['inputs']['strength_clip'] is None or node_data['inputs']['strength_clip'] == 1.0):
|
| 50 |
+
node_data['inputs']['strength_clip'] = scale_val
|
| 51 |
+
if 'lora_value' in item_data and ('lora_name' in node_data['inputs'] and not node_data['inputs']['lora_name']):
|
| 52 |
+
node_data['inputs']['lora_name'] = item_data['lora_value']
|
| 53 |
+
|
| 54 |
+
for type_name, input_name in input_map.items():
|
| 55 |
+
if type_name in current_connections:
|
| 56 |
+
node_data['inputs'][input_name] = current_connections[type_name]
|
| 57 |
+
|
| 58 |
+
new_node_id = assembler._get_unique_id()
|
| 59 |
+
assembler.workflow[new_node_id] = node_data
|
| 60 |
+
|
| 61 |
+
for idx_str, type_name in chain_output_map.items():
|
| 62 |
+
current_connections[type_name] = [new_node_id, int(idx_str)]
|
| 63 |
+
|
| 64 |
+
end_input_map = chain_definition.get('end_input_map', {})
|
| 65 |
+
for type_name, targets in end_input_map.items():
|
| 66 |
+
if type_name in current_connections:
|
| 67 |
+
if not isinstance(targets, list):
|
| 68 |
+
targets = [targets]
|
| 69 |
+
|
| 70 |
+
for target_str in targets:
|
| 71 |
+
end_node_name, end_input_name = target_str.split(':')
|
| 72 |
+
if end_node_name in assembler.node_map:
|
| 73 |
+
end_node_id = assembler.node_map[end_node_name]
|
| 74 |
+
assembler.workflow[end_node_id]['inputs'][end_input_name] = current_connections[type_name]
|
| 75 |
+
else:
|
| 76 |
+
print(f"Warning: End node '{end_node_name}' for dynamic chain not found. Skipping connection.")
|
comfy_integration/__init__.py
ADDED
|
File without changes
|
comfy_integration/nodes.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import execution
|
| 3 |
+
import server
|
| 4 |
+
from nodes import (
|
| 5 |
+
init_extra_nodes, CheckpointLoaderSimple, EmptyLatentImage, KSampler,
|
| 6 |
+
VAEDecode, SaveImage, NODE_CLASS_MAPPINGS, LoadImage, VAEEncode,
|
| 7 |
+
VAEEncodeForInpaint, ImagePadForOutpaint, LatentUpscaleBy, RepeatLatentBatch
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def import_custom_nodes() -> None:
|
| 12 |
+
loop = asyncio.new_event_loop()
|
| 13 |
+
asyncio.set_event_loop(loop)
|
| 14 |
+
try:
|
| 15 |
+
import inspect
|
| 16 |
+
sig = inspect.signature(server.PromptServer.__init__)
|
| 17 |
+
if "asset_manager" in sig.parameters:
|
| 18 |
+
from app.assets.manager import default_asset_manager
|
| 19 |
+
server_instance = server.PromptServer(loop, default_asset_manager())
|
| 20 |
+
else:
|
| 21 |
+
server_instance = server.PromptServer(loop)
|
| 22 |
+
except Exception:
|
| 23 |
+
try:
|
| 24 |
+
from app.assets.manager import default_asset_manager
|
| 25 |
+
server_instance = server.PromptServer(loop, default_asset_manager())
|
| 26 |
+
except Exception:
|
| 27 |
+
server_instance = server.PromptServer(loop)
|
| 28 |
+
execution.PromptQueue(server_instance)
|
| 29 |
+
|
| 30 |
+
loop.run_until_complete(init_extra_nodes())
|
| 31 |
+
|
| 32 |
+
import_custom_nodes()
|
| 33 |
+
|
| 34 |
+
CLIPTextEncode = NODE_CLASS_MAPPINGS['CLIPTextEncode']
|
| 35 |
+
CLIPTextEncodeSDXL = NODE_CLASS_MAPPINGS['CLIPTextEncodeSDXL']
|
| 36 |
+
LoraLoader = NODE_CLASS_MAPPINGS['LoraLoader']
|
| 37 |
+
CLIPSetLastLayer = NODE_CLASS_MAPPINGS['CLIPSetLastLayer']
|
| 38 |
+
|
| 39 |
+
if 'EmptyHunyuanImageLatent' in NODE_CLASS_MAPPINGS:
|
| 40 |
+
EmptyHunyuanImageLatent = NODE_CLASS_MAPPINGS['EmptyHunyuanImageLatent']
|
| 41 |
+
else:
|
| 42 |
+
print("⚠️ Warning: 'EmptyHunyuanImageLatent' not found in NODE_CLASS_MAPPINGS. HunyuanImage txt2img may fail if this node is required.")
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
KSamplerNode = NODE_CLASS_MAPPINGS['KSampler']
|
| 46 |
+
SAMPLER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["sampler_name"][0]
|
| 47 |
+
SCHEDULER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["scheduler"][0]
|
| 48 |
+
except Exception:
|
| 49 |
+
print("⚠️ Could not dynamically get sampler/scheduler choices, using fallback list.")
|
| 50 |
+
SAMPLER_CHOICES = ['euler', 'dpmpp_2m_sde_gpu']
|
| 51 |
+
SCHEDULER_CHOICES = ['normal', 'karras']
|
| 52 |
+
|
| 53 |
+
checkpointloadersimple = CheckpointLoaderSimple()
|
| 54 |
+
loraloader = LoraLoader()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
print("✅ ComfyUI custom nodes and class mappings are ready.")
|
comfy_integration/setup.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import shutil
|
| 4 |
+
|
| 5 |
+
from core.settings import *
|
| 6 |
+
|
| 7 |
+
def move_and_overwrite(src, dst):
|
| 8 |
+
if os.path.isdir(src):
|
| 9 |
+
os.makedirs(dst, exist_ok=True)
|
| 10 |
+
for item in os.listdir(src):
|
| 11 |
+
s_child = os.path.join(src, item)
|
| 12 |
+
d_child = os.path.join(dst, item)
|
| 13 |
+
move_and_overwrite(s_child, d_child)
|
| 14 |
+
elif os.path.isfile(src):
|
| 15 |
+
if os.path.exists(dst):
|
| 16 |
+
try:
|
| 17 |
+
os.remove(dst)
|
| 18 |
+
except OSError:
|
| 19 |
+
pass
|
| 20 |
+
shutil.move(src, dst)
|
| 21 |
+
|
| 22 |
+
def initialize_comfyui():
|
| 23 |
+
APP_DIR = sys.path[0]
|
| 24 |
+
COMFYUI_TEMP_DIR = "ComfyUI_temp"
|
| 25 |
+
|
| 26 |
+
print("--- Cloning ComfyUI Repository ---")
|
| 27 |
+
if not os.path.exists(COMFYUI_TEMP_DIR):
|
| 28 |
+
os.system(f"git clone https://github.com/comfy-Org/ComfyUI {COMFYUI_TEMP_DIR}")
|
| 29 |
+
print("✅ ComfyUI repository cloned.")
|
| 30 |
+
else:
|
| 31 |
+
print("✅ ComfyUI repository already exists.")
|
| 32 |
+
|
| 33 |
+
print(f"--- Merging ComfyUI from '{COMFYUI_TEMP_DIR}' to '{APP_DIR}' ---")
|
| 34 |
+
for item in os.listdir(COMFYUI_TEMP_DIR):
|
| 35 |
+
src_path = os.path.join(COMFYUI_TEMP_DIR, item)
|
| 36 |
+
dst_path = os.path.join(APP_DIR, item)
|
| 37 |
+
if item == '.git':
|
| 38 |
+
continue
|
| 39 |
+
move_and_overwrite(src_path, dst_path)
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
shutil.rmtree(COMFYUI_TEMP_DIR)
|
| 43 |
+
print("✅ ComfyUI merged and temporary directory removed.")
|
| 44 |
+
except OSError as e:
|
| 45 |
+
print(f"⚠️ Could not remove temporary directory '{COMFYUI_TEMP_DIR}': {e}")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
print(f"✅ Current working directory is: {os.getcwd()}")
|
| 51 |
+
|
| 52 |
+
# [ZeroGPU / Upstream ComfyUI Compatibility]
|
| 53 |
+
# Guard against ComfyUI PR #16746 is_integrated attribute check crash under ZeroGPU SimpleNamespace
|
| 54 |
+
try:
|
| 55 |
+
import torch
|
| 56 |
+
if hasattr(torch, "cuda") and hasattr(torch.cuda, "get_device_properties"):
|
| 57 |
+
_orig_gdp = torch.cuda.get_device_properties
|
| 58 |
+
def _safe_gdp(*args, **kwargs):
|
| 59 |
+
p = _orig_gdp(*args, **kwargs)
|
| 60 |
+
if not hasattr(p, "is_integrated"):
|
| 61 |
+
try:
|
| 62 |
+
p.is_integrated = False
|
| 63 |
+
except Exception:
|
| 64 |
+
pass
|
| 65 |
+
return p
|
| 66 |
+
torch.cuda.get_device_properties = _safe_gdp
|
| 67 |
+
except Exception:
|
| 68 |
+
pass
|
| 69 |
+
|
| 70 |
+
mm_path = os.path.join(APP_DIR, "comfy", "model_management.py")
|
| 71 |
+
if os.path.exists(mm_path):
|
| 72 |
+
try:
|
| 73 |
+
with open(mm_path, "r", encoding="utf-8") as f:
|
| 74 |
+
mm_code = f.read()
|
| 75 |
+
unsafe_check = "bool(torch.cuda.get_device_properties(device).is_integrated)"
|
| 76 |
+
safe_check = "bool(getattr(torch.cuda.get_device_properties(device), 'is_integrated', False))"
|
| 77 |
+
if unsafe_check in mm_code:
|
| 78 |
+
with open(mm_path, "w", encoding="utf-8") as f:
|
| 79 |
+
f.write(mm_code.replace(unsafe_check, safe_check))
|
| 80 |
+
print("🛡️ [Setup] Patched comfy/model_management.py for safe is_integrated attribute access.")
|
| 81 |
+
except Exception as e:
|
| 82 |
+
print(f"⚠️ [Setup] Failed to patch comfy/model_management.py: {e}")
|
| 83 |
+
|
| 84 |
+
import comfy.model_management
|
| 85 |
+
print("--- Environment Ready ---")
|
| 86 |
+
|
| 87 |
+
print("✅ ComfyUI initialized with default attention mechanism.")
|
| 88 |
+
|
| 89 |
+
for dir_path in CATEGORY_TO_DIR_MAP.values():
|
| 90 |
+
os.makedirs(os.path.join(APP_DIR, dir_path), exist_ok=True)
|
| 91 |
+
|
| 92 |
+
os.makedirs(os.path.join(APP_DIR, INPUT_DIR), exist_ok=True)
|
| 93 |
+
os.makedirs(os.path.join(APP_DIR, OUTPUT_DIR), exist_ok=True)
|
| 94 |
+
|
| 95 |
+
print("✅ All required model directories are present.")
|
core/__init__.py
ADDED
|
File without changes
|
core/generation_logic.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import glob
|
| 3 |
+
from typing import Any, Dict, List
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import spaces
|
| 6 |
+
|
| 7 |
+
from core.pipelines.workflow_executor import WorkflowExecutor
|
| 8 |
+
from core.model_manager import model_manager
|
| 9 |
+
|
| 10 |
+
def _extract_required_models(workflow: Dict[str, Any]) -> List[str]:
|
| 11 |
+
required_models = []
|
| 12 |
+
MODEL_KEYS = {'unet_name', 'clip_name', 'vae_name', 'model_name', 'ckpt_name', 'clip_name1', 'clip_name2'}
|
| 13 |
+
MODEL_EXTENSIONS = ('.safetensors', '.ckpt', '.pt', '.bin', '.pth')
|
| 14 |
+
|
| 15 |
+
for node_id, node_data in workflow.items():
|
| 16 |
+
if node_data.get('class_type') == 'LoraLoader':
|
| 17 |
+
continue
|
| 18 |
+
inputs = node_data.get('inputs', {})
|
| 19 |
+
for k, v in inputs.items():
|
| 20 |
+
if isinstance(v, str) and v and k != 'lora_name':
|
| 21 |
+
if k in MODEL_KEYS or any(v.lower().endswith(ext) for ext in MODEL_EXTENSIONS):
|
| 22 |
+
if v not in required_models and not v.startswith('[') and not v.endswith(']'):
|
| 23 |
+
required_models.append(v)
|
| 24 |
+
return required_models
|
| 25 |
+
|
| 26 |
+
def _extract_video_paths(out: Any) -> List[str]:
|
| 27 |
+
video_files = []
|
| 28 |
+
|
| 29 |
+
def process_item(item):
|
| 30 |
+
if item is None:
|
| 31 |
+
return
|
| 32 |
+
if isinstance(item, (list, tuple)):
|
| 33 |
+
for sub in item:
|
| 34 |
+
process_item(sub)
|
| 35 |
+
return
|
| 36 |
+
if isinstance(item, str) and os.path.exists(item):
|
| 37 |
+
video_files.append(item)
|
| 38 |
+
return
|
| 39 |
+
for attr in ['path', 'saved_path', 'filepath', 'filename', 'full_path']:
|
| 40 |
+
val = getattr(item, attr, None)
|
| 41 |
+
if isinstance(val, str) and os.path.exists(val):
|
| 42 |
+
video_files.append(val)
|
| 43 |
+
return
|
| 44 |
+
elif isinstance(val, str):
|
| 45 |
+
try:
|
| 46 |
+
import folder_paths
|
| 47 |
+
possible = os.path.join(folder_paths.get_output_directory(), val)
|
| 48 |
+
if os.path.exists(possible):
|
| 49 |
+
video_files.append(possible)
|
| 50 |
+
return
|
| 51 |
+
except Exception:
|
| 52 |
+
pass
|
| 53 |
+
if hasattr(item, '__dict__'):
|
| 54 |
+
for k, v in item.__dict__.items():
|
| 55 |
+
if isinstance(v, str) and (v.endswith('.mp4') or v.endswith('.webm') or v.endswith('.gif')):
|
| 56 |
+
if os.path.exists(v):
|
| 57 |
+
video_files.append(v)
|
| 58 |
+
return
|
| 59 |
+
try:
|
| 60 |
+
import folder_paths
|
| 61 |
+
possible = os.path.join(folder_paths.get_output_directory(), v)
|
| 62 |
+
if os.path.exists(possible):
|
| 63 |
+
video_files.append(possible)
|
| 64 |
+
return
|
| 65 |
+
except Exception:
|
| 66 |
+
pass
|
| 67 |
+
if isinstance(item, dict):
|
| 68 |
+
ui_info = item.get("ui", {})
|
| 69 |
+
for key in ["images", "videos", "video"]:
|
| 70 |
+
for sub in ui_info.get(key, []):
|
| 71 |
+
if isinstance(sub, dict) and "filename" in sub:
|
| 72 |
+
fn = sub["filename"]
|
| 73 |
+
subfolder = sub.get("subfolder", "")
|
| 74 |
+
try:
|
| 75 |
+
import folder_paths
|
| 76 |
+
full = os.path.join(folder_paths.get_output_directory(), subfolder, fn) if subfolder else os.path.join(folder_paths.get_output_directory(), fn)
|
| 77 |
+
if os.path.exists(full):
|
| 78 |
+
video_files.append(full)
|
| 79 |
+
return
|
| 80 |
+
except Exception:
|
| 81 |
+
pass
|
| 82 |
+
|
| 83 |
+
process_item(out)
|
| 84 |
+
|
| 85 |
+
if not video_files:
|
| 86 |
+
try:
|
| 87 |
+
import folder_paths
|
| 88 |
+
out_dir = folder_paths.get_output_directory()
|
| 89 |
+
mp4_files = glob.glob(os.path.join(out_dir, "**", "*.mp4"), recursive=True)
|
| 90 |
+
if mp4_files:
|
| 91 |
+
mp4_files.sort(key=os.path.getmtime, reverse=True)
|
| 92 |
+
video_files.append(mp4_files[0])
|
| 93 |
+
except Exception:
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
return video_files
|
| 97 |
+
|
| 98 |
+
def _execute_h3_workflow_gpu(workflow: Dict[str, Any]):
|
| 99 |
+
initial_objects = {}
|
| 100 |
+
return WorkflowExecutor.execute_workflow(workflow, initial_objects=initial_objects)
|
| 101 |
+
|
| 102 |
+
def generate_h3_video_wrapper(process_inputs_func, ui_inputs: dict, progress=gr.Progress(track_tqdm=True)):
|
| 103 |
+
progress(0.1, desc="Assembling H3 Video Workflow...")
|
| 104 |
+
try:
|
| 105 |
+
workflow, extra_data = process_inputs_func(ui_inputs, progress=progress)
|
| 106 |
+
except TypeError:
|
| 107 |
+
workflow, extra_data = process_inputs_func(ui_inputs)
|
| 108 |
+
|
| 109 |
+
required_models = _extract_required_models(workflow)
|
| 110 |
+
if required_models:
|
| 111 |
+
progress(0.2, desc=f"Ensuring models are downloaded: {len(required_models)} file(s)...")
|
| 112 |
+
model_manager.ensure_models_downloaded(required_models, progress=progress)
|
| 113 |
+
|
| 114 |
+
zero_gpu_duration = ui_inputs.get('zero_gpu_duration', 120)
|
| 115 |
+
try:
|
| 116 |
+
duration = int(zero_gpu_duration)
|
| 117 |
+
except (ValueError, TypeError):
|
| 118 |
+
duration = 120
|
| 119 |
+
if duration <= 0:
|
| 120 |
+
duration = 120
|
| 121 |
+
|
| 122 |
+
progress(0.4, desc=f"Executing H3 Video Workflow on GPU (ZeroGPU {duration}s)...")
|
| 123 |
+
gpu_runner = spaces.GPU(duration=duration)(_execute_h3_workflow_gpu)
|
| 124 |
+
raw_output = gpu_runner(workflow)
|
| 125 |
+
|
| 126 |
+
video_files = _extract_video_paths(raw_output)
|
| 127 |
+
final_video = video_files[0] if video_files else None
|
| 128 |
+
print("✅ H3 Video generated successfully")
|
| 129 |
+
|
| 130 |
+
progress(1.0, desc="H3 Video Generation Complete!")
|
| 131 |
+
return final_video
|
core/model_manager.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
from typing import List
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from utils.app_utils import _ensure_model_downloaded
|
| 5 |
+
from core.settings import ALL_MODEL_MAP
|
| 6 |
+
|
| 7 |
+
class ModelManager:
|
| 8 |
+
_instance = None
|
| 9 |
+
|
| 10 |
+
def __new__(cls, *args, **kwargs):
|
| 11 |
+
if not cls._instance:
|
| 12 |
+
cls._instance = super(ModelManager, cls).__new__(cls, *args, **kwargs)
|
| 13 |
+
return cls._instance
|
| 14 |
+
|
| 15 |
+
def __init__(self):
|
| 16 |
+
if hasattr(self, 'initialized'):
|
| 17 |
+
return
|
| 18 |
+
self.initialized = True
|
| 19 |
+
print("✅ ModelManager initialized.")
|
| 20 |
+
|
| 21 |
+
def ensure_models_downloaded(self, required_models: List[str], progress):
|
| 22 |
+
print(f"--- [ModelManager] Ensuring models are downloaded: {required_models} ---")
|
| 23 |
+
for i, display_name in enumerate(required_models):
|
| 24 |
+
if progress and hasattr(progress, '__call__'):
|
| 25 |
+
progress(i / max(len(required_models), 1), desc=f"Checking file: {display_name}")
|
| 26 |
+
try:
|
| 27 |
+
_ensure_model_downloaded(display_name, progress)
|
| 28 |
+
except Exception as e:
|
| 29 |
+
raise gr.Error(f"Failed to download model '{display_name}'. Reason: {e}")
|
| 30 |
+
print(f"--- [ModelManager] ✅ All required models are present on disk. ---")
|
| 31 |
+
|
| 32 |
+
model_manager = ModelManager()
|
core/pipelines/__init__.py
ADDED
|
File without changes
|
core/pipelines/base_pipeline.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from abc import ABC, abstractmethod
|
| 2 |
+
from typing import List, Any, Dict
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import spaces
|
| 5 |
+
import tempfile
|
| 6 |
+
import imageio
|
| 7 |
+
import numpy as np
|
| 8 |
+
import sys
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
class BasePipeline(ABC):
|
| 12 |
+
def __init__(self):
|
| 13 |
+
from core.model_manager import model_manager
|
| 14 |
+
self.model_manager = model_manager
|
| 15 |
+
|
| 16 |
+
@abstractmethod
|
| 17 |
+
def get_required_models(self, **kwargs) -> List[str]:
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
@abstractmethod
|
| 21 |
+
def run(self, *args, progress: gr.Progress, **kwargs) -> Any:
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
def _ensure_models_downloaded(self, progress: gr.Progress, **kwargs):
|
| 25 |
+
"""Ensures model files are downloaded before requesting GPU."""
|
| 26 |
+
required_models = self.get_required_models(**kwargs)
|
| 27 |
+
self.model_manager.ensure_models_downloaded(required_models, progress=progress)
|
| 28 |
+
|
| 29 |
+
def _execute_gpu_logic(self, gpu_function: callable, duration: int, default_duration: int, task_name: str, *args, **kwargs):
|
| 30 |
+
final_duration = default_duration
|
| 31 |
+
try:
|
| 32 |
+
if duration is not None and int(duration) > 0:
|
| 33 |
+
final_duration = int(duration)
|
| 34 |
+
except (ValueError, TypeError):
|
| 35 |
+
print(f"Invalid ZeroGPU duration input for {task_name}. Using default {default_duration}s.")
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
print(f"Requesting ZeroGPU for {task_name} with duration: {final_duration} seconds.")
|
| 39 |
+
gpu_runner = spaces.GPU(duration=final_duration)(gpu_function)
|
| 40 |
+
|
| 41 |
+
return gpu_runner(*args, **kwargs)
|
| 42 |
+
|
| 43 |
+
def _encode_video_from_frames(self, frames_tensor_cpu: 'torch.Tensor', fps: int, progress: gr.Progress) -> str:
|
| 44 |
+
progress(0.9, desc="Encoding video on CPU...")
|
| 45 |
+
frames_np = (frames_tensor_cpu.numpy() * 255.0).astype(np.uint8)
|
| 46 |
+
|
| 47 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as temp_video_file:
|
| 48 |
+
video_path = temp_video_file.name
|
| 49 |
+
writer = imageio.get_writer(video_path, fps=fps, codec='libx264', quality=8)
|
| 50 |
+
for frame in frames_np:
|
| 51 |
+
writer.append_data(frame)
|
| 52 |
+
writer.close()
|
| 53 |
+
|
| 54 |
+
progress(1.0, desc="Done!")
|
| 55 |
+
return video_path
|
core/pipelines/pipeline_input_processor.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from typing import Dict, Any
|
| 4 |
+
|
| 5 |
+
from core.settings import LORA_DIR
|
| 6 |
+
from utils.app_utils import sanitize_filename, get_lora_path
|
| 7 |
+
|
| 8 |
+
def process_pipeline_inputs(ui_inputs: Dict[str, Any], progress: gr.Progress, workflow_model_type: str = "h3") -> Dict[str, Any]:
|
| 9 |
+
active_loras_for_gpu, active_loras_for_meta = [], []
|
| 10 |
+
lora_data = ui_inputs.get('lora_data', [])
|
| 11 |
+
if lora_data:
|
| 12 |
+
sources, ids, scales, files = lora_data[0::4], lora_data[1::4], lora_data[2::4], lora_data[3::4]
|
| 13 |
+
for i, (source, lora_id, scale, _) in enumerate(zip(sources, ids, scales, files)):
|
| 14 |
+
if scale > 0 and lora_id and lora_id.strip():
|
| 15 |
+
lora_filename = None
|
| 16 |
+
if source == "File":
|
| 17 |
+
lora_filename = sanitize_filename(lora_id)
|
| 18 |
+
local_path = os.path.join(LORA_DIR, lora_filename)
|
| 19 |
+
if not os.path.exists(local_path):
|
| 20 |
+
raise gr.Error(f"Uploaded LoRA file '{lora_id}' no longer exists on server. Please re-upload it.")
|
| 21 |
+
elif source in ("Civitai", "Hugging Face"):
|
| 22 |
+
local_path, status = get_lora_path(source, lora_id, os.environ.get("CIVITAI_API_KEY", ""), progress)
|
| 23 |
+
if local_path:
|
| 24 |
+
lora_filename = os.path.basename(local_path)
|
| 25 |
+
else:
|
| 26 |
+
raise gr.Error(f"Failed to prepare LoRA {lora_id}: {status}")
|
| 27 |
+
|
| 28 |
+
if lora_filename:
|
| 29 |
+
active_loras_for_gpu.append({"lora_name": lora_filename, "strength_model": scale, "strength_clip": scale})
|
| 30 |
+
active_loras_for_meta.append(f"{source} {lora_id}:{scale}")
|
| 31 |
+
|
| 32 |
+
return {
|
| 33 |
+
"active_loras_for_gpu": active_loras_for_gpu,
|
| 34 |
+
"active_loras_for_meta": active_loras_for_meta,
|
| 35 |
+
"temp_files_to_clean": []
|
| 36 |
+
}
|
core/pipelines/workflow_executor.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
from collections import defaultdict, deque
|
| 4 |
+
from typing import Dict, Any, List
|
| 5 |
+
from comfy_integration.nodes import NODE_CLASS_MAPPINGS
|
| 6 |
+
from utils.app_utils import get_value_at_index
|
| 7 |
+
|
| 8 |
+
class DummyHidden:
|
| 9 |
+
extra_pnginfo = None
|
| 10 |
+
prompt = None
|
| 11 |
+
|
| 12 |
+
class WorkflowExecutor:
|
| 13 |
+
@staticmethod
|
| 14 |
+
def topological_sort(workflow: Dict[str, Any]) -> List[str]:
|
| 15 |
+
graph = defaultdict(list)
|
| 16 |
+
in_degree = {node_id: 0 for node_id in workflow}
|
| 17 |
+
|
| 18 |
+
for node_id, node_info in workflow.items():
|
| 19 |
+
for input_value in node_info.get('inputs', {}).values():
|
| 20 |
+
if isinstance(input_value, list) and len(input_value) == 2 and isinstance(input_value[0], str):
|
| 21 |
+
source_node_id = input_value[0]
|
| 22 |
+
if source_node_id in workflow:
|
| 23 |
+
graph[source_node_id].append(node_id)
|
| 24 |
+
in_degree[node_id] += 1
|
| 25 |
+
|
| 26 |
+
queue = deque([node_id for node_id, degree in in_degree.items() if degree == 0])
|
| 27 |
+
|
| 28 |
+
sorted_nodes = []
|
| 29 |
+
while queue:
|
| 30 |
+
current_node_id = queue.popleft()
|
| 31 |
+
sorted_nodes.append(current_node_id)
|
| 32 |
+
|
| 33 |
+
for neighbor_node_id in graph[current_node_id]:
|
| 34 |
+
in_degree[neighbor_node_id] -= 1
|
| 35 |
+
if in_degree[neighbor_node_id] == 0:
|
| 36 |
+
queue.append(neighbor_node_id)
|
| 37 |
+
|
| 38 |
+
if len(sorted_nodes) != len(workflow):
|
| 39 |
+
raise RuntimeError("Workflow contains a cycle and cannot be executed.")
|
| 40 |
+
|
| 41 |
+
return sorted_nodes
|
| 42 |
+
|
| 43 |
+
@staticmethod
|
| 44 |
+
def execute_workflow(workflow: Dict[str, Any], initial_objects: Dict[str, Any]):
|
| 45 |
+
with torch.no_grad():
|
| 46 |
+
computed_outputs = initial_objects
|
| 47 |
+
|
| 48 |
+
sorted_node_ids = WorkflowExecutor.topological_sort(workflow)
|
| 49 |
+
|
| 50 |
+
final_node_id = None
|
| 51 |
+
for node_id in reversed(sorted_node_ids):
|
| 52 |
+
if workflow[node_id].get('class_type') in ['SaveVideo', 'CreateVideo']:
|
| 53 |
+
final_node_id = node_id
|
| 54 |
+
break
|
| 55 |
+
|
| 56 |
+
if final_node_id:
|
| 57 |
+
required_nodes = set()
|
| 58 |
+
nodes_to_visit = [final_node_id]
|
| 59 |
+
while nodes_to_visit:
|
| 60 |
+
curr_id = nodes_to_visit.pop()
|
| 61 |
+
if curr_id in required_nodes:
|
| 62 |
+
continue
|
| 63 |
+
required_nodes.add(curr_id)
|
| 64 |
+
curr_info = workflow.get(curr_id, {})
|
| 65 |
+
for input_val in curr_info.get('inputs', {}).values():
|
| 66 |
+
if isinstance(input_val, list) and len(input_val) == 2 and isinstance(input_val[0], str):
|
| 67 |
+
src_id = input_val[0]
|
| 68 |
+
if src_id in workflow and src_id not in required_nodes:
|
| 69 |
+
nodes_to_visit.append(src_id)
|
| 70 |
+
|
| 71 |
+
sorted_node_ids = [nid for nid in sorted_node_ids if nid in required_nodes]
|
| 72 |
+
|
| 73 |
+
print(f"--- [Workflow Executor] Execution order: {sorted_node_ids}")
|
| 74 |
+
|
| 75 |
+
for node_id in sorted_node_ids:
|
| 76 |
+
if node_id in computed_outputs:
|
| 77 |
+
continue
|
| 78 |
+
|
| 79 |
+
node_info = workflow[node_id]
|
| 80 |
+
class_type = node_info['class_type']
|
| 81 |
+
|
| 82 |
+
is_loader_with_filename = 'Loader' in class_type and any(key.endswith('_name') for key in node_info['inputs'])
|
| 83 |
+
if node_id in initial_objects and is_loader_with_filename:
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
node_class = NODE_CLASS_MAPPINGS.get(class_type)
|
| 87 |
+
if node_class is None:
|
| 88 |
+
raise RuntimeError(f"Could not find node class '{class_type}'. Is it imported in comfy_integration/nodes.py?")
|
| 89 |
+
|
| 90 |
+
node_instance = node_class()
|
| 91 |
+
|
| 92 |
+
if not hasattr(node_class, 'hidden') or getattr(node_class, 'hidden', None) is None:
|
| 93 |
+
setattr(node_class, 'hidden', DummyHidden())
|
| 94 |
+
if not hasattr(node_instance, 'hidden') or getattr(node_instance, 'hidden', None) is None:
|
| 95 |
+
setattr(node_instance, 'hidden', DummyHidden())
|
| 96 |
+
|
| 97 |
+
kwargs = {}
|
| 98 |
+
for param_name, param_value in node_info['inputs'].items():
|
| 99 |
+
if isinstance(param_value, list) and len(param_value) == 2 and isinstance(param_value[0], str):
|
| 100 |
+
source_node_id, output_index = param_value
|
| 101 |
+
if source_node_id not in computed_outputs:
|
| 102 |
+
raise RuntimeError(f"Workflow integrity error: Output of node {source_node_id} needed for {node_id} but not yet computed.")
|
| 103 |
+
|
| 104 |
+
source_output_tuple = computed_outputs[source_node_id]
|
| 105 |
+
actual_value = get_value_at_index(source_output_tuple, output_index)
|
| 106 |
+
else:
|
| 107 |
+
actual_value = param_value
|
| 108 |
+
|
| 109 |
+
if '.' in param_name:
|
| 110 |
+
parent_key, child_key = param_name.split('.', 1)
|
| 111 |
+
if parent_key not in kwargs or not isinstance(kwargs[parent_key], dict):
|
| 112 |
+
kwargs[parent_key] = {}
|
| 113 |
+
kwargs[parent_key][child_key] = actual_value
|
| 114 |
+
else:
|
| 115 |
+
kwargs[param_name] = actual_value
|
| 116 |
+
|
| 117 |
+
function_name = getattr(node_class, 'FUNCTION')
|
| 118 |
+
execution_method = getattr(node_instance, function_name)
|
| 119 |
+
|
| 120 |
+
result = execution_method(**kwargs)
|
| 121 |
+
computed_outputs[node_id] = result
|
| 122 |
+
|
| 123 |
+
out = computed_outputs.get(final_node_id, {})
|
| 124 |
+
print(f"--- [Workflow Executor] Raw final node output: {type(out)}")
|
| 125 |
+
return out
|
core/settings.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
import os
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
|
| 5 |
+
CHECKPOINT_DIR = "models/checkpoints"
|
| 6 |
+
LORA_DIR = "models/loras"
|
| 7 |
+
EMBEDDING_DIR = "models/embeddings"
|
| 8 |
+
CONTROLNET_DIR = "models/controlnet"
|
| 9 |
+
MODEL_PATCHES_DIR = "models/model_patches"
|
| 10 |
+
DIFFUSION_MODELS_DIR = "models/diffusion_models"
|
| 11 |
+
VAE_DIR = "models/vae"
|
| 12 |
+
TEXT_ENCODERS_DIR = "models/text_encoders"
|
| 13 |
+
STYLE_MODELS_DIR = "models/style_models"
|
| 14 |
+
CLIP_VISION_DIR = "models/clip_vision"
|
| 15 |
+
IPADAPTER_DIR = "models/ipadapter"
|
| 16 |
+
IPADAPTER_FLUX_DIR = "models/ipadapter-flux"
|
| 17 |
+
INPUT_DIR = "input"
|
| 18 |
+
OUTPUT_DIR = "output"
|
| 19 |
+
|
| 20 |
+
CATEGORY_TO_DIR_MAP = {
|
| 21 |
+
"diffusion_models": DIFFUSION_MODELS_DIR,
|
| 22 |
+
"text_encoders": TEXT_ENCODERS_DIR,
|
| 23 |
+
"vae": VAE_DIR,
|
| 24 |
+
"checkpoints": CHECKPOINT_DIR,
|
| 25 |
+
"loras": LORA_DIR,
|
| 26 |
+
"controlnet": CONTROLNET_DIR,
|
| 27 |
+
"model_patches": MODEL_PATCHES_DIR,
|
| 28 |
+
"embeddings": EMBEDDING_DIR,
|
| 29 |
+
"style_models": STYLE_MODELS_DIR,
|
| 30 |
+
"clip_vision": CLIP_VISION_DIR,
|
| 31 |
+
"ipadapter": IPADAPTER_DIR,
|
| 32 |
+
"ipadapter-flux": IPADAPTER_FLUX_DIR
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 36 |
+
_FILE_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'file_list.yaml')
|
| 37 |
+
_CONSTANTS_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'constants.yaml')
|
| 38 |
+
|
| 39 |
+
def load_constants_from_yaml(filepath=_CONSTANTS_PATH):
|
| 40 |
+
if not os.path.exists(filepath):
|
| 41 |
+
print(f"Warning: Constants file not found at {filepath}. Using fallback values.")
|
| 42 |
+
return {}
|
| 43 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 44 |
+
return yaml.safe_load(f)
|
| 45 |
+
|
| 46 |
+
def load_file_download_map(filepath=_FILE_LIST_PATH):
|
| 47 |
+
if not os.path.exists(filepath):
|
| 48 |
+
raise FileNotFoundError(f"The file list (for downloads) was not found at: {filepath}")
|
| 49 |
+
|
| 50 |
+
with open(filepath, 'r', encoding='utf-8') as f:
|
| 51 |
+
file_list_data = yaml.safe_load(f)
|
| 52 |
+
|
| 53 |
+
download_info_map = {}
|
| 54 |
+
for category, files in file_list_data.get('file', {}).items():
|
| 55 |
+
if isinstance(files, list):
|
| 56 |
+
for file_info in files:
|
| 57 |
+
if 'filename' in file_info:
|
| 58 |
+
file_info['category'] = category
|
| 59 |
+
download_info_map[file_info['filename']] = file_info
|
| 60 |
+
return download_info_map
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
ALL_FILE_DOWNLOAD_MAP = load_file_download_map()
|
| 64 |
+
|
| 65 |
+
category_to_model_type = {
|
| 66 |
+
"diffusion_models": "UNET",
|
| 67 |
+
"text_encoders": "TEXT_ENCODER",
|
| 68 |
+
"vae": "VAE",
|
| 69 |
+
"checkpoints": "SDXL",
|
| 70 |
+
"loras": "LORA",
|
| 71 |
+
"controlnet": "CONTROLNET",
|
| 72 |
+
"model_patches": "MODEL_PATCH",
|
| 73 |
+
"style_models": "STYLE",
|
| 74 |
+
"clip_vision": "CLIP_VISION",
|
| 75 |
+
"ipadapter": "IPADAPTER",
|
| 76 |
+
"ipadapter-flux": "IPADAPTER_FLUX"
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
MODEL_MAP_CHECKPOINT = OrderedDict()
|
| 80 |
+
ALL_MODEL_MAP = OrderedDict()
|
| 81 |
+
|
| 82 |
+
for filename, file_info in ALL_FILE_DOWNLOAD_MAP.items():
|
| 83 |
+
category = file_info.get('category')
|
| 84 |
+
repo_id = file_info.get('repo_id', '')
|
| 85 |
+
model_type = category_to_model_type.get(category, 'UNKNOWN')
|
| 86 |
+
|
| 87 |
+
model_tuple = (repo_id, filename, model_type, "latent", category)
|
| 88 |
+
ALL_MODEL_MAP[filename] = model_tuple
|
| 89 |
+
|
| 90 |
+
if category == 'checkpoints':
|
| 91 |
+
MODEL_MAP_CHECKPOINT[filename] = model_tuple
|
| 92 |
+
|
| 93 |
+
MODEL_TYPE_MAP = {k: v[2] for k, v in ALL_MODEL_MAP.items()}
|
| 94 |
+
|
| 95 |
+
ARCH_CATEGORIES_MAP = {}
|
| 96 |
+
for display_name, info in MODEL_MAP_CHECKPOINT.items():
|
| 97 |
+
arch = info[2]
|
| 98 |
+
cat = info[4] if len(info) > 4 else None
|
| 99 |
+
if arch not in ARCH_CATEGORIES_MAP:
|
| 100 |
+
ARCH_CATEGORIES_MAP[arch] = []
|
| 101 |
+
if cat and cat not in ARCH_CATEGORIES_MAP[arch]:
|
| 102 |
+
ARCH_CATEGORIES_MAP[arch].append(cat)
|
| 103 |
+
|
| 104 |
+
except Exception as e:
|
| 105 |
+
print(f"FATAL: Could not load file download map from YAML. Error: {e}")
|
| 106 |
+
ALL_FILE_DOWNLOAD_MAP = {}
|
| 107 |
+
MODEL_MAP_CHECKPOINT, ALL_MODEL_MAP = OrderedDict(), OrderedDict()
|
| 108 |
+
MODEL_TYPE_MAP = {}
|
| 109 |
+
ARCH_CATEGORIES_MAP = {}
|
| 110 |
+
|
| 111 |
+
try:
|
| 112 |
+
_constants = load_constants_from_yaml()
|
| 113 |
+
MAX_LORAS = _constants.get('MAX_LORAS', 10)
|
| 114 |
+
MAX_EMBEDDINGS = _constants.get('MAX_EMBEDDINGS', 5)
|
| 115 |
+
MAX_CONDITIONINGS = _constants.get('MAX_CONDITIONINGS', 10)
|
| 116 |
+
MAX_CONTROLNETS = _constants.get('MAX_CONTROLNETS', 5)
|
| 117 |
+
MAX_H3_GUIDES = _constants.get('MAX_H3_GUIDES', 5)
|
| 118 |
+
MAX_IPADAPTERS = _constants.get('MAX_IPADAPTERS', 5)
|
| 119 |
+
LORA_SOURCE_CHOICES = _constants.get('LORA_SOURCE_CHOICES', ["Hugging Face", "Civitai", "File"])
|
| 120 |
+
RESOLUTION_MAP = _constants.get('RESOLUTION_MAP', {})
|
| 121 |
+
MULTIPLIERS_MAP = _constants.get('MULTIPLIERS_MAP', {})
|
| 122 |
+
ARCHITECTURES_CONFIG = {"architectures": {}, "architecture_order": []}
|
| 123 |
+
FEATURES_CONFIG = {"default": {"enabled_chains": ["lora"]}}
|
| 124 |
+
MODEL_DEFAULTS_CONFIG = {"Default": {}}
|
| 125 |
+
except Exception as e:
|
| 126 |
+
print(f"FATAL: Could not load constants from YAML. Error: {e}")
|
| 127 |
+
MAX_LORAS, MAX_EMBEDDINGS, MAX_CONDITIONINGS, MAX_CONTROLNETS, MAX_IPADAPTERS = 10, 5, 10, 5, 5
|
| 128 |
+
MAX_H3_GUIDES = 5
|
| 129 |
+
LORA_SOURCE_CHOICES = ["Hugging Face", "Civitai", "File"]
|
| 130 |
+
RESOLUTION_MAP = {}
|
| 131 |
+
MULTIPLIERS_MAP = {}
|
| 132 |
+
ARCHITECTURES_CONFIG = {"architectures": {}, "architecture_order": []}
|
| 133 |
+
FEATURES_CONFIG = {"default": {"enabled_chains": ["lora"]}}
|
| 134 |
+
MODEL_DEFAULTS_CONFIG = {"Default": {}}
|
core/shared_state.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
INVALID_MODEL_URLS = {}
|
core/workflow_assembler.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import yaml
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import importlib
|
| 5 |
+
from copy import deepcopy
|
| 6 |
+
from comfy_integration.nodes import NODE_CLASS_MAPPINGS
|
| 7 |
+
from chain_injectors import discover_injectors, get_registered_features
|
| 8 |
+
from core.settings import FEATURES_CONFIG
|
| 9 |
+
|
| 10 |
+
class WorkflowAssembler:
|
| 11 |
+
def __init__(self, recipe_path, dynamic_values=None):
|
| 12 |
+
self.base_path = os.path.dirname(recipe_path)
|
| 13 |
+
self.dynamic_values = dynamic_values or {}
|
| 14 |
+
self.node_counter = 0
|
| 15 |
+
self.workflow = {}
|
| 16 |
+
self.node_map = {}
|
| 17 |
+
|
| 18 |
+
model_type = self.dynamic_values.get('model_type')
|
| 19 |
+
self._load_injector_config(model_type=model_type)
|
| 20 |
+
|
| 21 |
+
self.recipe = self._load_and_merge_recipe(os.path.basename(recipe_path), self.dynamic_values)
|
| 22 |
+
|
| 23 |
+
def _load_injector_config(self, model_type=None):
|
| 24 |
+
self.global_injectors = discover_injectors()
|
| 25 |
+
registered_features = get_registered_features()
|
| 26 |
+
|
| 27 |
+
order = []
|
| 28 |
+
if model_type and model_type in FEATURES_CONFIG:
|
| 29 |
+
enabled_features = FEATURES_CONFIG[model_type].get('enabled_chains', [])
|
| 30 |
+
for feat in enabled_features:
|
| 31 |
+
if feat in registered_features:
|
| 32 |
+
chain_key = registered_features[feat]['chain_type']
|
| 33 |
+
else:
|
| 34 |
+
chain_key = f"dynamic_{feat}_chains"
|
| 35 |
+
if chain_key in self.global_injectors and chain_key not in order:
|
| 36 |
+
order.append(chain_key)
|
| 37 |
+
|
| 38 |
+
for chain_key in self.global_injectors.keys():
|
| 39 |
+
if chain_key not in order:
|
| 40 |
+
order.append(chain_key)
|
| 41 |
+
|
| 42 |
+
self.injector_order = order
|
| 43 |
+
|
| 44 |
+
def _get_unique_id(self):
|
| 45 |
+
self.node_counter += 1
|
| 46 |
+
return str(self.node_counter)
|
| 47 |
+
|
| 48 |
+
def _get_node_template(self, class_type):
|
| 49 |
+
if class_type not in NODE_CLASS_MAPPINGS:
|
| 50 |
+
raise ValueError(f"Node class '{class_type}' not found. Ensure it's correctly imported in comfy_integration/nodes.py.")
|
| 51 |
+
|
| 52 |
+
node_class = NODE_CLASS_MAPPINGS[class_type]
|
| 53 |
+
input_types = node_class.INPUT_TYPES()
|
| 54 |
+
|
| 55 |
+
template = {
|
| 56 |
+
"inputs": {},
|
| 57 |
+
"class_type": class_type,
|
| 58 |
+
"_meta": {"title": node_class.NODE_NAME if hasattr(node_class, 'NODE_NAME') else class_type}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
all_inputs = {**input_types.get('required', {}), **input_types.get('optional', {})}
|
| 62 |
+
for name, details in all_inputs.items():
|
| 63 |
+
config = details[1] if len(details) > 1 and isinstance(details[1], dict) else {}
|
| 64 |
+
template["inputs"][name] = config.get("default")
|
| 65 |
+
|
| 66 |
+
return template
|
| 67 |
+
|
| 68 |
+
def _load_and_merge_recipe(self, recipe_filename, dynamic_values, search_context_dir=None):
|
| 69 |
+
search_path = search_context_dir or self.base_path
|
| 70 |
+
recipe_path_to_use = os.path.join(search_path, recipe_filename)
|
| 71 |
+
|
| 72 |
+
if not os.path.exists(recipe_path_to_use):
|
| 73 |
+
raise FileNotFoundError(f"Recipe file not found: {recipe_path_to_use}")
|
| 74 |
+
|
| 75 |
+
with open(recipe_path_to_use, 'r', encoding='utf-8') as f:
|
| 76 |
+
content = f.read()
|
| 77 |
+
|
| 78 |
+
for key, value in dynamic_values.items():
|
| 79 |
+
if value is not None:
|
| 80 |
+
content = content.replace(f"{{{{ {key} }}}}", str(value))
|
| 81 |
+
|
| 82 |
+
main_recipe = yaml.safe_load(content)
|
| 83 |
+
|
| 84 |
+
merged_recipe = {'nodes': {}, 'connections': [], 'ui_map': {}}
|
| 85 |
+
for key in self.injector_order:
|
| 86 |
+
if key.startswith('dynamic_'):
|
| 87 |
+
merged_recipe[key] = {}
|
| 88 |
+
|
| 89 |
+
parent_recipe_dir = os.path.dirname(recipe_path_to_use)
|
| 90 |
+
for import_path_template in main_recipe.get('imports', []):
|
| 91 |
+
import_path = import_path_template
|
| 92 |
+
for key, value in dynamic_values.items():
|
| 93 |
+
if value is not None:
|
| 94 |
+
import_path = import_path.replace(f"{{{{ {key} }}}}", str(value))
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
imported_recipe = self._load_and_merge_recipe(import_path, dynamic_values, search_context_dir=parent_recipe_dir)
|
| 98 |
+
merged_recipe['nodes'].update(imported_recipe.get('nodes', {}))
|
| 99 |
+
merged_recipe['connections'].extend(imported_recipe.get('connections', []))
|
| 100 |
+
merged_recipe['ui_map'].update(imported_recipe.get('ui_map', {}))
|
| 101 |
+
for key in self.injector_order:
|
| 102 |
+
if key in imported_recipe and key.startswith('dynamic_'):
|
| 103 |
+
merged_recipe[key].update(imported_recipe.get(key, {}))
|
| 104 |
+
except FileNotFoundError:
|
| 105 |
+
print(f"Warning: Optional recipe partial '{import_path}' not found. Skipping.")
|
| 106 |
+
|
| 107 |
+
merged_recipe['nodes'].update(main_recipe.get('nodes', {}))
|
| 108 |
+
merged_recipe['connections'].extend(main_recipe.get('connections', []))
|
| 109 |
+
merged_recipe['ui_map'].update(main_recipe.get('ui_map', {}))
|
| 110 |
+
for key in self.injector_order:
|
| 111 |
+
if key in main_recipe and key.startswith('dynamic_'):
|
| 112 |
+
merged_recipe[key].update(main_recipe.get(key, {}))
|
| 113 |
+
|
| 114 |
+
return merged_recipe
|
| 115 |
+
|
| 116 |
+
def add_node(self, class_type: str, inputs: dict = None, title: str = None) -> str:
|
| 117 |
+
template = self._get_node_template(class_type)
|
| 118 |
+
node_data = deepcopy(template)
|
| 119 |
+
if title:
|
| 120 |
+
node_data['_meta']['title'] = title
|
| 121 |
+
if inputs:
|
| 122 |
+
for k, v in inputs.items():
|
| 123 |
+
node_data['inputs'][k] = v
|
| 124 |
+
node_id = self._get_unique_id()
|
| 125 |
+
self.workflow[node_id] = node_data
|
| 126 |
+
return node_id
|
| 127 |
+
|
| 128 |
+
def connect(self, from_node: str, from_output_idx: int, to_node: str, to_input_name: str):
|
| 129 |
+
from_id = self.node_map.get(from_node, from_node)
|
| 130 |
+
to_id = self.node_map.get(to_node, to_node)
|
| 131 |
+
if from_id in self.workflow and to_id in self.workflow:
|
| 132 |
+
self.workflow[to_id]['inputs'][to_input_name] = [from_id, int(from_output_idx)]
|
| 133 |
+
else:
|
| 134 |
+
print(f"Warning: Cannot connect '{from_node}' -> '{to_node}'. Node ID not found.")
|
| 135 |
+
|
| 136 |
+
def assemble(self, ui_values):
|
| 137 |
+
self.ui_values = ui_values
|
| 138 |
+
for name, details in self.recipe['nodes'].items():
|
| 139 |
+
if 'class_type' not in details:
|
| 140 |
+
continue
|
| 141 |
+
class_type = details['class_type']
|
| 142 |
+
match = re.search(r"\{\{\s*(\w+)\s*\}\}", class_type)
|
| 143 |
+
if match:
|
| 144 |
+
placeholder_key = match.group(1)
|
| 145 |
+
if placeholder_key in ui_values and ui_values[placeholder_key] is not None:
|
| 146 |
+
class_type = ui_values[placeholder_key]
|
| 147 |
+
else:
|
| 148 |
+
continue
|
| 149 |
+
|
| 150 |
+
template = self._get_node_template(class_type)
|
| 151 |
+
node_data = deepcopy(template)
|
| 152 |
+
|
| 153 |
+
unique_id = self._get_unique_id()
|
| 154 |
+
self.node_map[name] = unique_id
|
| 155 |
+
|
| 156 |
+
if 'title' in details:
|
| 157 |
+
node_data['_meta']['title'] = details['title']
|
| 158 |
+
|
| 159 |
+
if 'params' in details:
|
| 160 |
+
for param, value in details['params'].items():
|
| 161 |
+
if param in node_data['inputs']:
|
| 162 |
+
node_data['inputs'][param] = value
|
| 163 |
+
|
| 164 |
+
self.workflow[unique_id] = node_data
|
| 165 |
+
|
| 166 |
+
for ui_key, target in self.recipe.get('ui_map', {}).items():
|
| 167 |
+
if ui_key in ui_values and ui_values[ui_key] is not None:
|
| 168 |
+
target_list = target if isinstance(target, list) else [target]
|
| 169 |
+
for t in target_list:
|
| 170 |
+
if isinstance(t, str) and ':' in t:
|
| 171 |
+
target_name, target_param = t.split(':')
|
| 172 |
+
if target_name in self.node_map:
|
| 173 |
+
self.workflow[self.node_map[target_name]]['inputs'][target_param] = ui_values[ui_key]
|
| 174 |
+
|
| 175 |
+
for conn in self.recipe.get('connections', []):
|
| 176 |
+
if not isinstance(conn.get('to'), str) or not isinstance(conn.get('from'), str):
|
| 177 |
+
continue
|
| 178 |
+
from_name, from_output_idx = conn['from'].split(':')
|
| 179 |
+
to_name, to_input_name = conn['to'].split(':')
|
| 180 |
+
|
| 181 |
+
from_id = self.node_map.get(from_name)
|
| 182 |
+
to_id = self.node_map.get(to_name)
|
| 183 |
+
|
| 184 |
+
if from_id and to_id:
|
| 185 |
+
self.workflow[to_id]['inputs'][to_input_name] = [from_id, int(from_output_idx)]
|
| 186 |
+
|
| 187 |
+
print("--- [Assembler] Applying dynamic injectors ---")
|
| 188 |
+
recipe_chain_types = {key for key in self.recipe if key.startswith('dynamic_')}
|
| 189 |
+
processing_order = [key for key in self.injector_order if key in recipe_chain_types]
|
| 190 |
+
|
| 191 |
+
for chain_type in processing_order:
|
| 192 |
+
injector_func = self.global_injectors.get(chain_type)
|
| 193 |
+
if injector_func:
|
| 194 |
+
for chain_key, chain_def in self.recipe.get(chain_type, {}).items():
|
| 195 |
+
if chain_key in ui_values and ui_values[chain_key]:
|
| 196 |
+
print(f" -> Injecting '{chain_type}' for '{chain_key}'...")
|
| 197 |
+
chain_items = ui_values[chain_key]
|
| 198 |
+
injector_func(self, chain_def, chain_items)
|
| 199 |
+
|
| 200 |
+
print("--- [Assembler] Finished applying injectors ---")
|
| 201 |
+
|
| 202 |
+
return self.workflow
|
mcp_tools/__init__.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def __getattr__(name):
|
| 2 |
+
if name in ("types", "server", "client", "shared"):
|
| 3 |
+
raise ImportError(f"No module named 'mcp.{name}' in local mcp package")
|
| 4 |
+
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
|
| 5 |
+
|
| 6 |
+
from . import hf_private # ESVIAL: refs privadas con HF_TOKEN
|
| 7 |
+
from .get_task_list import handle_get_task_list
|
| 8 |
+
from .run import handle_run
|
| 9 |
+
from .get_task_status import handle_get_task_status
|
| 10 |
+
from .error_schema import make_error, make_validation_error, make_not_found_error
|
| 11 |
+
try:
|
| 12 |
+
from .mcp_gradio_integration import (
|
| 13 |
+
register_high_level_mcp_apis,
|
| 14 |
+
cleanup_dependencies_api_names,
|
| 15 |
+
patch_gradio_api_suppression,
|
| 16 |
+
HIGH_LEVEL_MCP_API_NAMES,
|
| 17 |
+
)
|
| 18 |
+
except ImportError:
|
| 19 |
+
register_high_level_mcp_apis = None
|
| 20 |
+
cleanup_dependencies_api_names = None
|
| 21 |
+
patch_gradio_api_suppression = None
|
| 22 |
+
HIGH_LEVEL_MCP_API_NAMES = set()
|
| 23 |
+
|
| 24 |
+
MCP_FUNCTIONS = [
|
| 25 |
+
handle_get_task_list,
|
| 26 |
+
handle_run,
|
| 27 |
+
handle_get_task_status,
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
"handle_get_task_list",
|
| 32 |
+
"handle_run",
|
| 33 |
+
"handle_get_task_status",
|
| 34 |
+
"make_error",
|
| 35 |
+
"make_validation_error",
|
| 36 |
+
"make_not_found_error",
|
| 37 |
+
"register_high_level_mcp_apis",
|
| 38 |
+
"cleanup_dependencies_api_names",
|
| 39 |
+
"patch_gradio_api_suppression",
|
| 40 |
+
"HIGH_LEVEL_MCP_API_NAMES",
|
| 41 |
+
"MCP_FUNCTIONS",
|
| 42 |
+
]
|
mcp_tools/common.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Common Utilities & Data Structures
|
| 3 |
+
Contains image parsing utilities, task definitions, aspect ratio presets, and async task database for MiniMax H3 Video Generation.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
import urllib.parse
|
| 10 |
+
import urllib.request
|
| 11 |
+
import urllib.error
|
| 12 |
+
import base64
|
| 13 |
+
import io
|
| 14 |
+
import yaml
|
| 15 |
+
from typing import Dict, Any
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
_YAML_DIR = os.path.join(_PROJECT_ROOT, "yaml")
|
| 20 |
+
|
| 21 |
+
_MAX_IMAGE_DOWNLOAD_BYTES = 50 * 1024 * 1024 # 50 MB
|
| 22 |
+
_IMAGE_DOWNLOAD_TIMEOUT = 30 # seconds
|
| 23 |
+
_MAX_VIDEO_DOWNLOAD_BYTES = 200 * 1024 * 1024 # 200 MB
|
| 24 |
+
_VIDEO_DOWNLOAD_TIMEOUT = 60 # seconds
|
| 25 |
+
_MAX_AUDIO_DOWNLOAD_BYTES = 100 * 1024 * 1024 # 100 MB
|
| 26 |
+
_AUDIO_DOWNLOAD_TIMEOUT = 60 # seconds
|
| 27 |
+
|
| 28 |
+
_ALLOWED_IMAGE_CONTENT_TYPES = frozenset([
|
| 29 |
+
"image/png", "image/jpeg", "image/jpg", "image/gif",
|
| 30 |
+
"image/webp", "image/bmp", "image/tiff",
|
| 31 |
+
])
|
| 32 |
+
|
| 33 |
+
ASPECT_RATIO_PRESETS = {
|
| 34 |
+
"16:9 (Landscape)": {"width": 1344, "height": 768},
|
| 35 |
+
"9:16 (Portrait)": {"width": 768, "height": 1344},
|
| 36 |
+
"1:1 (Square)": {"width": 1024, "height": 1024},
|
| 37 |
+
"4:3 (Classic TV)": {"width": 1152, "height": 864},
|
| 38 |
+
"3:4 (Classic Portrait)": {"width": 864, "height": 1152},
|
| 39 |
+
"3:2 (Landscape)": {"width": 1248, "height": 832},
|
| 40 |
+
"2:3 (Portrait)": {"width": 832, "height": 1248},
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _parse_image_param(image_param: Any) -> Any:
|
| 45 |
+
"""Parse a Base64 Data URI, HTTP/HTTPS URL, or PIL.Image into a PIL Image object."""
|
| 46 |
+
if isinstance(image_param, Image.Image):
|
| 47 |
+
return image_param
|
| 48 |
+
|
| 49 |
+
if not isinstance(image_param, str) or not image_param.strip():
|
| 50 |
+
return None
|
| 51 |
+
|
| 52 |
+
image_param = image_param.strip()
|
| 53 |
+
|
| 54 |
+
if os.path.exists(image_param):
|
| 55 |
+
return Image.open(image_param)
|
| 56 |
+
|
| 57 |
+
if image_param.startswith("http://") or image_param.startswith("https://"):
|
| 58 |
+
return _download_image_from_url(image_param)
|
| 59 |
+
|
| 60 |
+
if image_param.startswith("data:image/"):
|
| 61 |
+
_, encoded = image_param.split(",", 1) if "," in image_param else ("", image_param)
|
| 62 |
+
data = base64.b64decode(encoded)
|
| 63 |
+
return Image.open(io.BytesIO(data))
|
| 64 |
+
|
| 65 |
+
if len(image_param) > 100:
|
| 66 |
+
try:
|
| 67 |
+
data = base64.b64decode(image_param)
|
| 68 |
+
return Image.open(io.BytesIO(data))
|
| 69 |
+
except Exception:
|
| 70 |
+
pass
|
| 71 |
+
|
| 72 |
+
raise ValueError(
|
| 73 |
+
"Invalid image parameter format. Expected a file path, Base64 Data URI, or an HTTP/HTTPS URL."
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _download_image_from_url(url: str) -> Image.Image:
|
| 78 |
+
"""Download an image from an HTTP/HTTPS URL and return it as a PIL Image."""
|
| 79 |
+
req = urllib.request.Request(url, headers={"User-Agent": "H3-VideoGen-MCP/1.0"})
|
| 80 |
+
try:
|
| 81 |
+
with urllib.request.urlopen(req, timeout=_IMAGE_DOWNLOAD_TIMEOUT) as resp:
|
| 82 |
+
content_type = resp.headers.get("Content-Type", "").split(";")[0].strip().lower()
|
| 83 |
+
if content_type and content_type not in _ALLOWED_IMAGE_CONTENT_TYPES:
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"URL returned non-image Content-Type '{content_type}'. "
|
| 86 |
+
f"Expected one of: {', '.join(sorted(_ALLOWED_IMAGE_CONTENT_TYPES))}."
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
content_length = resp.headers.get("Content-Length")
|
| 90 |
+
if content_length and int(content_length) > _MAX_IMAGE_DOWNLOAD_BYTES:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
f"Image at URL is too large ({int(content_length)} bytes). "
|
| 93 |
+
f"Maximum allowed size is {_MAX_IMAGE_DOWNLOAD_BYTES} bytes."
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
chunks = []
|
| 97 |
+
total = 0
|
| 98 |
+
while True:
|
| 99 |
+
chunk = resp.read(8192)
|
| 100 |
+
if not chunk:
|
| 101 |
+
break
|
| 102 |
+
total += len(chunk)
|
| 103 |
+
if total > _MAX_IMAGE_DOWNLOAD_BYTES:
|
| 104 |
+
raise ValueError(f"Image download exceeded maximum allowed size of {_MAX_IMAGE_DOWNLOAD_BYTES} bytes.")
|
| 105 |
+
chunks.append(chunk)
|
| 106 |
+
|
| 107 |
+
data = b"".join(chunks)
|
| 108 |
+
|
| 109 |
+
except urllib.error.URLError as e:
|
| 110 |
+
raise ValueError(f"Failed to download image from URL: {e}") from e
|
| 111 |
+
except urllib.error.HTTPError as e:
|
| 112 |
+
raise ValueError(f"HTTP error {e.code} when downloading image from URL: {e.reason}") from e
|
| 113 |
+
|
| 114 |
+
if not data:
|
| 115 |
+
raise ValueError("Downloaded image data is empty.")
|
| 116 |
+
|
| 117 |
+
return Image.open(io.BytesIO(data))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _download_file_from_url(url: str, suffix: str = ".mp4", max_bytes: int = _MAX_VIDEO_DOWNLOAD_BYTES, timeout: int = _VIDEO_DOWNLOAD_TIMEOUT) -> str:
|
| 121 |
+
"""Download a media file from an HTTP/HTTPS URL and save it to a temporary local path."""
|
| 122 |
+
req = urllib.request.Request(url, headers={"User-Agent": "H3-VideoGen-MCP/1.0"})
|
| 123 |
+
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 124 |
+
os.makedirs(input_dir, exist_ok=True)
|
| 125 |
+
temp_path = os.path.join(input_dir, f"mcp_download_{uuid.uuid4().hex[:10]}{suffix}")
|
| 126 |
+
try:
|
| 127 |
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
| 128 |
+
content_length = resp.headers.get("Content-Length")
|
| 129 |
+
if content_length and int(content_length) > max_bytes:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
f"File at URL is too large ({int(content_length)} bytes). "
|
| 132 |
+
f"Maximum allowed size is {max_bytes} bytes."
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
total = 0
|
| 136 |
+
with open(temp_path, "wb") as f:
|
| 137 |
+
while True:
|
| 138 |
+
chunk = resp.read(65536)
|
| 139 |
+
if not chunk:
|
| 140 |
+
break
|
| 141 |
+
total += len(chunk)
|
| 142 |
+
if total > max_bytes:
|
| 143 |
+
raise ValueError(f"File download exceeded maximum allowed size of {max_bytes} bytes.")
|
| 144 |
+
f.write(chunk)
|
| 145 |
+
return temp_path
|
| 146 |
+
except Exception as e:
|
| 147 |
+
if os.path.exists(temp_path):
|
| 148 |
+
try:
|
| 149 |
+
os.remove(temp_path)
|
| 150 |
+
except Exception:
|
| 151 |
+
pass
|
| 152 |
+
raise ValueError(f"Failed to download file from URL '{url}': {e}") from e
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _parse_video_param(video_param: Any) -> Any:
|
| 156 |
+
"""Parse a file path, Base64 Data URI, or an HTTP/HTTPS URL into a local video file path."""
|
| 157 |
+
if not isinstance(video_param, str) or not video_param.strip():
|
| 158 |
+
return None
|
| 159 |
+
|
| 160 |
+
video_param = video_param.strip()
|
| 161 |
+
|
| 162 |
+
if os.path.exists(video_param):
|
| 163 |
+
return video_param
|
| 164 |
+
|
| 165 |
+
if video_param.startswith("http://") or video_param.startswith("https://"):
|
| 166 |
+
parsed_url = urllib.parse.urlparse(video_param)
|
| 167 |
+
ext = os.path.splitext(parsed_url.path)[1] or ".mp4"
|
| 168 |
+
return _download_file_from_url(video_param, suffix=ext, max_bytes=_MAX_VIDEO_DOWNLOAD_BYTES, timeout=_VIDEO_DOWNLOAD_TIMEOUT)
|
| 169 |
+
|
| 170 |
+
if video_param.startswith("data:video/"):
|
| 171 |
+
_, encoded = video_param.split(",", 1) if "," in video_param else ("", video_param)
|
| 172 |
+
data = base64.b64decode(encoded)
|
| 173 |
+
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 174 |
+
os.makedirs(input_dir, exist_ok=True)
|
| 175 |
+
temp_path = os.path.join(input_dir, f"mcp_upload_{uuid.uuid4().hex[:10]}.mp4")
|
| 176 |
+
with open(temp_path, "wb") as f:
|
| 177 |
+
f.write(data)
|
| 178 |
+
return temp_path
|
| 179 |
+
|
| 180 |
+
return video_param
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _parse_audio_param(audio_param: Any) -> Any:
|
| 184 |
+
"""Parse a file path, Base64 Data URI, or an HTTP/HTTPS URL into a local audio file path."""
|
| 185 |
+
if not isinstance(audio_param, str) or not audio_param.strip():
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
audio_param = audio_param.strip()
|
| 189 |
+
|
| 190 |
+
if os.path.exists(audio_param):
|
| 191 |
+
return audio_param
|
| 192 |
+
|
| 193 |
+
if audio_param.startswith("http://") or audio_param.startswith("https://"):
|
| 194 |
+
parsed_url = urllib.parse.urlparse(audio_param)
|
| 195 |
+
ext = os.path.splitext(parsed_url.path)[1] or ".mp3"
|
| 196 |
+
return _download_file_from_url(audio_param, suffix=ext, max_bytes=_MAX_AUDIO_DOWNLOAD_BYTES, timeout=_AUDIO_DOWNLOAD_TIMEOUT)
|
| 197 |
+
|
| 198 |
+
if audio_param.startswith("data:audio/"):
|
| 199 |
+
_, encoded = audio_param.split(",", 1) if "," in audio_param else ("", audio_param)
|
| 200 |
+
data = base64.b64decode(encoded)
|
| 201 |
+
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 202 |
+
os.makedirs(input_dir, exist_ok=True)
|
| 203 |
+
temp_path = os.path.join(input_dir, f"mcp_upload_{uuid.uuid4().hex[:10]}.mp3")
|
| 204 |
+
with open(temp_path, "wb") as f:
|
| 205 |
+
f.write(data)
|
| 206 |
+
return temp_path
|
| 207 |
+
|
| 208 |
+
return audio_param
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _load_yaml(filepath: str) -> dict:
|
| 212 |
+
"""Safely load a YAML file."""
|
| 213 |
+
if not os.path.exists(filepath):
|
| 214 |
+
print(f"Warning: YAML file not found: {filepath}")
|
| 215 |
+
return {}
|
| 216 |
+
with open(filepath, "r", encoding="utf-8") as f:
|
| 217 |
+
return yaml.safe_load(f) or {}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
_GLOBAL_OPTIONAL_INPUTS_SCHEMA = {
|
| 221 |
+
"seed": {
|
| 222 |
+
"type": "integer",
|
| 223 |
+
"default": -1,
|
| 224 |
+
"description": "Random seed for video generation (-1 for random seed, >=0 for deterministic reproduction)."
|
| 225 |
+
},
|
| 226 |
+
"zero_gpu_duration": {
|
| 227 |
+
"type": "integer",
|
| 228 |
+
"default": 120,
|
| 229 |
+
"minimum": 1,
|
| 230 |
+
"description": "GPU execution time quota allocation in seconds on HuggingFace ZeroGPU spaces (default: 120)."
|
| 231 |
+
},
|
| 232 |
+
"loras": {
|
| 233 |
+
"type": "array",
|
| 234 |
+
"description": "List of LoRA configurations to apply. E.g., [{'source': 'Hugging Face', 'id_or_url': 'repo/lora.safetensors', 'scale': 1.0}] or [{'lora_name': 'my_lora.safetensors', 'strength_model': 1.0, 'strength_clip': 1.0}].",
|
| 235 |
+
"items": {
|
| 236 |
+
"type": "object"
|
| 237 |
+
}
|
| 238 |
+
},
|
| 239 |
+
"h3_controlnets": {
|
| 240 |
+
"type": "array",
|
| 241 |
+
"description": "List of H3 ControlNet configurations. E.g., [{'video': 'https://example.com/pose.mp4', 'control_net_name': 'minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors', 'strength': 1.0, 'start_percent': 0.0, 'end_percent': 1.0}].",
|
| 242 |
+
"items": {
|
| 243 |
+
"type": "object"
|
| 244 |
+
}
|
| 245 |
+
},
|
| 246 |
+
"control_video": {
|
| 247 |
+
"type": "string",
|
| 248 |
+
"description": "Convenience parameter: URL, file path, or Base64 Data URI of a single control video for H3 ControlNet."
|
| 249 |
+
},
|
| 250 |
+
"control_strength": {
|
| 251 |
+
"type": "number",
|
| 252 |
+
"default": 1.0,
|
| 253 |
+
"description": "Strength for single convenience control video (default: 1.0)."
|
| 254 |
+
},
|
| 255 |
+
"control_net_name": {
|
| 256 |
+
"type": "string",
|
| 257 |
+
"default": "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors",
|
| 258 |
+
"description": "Model filename for H3 ControlNet (default: minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors)."
|
| 259 |
+
},
|
| 260 |
+
"h3_guides": {
|
| 261 |
+
"type": "array",
|
| 262 |
+
"description": "List of MiniMax H3 timeline Keyframe Guide configurations (Add Guide for MiniMax H3). E.g., [{'image': 'https://example.com/frame.png', 'video': 'https://example.com/clip.mp4', 'audio': 'https://example.com/voice.mp3', 'frame_idx': 36, 'time_seconds': 1.5}].",
|
| 263 |
+
"items": {
|
| 264 |
+
"type": "object"
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
_COMMON_OPTIONAL_INPUTS = [
|
| 270 |
+
"seed", "zero_gpu_duration", "loras", "h3_controlnets", "control_video", "control_strength", "control_net_name", "h3_guides"
|
| 271 |
+
]
|
| 272 |
+
|
| 273 |
+
_TASK_DEFINITIONS = [
|
| 274 |
+
{
|
| 275 |
+
"task_type": "t2va",
|
| 276 |
+
"display_name": "Text-to-Video (H3 FL2VA)",
|
| 277 |
+
"description": "Generate videos from text prompt without input frames. Supports LoRAs and H3 ControlNet.",
|
| 278 |
+
"required_inputs": ["prompt", "width", "height", "duration"],
|
| 279 |
+
"optional_inputs": _COMMON_OPTIONAL_INPUTS,
|
| 280 |
+
"optional_inputs_schema": _GLOBAL_OPTIONAL_INPUTS_SCHEMA,
|
| 281 |
+
"aspect_ratio_presets": ASPECT_RATIO_PRESETS,
|
| 282 |
+
"example_json_params": {
|
| 283 |
+
"task_type": "t2va",
|
| 284 |
+
"prompt": "A futuristic city with flying cars at sunset, cinematic 4k",
|
| 285 |
+
"width": 1344,
|
| 286 |
+
"height": 768,
|
| 287 |
+
"duration": 5.0,
|
| 288 |
+
"seed": -1,
|
| 289 |
+
"zero_gpu_duration": 120
|
| 290 |
+
}
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"task_type": "i2va",
|
| 294 |
+
"display_name": "Image-to-Video (H3 FL2VA)",
|
| 295 |
+
"description": "Generate videos starting from a single initial image frame (first frame). Supports LoRAs and H3 ControlNet.",
|
| 296 |
+
"required_inputs": ["prompt", "width", "height", "duration", "first_frame_image"],
|
| 297 |
+
"optional_inputs": _COMMON_OPTIONAL_INPUTS,
|
| 298 |
+
"optional_inputs_schema": _GLOBAL_OPTIONAL_INPUTS_SCHEMA,
|
| 299 |
+
"aspect_ratio_presets": ASPECT_RATIO_PRESETS,
|
| 300 |
+
"example_json_params": {
|
| 301 |
+
"task_type": "i2va",
|
| 302 |
+
"prompt": "A majestic lion standing on a rock looking at the horizon",
|
| 303 |
+
"width": 1344,
|
| 304 |
+
"height": 768,
|
| 305 |
+
"duration": 5.0,
|
| 306 |
+
"first_frame_image": "https://example.com/first_frame.png",
|
| 307 |
+
"seed": -1,
|
| 308 |
+
"zero_gpu_duration": 120
|
| 309 |
+
}
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"task_type": "flf2va",
|
| 313 |
+
"display_name": "First & Last Frame-to-Video (H3 FL2VA)",
|
| 314 |
+
"description": "Generate videos guided by both a starting frame (first frame) and ending frame (last frame). Supports LoRAs and H3 ControlNet.",
|
| 315 |
+
"required_inputs": ["prompt", "width", "height", "duration", "first_frame_image", "last_frame_image"],
|
| 316 |
+
"optional_inputs": _COMMON_OPTIONAL_INPUTS,
|
| 317 |
+
"optional_inputs_schema": _GLOBAL_OPTIONAL_INPUTS_SCHEMA,
|
| 318 |
+
"aspect_ratio_presets": ASPECT_RATIO_PRESETS,
|
| 319 |
+
"example_json_params": {
|
| 320 |
+
"task_type": "flf2va",
|
| 321 |
+
"prompt": "Smooth transition of a flower blooming from start to finish",
|
| 322 |
+
"width": 1344,
|
| 323 |
+
"height": 768,
|
| 324 |
+
"duration": 5.0,
|
| 325 |
+
"first_frame_image": "https://example.com/first_frame.png",
|
| 326 |
+
"last_frame_image": "https://example.com/last_frame.png",
|
| 327 |
+
"seed": -1,
|
| 328 |
+
"zero_gpu_duration": 120
|
| 329 |
+
}
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"task_type": "ref2va",
|
| 333 |
+
"display_name": "Reference-to-Video (H3 REF2VA)",
|
| 334 |
+
"description": "Generate videos with multi-modal references (up to 9 ref images, 3 ref videos, and 3 ref audios). Supports LoRAs, H3 ControlNet, and timeline Keyframe Guides (Add Guide for MiniMax H3).",
|
| 335 |
+
"required_inputs": ["prompt", "width", "height", "duration"],
|
| 336 |
+
"optional_inputs": [
|
| 337 |
+
*_COMMON_OPTIONAL_INPUTS,
|
| 338 |
+
"ref_image1", "ref_image2", "ref_image3", "ref_image4", "ref_image5", "ref_image6", "ref_image7", "ref_image8", "ref_image9",
|
| 339 |
+
"ref_video1", "ref_video2", "ref_video3",
|
| 340 |
+
"ref_audio1", "ref_audio2", "ref_audio3",
|
| 341 |
+
"h3_guides"
|
| 342 |
+
],
|
| 343 |
+
"optional_inputs_schema": _GLOBAL_OPTIONAL_INPUTS_SCHEMA,
|
| 344 |
+
"aspect_ratio_presets": ASPECT_RATIO_PRESETS,
|
| 345 |
+
"example_json_params": {
|
| 346 |
+
"task_type": "ref2va",
|
| 347 |
+
"prompt": "A character dancing in a cyberpunk room guided by reference media",
|
| 348 |
+
"width": 1344,
|
| 349 |
+
"height": 768,
|
| 350 |
+
"duration": 5.0,
|
| 351 |
+
"ref_image1": "https://example.com/ref_character.png",
|
| 352 |
+
"ref_video1": "https://example.com/ref_motion.mp4",
|
| 353 |
+
"ref_audio1": "https://example.com/ref_bgm.mp3",
|
| 354 |
+
"seed": -1,
|
| 355 |
+
"zero_gpu_duration": 120
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
]
|
| 359 |
+
|
| 360 |
+
_TASKS_DB: Dict[str, Dict[str, Any]] = {}
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class DummyProgress:
|
| 364 |
+
def __call__(self, progress=0.0, desc=None):
|
| 365 |
+
pass
|
| 366 |
+
|
| 367 |
+
|
| 368 |
+
def _get_public_base_url() -> str:
|
| 369 |
+
"""Auto-resolve the publicly accessible base URL."""
|
| 370 |
+
public_url = os.getenv("PUBLIC_URL") or os.getenv("BASE_URL")
|
| 371 |
+
if public_url:
|
| 372 |
+
return public_url.rstrip("/")
|
| 373 |
+
|
| 374 |
+
space_host = os.getenv("SPACE_HOST")
|
| 375 |
+
if space_host:
|
| 376 |
+
if not space_host.startswith("http://") and not space_host.startswith("https://"):
|
| 377 |
+
return f"https://{space_host}"
|
| 378 |
+
return space_host.rstrip("/")
|
| 379 |
+
|
| 380 |
+
try:
|
| 381 |
+
from core.settings import GRADIO_SERVER_NAME, SERVER_PORT
|
| 382 |
+
except ImportError:
|
| 383 |
+
GRADIO_SERVER_NAME = "127.0.0.1"
|
| 384 |
+
SERVER_PORT = 7860
|
| 385 |
+
|
| 386 |
+
server_name = os.getenv("GRADIO_SERVER_NAME", GRADIO_SERVER_NAME)
|
| 387 |
+
if server_name == "0.0.0.0":
|
| 388 |
+
server_name = "127.0.0.1"
|
| 389 |
+
port = os.getenv("GRADIO_SERVER_PORT", str(SERVER_PORT))
|
| 390 |
+
|
| 391 |
+
return f"http://{server_name}:{port}"
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _execute_imagegen_pipeline(task_id: str, params: dict):
|
| 395 |
+
"""Execute the MiniMax H3 video generation pipeline in the background and update _TASKS_DB."""
|
| 396 |
+
start_time = time.time()
|
| 397 |
+
try:
|
| 398 |
+
_TASKS_DB[task_id]["status"] = "processing"
|
| 399 |
+
_TASKS_DB[task_id]["progress"] = 10
|
| 400 |
+
_TASKS_DB[task_id]["updated_at"] = int(start_time)
|
| 401 |
+
|
| 402 |
+
task_type = params.get("task_type", "t2va")
|
| 403 |
+
prompt = params.get("prompt", "")
|
| 404 |
+
width = int(params.get("width", 1344))
|
| 405 |
+
height = int(params.get("height", 768))
|
| 406 |
+
duration = float(params.get("duration", 5.0))
|
| 407 |
+
seed = int(params.get("seed", -1))
|
| 408 |
+
zero_gpu_duration = int(params.get("zero_gpu_duration", 120))
|
| 409 |
+
|
| 410 |
+
# Process LoRAs if provided
|
| 411 |
+
loras_param = params.get("loras")
|
| 412 |
+
loras_list = loras_param if isinstance(loras_param, list) else []
|
| 413 |
+
|
| 414 |
+
# Process H3 ControlNets if provided
|
| 415 |
+
h3_cns_param = params.get("h3_controlnets")
|
| 416 |
+
parsed_cns = []
|
| 417 |
+
if h3_cns_param and isinstance(h3_cns_param, list):
|
| 418 |
+
for item in h3_cns_param:
|
| 419 |
+
if isinstance(item, dict):
|
| 420 |
+
vid_raw = item.get("video") or item.get("control_video") or item.get("file")
|
| 421 |
+
vid_parsed = _parse_video_param(vid_raw) if vid_raw else None
|
| 422 |
+
if vid_parsed:
|
| 423 |
+
new_item = dict(item)
|
| 424 |
+
new_item["video"] = vid_parsed
|
| 425 |
+
parsed_cns.append(new_item)
|
| 426 |
+
elif params.get("control_video"):
|
| 427 |
+
vid_raw = params.get("control_video")
|
| 428 |
+
vid_parsed = _parse_video_param(vid_raw) if vid_raw else None
|
| 429 |
+
if vid_parsed:
|
| 430 |
+
parsed_cns.append({
|
| 431 |
+
"video": vid_parsed,
|
| 432 |
+
"control_net_name": params.get("control_net_name") or "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors",
|
| 433 |
+
"strength": float(params.get("control_strength", 1.0)),
|
| 434 |
+
"start_percent": float(params.get("control_start_percent", 0.0)),
|
| 435 |
+
"end_percent": float(params.get("control_end_percent", 1.0)),
|
| 436 |
+
})
|
| 437 |
+
|
| 438 |
+
parsed_guides = []
|
| 439 |
+
raw_guides = params.get("h3_guides") or params.get("guides")
|
| 440 |
+
if raw_guides and isinstance(raw_guides, list):
|
| 441 |
+
for item in raw_guides:
|
| 442 |
+
if isinstance(item, dict):
|
| 443 |
+
guide_entry = {}
|
| 444 |
+
if item.get("image"):
|
| 445 |
+
guide_entry["image"] = _parse_image_param(item["image"])
|
| 446 |
+
if item.get("video"):
|
| 447 |
+
guide_entry["video"] = _parse_video_param(item["video"])
|
| 448 |
+
if item.get("audio"):
|
| 449 |
+
guide_entry["audio"] = _parse_audio_param(item["audio"])
|
| 450 |
+
if item.get("frame_idx") is not None:
|
| 451 |
+
guide_entry["frame_idx"] = item["frame_idx"]
|
| 452 |
+
if item.get("time_seconds") is not None:
|
| 453 |
+
guide_entry["time_seconds"] = item["time_seconds"]
|
| 454 |
+
if guide_entry:
|
| 455 |
+
parsed_guides.append(guide_entry)
|
| 456 |
+
|
| 457 |
+
if task_type in ("t2va", "i2va", "flf2va"):
|
| 458 |
+
from ui.h3_logic import process_inputs as process_h3_inputs
|
| 459 |
+
|
| 460 |
+
first_frame_raw = params.get("first_frame_image") or params.get("first_frame")
|
| 461 |
+
last_frame_raw = params.get("last_frame_image") or params.get("last_frame")
|
| 462 |
+
|
| 463 |
+
first_frame_pil = _parse_image_param(first_frame_raw) if first_frame_raw else None
|
| 464 |
+
last_frame_pil = _parse_image_param(last_frame_raw) if last_frame_raw else None
|
| 465 |
+
|
| 466 |
+
ui_inputs = {
|
| 467 |
+
"task": task_type.upper(),
|
| 468 |
+
"first_frame": first_frame_pil,
|
| 469 |
+
"last_frame": last_frame_pil,
|
| 470 |
+
"prompt": prompt,
|
| 471 |
+
"resolution": "720p",
|
| 472 |
+
"aspect_ratio": "Custom",
|
| 473 |
+
"width": width,
|
| 474 |
+
"height": height,
|
| 475 |
+
"duration": duration,
|
| 476 |
+
"seed": seed,
|
| 477 |
+
"zero_gpu_duration": zero_gpu_duration,
|
| 478 |
+
"batch_count": 1,
|
| 479 |
+
"loras": loras_list,
|
| 480 |
+
"h3_controlnets": parsed_cns,
|
| 481 |
+
"h3_guides": parsed_guides,
|
| 482 |
+
}
|
| 483 |
+
elif task_type == "ref2va":
|
| 484 |
+
from ui.h3_logic import process_inputs as process_h3_inputs
|
| 485 |
+
|
| 486 |
+
ref_images = []
|
| 487 |
+
for i in range(1, 10):
|
| 488 |
+
img_val = params.get(f"ref_image{i}")
|
| 489 |
+
if img_val:
|
| 490 |
+
pil_img = _parse_image_param(img_val)
|
| 491 |
+
if pil_img:
|
| 492 |
+
ref_images.append(pil_img)
|
| 493 |
+
if not ref_images and "ref_images" in params and isinstance(params["ref_images"], list):
|
| 494 |
+
for img_val in params["ref_images"]:
|
| 495 |
+
if img_val:
|
| 496 |
+
pil_img = _parse_image_param(img_val)
|
| 497 |
+
if pil_img:
|
| 498 |
+
ref_images.append(pil_img)
|
| 499 |
+
|
| 500 |
+
ref_videos = []
|
| 501 |
+
for i in range(1, 4):
|
| 502 |
+
vid_val = params.get(f"ref_video{i}")
|
| 503 |
+
if vid_val:
|
| 504 |
+
parsed_vid = _parse_video_param(vid_val)
|
| 505 |
+
if parsed_vid:
|
| 506 |
+
ref_videos.append(parsed_vid)
|
| 507 |
+
if not ref_videos and "ref_videos" in params and isinstance(params["ref_videos"], list):
|
| 508 |
+
for vid_val in params["ref_videos"]:
|
| 509 |
+
if vid_val:
|
| 510 |
+
parsed_vid = _parse_video_param(vid_val)
|
| 511 |
+
if parsed_vid:
|
| 512 |
+
ref_videos.append(parsed_vid)
|
| 513 |
+
|
| 514 |
+
ref_audios = []
|
| 515 |
+
for i in range(1, 4):
|
| 516 |
+
aud_val = params.get(f"ref_audio{i}")
|
| 517 |
+
if aud_val:
|
| 518 |
+
parsed_aud = _parse_audio_param(aud_val)
|
| 519 |
+
if parsed_aud:
|
| 520 |
+
ref_audios.append(parsed_aud)
|
| 521 |
+
if not ref_audios and "ref_audios" in params and isinstance(params["ref_audios"], list):
|
| 522 |
+
for aud_val in params["ref_audios"]:
|
| 523 |
+
if aud_val:
|
| 524 |
+
parsed_aud = _parse_audio_param(aud_val)
|
| 525 |
+
if parsed_aud:
|
| 526 |
+
ref_audios.append(parsed_aud)
|
| 527 |
+
|
| 528 |
+
ui_inputs = {
|
| 529 |
+
"task": "REF2VA",
|
| 530 |
+
"prompt": prompt,
|
| 531 |
+
"resolution": "720p",
|
| 532 |
+
"aspect_ratio": "Custom",
|
| 533 |
+
"width": width,
|
| 534 |
+
"height": height,
|
| 535 |
+
"duration": duration,
|
| 536 |
+
"seed": seed,
|
| 537 |
+
"zero_gpu_duration": zero_gpu_duration,
|
| 538 |
+
"batch_count": 1,
|
| 539 |
+
"ref_images": ref_images,
|
| 540 |
+
"ref_videos": ref_videos,
|
| 541 |
+
"ref_audios": ref_audios,
|
| 542 |
+
"loras": loras_list,
|
| 543 |
+
"h3_controlnets": parsed_cns,
|
| 544 |
+
"h3_guides": parsed_guides,
|
| 545 |
+
}
|
| 546 |
+
else:
|
| 547 |
+
raise ValueError(f"Unsupported task_type '{task_type}'")
|
| 548 |
+
|
| 549 |
+
_TASKS_DB[task_id]["progress"] = 50
|
| 550 |
+
|
| 551 |
+
from core.generation_logic import generate_h3_video_wrapper
|
| 552 |
+
output = generate_h3_video_wrapper(process_h3_inputs, ui_inputs, progress=DummyProgress())
|
| 553 |
+
|
| 554 |
+
try:
|
| 555 |
+
from core.settings import OUTPUT_DIR
|
| 556 |
+
except ImportError:
|
| 557 |
+
OUTPUT_DIR = os.path.join(_PROJECT_ROOT, "output")
|
| 558 |
+
|
| 559 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 560 |
+
|
| 561 |
+
import tempfile
|
| 562 |
+
import gradio.processing_utils as pu
|
| 563 |
+
|
| 564 |
+
gradio_cache_dir = os.path.join(tempfile.gettempdir(), "gradio")
|
| 565 |
+
os.makedirs(gradio_cache_dir, exist_ok=True)
|
| 566 |
+
|
| 567 |
+
base_url = _get_public_base_url()
|
| 568 |
+
videos = []
|
| 569 |
+
raw_list = output if isinstance(output, list) else ([output] if output else [])
|
| 570 |
+
for idx, item in enumerate(raw_list):
|
| 571 |
+
target_path = None
|
| 572 |
+
if isinstance(item, str) and os.path.exists(item):
|
| 573 |
+
target_path = item
|
| 574 |
+
|
| 575 |
+
if target_path:
|
| 576 |
+
try:
|
| 577 |
+
cached_path = pu.save_file_to_cache(target_path, cache_dir=gradio_cache_dir)
|
| 578 |
+
abs_path = os.path.abspath(cached_path).replace("\\", "/")
|
| 579 |
+
except Exception as e:
|
| 580 |
+
print(f"Warning: Failed to cache video file to Gradio temp dir: {e}")
|
| 581 |
+
abs_path = os.path.abspath(target_path).replace("\\", "/")
|
| 582 |
+
|
| 583 |
+
url = f"{base_url}/gradio_api/file={urllib.parse.quote(abs_path)}"
|
| 584 |
+
videos.append(url)
|
| 585 |
+
elif item:
|
| 586 |
+
videos.append(str(item))
|
| 587 |
+
|
| 588 |
+
execution_time = round(time.time() - start_time, 2)
|
| 589 |
+
_TASKS_DB[task_id]["status"] = "completed"
|
| 590 |
+
_TASKS_DB[task_id]["progress"] = 100
|
| 591 |
+
_TASKS_DB[task_id]["completed_at"] = int(time.time())
|
| 592 |
+
_TASKS_DB[task_id]["result"] = {
|
| 593 |
+
"task_type": task_type,
|
| 594 |
+
"videos": videos,
|
| 595 |
+
"video_path": raw_list[0] if raw_list and isinstance(raw_list[0], str) else None,
|
| 596 |
+
"seed": seed,
|
| 597 |
+
"width": width,
|
| 598 |
+
"height": height,
|
| 599 |
+
"duration": duration,
|
| 600 |
+
"execution_time_seconds": execution_time,
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
except Exception as e:
|
| 604 |
+
_TASKS_DB[task_id]["status"] = "failed"
|
| 605 |
+
_TASKS_DB[task_id]["progress"] = 0
|
| 606 |
+
_TASKS_DB[task_id]["failed_at"] = int(time.time())
|
| 607 |
+
_TASKS_DB[task_id]["error"] = {
|
| 608 |
+
"code": "EXECUTION_ERROR",
|
| 609 |
+
"message": str(e),
|
| 610 |
+
}
|
mcp_tools/error_schema.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Unified MCP tool error response format.
|
| 3 |
+
|
| 4 |
+
Error code enumeration:
|
| 5 |
+
- INVALID_PARAMS: Parameter validation failed (missing required fields, type errors, value out of range)
|
| 6 |
+
- MODEL_NOT_FOUND: The specified model name does not exist
|
| 7 |
+
- ARCHITECTURE_NOT_FOUND: The specified architecture name does not exist
|
| 8 |
+
- CHAIN_TYPE_NOT_FOUND: The specified chain/injector type is invalid
|
| 9 |
+
- FEATURE_NOT_SUPPORTED: The current model does not support the requested feature
|
| 10 |
+
- TASK_NOT_FOUND: The async task ID does not exist
|
| 11 |
+
- MODEL_OOM: GPU out of memory
|
| 12 |
+
- INTERNAL_ERROR: Internal server error
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def make_error(code: str, message: str, details: dict = None) -> dict:
|
| 17 |
+
"""
|
| 18 |
+
Construct a unified MCP tool error response.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
code: Error code (UPPER_SNAKE_CASE format)
|
| 22 |
+
message: Human-readable error description
|
| 23 |
+
details: Optional details dictionary
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
Standardized error response dictionary
|
| 27 |
+
"""
|
| 28 |
+
error = {
|
| 29 |
+
"error": {
|
| 30 |
+
"code": code,
|
| 31 |
+
"message": message,
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
if details:
|
| 35 |
+
error["error"]["details"] = details
|
| 36 |
+
return error
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def make_validation_error(
|
| 40 |
+
message: str = "Request validation failed.",
|
| 41 |
+
missing_fields: list = None,
|
| 42 |
+
invalid_fields: dict = None,
|
| 43 |
+
) -> dict:
|
| 44 |
+
"""
|
| 45 |
+
Construct a parameter validation failure error response.
|
| 46 |
+
|
| 47 |
+
Args:
|
| 48 |
+
message: Error description
|
| 49 |
+
missing_fields: List of missing required field names
|
| 50 |
+
invalid_fields: Key-value pairs of invalid fields, key=field name, value=reason description
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
Standardized INVALID_PARAMS error response
|
| 54 |
+
"""
|
| 55 |
+
details = {}
|
| 56 |
+
if missing_fields:
|
| 57 |
+
details["missing_fields"] = missing_fields
|
| 58 |
+
if invalid_fields:
|
| 59 |
+
details["invalid_fields"] = invalid_fields
|
| 60 |
+
return make_error("INVALID_PARAMS", message, details if details else None)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def make_not_found_error(resource_type: str, resource_id: str) -> dict:
|
| 64 |
+
"""
|
| 65 |
+
Construct a resource-not-found error response.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
resource_type: Resource type (e.g., "model", "architecture", "chain_type", "task")
|
| 69 |
+
resource_id: Resource identifier
|
| 70 |
+
|
| 71 |
+
Returns:
|
| 72 |
+
Standardized *_NOT_FOUND error response
|
| 73 |
+
"""
|
| 74 |
+
code_map = {
|
| 75 |
+
"model": "MODEL_NOT_FOUND",
|
| 76 |
+
"architecture": "ARCHITECTURE_NOT_FOUND",
|
| 77 |
+
"chain_type": "CHAIN_TYPE_NOT_FOUND",
|
| 78 |
+
"task": "TASK_NOT_FOUND",
|
| 79 |
+
}
|
| 80 |
+
code = code_map.get(resource_type, f"{resource_type.upper()}_NOT_FOUND")
|
| 81 |
+
return make_error(
|
| 82 |
+
code,
|
| 83 |
+
f"The specified {resource_type} '{resource_id}' was not found.",
|
| 84 |
+
{"resource_type": resource_type, "resource_id": resource_id},
|
| 85 |
+
)
|
mcp_tools/get_task_list.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Tool: get_task_list
|
| 3 |
+
Get a list of all supported image generation task types along with their required/optional parameter lists.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from .common import _TASK_DEFINITIONS
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def handle_get_task_list() -> list:
|
| 10 |
+
"""Get a list of all supported image generation task types along with their required/optional parameter lists."""
|
| 11 |
+
return _TASK_DEFINITIONS
|
mcp_tools/get_task_status.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Tool: get_task_status
|
| 3 |
+
Query the processing progress and final results of an async image generation task.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from .common import _TASKS_DB
|
| 7 |
+
from .error_schema import make_validation_error, make_not_found_error
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def handle_get_task_status(task_id: str) -> dict:
|
| 11 |
+
"""Query the processing progress and final results of an async image generation task."""
|
| 12 |
+
if not task_id:
|
| 13 |
+
return make_validation_error(
|
| 14 |
+
"Parameter 'task_id' is required.",
|
| 15 |
+
missing_fields=["task_id"],
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
if task_id not in _TASKS_DB:
|
| 19 |
+
return make_not_found_error("task", task_id)
|
| 20 |
+
|
| 21 |
+
return _TASKS_DB[task_id]
|
mcp_tools/hf_private.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ESVIAL: permite leer referencias desde repos PRIVADOS de Hugging Face.
|
| 2 |
+
|
| 3 |
+
Si una URL de imagen/audio/video apunta a huggingface.co/.../resolve/..., se descarga con
|
| 4 |
+
huggingface_hub usando el secreto HF_TOKEN del Space (nunca se imprime). Cualquier otra URL
|
| 5 |
+
sigue el camino original.
|
| 6 |
+
|
| 7 |
+
Todo el parche va dentro de un try: si algo falla, el Space arranca igual con el
|
| 8 |
+
comportamiento original.
|
| 9 |
+
"""
|
| 10 |
+
import io
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import urllib.parse
|
| 14 |
+
|
| 15 |
+
_HF_RE = re.compile(
|
| 16 |
+
r"^https?://(?:huggingface\.co|hf\.co)/(datasets/|spaces/)?([^/]+/[^/]+)/resolve/([^/]+)/(.+)$"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _hf_local_path(url):
|
| 21 |
+
"""Devuelve la ruta local si la URL es de un repo de HF; None si no lo es."""
|
| 22 |
+
if not isinstance(url, str):
|
| 23 |
+
return None
|
| 24 |
+
m = _HF_RE.match(url.split("?", 1)[0])
|
| 25 |
+
if not m:
|
| 26 |
+
return None
|
| 27 |
+
from huggingface_hub import hf_hub_download
|
| 28 |
+
|
| 29 |
+
kind, repo_id, revision, filename = m.groups()
|
| 30 |
+
repo_type = "dataset" if kind == "datasets/" else ("space" if kind == "spaces/" else "model")
|
| 31 |
+
return hf_hub_download(
|
| 32 |
+
repo_id=repo_id,
|
| 33 |
+
filename=urllib.parse.unquote(filename),
|
| 34 |
+
revision=revision,
|
| 35 |
+
repo_type=repo_type,
|
| 36 |
+
token=os.environ.get("HF_TOKEN") or None,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
from . import common as _common
|
| 42 |
+
|
| 43 |
+
_orig_image = _common._download_image_from_url
|
| 44 |
+
_orig_file = _common._download_file_from_url
|
| 45 |
+
|
| 46 |
+
def _download_image_from_url(url, *args, **kwargs):
|
| 47 |
+
local = _hf_local_path(url)
|
| 48 |
+
if local:
|
| 49 |
+
from PIL import Image
|
| 50 |
+
|
| 51 |
+
with open(local, "rb") as fh:
|
| 52 |
+
return Image.open(io.BytesIO(fh.read()))
|
| 53 |
+
return _orig_image(url, *args, **kwargs)
|
| 54 |
+
|
| 55 |
+
def _download_file_from_url(url, *args, **kwargs):
|
| 56 |
+
local = _hf_local_path(url)
|
| 57 |
+
if local:
|
| 58 |
+
return local
|
| 59 |
+
return _orig_file(url, *args, **kwargs)
|
| 60 |
+
|
| 61 |
+
_common._download_image_from_url = _download_image_from_url
|
| 62 |
+
_common._download_file_from_url = _download_file_from_url
|
| 63 |
+
ESVIAL_HF_PRIVATE = True
|
| 64 |
+
except Exception as _e: # nunca tumbar el Space por este parche
|
| 65 |
+
ESVIAL_HF_PRIVATE = False
|
| 66 |
+
_ESVIAL_HF_PRIVATE_ERROR = repr(_e)
|
mcp_tools/mcp_gradio_integration.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP & Gradio Integration Module
|
| 3 |
+
|
| 4 |
+
Provides:
|
| 5 |
+
1. register_high_level_mcp_apis: Expose high-level abstract API/MCP endpoints (using gr.api without polluting the visual UI structure)
|
| 6 |
+
2. cleanup_dependencies_api_names: Force cleanup of show_api attribute for non-high-level APIs in dependencies
|
| 7 |
+
3. patch_gradio_api_suppression: No-op implementation retained for backward compatibility
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
from .get_task_list import handle_get_task_list
|
| 14 |
+
from .run import handle_run
|
| 15 |
+
from .get_task_status import handle_get_task_status
|
| 16 |
+
|
| 17 |
+
HIGH_LEVEL_MCP_API_NAMES = {
|
| 18 |
+
"get_task_list",
|
| 19 |
+
"run",
|
| 20 |
+
"get_task_status",
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sanitize_keys(obj):
|
| 25 |
+
"""Recursively ensure all dictionary keys are converted to str type to avoid Gradio 5 orjson TypeError: Dict key must be str."""
|
| 26 |
+
if isinstance(obj, dict):
|
| 27 |
+
return {str(k): sanitize_keys(v) for k, v in obj.items()}
|
| 28 |
+
elif isinstance(obj, list):
|
| 29 |
+
return [sanitize_keys(x) for x in obj]
|
| 30 |
+
elif isinstance(obj, tuple):
|
| 31 |
+
return tuple(sanitize_keys(x) for x in obj)
|
| 32 |
+
return obj
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def patch_gradio_api_suppression():
|
| 36 |
+
"""Retained for backward compatibility (no-op)."""
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def cleanup_dependencies_api_names(demo):
|
| 41 |
+
"""
|
| 42 |
+
Clean up residual auto-generated API names in demo.fns and demo.dependencies.
|
| 43 |
+
Force only high-level abstract MCP APIs to be exposed as public endpoints.
|
| 44 |
+
"""
|
| 45 |
+
for fn in demo.fns.values():
|
| 46 |
+
api_name = getattr(fn, "api_name", None)
|
| 47 |
+
if api_name not in HIGH_LEVEL_MCP_API_NAMES:
|
| 48 |
+
fn.show_api = False
|
| 49 |
+
fn.api_name = False
|
| 50 |
+
|
| 51 |
+
deps = getattr(demo, "dependencies", None)
|
| 52 |
+
if deps is None and hasattr(demo, "config") and isinstance(demo.config, dict):
|
| 53 |
+
deps = demo.config.get("dependencies", [])
|
| 54 |
+
|
| 55 |
+
if deps:
|
| 56 |
+
for dep in deps:
|
| 57 |
+
if isinstance(dep, dict):
|
| 58 |
+
api_name = dep.get("api_name")
|
| 59 |
+
if api_name not in HIGH_LEVEL_MCP_API_NAMES:
|
| 60 |
+
dep["show_api"] = False
|
| 61 |
+
dep["api_name"] = False
|
| 62 |
+
|
| 63 |
+
print("[MCP Protection] Cleaned up demo dependencies. Suppressed atomic API endpoints.")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def register_high_level_mcp_apis(demo):
|
| 67 |
+
"""
|
| 68 |
+
Explicitly register high-level abstract MCP API endpoints on the Gradio demo using gr.api.
|
| 69 |
+
Using gr.api() never adds any visual UI components (such as Row, Textbox, Button, etc.), avoiding duplicate interface rendering.
|
| 70 |
+
"""
|
| 71 |
+
def get_task_list() -> list:
|
| 72 |
+
"""[Recommended Flow Step 1] Get a list of supported video generation task types (t2va, i2va, flf2va, ref2va) along with their required/optional parameters and paste-and-run example_json_params."""
|
| 73 |
+
return sanitize_keys(handle_get_task_list())
|
| 74 |
+
|
| 75 |
+
def run(json_params: str = "{}") -> dict:
|
| 76 |
+
"""[Recommended Flow Step 2] Unified video generation task execution interface (t2va, i2va, flf2va, ref2va). Accepts a JSON string or dict of parameters.
|
| 77 |
+
|
| 78 |
+
REQUIRED PARAMETERS PER TASK TYPE:
|
| 79 |
+
- t2va: task_type, prompt, width, height, duration
|
| 80 |
+
- i2va: task_type, prompt, width, height, duration, first_frame_image
|
| 81 |
+
- flf2va: task_type, prompt, width, height, duration, first_frame_image, last_frame_image
|
| 82 |
+
- ref2va: task_type, prompt, width, height, duration
|
| 83 |
+
|
| 84 |
+
GLOBAL OPTIONAL CONTROL PARAMETERS:
|
| 85 |
+
- seed (int): Random seed (-1 for random, >=0 for deterministic reproducibility). Default: -1.
|
| 86 |
+
- zero_gpu_duration (int): GPU quota allocation in seconds on HuggingFace ZeroGPU spaces (default: 120).
|
| 87 |
+
|
| 88 |
+
REF2VA OPTIONAL MEDIA REFERENCES:
|
| 89 |
+
- ref_image1..9: Image file path or URL
|
| 90 |
+
- ref_video1..3: Video file path
|
| 91 |
+
- ref_audio1..3: Audio file path
|
| 92 |
+
"""
|
| 93 |
+
try:
|
| 94 |
+
if isinstance(json_params, dict):
|
| 95 |
+
params = json_params
|
| 96 |
+
else:
|
| 97 |
+
params = json.loads(json_params or "{}")
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return {"error": {"code": "INVALID_JSON", "message": f"Failed to parse JSON params: {e}"}}
|
| 100 |
+
return sanitize_keys(handle_run(params))
|
| 101 |
+
|
| 102 |
+
def get_task_status(task_id: str = "") -> dict:
|
| 103 |
+
"""Query the progress, status, and final generated results of an async video generation task."""
|
| 104 |
+
if isinstance(task_id, dict):
|
| 105 |
+
task_id = task_id.get("task_id") or task_id.get("id") or ""
|
| 106 |
+
task_id_str = task_id.strip() if isinstance(task_id, str) else ""
|
| 107 |
+
return sanitize_keys(handle_get_task_status(task_id_str))
|
| 108 |
+
|
| 109 |
+
funcs = [
|
| 110 |
+
get_task_list,
|
| 111 |
+
run,
|
| 112 |
+
get_task_status,
|
| 113 |
+
]
|
| 114 |
+
|
| 115 |
+
for func in funcs:
|
| 116 |
+
gr.api(func)
|
| 117 |
+
|
| 118 |
+
for fn in demo.fns.values():
|
| 119 |
+
if getattr(fn, "api_name", None) in HIGH_LEVEL_MCP_API_NAMES:
|
| 120 |
+
fn.show_api = True
|
| 121 |
+
|
| 122 |
+
print(f"[MCP Integration] Successfully registered {len(funcs)} High-Level Abstract MCP APIs via gr.api().")
|
mcp_tools/run.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Tool: run
|
| 3 |
+
Unified video generation task submission and execution interface.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import time
|
| 7 |
+
import uuid
|
| 8 |
+
import threading
|
| 9 |
+
from .common import (
|
| 10 |
+
_TASK_DEFINITIONS,
|
| 11 |
+
_TASKS_DB,
|
| 12 |
+
_execute_imagegen_pipeline,
|
| 13 |
+
)
|
| 14 |
+
from .error_schema import make_validation_error
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def handle_run(params: dict) -> dict:
|
| 18 |
+
"""
|
| 19 |
+
Unified MiniMax H3 video generation task execution interface.
|
| 20 |
+
|
| 21 |
+
[SUPPORTED TASK TYPES]
|
| 22 |
+
- t2va: Text-to-Video. Required: prompt, width, height, duration.
|
| 23 |
+
- i2va: Image-to-Video. Required: prompt, width, height, duration, first_frame_image.
|
| 24 |
+
- flf2va: First & Last Frame-to-Video. Required: prompt, width, height, duration, first_frame_image, last_frame_image.
|
| 25 |
+
- ref2va: Reference-to-Video. Required: prompt, width, height, duration. Optional: ref_image1..9, ref_video1..3, ref_audio1..3, h3_guides.
|
| 26 |
+
|
| 27 |
+
[GLOBAL OPTIONAL PARAMETERS]
|
| 28 |
+
- seed (int): Random seed (-1 for random seed, >=0 for deterministic reproduction). Default: -1.
|
| 29 |
+
- zero_gpu_duration (int): GPU execution time quota allocation in seconds on HuggingFace ZeroGPU spaces (default: 120).
|
| 30 |
+
- loras (list[dict]): List of LoRA configurations (e.g., [{"source": "Hugging Face", "id_or_url": "repo/lora.safetensors", "scale": 1.0}]).
|
| 31 |
+
- h3_controlnets (list[dict]): List of H3 ControlNet configurations (e.g., [{"video": "https://.../pose.mp4", "strength": 1.0}]).
|
| 32 |
+
- h3_guides (list[dict]): List of keyframe guide configurations (e.g., [{"image": "https://.../keyframe.png", "time_seconds": 1.5}]). Supported across all H3 tasks (FL2VA & Ref2VA).
|
| 33 |
+
- control_video (str): Single convenience control video URL/path/base64 for H3 ControlNet.
|
| 34 |
+
- control_strength (float): Strength for single convenience control video (default: 1.0).
|
| 35 |
+
|
| 36 |
+
[Paste-and-Run json_params Example (t2va)]
|
| 37 |
+
{
|
| 38 |
+
"task_type": "t2va",
|
| 39 |
+
"prompt": "A futuristic city with flying cars at sunset, 4k resolution",
|
| 40 |
+
"width": 1344,
|
| 41 |
+
"height": 768,
|
| 42 |
+
"duration": 5.0,
|
| 43 |
+
"seed": -1,
|
| 44 |
+
"zero_gpu_duration": 120
|
| 45 |
+
}
|
| 46 |
+
"""
|
| 47 |
+
if not isinstance(params, dict):
|
| 48 |
+
return make_validation_error("Request params must be an object.")
|
| 49 |
+
|
| 50 |
+
valid_tasks = [t["task_type"] for t in _TASK_DEFINITIONS]
|
| 51 |
+
task_type = params.get("task_type")
|
| 52 |
+
if not task_type or task_type not in valid_tasks:
|
| 53 |
+
return make_validation_error(
|
| 54 |
+
f"Invalid or missing 'task_type'. Must be one of {valid_tasks}.",
|
| 55 |
+
invalid_fields={"task_type": f"Must be in {valid_tasks}"},
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
task_def = next((t for t in _TASK_DEFINITIONS if t["task_type"] == task_type), None)
|
| 59 |
+
required_fields = task_def["required_inputs"] if task_def else ["prompt", "width", "height", "duration"]
|
| 60 |
+
|
| 61 |
+
missing = []
|
| 62 |
+
for req_field in required_fields:
|
| 63 |
+
if req_field not in params or params[req_field] is None or params[req_field] == "":
|
| 64 |
+
missing.append(req_field)
|
| 65 |
+
if missing:
|
| 66 |
+
return make_validation_error(
|
| 67 |
+
f"Missing required parameter(s) for task '{task_type}': {', '.join(missing)}",
|
| 68 |
+
missing_fields=missing,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
task_id = f"v_task_{uuid.uuid4().hex[:10]}"
|
| 72 |
+
created_at = int(time.time())
|
| 73 |
+
|
| 74 |
+
_TASKS_DB[task_id] = {
|
| 75 |
+
"task_id": task_id,
|
| 76 |
+
"status": "queued",
|
| 77 |
+
"progress": 0,
|
| 78 |
+
"created_at": created_at,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
async_exec = params.get("async_execution", False)
|
| 82 |
+
|
| 83 |
+
if async_exec:
|
| 84 |
+
t = threading.Thread(target=_execute_imagegen_pipeline, args=(task_id, params), daemon=True)
|
| 85 |
+
t.start()
|
| 86 |
+
return {
|
| 87 |
+
"status": "queued",
|
| 88 |
+
"task_id": task_id,
|
| 89 |
+
"poll_interval_ms": 2000,
|
| 90 |
+
"message": "Task queued successfully. Poll get_task_status for results.",
|
| 91 |
+
}
|
| 92 |
+
else:
|
| 93 |
+
_execute_imagegen_pipeline(task_id, params)
|
| 94 |
+
return _TASKS_DB[task_id]
|
mcp_tools/tool_handlers.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MCP Tool Handlers — Aggregation entry point.
|
| 3 |
+
Core logic is located in individual task files (get_task_list.py, run.py, get_task_status.py).
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from .get_task_list import handle_get_task_list
|
| 7 |
+
from .run import handle_run
|
| 8 |
+
from .get_task_status import handle_get_task_status
|
| 9 |
+
from .common import (
|
| 10 |
+
_TASK_DEFINITIONS,
|
| 11 |
+
_TASKS_DB,
|
| 12 |
+
_load_yaml,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
"handle_get_task_list",
|
| 17 |
+
"handle_run",
|
| 18 |
+
"handle_get_task_status",
|
| 19 |
+
]
|
requirements.txt
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
comfyui-frontend-package==1.53.10
|
| 2 |
+
comfyui-workflow-templates==0.11.76
|
| 3 |
+
comfyui-embedded-docs==0.5.13
|
| 4 |
+
torch
|
| 5 |
+
torchsde
|
| 6 |
+
torchvision
|
| 7 |
+
numpy>=1.25.0
|
| 8 |
+
einops
|
| 9 |
+
transformers>=4.50.3
|
| 10 |
+
tokenizers>=0.13.3
|
| 11 |
+
sentencepiece
|
| 12 |
+
safetensors>=0.4.2
|
| 13 |
+
aiohttp>=3.11.8
|
| 14 |
+
yarl>=1.18.0
|
| 15 |
+
pyyaml
|
| 16 |
+
Pillow
|
| 17 |
+
scipy
|
| 18 |
+
tqdm
|
| 19 |
+
psutil
|
| 20 |
+
alembic
|
| 21 |
+
SQLAlchemy>=2.0.0
|
| 22 |
+
filelock
|
| 23 |
+
av>=17.0.0
|
| 24 |
+
comfy-kitchen==0.2.37
|
| 25 |
+
comfy-aimdo==0.5.5
|
| 26 |
+
requests
|
| 27 |
+
simpleeval>=1.0.0
|
| 28 |
+
blake3
|
| 29 |
+
|
| 30 |
+
#non essential dependencies:
|
| 31 |
+
kornia>=0.7.1
|
| 32 |
+
spandrel
|
| 33 |
+
pydantic~=2.0
|
| 34 |
+
pydantic-settings~=2.0
|
| 35 |
+
PyOpenGL>=3.1.8
|
| 36 |
+
comfy-angle
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
huggingface-hub
|
| 40 |
+
imageio
|
| 41 |
+
spaces
|
| 42 |
+
sageattention @ https://huggingface.co/RioShiina/Sage-Attention-ZeroGPU-Space-Build/resolve/main/sageattention-2.2.0-cp312-cp312-linux_x86_64.whl
|
tests/test_h3_guide.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import unittest
|
| 4 |
+
from unittest.mock import MagicMock
|
| 5 |
+
|
| 6 |
+
# Add project root to sys.path
|
| 7 |
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 8 |
+
if PROJECT_ROOT not in sys.path:
|
| 9 |
+
sys.path.insert(0, PROJECT_ROOT)
|
| 10 |
+
|
| 11 |
+
import asyncio
|
| 12 |
+
|
| 13 |
+
if 'torch' not in sys.modules:
|
| 14 |
+
sys.modules['torch'] = MagicMock()
|
| 15 |
+
if 'numpy' not in sys.modules:
|
| 16 |
+
sys.modules['numpy'] = MagicMock()
|
| 17 |
+
if 'gradio' not in sys.modules:
|
| 18 |
+
sys.modules['gradio'] = MagicMock()
|
| 19 |
+
if 'spaces' not in sys.modules:
|
| 20 |
+
mock_spaces = MagicMock()
|
| 21 |
+
mock_spaces.GPU = lambda fn: fn
|
| 22 |
+
sys.modules['spaces'] = mock_spaces
|
| 23 |
+
if 'huggingface_hub' not in sys.modules:
|
| 24 |
+
mock_hf = MagicMock()
|
| 25 |
+
sys.modules['huggingface_hub'] = mock_hf
|
| 26 |
+
sys.modules['huggingface_hub.constants'] = MagicMock()
|
| 27 |
+
if 'PIL' not in sys.modules:
|
| 28 |
+
mock_pil = MagicMock()
|
| 29 |
+
class MockImage:
|
| 30 |
+
pass
|
| 31 |
+
mock_pil.Image = MagicMock()
|
| 32 |
+
mock_pil.Image.Image = MockImage
|
| 33 |
+
sys.modules['PIL'] = mock_pil
|
| 34 |
+
sys.modules['PIL.Image'] = mock_pil.Image
|
| 35 |
+
|
| 36 |
+
# Mock ComfyUI environment if not installed locally
|
| 37 |
+
if 'execution' not in sys.modules:
|
| 38 |
+
sys.modules['execution'] = MagicMock()
|
| 39 |
+
if 'server' not in sys.modules:
|
| 40 |
+
sys.modules['server'] = MagicMock()
|
| 41 |
+
if 'nodes' not in sys.modules:
|
| 42 |
+
mock_nodes = MagicMock()
|
| 43 |
+
async def async_noop():
|
| 44 |
+
pass
|
| 45 |
+
mock_nodes.init_extra_nodes = async_noop
|
| 46 |
+
dummy_cls = MagicMock()
|
| 47 |
+
mock_nodes.NODE_CLASS_MAPPINGS = {
|
| 48 |
+
'CLIPTextEncode': dummy_cls,
|
| 49 |
+
'CLIPTextEncodeSDXL': dummy_cls,
|
| 50 |
+
'LoraLoader': dummy_cls,
|
| 51 |
+
'CLIPSetLastLayer': dummy_cls,
|
| 52 |
+
'CheckpointLoaderSimple': dummy_cls,
|
| 53 |
+
}
|
| 54 |
+
mock_nodes.CheckpointLoaderSimple = dummy_cls
|
| 55 |
+
mock_nodes.LoraLoader = dummy_cls
|
| 56 |
+
sys.modules['nodes'] = mock_nodes
|
| 57 |
+
|
| 58 |
+
# Helper to create dummy ComfyUI node class
|
| 59 |
+
def make_mock_node(name, required_inputs=None, optional_inputs=None):
|
| 60 |
+
req = required_inputs or {}
|
| 61 |
+
opt = optional_inputs or {}
|
| 62 |
+
class MockNode:
|
| 63 |
+
NODE_NAME = name
|
| 64 |
+
@classmethod
|
| 65 |
+
def INPUT_TYPES(cls):
|
| 66 |
+
return {"required": req, "optional": opt}
|
| 67 |
+
return MockNode
|
| 68 |
+
|
| 69 |
+
from comfy_integration import nodes as ci_nodes
|
| 70 |
+
|
| 71 |
+
# Register mock nodes for testing
|
| 72 |
+
TEST_NODE_MAPPINGS = {
|
| 73 |
+
"UNETLoader": make_mock_node("UNETLoader", {"unet_name": (["model.safetensors"],), "weight_dtype": (["default"],)}),
|
| 74 |
+
"CLIPLoader": make_mock_node("CLIPLoader", {"clip_name": (["clip.safetensors"],), "type": (["minimax"],)}),
|
| 75 |
+
"VAELoader": make_mock_node("VAELoader", {"vae_name": (["vae.safetensors"],)}),
|
| 76 |
+
"MiniMaxH3ReferenceToVideo": make_mock_node("MiniMaxH3ReferenceToVideo", {
|
| 77 |
+
"clip": ("CLIP",), "vae": ("VAE",), "audio_vae": ("VAE",),
|
| 78 |
+
"prompt": ("STRING", {"default": ""}), "width": ("INT", {"default": 960}),
|
| 79 |
+
"height": ("INT", {"default": 544}), "length": ("INT", {"default": 73})
|
| 80 |
+
}),
|
| 81 |
+
"BasicGuider": make_mock_node("BasicGuider", {"model": ("MODEL",), "conditioning": ("CONDITIONING",)}),
|
| 82 |
+
"KSamplerSelect": make_mock_node("KSamplerSelect", {"sampler_name": (["res_multistep"], {"default": "res_multistep"})}),
|
| 83 |
+
"BasicScheduler": make_mock_node("BasicScheduler", {"model": ("MODEL",), "scheduler": (["simple"], {"default": "simple"}), "steps": ("INT", {"default": 20})}),
|
| 84 |
+
"RandomNoise": make_mock_node("RandomNoise", {"noise_seed": ("INT", {"default": 0})}),
|
| 85 |
+
"SamplerCustomAdvanced": make_mock_node("SamplerCustomAdvanced", {
|
| 86 |
+
"noise": ("NOISE",), "guider": ("GUIDER",), "sampler": ("SAMPLER",),
|
| 87 |
+
"sigmas": ("SIGMAS",), "latent_image": ("LATENT",)
|
| 88 |
+
}),
|
| 89 |
+
"VAEDecode": make_mock_node("VAEDecode", {"samples": ("LATENT",), "vae": ("VAE",)}),
|
| 90 |
+
"VAEDecodeAudio": make_mock_node("VAEDecodeAudio", {"samples": ("LATENT",), "vae": ("VAE",)}),
|
| 91 |
+
"CreateVideo": make_mock_node("CreateVideo", {"images": ("IMAGE",), "audio": ("AUDIO",), "fps": ("INT", {"default": 24})}),
|
| 92 |
+
"SaveVideo": make_mock_node("SaveVideo", {"video": ("VIDEO",), "filename_prefix": ("STRING", {"default": "video/test"})}),
|
| 93 |
+
"LoadImage": make_mock_node("LoadImage", {"image": ("STRING", {"default": ""})}),
|
| 94 |
+
"LoadVideo": make_mock_node("LoadVideo", {"file": ("STRING", {"default": ""})}),
|
| 95 |
+
"GetVideoComponents": make_mock_node("GetVideoComponents", {"video": ("VIDEO",)}),
|
| 96 |
+
"LoadAudio": make_mock_node("LoadAudio", {"audio": ("STRING", {"default": ""})}),
|
| 97 |
+
"MiniMaxH3AddGuide": make_mock_node("MiniMaxH3AddGuide", {
|
| 98 |
+
"positive": ("CONDITIONING",),
|
| 99 |
+
"latent": ("LATENT",),
|
| 100 |
+
"frame_idx": ("INT", {"default": 0}),
|
| 101 |
+
}, {
|
| 102 |
+
"vae": ("VAE",),
|
| 103 |
+
"audio_vae": ("VAE",),
|
| 104 |
+
"image": ("IMAGE",),
|
| 105 |
+
"audio": ("AUDIO",),
|
| 106 |
+
}),
|
| 107 |
+
"LoraLoader": make_mock_node("LoraLoader", {"model": ("MODEL",), "clip": ("CLIP",), "lora_name": ("STRING",)}),
|
| 108 |
+
"MiniMaxH3ImageToVideo": make_mock_node("MiniMaxH3ImageToVideo", {
|
| 109 |
+
"clip": ("CLIP",), "vae": ("VAE",),
|
| 110 |
+
"prompt": ("STRING", {"default": ""}), "width": ("INT", {"default": 1344}),
|
| 111 |
+
"height": ("INT", {"default": 768}), "length": ("INT", {"default": 73})
|
| 112 |
+
}, {
|
| 113 |
+
"first_frame": ("IMAGE",), "last_frame": ("IMAGE",)
|
| 114 |
+
}),
|
| 115 |
+
"ImageScale": make_mock_node("ImageScale", {
|
| 116 |
+
"image": ("IMAGE",), "width": ("INT", {"default": 512}), "height": ("INT", {"default": 512}),
|
| 117 |
+
"upscale_method": (["nearest-exact"],), "crop": (["center"],)
|
| 118 |
+
}),
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
ci_nodes.NODE_CLASS_MAPPINGS.update(TEST_NODE_MAPPINGS)
|
| 122 |
+
|
| 123 |
+
from chain_injectors import discover_injectors, get_registered_features
|
| 124 |
+
from utils.app_utils import process_h3_guide_inputs
|
| 125 |
+
from core.workflow_assembler import WorkflowAssembler
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class TestH3GuideIntegration(unittest.TestCase):
|
| 129 |
+
def setUp(self):
|
| 130 |
+
self.recipe_path = os.path.join(PROJECT_ROOT, "ui", "shared", "h3_ref2va_recipe.yaml")
|
| 131 |
+
|
| 132 |
+
def test_injector_discovery(self):
|
| 133 |
+
injectors = discover_injectors()
|
| 134 |
+
self.assertIn("dynamic_h3_guide_chains", injectors)
|
| 135 |
+
self.assertTrue(callable(injectors["dynamic_h3_guide_chains"]))
|
| 136 |
+
|
| 137 |
+
def test_registered_features(self):
|
| 138 |
+
import yaml
|
| 139 |
+
features = get_registered_features()
|
| 140 |
+
self.assertIn("h3_guide", features)
|
| 141 |
+
self.assertEqual(features["h3_guide"]["chain_type"], "dynamic_h3_guide_chains")
|
| 142 |
+
|
| 143 |
+
with open(os.path.join(PROJECT_ROOT, "yaml", "chain_features.yaml"), "r", encoding="utf-8") as f:
|
| 144 |
+
chain_features = yaml.safe_load(f)
|
| 145 |
+
self.assertIn("h3_guide", chain_features)
|
| 146 |
+
schema = chain_features["h3_guide"]["parameters_schema"]
|
| 147 |
+
self.assertIn("frame_idx", schema["properties"])
|
| 148 |
+
self.assertIn("time_seconds", schema["properties"])
|
| 149 |
+
self.assertIn("image", schema["properties"])
|
| 150 |
+
self.assertIn("video", schema["properties"])
|
| 151 |
+
self.assertIn("audio", schema["properties"])
|
| 152 |
+
|
| 153 |
+
def test_process_h3_guide_inputs_direct_list(self):
|
| 154 |
+
raw_guides = [
|
| 155 |
+
{"image": "path/to/img1.png", "time_seconds": 1.5},
|
| 156 |
+
{"image": "path/to/img2.png", "frame_idx": 10},
|
| 157 |
+
]
|
| 158 |
+
ui_values = {"h3_guides": raw_guides}
|
| 159 |
+
processed = process_h3_guide_inputs(ui_values)
|
| 160 |
+
self.assertEqual(len(processed), 2)
|
| 161 |
+
# Should be sorted by frame_idx: 10 comes before round(1.5 * 24) = 36
|
| 162 |
+
self.assertEqual(processed[0]["frame_idx"], 10)
|
| 163 |
+
self.assertEqual(processed[1]["frame_idx"], 36)
|
| 164 |
+
self.assertEqual(processed[0]["image"], "img2.png")
|
| 165 |
+
self.assertEqual(processed[1]["image"], "img1.png")
|
| 166 |
+
|
| 167 |
+
def test_process_h3_guide_inputs_ui_prefix(self):
|
| 168 |
+
ui_values = {
|
| 169 |
+
"h3_guide_images_test": ["img_a.png", "img_b.png"],
|
| 170 |
+
"h3_guide_videos_test": [None, None],
|
| 171 |
+
"h3_guide_audios_test": [None, None],
|
| 172 |
+
"h3_guide_times_test": [2.0, 0.5],
|
| 173 |
+
"h3_guide_frames_test": [None, None],
|
| 174 |
+
}
|
| 175 |
+
processed = process_h3_guide_inputs(ui_values, prefix="test")
|
| 176 |
+
self.assertEqual(len(processed), 2)
|
| 177 |
+
# Sorted: 0.5s (12 frames) then 2.0s (48 frames)
|
| 178 |
+
self.assertEqual(processed[0]["frame_idx"], 12)
|
| 179 |
+
self.assertEqual(processed[1]["frame_idx"], 48)
|
| 180 |
+
self.assertEqual(processed[0]["image"], "img_b.png")
|
| 181 |
+
self.assertEqual(processed[1]["image"], "img_a.png")
|
| 182 |
+
|
| 183 |
+
def test_workflow_assembler_without_guides(self):
|
| 184 |
+
assembler = WorkflowAssembler(self.recipe_path)
|
| 185 |
+
ui_values = {
|
| 186 |
+
"prompt": "test prompt",
|
| 187 |
+
"width": 960,
|
| 188 |
+
"height": 544,
|
| 189 |
+
"length": 73,
|
| 190 |
+
"h3_guides": []
|
| 191 |
+
}
|
| 192 |
+
workflow = assembler.assemble(ui_values)
|
| 193 |
+
# BasicGuider conditioning should connect directly to minimax_h3:0
|
| 194 |
+
guider_id = assembler.node_map["basic_guider"]
|
| 195 |
+
minimax_id = assembler.node_map["minimax_h3"]
|
| 196 |
+
cond_input = workflow[guider_id]["inputs"]["conditioning"]
|
| 197 |
+
self.assertEqual(cond_input, [minimax_id, 0])
|
| 198 |
+
|
| 199 |
+
def test_workflow_assembler_with_single_guide(self):
|
| 200 |
+
assembler = WorkflowAssembler(self.recipe_path)
|
| 201 |
+
ui_values = {
|
| 202 |
+
"prompt": "test prompt",
|
| 203 |
+
"width": 960,
|
| 204 |
+
"height": 544,
|
| 205 |
+
"length": 73,
|
| 206 |
+
"h3_guides": [
|
| 207 |
+
{"image": "test_guide.png", "frame_idx": 24}
|
| 208 |
+
]
|
| 209 |
+
}
|
| 210 |
+
workflow = assembler.assemble(ui_values)
|
| 211 |
+
guider_id = assembler.node_map["basic_guider"]
|
| 212 |
+
minimax_id = assembler.node_map["minimax_h3"]
|
| 213 |
+
vae_id = assembler.node_map["video_vae_loader"]
|
| 214 |
+
audio_vae_id = assembler.node_map["audio_vae_loader"]
|
| 215 |
+
|
| 216 |
+
# Find MiniMaxH3AddGuide node in workflow
|
| 217 |
+
guide_nodes = [
|
| 218 |
+
(nid, n) for nid, n in workflow.items()
|
| 219 |
+
if n.get("class_type") == "MiniMaxH3AddGuide"
|
| 220 |
+
]
|
| 221 |
+
self.assertEqual(len(guide_nodes), 1)
|
| 222 |
+
guide_id, guide_data = guide_nodes[0]
|
| 223 |
+
|
| 224 |
+
# Verify guide inputs
|
| 225 |
+
self.assertEqual(guide_data["inputs"]["frame_idx"], 24)
|
| 226 |
+
self.assertEqual(guide_data["inputs"]["positive"], [minimax_id, 0])
|
| 227 |
+
self.assertEqual(guide_data["inputs"]["latent"], [minimax_id, 1])
|
| 228 |
+
self.assertEqual(guide_data["inputs"]["vae"], [vae_id, 0])
|
| 229 |
+
self.assertEqual(guide_data["inputs"]["audio_vae"], [audio_vae_id, 0])
|
| 230 |
+
|
| 231 |
+
# Verify basic_guider points to the guide output
|
| 232 |
+
self.assertEqual(workflow[guider_id]["inputs"]["conditioning"], [guide_id, 0])
|
| 233 |
+
|
| 234 |
+
def test_workflow_assembler_with_chained_guides(self):
|
| 235 |
+
assembler = WorkflowAssembler(self.recipe_path)
|
| 236 |
+
ui_values = {
|
| 237 |
+
"prompt": "test prompt",
|
| 238 |
+
"width": 960,
|
| 239 |
+
"height": 544,
|
| 240 |
+
"length": 73,
|
| 241 |
+
"h3_guides": [
|
| 242 |
+
{"image": "guide1.png", "frame_idx": 10},
|
| 243 |
+
{"image": "guide2.png", "frame_idx": 36},
|
| 244 |
+
{"image": "guide3.png", "frame_idx": 72}
|
| 245 |
+
]
|
| 246 |
+
}
|
| 247 |
+
workflow = assembler.assemble(ui_values)
|
| 248 |
+
guider_id = assembler.node_map["basic_guider"]
|
| 249 |
+
minimax_id = assembler.node_map["minimax_h3"]
|
| 250 |
+
|
| 251 |
+
guide_nodes = [
|
| 252 |
+
(nid, n) for nid, n in workflow.items()
|
| 253 |
+
if n.get("class_type") == "MiniMaxH3AddGuide"
|
| 254 |
+
]
|
| 255 |
+
self.assertEqual(len(guide_nodes), 3)
|
| 256 |
+
|
| 257 |
+
# Sort by frame_idx
|
| 258 |
+
guide_nodes_sorted = sorted(guide_nodes, key=lambda x: x[1]["inputs"]["frame_idx"])
|
| 259 |
+
g1_id, g1 = guide_nodes_sorted[0]
|
| 260 |
+
g2_id, g2 = guide_nodes_sorted[1]
|
| 261 |
+
g3_id, g3 = guide_nodes_sorted[2]
|
| 262 |
+
|
| 263 |
+
self.assertEqual(g1["inputs"]["positive"], [minimax_id, 0])
|
| 264 |
+
self.assertEqual(g2["inputs"]["positive"], [g1_id, 0])
|
| 265 |
+
self.assertEqual(g3["inputs"]["positive"], [g2_id, 0])
|
| 266 |
+
|
| 267 |
+
# BasicGuider connects to last guide in chain
|
| 268 |
+
self.assertEqual(workflow[guider_id]["inputs"]["conditioning"], [g3_id, 0])
|
| 269 |
+
|
| 270 |
+
def test_workflow_assembler_with_video_and_audio_guides(self):
|
| 271 |
+
assembler = WorkflowAssembler(self.recipe_path)
|
| 272 |
+
ui_values = {
|
| 273 |
+
"prompt": "test prompt",
|
| 274 |
+
"width": 960,
|
| 275 |
+
"height": 544,
|
| 276 |
+
"length": 73,
|
| 277 |
+
"h3_guides": [
|
| 278 |
+
{"video": "clip.mp4", "frame_idx": 24},
|
| 279 |
+
{"audio": "audio.mp3", "frame_idx": 48}
|
| 280 |
+
]
|
| 281 |
+
}
|
| 282 |
+
workflow = assembler.assemble(ui_values)
|
| 283 |
+
|
| 284 |
+
guide_nodes = [
|
| 285 |
+
(nid, n) for nid, n in workflow.items()
|
| 286 |
+
if n.get("class_type") == "MiniMaxH3AddGuide"
|
| 287 |
+
]
|
| 288 |
+
self.assertEqual(len(guide_nodes), 2)
|
| 289 |
+
|
| 290 |
+
# Check LoadVideo + GetVideoComponents created
|
| 291 |
+
load_vids = [n for n in workflow.values() if n.get("class_type") == "LoadVideo"]
|
| 292 |
+
get_comps = [n for n in workflow.values() if n.get("class_type") == "GetVideoComponents"]
|
| 293 |
+
load_auds = [n for n in workflow.values() if n.get("class_type") == "LoadAudio"]
|
| 294 |
+
|
| 295 |
+
self.assertEqual(len(load_vids), 1)
|
| 296 |
+
self.assertEqual(len(get_comps), 1)
|
| 297 |
+
self.assertEqual(len(load_auds), 1)
|
| 298 |
+
|
| 299 |
+
def test_h3_guide_ui_configuration(self):
|
| 300 |
+
from ui.shared.ui_components import create_h3_guide_ui
|
| 301 |
+
import gradio as gr
|
| 302 |
+
|
| 303 |
+
gr.Slider.reset_mock()
|
| 304 |
+
gr.Number.reset_mock()
|
| 305 |
+
|
| 306 |
+
comps = create_h3_guide_ui("test_ui")
|
| 307 |
+
times = comps.get("h3_guide_times_test_ui", [])
|
| 308 |
+
frames = comps.get("h3_guide_frames_test_ui", [])
|
| 309 |
+
|
| 310 |
+
# Step must be 0.5 for all slider calls
|
| 311 |
+
self.assertGreater(len(times), 0)
|
| 312 |
+
self.assertGreater(len(gr.Slider.call_args_list), 0)
|
| 313 |
+
for call in gr.Slider.call_args_list:
|
| 314 |
+
self.assertEqual(call.kwargs.get("step"), 0.5)
|
| 315 |
+
|
| 316 |
+
# No Frame Index components displayed
|
| 317 |
+
self.assertEqual(len(frames), 0)
|
| 318 |
+
for call in gr.Number.call_args_list:
|
| 319 |
+
label = call.kwargs.get("label", "")
|
| 320 |
+
self.assertNotIn("Frame Index", label)
|
| 321 |
+
self.assertNotIn("24 fps", label.lower())
|
| 322 |
+
|
| 323 |
+
def test_h3_fl2va_recipe_guide_integration(self):
|
| 324 |
+
fl2va_recipe_path = os.path.join(PROJECT_ROOT, "ui", "shared", "h3_fl2va_recipe.yaml")
|
| 325 |
+
assembler = WorkflowAssembler(fl2va_recipe_path)
|
| 326 |
+
ui_values = {
|
| 327 |
+
"prompt": "sunset test",
|
| 328 |
+
"width": 1344,
|
| 329 |
+
"height": 768,
|
| 330 |
+
"length": 73,
|
| 331 |
+
"h3_guides": [
|
| 332 |
+
{"image": "intermediate_keyframe.png", "frame_idx": 36}
|
| 333 |
+
]
|
| 334 |
+
}
|
| 335 |
+
workflow = assembler.assemble(ui_values)
|
| 336 |
+
guider_id = assembler.node_map["basic_guider"]
|
| 337 |
+
minimax_id = assembler.node_map["minimax_h3"]
|
| 338 |
+
|
| 339 |
+
guide_nodes = [
|
| 340 |
+
(nid, n) for nid, n in workflow.items()
|
| 341 |
+
if n.get("class_type") == "MiniMaxH3AddGuide"
|
| 342 |
+
]
|
| 343 |
+
self.assertEqual(len(guide_nodes), 1)
|
| 344 |
+
guide_id, guide_data = guide_nodes[0]
|
| 345 |
+
self.assertEqual(guide_data["inputs"]["frame_idx"], 36)
|
| 346 |
+
self.assertEqual(guide_data["inputs"]["positive"], [minimax_id, 0])
|
| 347 |
+
self.assertEqual(workflow[guider_id]["inputs"]["conditioning"], [guide_id, 0])
|
| 348 |
+
|
| 349 |
+
def test_h3_fl2va_ui_integration(self):
|
| 350 |
+
from ui.shared import h3_fl2va_ui
|
| 351 |
+
|
| 352 |
+
comps = h3_fl2va_ui.create_ui()
|
| 353 |
+
self.assertIn("h3_guide_times_h3_fl2va", comps)
|
| 354 |
+
self.assertIn("h3_guide_images_h3_fl2va", comps)
|
| 355 |
+
self.assertIn("h3_guide_videos_h3_fl2va", comps)
|
| 356 |
+
self.assertIn("h3_guide_audios_h3_fl2va", comps)
|
| 357 |
+
|
| 358 |
+
def test_unified_h3_ui_integration(self):
|
| 359 |
+
from ui.h3_ui import create_ui
|
| 360 |
+
comps = create_ui()
|
| 361 |
+
self.assertIn("task", comps)
|
| 362 |
+
self.assertIn("first_frame", comps)
|
| 363 |
+
self.assertIn("last_frame", comps)
|
| 364 |
+
self.assertIn("h3_guide_times_h3", comps)
|
| 365 |
+
self.assertIn("h3_guide_images_h3", comps)
|
| 366 |
+
self.assertIn("h3_guide_videos_h3", comps)
|
| 367 |
+
self.assertIn("h3_guide_audios_h3", comps)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
if __name__ == "__main__":
|
| 371 |
+
unittest.main()
|
| 372 |
+
|
| 373 |
+
|
ui/__init__.py
ADDED
|
File without changes
|
ui/events/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .main import attach_event_handlers
|
ui/events/chain_handlers.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import yaml
|
| 3 |
+
from functools import lru_cache
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from core.settings import LORA_DIR, MAX_CONTROLNETS, MAX_LORAS, MAX_H3_GUIDES
|
| 6 |
+
from utils.app_utils import save_uploaded_file_with_hash, load_h3_controlnet_config, get_h3_cn_defaults
|
| 7 |
+
|
| 8 |
+
def on_lora_upload(file_obj):
|
| 9 |
+
if not file_obj:
|
| 10 |
+
return gr.update(), gr.update()
|
| 11 |
+
|
| 12 |
+
hashed_filename = save_uploaded_file_with_hash(file_obj, LORA_DIR)
|
| 13 |
+
return hashed_filename, "File"
|
| 14 |
+
|
| 15 |
+
def create_lora_event_handlers(prefix, ui_components):
|
| 16 |
+
lora_rows = ui_components.get(f'lora_rows_{prefix}')
|
| 17 |
+
if not lora_rows: return
|
| 18 |
+
lora_ids = ui_components[f'lora_ids_{prefix}']
|
| 19 |
+
lora_scales = ui_components[f'lora_scales_{prefix}']
|
| 20 |
+
lora_uploads = ui_components[f'lora_uploads_{prefix}']
|
| 21 |
+
lora_sources = ui_components[f'lora_sources_{prefix}']
|
| 22 |
+
count_state = ui_components[f'lora_count_state_{prefix}']
|
| 23 |
+
add_button = ui_components[f'add_lora_button_{prefix}']
|
| 24 |
+
del_button = ui_components[f'delete_lora_button_{prefix}']
|
| 25 |
+
|
| 26 |
+
for i in range(MAX_LORAS):
|
| 27 |
+
lora_uploads[i].upload(
|
| 28 |
+
fn=on_lora_upload,
|
| 29 |
+
inputs=[lora_uploads[i]],
|
| 30 |
+
outputs=[lora_ids[i], lora_sources[i]],
|
| 31 |
+
show_progress=True,
|
| 32 |
+
api_name=False
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
def add_lora_row(c):
|
| 36 |
+
updates = {}
|
| 37 |
+
if c < MAX_LORAS:
|
| 38 |
+
c += 1
|
| 39 |
+
updates[lora_rows[c - 1]] = gr.update(visible=True)
|
| 40 |
+
|
| 41 |
+
updates[count_state] = c
|
| 42 |
+
updates[add_button] = gr.update(visible=c < MAX_LORAS)
|
| 43 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 44 |
+
return updates
|
| 45 |
+
|
| 46 |
+
def del_lora_row(c):
|
| 47 |
+
updates = {}
|
| 48 |
+
if c > 1:
|
| 49 |
+
updates[lora_rows[c - 1]] = gr.update(visible=False)
|
| 50 |
+
updates[lora_ids[c - 1]] = ""
|
| 51 |
+
updates[lora_scales[c - 1]] = 0.0
|
| 52 |
+
updates[lora_uploads[c - 1]] = None
|
| 53 |
+
c -= 1
|
| 54 |
+
|
| 55 |
+
updates[count_state] = c
|
| 56 |
+
updates[add_button] = gr.update(visible=True)
|
| 57 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 58 |
+
return updates
|
| 59 |
+
|
| 60 |
+
add_outputs = [count_state, add_button, del_button] + lora_rows
|
| 61 |
+
del_outputs = [count_state, add_button, del_button] + lora_rows + lora_ids + lora_scales + lora_uploads
|
| 62 |
+
|
| 63 |
+
add_button.click(add_lora_row, [count_state], add_outputs, show_progress=False, api_name=False)
|
| 64 |
+
del_button.click(del_lora_row, [count_state], del_outputs, show_progress=False, api_name=False)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def create_h3_controlnet_event_handlers(prefix, ui_components):
|
| 68 |
+
cn_rows = ui_components.get(f'h3_controlnet_rows_{prefix}')
|
| 69 |
+
if not cn_rows: return
|
| 70 |
+
cn_types = ui_components[f'h3_controlnet_types_{prefix}']
|
| 71 |
+
cn_series = ui_components[f'h3_controlnet_series_{prefix}']
|
| 72 |
+
cn_filepaths = ui_components[f'h3_controlnet_filepaths_{prefix}']
|
| 73 |
+
cn_videos = ui_components[f'h3_controlnet_videos_{prefix}']
|
| 74 |
+
cn_strengths = ui_components[f'h3_controlnet_strengths_{prefix}']
|
| 75 |
+
cn_start_percents = ui_components[f'h3_controlnet_start_percents_{prefix}']
|
| 76 |
+
cn_end_percents = ui_components[f'h3_controlnet_end_percents_{prefix}']
|
| 77 |
+
|
| 78 |
+
count_state = ui_components[f'h3_controlnet_count_state_{prefix}']
|
| 79 |
+
add_button = ui_components[f'add_h3_controlnet_button_{prefix}']
|
| 80 |
+
del_button = ui_components[f'delete_h3_controlnet_button_{prefix}']
|
| 81 |
+
|
| 82 |
+
def add_cn_row(c):
|
| 83 |
+
updates = {}
|
| 84 |
+
if c < MAX_CONTROLNETS:
|
| 85 |
+
c += 1
|
| 86 |
+
updates[cn_rows[c-1]] = gr.update(visible=True)
|
| 87 |
+
updates[count_state] = c
|
| 88 |
+
updates[add_button] = gr.update(visible=c < MAX_CONTROLNETS)
|
| 89 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 90 |
+
return updates
|
| 91 |
+
|
| 92 |
+
def del_cn_row(c):
|
| 93 |
+
updates = {}
|
| 94 |
+
if c > 1:
|
| 95 |
+
updates[cn_rows[c-1]] = gr.update(visible=False)
|
| 96 |
+
updates[cn_videos[c-1]] = None
|
| 97 |
+
updates[cn_strengths[c-1]] = 1.0
|
| 98 |
+
updates[cn_start_percents[c-1]] = 0.0
|
| 99 |
+
updates[cn_end_percents[c-1]] = 1.0
|
| 100 |
+
c -= 1
|
| 101 |
+
updates[count_state] = c
|
| 102 |
+
updates[add_button] = gr.update(visible=True)
|
| 103 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 104 |
+
return updates
|
| 105 |
+
|
| 106 |
+
add_outputs = [count_state, add_button, del_button] + cn_rows
|
| 107 |
+
del_outputs = [count_state, add_button, del_button] + cn_rows + cn_videos + cn_strengths + cn_start_percents + cn_end_percents
|
| 108 |
+
|
| 109 |
+
add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False, api_name=False)
|
| 110 |
+
del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False, api_name=False)
|
| 111 |
+
|
| 112 |
+
def on_cn_type_change(selected_type):
|
| 113 |
+
cn_full_config = load_h3_controlnet_config()
|
| 114 |
+
cn_config = cn_full_config.get("MiniMax-H3", [])
|
| 115 |
+
if not cn_config and cn_full_config:
|
| 116 |
+
cn_config = next(iter(cn_full_config.values()), [])
|
| 117 |
+
|
| 118 |
+
series_choices = []
|
| 119 |
+
if selected_type:
|
| 120 |
+
for model in cn_config:
|
| 121 |
+
if selected_type in model.get("Type", []):
|
| 122 |
+
s = model.get("Series", "Default")
|
| 123 |
+
if s not in series_choices:
|
| 124 |
+
series_choices.append(s)
|
| 125 |
+
default_series = series_choices[0] if series_choices else None
|
| 126 |
+
filepath = "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 127 |
+
if default_series:
|
| 128 |
+
for model in cn_config:
|
| 129 |
+
if model.get("Series") == default_series and selected_type in model.get("Type", []):
|
| 130 |
+
filepath = model.get("Filepath", "")
|
| 131 |
+
break
|
| 132 |
+
return gr.update(choices=series_choices, value=default_series), filepath
|
| 133 |
+
|
| 134 |
+
def on_cn_series_change(selected_series, selected_type):
|
| 135 |
+
cn_full_config = load_h3_controlnet_config()
|
| 136 |
+
cn_config = cn_full_config.get("MiniMax-H3", [])
|
| 137 |
+
if not cn_config and cn_full_config:
|
| 138 |
+
cn_config = next(iter(cn_full_config.values()), [])
|
| 139 |
+
|
| 140 |
+
filepath = "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 141 |
+
if selected_series and selected_type:
|
| 142 |
+
for model in cn_config:
|
| 143 |
+
if model.get("Series") == selected_series and selected_type in model.get("Type", []):
|
| 144 |
+
filepath = model.get("Filepath", "")
|
| 145 |
+
break
|
| 146 |
+
return filepath
|
| 147 |
+
|
| 148 |
+
for i in range(MAX_CONTROLNETS):
|
| 149 |
+
cn_types[i].change(
|
| 150 |
+
fn=on_cn_type_change,
|
| 151 |
+
inputs=[cn_types[i]],
|
| 152 |
+
outputs=[cn_series[i], cn_filepaths[i]],
|
| 153 |
+
show_progress=False,
|
| 154 |
+
api_name=False
|
| 155 |
+
)
|
| 156 |
+
cn_series[i].change(
|
| 157 |
+
fn=on_cn_series_change,
|
| 158 |
+
inputs=[cn_series[i], cn_types[i]],
|
| 159 |
+
outputs=[cn_filepaths[i]],
|
| 160 |
+
show_progress=False,
|
| 161 |
+
api_name=False
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def create_h3_guide_event_handlers(prefix, ui_components):
|
| 166 |
+
guide_rows = ui_components.get(f'h3_guide_rows_{prefix}')
|
| 167 |
+
if not guide_rows: return
|
| 168 |
+
images = ui_components[f'h3_guide_images_{prefix}']
|
| 169 |
+
videos = ui_components[f'h3_guide_videos_{prefix}']
|
| 170 |
+
audios = ui_components[f'h3_guide_audios_{prefix}']
|
| 171 |
+
times = ui_components[f'h3_guide_times_{prefix}']
|
| 172 |
+
frames = ui_components.get(f'h3_guide_frames_{prefix}', [])
|
| 173 |
+
|
| 174 |
+
count_state = ui_components[f'h3_guide_count_state_{prefix}']
|
| 175 |
+
add_button = ui_components[f'add_h3_guide_button_{prefix}']
|
| 176 |
+
del_button = ui_components[f'delete_h3_guide_button_{prefix}']
|
| 177 |
+
|
| 178 |
+
def add_guide_row(c):
|
| 179 |
+
updates = {}
|
| 180 |
+
if c < MAX_H3_GUIDES:
|
| 181 |
+
c += 1
|
| 182 |
+
updates[guide_rows[c-1]] = gr.update(visible=True)
|
| 183 |
+
updates[count_state] = c
|
| 184 |
+
updates[add_button] = gr.update(visible=c < MAX_H3_GUIDES)
|
| 185 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 186 |
+
return updates
|
| 187 |
+
|
| 188 |
+
def del_guide_row(c):
|
| 189 |
+
updates = {}
|
| 190 |
+
if c > 1:
|
| 191 |
+
updates[guide_rows[c-1]] = gr.update(visible=False)
|
| 192 |
+
updates[images[c-1]] = None
|
| 193 |
+
updates[videos[c-1]] = None
|
| 194 |
+
updates[audios[c-1]] = None
|
| 195 |
+
c -= 1
|
| 196 |
+
updates[count_state] = c
|
| 197 |
+
updates[add_button] = gr.update(visible=True)
|
| 198 |
+
updates[del_button] = gr.update(visible=c > 1)
|
| 199 |
+
return updates
|
| 200 |
+
|
| 201 |
+
add_outputs = [count_state, add_button, del_button] + guide_rows
|
| 202 |
+
del_outputs = [count_state, add_button, del_button] + guide_rows + images + videos + audios
|
| 203 |
+
|
| 204 |
+
add_button.click(fn=add_guide_row, inputs=[count_state], outputs=add_outputs, show_progress=False, api_name=False)
|
| 205 |
+
del_button.click(fn=del_guide_row, inputs=[count_state], outputs=del_outputs, show_progress=False, api_name=False)
|
| 206 |
+
|
| 207 |
+
if frames:
|
| 208 |
+
for i in range(min(MAX_H3_GUIDES, len(frames))):
|
| 209 |
+
def make_sync_handler():
|
| 210 |
+
def sync_time_to_frame(t):
|
| 211 |
+
if t is None:
|
| 212 |
+
return 0
|
| 213 |
+
return int(round(float(t) * 24))
|
| 214 |
+
return sync_time_to_frame
|
| 215 |
+
|
| 216 |
+
times[i].change(
|
| 217 |
+
fn=make_sync_handler(),
|
| 218 |
+
inputs=[times[i]],
|
| 219 |
+
outputs=[frames[i]],
|
| 220 |
+
show_progress=False,
|
| 221 |
+
api_name=False
|
| 222 |
+
)
|
ui/events/main.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from .chain_handlers import create_lora_event_handlers, create_h3_controlnet_event_handlers, create_h3_guide_event_handlers
|
| 3 |
+
|
| 4 |
+
def attach_event_handlers(ui_components, demo):
|
| 5 |
+
if 'task' in ui_components or 'run_button' in ui_components:
|
| 6 |
+
from ..h3_ui import create_event_handlers as create_h3_event_handlers
|
| 7 |
+
create_h3_event_handlers(ui_components, demo)
|
| 8 |
+
return
|
| 9 |
+
|
| 10 |
+
if 'h3_fl2va' in ui_components:
|
| 11 |
+
from ui.shared import h3_fl2va_ui
|
| 12 |
+
h3_fl2va_ui.create_event_handlers(ui_components['h3_fl2va'], demo)
|
| 13 |
+
create_lora_event_handlers("h3_fl2va", ui_components)
|
| 14 |
+
create_h3_controlnet_event_handlers("h3_fl2va", ui_components)
|
| 15 |
+
create_h3_guide_event_handlers("h3_fl2va", ui_components)
|
| 16 |
+
|
| 17 |
+
if 'h3_ref2va' in ui_components:
|
| 18 |
+
from ui.shared import h3_ref2va_ui
|
| 19 |
+
h3_ref2va_ui.create_event_handlers(ui_components['h3_ref2va'], demo)
|
| 20 |
+
create_lora_event_handlers("h3_ref2va", ui_components)
|
| 21 |
+
create_h3_controlnet_event_handlers("h3_ref2va", ui_components)
|
| 22 |
+
create_h3_guide_event_handlers("h3_ref2va", ui_components)
|
ui/h3_logic.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
from core.workflow_assembler import WorkflowAssembler
|
| 4 |
+
from utils.app_utils import (
|
| 5 |
+
handle_seed,
|
| 6 |
+
save_temp_image,
|
| 7 |
+
save_temp_video,
|
| 8 |
+
save_temp_audio,
|
| 9 |
+
get_filename_prefix,
|
| 10 |
+
process_lora_inputs,
|
| 11 |
+
process_h3_controlnet_inputs,
|
| 12 |
+
process_h3_guide_inputs,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
UI_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 16 |
+
PROJECT_ROOT = os.path.dirname(UI_DIR)
|
| 17 |
+
|
| 18 |
+
# Support recipe lookup from workflow_recipes/ or ui/shared/
|
| 19 |
+
def _get_recipe_path(recipe_filename: str) -> str:
|
| 20 |
+
possible_paths = [
|
| 21 |
+
os.path.join(PROJECT_ROOT, "workflow_recipes", recipe_filename),
|
| 22 |
+
os.path.join(UI_DIR, "shared", recipe_filename),
|
| 23 |
+
os.path.join(PROJECT_ROOT, "yaml", recipe_filename),
|
| 24 |
+
]
|
| 25 |
+
for p in possible_paths:
|
| 26 |
+
if os.path.exists(p):
|
| 27 |
+
return p
|
| 28 |
+
return os.path.join(PROJECT_ROOT, "workflow_recipes", recipe_filename)
|
| 29 |
+
|
| 30 |
+
RESOLUTION_PRESETS = {
|
| 31 |
+
"1080p": {
|
| 32 |
+
"16:9 (Landscape)": (1920, 1088),
|
| 33 |
+
"9:16 (Portrait)": (1088, 1920),
|
| 34 |
+
"1:1 (Square)": (1440, 1440),
|
| 35 |
+
"4:3 (Classic TV)": (1664, 1248),
|
| 36 |
+
"3:4 (Classic Portrait)": (1248, 1664),
|
| 37 |
+
"3:2 (Landscape)": (1760, 1184),
|
| 38 |
+
"2:3 (Portrait)": (1184, 1760),
|
| 39 |
+
},
|
| 40 |
+
"768p": {
|
| 41 |
+
"16:9 (Landscape)": (1344, 768),
|
| 42 |
+
"9:16 (Portrait)": (768, 1344),
|
| 43 |
+
"1:1 (Square)": (1024, 1024),
|
| 44 |
+
"4:3 (Classic TV)": (1152, 864),
|
| 45 |
+
"3:4 (Classic Portrait)": (864, 1152),
|
| 46 |
+
"3:2 (Landscape)": (1248, 832),
|
| 47 |
+
"2:3 (Portrait)": (832, 1248),
|
| 48 |
+
},
|
| 49 |
+
"544p": {
|
| 50 |
+
"16:9 (Landscape)": (960, 544),
|
| 51 |
+
"9:16 (Portrait)": (544, 960),
|
| 52 |
+
"1:1 (Square)": (736, 736),
|
| 53 |
+
"4:3 (Classic TV)": (832, 640),
|
| 54 |
+
"3:4 (Classic Portrait)": (640, 832),
|
| 55 |
+
"3:2 (Landscape)": (864, 576),
|
| 56 |
+
"2:3 (Portrait)": (576, 864),
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
ASPECT_RATIO_PRESETS = RESOLUTION_PRESETS["768p"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def calculate_h3_frame_length(duration_seconds: float) -> int:
|
| 64 |
+
"""
|
| 65 |
+
Converts duration (seconds) at 24fps to a valid frame length
|
| 66 |
+
snapped up to the model's 17-frame-per-block (17k+5) grid.
|
| 67 |
+
Grid sequence: 5, 22, 39, 56, 73, 90, 107, 124, 141...
|
| 68 |
+
"""
|
| 69 |
+
raw_frames = int(round(duration_seconds * 24))
|
| 70 |
+
if raw_frames <= 5:
|
| 71 |
+
return 5
|
| 72 |
+
return 5 + 17 * math.ceil((raw_frames - 5) / 17)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def process_inputs(ui_values: dict, seed_override=None, progress=None):
|
| 76 |
+
local_ui_values = ui_values.copy()
|
| 77 |
+
task = str(local_ui_values.get('task', 'T2VA')).upper()
|
| 78 |
+
|
| 79 |
+
width = int(local_ui_values.get('width') or 0)
|
| 80 |
+
height = int(local_ui_values.get('height') or 0)
|
| 81 |
+
|
| 82 |
+
if width <= 0 or height <= 0:
|
| 83 |
+
resolution = local_ui_values.get('resolution', '544p')
|
| 84 |
+
selected_ratio = local_ui_values.get('aspect_ratio', "16:9 (Landscape)")
|
| 85 |
+
width, height = RESOLUTION_PRESETS.get(resolution, {}).get(selected_ratio, (960, 544))
|
| 86 |
+
|
| 87 |
+
local_ui_values['width'] = width
|
| 88 |
+
local_ui_values['height'] = height
|
| 89 |
+
local_ui_values['steps'] = int(local_ui_values.get('steps') or 20)
|
| 90 |
+
local_ui_values['cfg_scale'] = float(local_ui_values.get('cfg_scale') or 5.0)
|
| 91 |
+
|
| 92 |
+
duration = float(local_ui_values.get('duration', 5.0))
|
| 93 |
+
local_ui_values['length'] = calculate_h3_frame_length(duration)
|
| 94 |
+
|
| 95 |
+
seed = seed_override if seed_override is not None else int(local_ui_values.get('seed', -1))
|
| 96 |
+
local_ui_values['seed'] = handle_seed(seed)
|
| 97 |
+
|
| 98 |
+
filename_prefix = get_filename_prefix()
|
| 99 |
+
local_ui_values['filename_prefix'] = f"video/{filename_prefix}"
|
| 100 |
+
|
| 101 |
+
# Extract LoRA inputs across prefixes or direct dictionary
|
| 102 |
+
loras = []
|
| 103 |
+
if 'loras' in ui_values and isinstance(ui_values['loras'], list):
|
| 104 |
+
loras = ui_values['loras']
|
| 105 |
+
else:
|
| 106 |
+
for prefix in ('h3', 'h3_lora', 'h3_fl2va', 'h3_ref2va', ''):
|
| 107 |
+
found = process_lora_inputs(ui_values, prefix, progress=progress)
|
| 108 |
+
if found:
|
| 109 |
+
loras = found
|
| 110 |
+
break
|
| 111 |
+
local_ui_values['loras'] = loras
|
| 112 |
+
|
| 113 |
+
# Extract ControlNet inputs across prefixes or direct dictionary
|
| 114 |
+
cns = []
|
| 115 |
+
if 'h3_controlnets' in ui_values and isinstance(ui_values['h3_controlnets'], list):
|
| 116 |
+
cns = ui_values['h3_controlnets']
|
| 117 |
+
else:
|
| 118 |
+
for prefix in ('h3', 'h3_controlnet', 'h3_fl2va', 'h3_ref2va', ''):
|
| 119 |
+
found = process_h3_controlnet_inputs(ui_values, prefix, progress=progress)
|
| 120 |
+
if found:
|
| 121 |
+
cns = found
|
| 122 |
+
break
|
| 123 |
+
local_ui_values['h3_controlnets'] = cns
|
| 124 |
+
|
| 125 |
+
# Extract Guide inputs across prefixes or direct dictionary
|
| 126 |
+
guides = []
|
| 127 |
+
if 'h3_guides' in ui_values and isinstance(ui_values['h3_guides'], list):
|
| 128 |
+
guides = ui_values['h3_guides']
|
| 129 |
+
else:
|
| 130 |
+
for prefix in ('h3', 'h3_guide', 'h3_fl2va', 'h3_ref2va', ''):
|
| 131 |
+
found = process_h3_guide_inputs(ui_values, prefix, progress=progress)
|
| 132 |
+
if found:
|
| 133 |
+
guides = found
|
| 134 |
+
break
|
| 135 |
+
local_ui_values['h3_guides'] = guides
|
| 136 |
+
|
| 137 |
+
if task == "REF2VA":
|
| 138 |
+
recipe_path = _get_recipe_path("h3_ref2va_recipe.yaml")
|
| 139 |
+
|
| 140 |
+
ref_images_input = local_ui_values.get('ref_images', [])
|
| 141 |
+
saved_ref_images = []
|
| 142 |
+
if isinstance(ref_images_input, list):
|
| 143 |
+
for img in ref_images_input:
|
| 144 |
+
if img is not None:
|
| 145 |
+
saved_ref_images.append(save_temp_image(img))
|
| 146 |
+
local_ui_values['ref_images'] = saved_ref_images
|
| 147 |
+
|
| 148 |
+
ref_videos_input = local_ui_values.get('ref_videos', [])
|
| 149 |
+
saved_ref_videos = []
|
| 150 |
+
if isinstance(ref_videos_input, list):
|
| 151 |
+
for video_path in ref_videos_input:
|
| 152 |
+
if video_path:
|
| 153 |
+
saved_vid = save_temp_video(video_path)
|
| 154 |
+
if saved_vid:
|
| 155 |
+
saved_ref_videos.append(saved_vid)
|
| 156 |
+
local_ui_values['ref_videos'] = saved_ref_videos
|
| 157 |
+
|
| 158 |
+
ref_audios_input = local_ui_values.get('ref_audios', [])
|
| 159 |
+
saved_ref_audios = []
|
| 160 |
+
if isinstance(ref_audios_input, list):
|
| 161 |
+
for audio_path in ref_audios_input:
|
| 162 |
+
if audio_path:
|
| 163 |
+
saved_aud = save_temp_audio(audio_path)
|
| 164 |
+
if saved_aud:
|
| 165 |
+
saved_ref_audios.append(saved_aud)
|
| 166 |
+
local_ui_values['ref_audios'] = saved_ref_audios
|
| 167 |
+
|
| 168 |
+
assembler = WorkflowAssembler(recipe_path)
|
| 169 |
+
final_workflow = assembler.assemble(local_ui_values)
|
| 170 |
+
else:
|
| 171 |
+
recipe_path = _get_recipe_path("h3_fl2va_recipe.yaml")
|
| 172 |
+
|
| 173 |
+
# T2VA does not load frames; I2VA loads first frame; FLF2VA loads first & last frame
|
| 174 |
+
allow_first_frame = task in ("I2VA", "FLF2VA", "FL2VA")
|
| 175 |
+
allow_last_frame = task in ("FLF2VA", "FL2VA")
|
| 176 |
+
|
| 177 |
+
first_frame_img = local_ui_values.get('first_frame') if allow_first_frame else None
|
| 178 |
+
if first_frame_img is not None:
|
| 179 |
+
local_ui_values['first_frame_loader_class'] = "LoadImage"
|
| 180 |
+
local_ui_values['first_frame_scale_class'] = "ImageScale"
|
| 181 |
+
local_ui_values['first_frame_image'] = save_temp_image(first_frame_img)
|
| 182 |
+
else:
|
| 183 |
+
local_ui_values['first_frame_loader_class'] = None
|
| 184 |
+
local_ui_values['first_frame_scale_class'] = None
|
| 185 |
+
|
| 186 |
+
last_frame_img = local_ui_values.get('last_frame') if allow_last_frame else None
|
| 187 |
+
if last_frame_img is not None:
|
| 188 |
+
local_ui_values['last_frame_loader_class'] = "LoadImage"
|
| 189 |
+
local_ui_values['last_frame_scale_class'] = "ImageScale"
|
| 190 |
+
local_ui_values['last_frame_image'] = save_temp_image(last_frame_img)
|
| 191 |
+
else:
|
| 192 |
+
local_ui_values['last_frame_loader_class'] = None
|
| 193 |
+
local_ui_values['last_frame_scale_class'] = None
|
| 194 |
+
|
| 195 |
+
assembler = WorkflowAssembler(recipe_path)
|
| 196 |
+
final_workflow = assembler.assemble(local_ui_values)
|
| 197 |
+
|
| 198 |
+
return final_workflow, None
|
ui/h3_ui.py
ADDED
|
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from .h3_logic import process_inputs, RESOLUTION_PRESETS
|
| 3 |
+
from core.generation_logic import generate_h3_video_wrapper
|
| 4 |
+
from .shared.ui_components import (
|
| 5 |
+
create_lora_settings_ui,
|
| 6 |
+
create_h3_controlnet_ui,
|
| 7 |
+
create_h3_guide_ui
|
| 8 |
+
)
|
| 9 |
+
from .events.chain_handlers import (
|
| 10 |
+
create_lora_event_handlers,
|
| 11 |
+
create_h3_controlnet_event_handlers,
|
| 12 |
+
create_h3_guide_event_handlers
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
MAX_REF_IMAGES = 9
|
| 16 |
+
MAX_REF_VIDEOS = 3
|
| 17 |
+
MAX_REF_AUDIOS = 3
|
| 18 |
+
TASK_CHOICES = ["T2VA", "I2VA", "FLF2VA", "REF2VA"]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def create_ui():
|
| 22 |
+
prefix = "h3"
|
| 23 |
+
components = {}
|
| 24 |
+
|
| 25 |
+
with gr.Column():
|
| 26 |
+
gr.Markdown("## MiniMax H3 Video Generation")
|
| 27 |
+
gr.Markdown(
|
| 28 |
+
"💡 **Tip:** Under the default ZeroGPU Duration of 120s, tasks with 544p resolution, 20 steps, and 5s duration complete successfully."
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
components['task'] = gr.Radio(
|
| 32 |
+
choices=TASK_CHOICES,
|
| 33 |
+
value="T2VA",
|
| 34 |
+
label="Task",
|
| 35 |
+
interactive=True
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
with gr.Row(visible=False) as frame_row:
|
| 39 |
+
components['first_frame'] = gr.Image(type="pil", label="First Frame", height=220, visible=False)
|
| 40 |
+
components['last_frame'] = gr.Image(type="pil", label="Last Frame", height=220, visible=False)
|
| 41 |
+
components['frame_row'] = frame_row
|
| 42 |
+
|
| 43 |
+
components['prompt'] = gr.Textbox(label="Prompt", lines=5)
|
| 44 |
+
|
| 45 |
+
with gr.Row():
|
| 46 |
+
with gr.Column(scale=1):
|
| 47 |
+
with gr.Row():
|
| 48 |
+
components['resolution'] = gr.Radio(
|
| 49 |
+
label="Resolution",
|
| 50 |
+
choices=["544p", "768p", "1080p"],
|
| 51 |
+
value="544p",
|
| 52 |
+
interactive=True
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
with gr.Row():
|
| 56 |
+
components['aspect_ratio'] = gr.Dropdown(
|
| 57 |
+
label="Aspect Ratio",
|
| 58 |
+
choices=list(RESOLUTION_PRESETS["544p"].keys()),
|
| 59 |
+
value="16:9 (Landscape)",
|
| 60 |
+
interactive=True
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
with gr.Row():
|
| 64 |
+
components['width'] = gr.Number(label="Width", value=960, precision=0)
|
| 65 |
+
components['height'] = gr.Number(label="Height", value=544, precision=0)
|
| 66 |
+
|
| 67 |
+
with gr.Row(visible=False):
|
| 68 |
+
components['sampler'] = gr.Dropdown(label="Sampler", choices=["res_multistep", "euler"], value="res_multistep", visible=False)
|
| 69 |
+
components['scheduler'] = gr.Dropdown(label="Scheduler", choices=["simple", "normal"], value="simple", visible=False)
|
| 70 |
+
|
| 71 |
+
with gr.Row():
|
| 72 |
+
components['steps'] = gr.Slider(label="Steps", minimum=1, maximum=50, step=1, value=20, interactive=True)
|
| 73 |
+
components['duration'] = gr.Slider(label="Duration (s)", minimum=0.2, maximum=15.0, step=0.1, value=5.0, interactive=True)
|
| 74 |
+
|
| 75 |
+
with gr.Row():
|
| 76 |
+
components['cfg_scale'] = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, step=0.1, value=5.0, visible=False)
|
| 77 |
+
components['seed'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)
|
| 78 |
+
components['zero_gpu_duration'] = gr.Number(
|
| 79 |
+
label="ZeroGPU Duration (s)",
|
| 80 |
+
value=120,
|
| 81 |
+
placeholder="Default: 120s, Max: 120s"
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
with gr.Column(scale=1):
|
| 85 |
+
components['output_video'] = gr.Video(label="Result", interactive=False, height=492)
|
| 86 |
+
|
| 87 |
+
# Chain Modules (LoRA)
|
| 88 |
+
components.update(create_lora_settings_ui(prefix))
|
| 89 |
+
|
| 90 |
+
# Multi-modal Reference Panels (REF2VA)
|
| 91 |
+
with gr.Accordion("Reference Image Settings", open=False, visible=False) as ref_img_accordion:
|
| 92 |
+
ref_image_groups = []
|
| 93 |
+
ref_image_inputs = []
|
| 94 |
+
with gr.Row():
|
| 95 |
+
for i in range(MAX_REF_IMAGES):
|
| 96 |
+
with gr.Column(visible=(i < 1), min_width=160) as img_col:
|
| 97 |
+
img_comp = gr.Image(type="pil", label=f"Ref Image {i+1}", sources=["upload"], height=160)
|
| 98 |
+
ref_image_groups.append(img_col)
|
| 99 |
+
ref_image_inputs.append(img_comp)
|
| 100 |
+
components['ref_image_groups'] = ref_image_groups
|
| 101 |
+
components['ref_image_inputs'] = ref_image_inputs
|
| 102 |
+
components['ref_images'] = ref_image_inputs
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
components['add_ref_button'] = gr.Button("✚ Add Reference Image")
|
| 106 |
+
components['delete_ref_button'] = gr.Button("➖ Delete Reference Image", visible=False)
|
| 107 |
+
components['ref_count_state'] = gr.State(1)
|
| 108 |
+
components['ref_img_accordion'] = ref_img_accordion
|
| 109 |
+
|
| 110 |
+
with gr.Accordion("Reference Video Settings", open=False, visible=False) as ref_vid_accordion:
|
| 111 |
+
ref_video_groups = []
|
| 112 |
+
ref_video_inputs = []
|
| 113 |
+
with gr.Row():
|
| 114 |
+
for i in range(MAX_REF_VIDEOS):
|
| 115 |
+
with gr.Column(visible=(i < 1), min_width=200) as vid_col:
|
| 116 |
+
vid_comp = gr.Video(label=f"Ref Video {i+1}", sources=["upload"], height=200)
|
| 117 |
+
ref_video_groups.append(vid_col)
|
| 118 |
+
ref_video_inputs.append(vid_comp)
|
| 119 |
+
components['ref_video_groups'] = ref_video_groups
|
| 120 |
+
components['ref_video_inputs'] = ref_video_inputs
|
| 121 |
+
components['ref_videos'] = ref_video_inputs
|
| 122 |
+
|
| 123 |
+
with gr.Row():
|
| 124 |
+
components['add_ref_video_button'] = gr.Button("✚ Add Reference Video")
|
| 125 |
+
components['delete_ref_video_button'] = gr.Button("➖ Delete Reference Video", visible=False)
|
| 126 |
+
components['ref_video_count_state'] = gr.State(1)
|
| 127 |
+
components['ref_vid_accordion'] = ref_vid_accordion
|
| 128 |
+
|
| 129 |
+
with gr.Accordion("Reference Audio Settings", open=False, visible=False) as ref_aud_accordion:
|
| 130 |
+
ref_audio_groups = []
|
| 131 |
+
ref_audio_inputs = []
|
| 132 |
+
with gr.Row():
|
| 133 |
+
for i in range(MAX_REF_AUDIOS):
|
| 134 |
+
with gr.Column(visible=(i < 1), min_width=200) as aud_col:
|
| 135 |
+
aud_comp = gr.Audio(label=f"Ref Audio {i+1}", sources=["upload"], type="filepath")
|
| 136 |
+
ref_audio_groups.append(aud_col)
|
| 137 |
+
ref_audio_inputs.append(aud_comp)
|
| 138 |
+
components['ref_audio_groups'] = ref_audio_groups
|
| 139 |
+
components['ref_audio_inputs'] = ref_audio_inputs
|
| 140 |
+
components['ref_audios'] = ref_audio_inputs
|
| 141 |
+
|
| 142 |
+
with gr.Row():
|
| 143 |
+
components['add_ref_audio_button'] = gr.Button("✚ Add Reference Audio")
|
| 144 |
+
components['delete_ref_audio_button'] = gr.Button("➖ Delete Reference Audio", visible=False)
|
| 145 |
+
components['ref_audio_count_state'] = gr.State(1)
|
| 146 |
+
components['ref_aud_accordion'] = ref_aud_accordion
|
| 147 |
+
|
| 148 |
+
# ControlNet Settings (Placed below Reference Audio Settings)
|
| 149 |
+
components.update(create_h3_controlnet_ui(prefix))
|
| 150 |
+
|
| 151 |
+
# Timeline Keyframe Guide Panel (Shared across all tasks)
|
| 152 |
+
components.update(create_h3_guide_ui(prefix))
|
| 153 |
+
|
| 154 |
+
components['run_button'] = gr.Button("🎬 Generate H3 Video", variant="primary")
|
| 155 |
+
|
| 156 |
+
return components
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def create_event_handlers(components: dict, demo: gr.Blocks):
|
| 160 |
+
prefix = "h3"
|
| 161 |
+
|
| 162 |
+
create_lora_event_handlers(prefix, components)
|
| 163 |
+
create_h3_controlnet_event_handlers(prefix, components)
|
| 164 |
+
create_h3_guide_event_handlers(prefix, components)
|
| 165 |
+
|
| 166 |
+
def on_task_change(task_val):
|
| 167 |
+
is_i2va = (task_val == "I2VA")
|
| 168 |
+
is_flf2va = (task_val in ("FLF2VA", "FL2VA"))
|
| 169 |
+
is_ref2va = (task_val == "REF2VA")
|
| 170 |
+
show_frame_row = is_i2va or is_flf2va
|
| 171 |
+
|
| 172 |
+
return (
|
| 173 |
+
gr.update(visible=show_frame_row), # frame_row
|
| 174 |
+
gr.update(visible=show_frame_row), # first_frame
|
| 175 |
+
gr.update(visible=is_flf2va), # last_frame
|
| 176 |
+
gr.update(visible=is_ref2va), # ref_img_accordion
|
| 177 |
+
gr.update(visible=is_ref2va), # ref_vid_accordion
|
| 178 |
+
gr.update(visible=is_ref2va) # ref_aud_accordion
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
components['task'].change(
|
| 182 |
+
fn=on_task_change,
|
| 183 |
+
inputs=[components['task']],
|
| 184 |
+
outputs=[
|
| 185 |
+
components['frame_row'],
|
| 186 |
+
components['first_frame'],
|
| 187 |
+
components['last_frame'],
|
| 188 |
+
components['ref_img_accordion'],
|
| 189 |
+
components['ref_vid_accordion'],
|
| 190 |
+
components['ref_aud_accordion']
|
| 191 |
+
],
|
| 192 |
+
api_name=False
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
def update_dimensions(resolution, aspect_ratio):
|
| 196 |
+
w, h = RESOLUTION_PRESETS.get(resolution, {}).get(aspect_ratio, (960, 544))
|
| 197 |
+
return w, h
|
| 198 |
+
|
| 199 |
+
components['resolution'].change(
|
| 200 |
+
fn=update_dimensions,
|
| 201 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 202 |
+
outputs=[components['width'], components['height']],
|
| 203 |
+
api_name=False
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
components['aspect_ratio'].change(
|
| 207 |
+
fn=update_dimensions,
|
| 208 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 209 |
+
outputs=[components['width'], components['height']],
|
| 210 |
+
api_name=False
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Reference Image events
|
| 214 |
+
ref_count_state = components['ref_count_state']
|
| 215 |
+
add_ref_btn = components['add_ref_button']
|
| 216 |
+
del_ref_btn = components['delete_ref_button']
|
| 217 |
+
ref_image_groups = components['ref_image_groups']
|
| 218 |
+
ref_image_inputs = components['ref_image_inputs']
|
| 219 |
+
|
| 220 |
+
def add_ref_row(count):
|
| 221 |
+
count += 1
|
| 222 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_IMAGES))
|
| 223 |
+
return (count, gr.update(visible=count < MAX_REF_IMAGES), gr.update(visible=count > 1)) + visibility_updates
|
| 224 |
+
|
| 225 |
+
def delete_ref_row(count):
|
| 226 |
+
count -= 1
|
| 227 |
+
image_clear_updates = [gr.update()] * MAX_REF_IMAGES
|
| 228 |
+
if count >= 0:
|
| 229 |
+
image_clear_updates[count] = None
|
| 230 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_IMAGES))
|
| 231 |
+
return (count, gr.update(visible=count < MAX_REF_IMAGES), gr.update(visible=count > 1)) + visibility_updates + tuple(image_clear_updates)
|
| 232 |
+
|
| 233 |
+
add_ref_outputs = [ref_count_state, add_ref_btn, del_ref_btn] + ref_image_groups
|
| 234 |
+
del_ref_outputs = [ref_count_state, add_ref_btn, del_ref_btn] + ref_image_groups + ref_image_inputs
|
| 235 |
+
|
| 236 |
+
add_ref_btn.click(
|
| 237 |
+
fn=add_ref_row,
|
| 238 |
+
inputs=[ref_count_state],
|
| 239 |
+
outputs=add_ref_outputs,
|
| 240 |
+
show_progress=False,
|
| 241 |
+
api_name=False
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
del_ref_btn.click(
|
| 245 |
+
fn=delete_ref_row,
|
| 246 |
+
inputs=[ref_count_state],
|
| 247 |
+
outputs=del_ref_outputs,
|
| 248 |
+
show_progress=False,
|
| 249 |
+
api_name=False
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
# Reference Video events
|
| 253 |
+
ref_video_count_state = components['ref_video_count_state']
|
| 254 |
+
add_ref_vid_btn = components['add_ref_video_button']
|
| 255 |
+
del_ref_vid_btn = components['delete_ref_video_button']
|
| 256 |
+
ref_video_groups = components['ref_video_groups']
|
| 257 |
+
ref_video_inputs = components['ref_video_inputs']
|
| 258 |
+
|
| 259 |
+
def add_ref_video_row(count):
|
| 260 |
+
count += 1
|
| 261 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_VIDEOS))
|
| 262 |
+
return (count, gr.update(visible=count < MAX_REF_VIDEOS), gr.update(visible=count > 1)) + visibility_updates
|
| 263 |
+
|
| 264 |
+
def delete_ref_video_row(count):
|
| 265 |
+
count -= 1
|
| 266 |
+
video_clear_updates = [gr.update()] * MAX_REF_VIDEOS
|
| 267 |
+
if count >= 0:
|
| 268 |
+
video_clear_updates[count] = None
|
| 269 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_VIDEOS))
|
| 270 |
+
return (count, gr.update(visible=count < MAX_REF_VIDEOS), gr.update(visible=count > 1)) + visibility_updates + tuple(video_clear_updates)
|
| 271 |
+
|
| 272 |
+
add_ref_vid_outputs = [ref_video_count_state, add_ref_vid_btn, del_ref_vid_btn] + ref_video_groups
|
| 273 |
+
del_ref_vid_outputs = [ref_video_count_state, add_ref_vid_btn, del_ref_vid_btn] + ref_video_groups + ref_video_inputs
|
| 274 |
+
|
| 275 |
+
add_ref_vid_btn.click(
|
| 276 |
+
fn=add_ref_video_row,
|
| 277 |
+
inputs=[ref_video_count_state],
|
| 278 |
+
outputs=add_ref_vid_outputs,
|
| 279 |
+
show_progress=False,
|
| 280 |
+
api_name=False
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
del_ref_vid_btn.click(
|
| 284 |
+
fn=delete_ref_video_row,
|
| 285 |
+
inputs=[ref_video_count_state],
|
| 286 |
+
outputs=del_ref_vid_outputs,
|
| 287 |
+
show_progress=False,
|
| 288 |
+
api_name=False
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
# Reference Audio events
|
| 292 |
+
ref_audio_count_state = components['ref_audio_count_state']
|
| 293 |
+
add_ref_aud_btn = components['add_ref_audio_button']
|
| 294 |
+
del_ref_aud_btn = components['delete_ref_audio_button']
|
| 295 |
+
ref_audio_groups = components['ref_audio_groups']
|
| 296 |
+
ref_audio_inputs = components['ref_audio_inputs']
|
| 297 |
+
|
| 298 |
+
def add_ref_audio_row(count):
|
| 299 |
+
count += 1
|
| 300 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_AUDIOS))
|
| 301 |
+
return (count, gr.update(visible=count < MAX_REF_AUDIOS), gr.update(visible=count > 1)) + visibility_updates
|
| 302 |
+
|
| 303 |
+
def delete_ref_audio_row(count):
|
| 304 |
+
count -= 1
|
| 305 |
+
audio_clear_updates = [gr.update()] * MAX_REF_AUDIOS
|
| 306 |
+
if count >= 0:
|
| 307 |
+
audio_clear_updates[count] = None
|
| 308 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_AUDIOS))
|
| 309 |
+
return (count, gr.update(visible=count < MAX_REF_AUDIOS), gr.update(visible=count > 1)) + visibility_updates + tuple(audio_clear_updates)
|
| 310 |
+
|
| 311 |
+
add_ref_aud_outputs = [ref_audio_count_state, add_ref_aud_btn, del_ref_aud_btn] + ref_audio_groups
|
| 312 |
+
del_ref_aud_outputs = [ref_audio_count_state, add_ref_aud_btn, del_ref_aud_btn] + ref_audio_groups + ref_audio_inputs
|
| 313 |
+
|
| 314 |
+
add_ref_aud_btn.click(
|
| 315 |
+
fn=add_ref_audio_row,
|
| 316 |
+
inputs=[ref_audio_count_state],
|
| 317 |
+
outputs=add_ref_aud_outputs,
|
| 318 |
+
show_progress=False,
|
| 319 |
+
api_name=False
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
del_ref_aud_btn.click(
|
| 323 |
+
fn=delete_ref_audio_row,
|
| 324 |
+
inputs=[ref_audio_count_state],
|
| 325 |
+
outputs=del_ref_aud_outputs,
|
| 326 |
+
show_progress=False,
|
| 327 |
+
api_name=False
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
# Collect LoRA, ControlNet, and Guide components
|
| 331 |
+
lora_sources = components.get(f'lora_sources_{prefix}', [])
|
| 332 |
+
lora_ids = components.get(f'lora_ids_{prefix}', [])
|
| 333 |
+
lora_scales = components.get(f'lora_scales_{prefix}', [])
|
| 334 |
+
|
| 335 |
+
cn_videos = components.get(f'h3_controlnet_videos_{prefix}', [])
|
| 336 |
+
cn_types = components.get(f'h3_controlnet_types_{prefix}', [])
|
| 337 |
+
cn_series = components.get(f'h3_controlnet_series_{prefix}', [])
|
| 338 |
+
cn_strengths = components.get(f'h3_controlnet_strengths_{prefix}', [])
|
| 339 |
+
cn_start_percents = components.get(f'h3_controlnet_start_percents_{prefix}', [])
|
| 340 |
+
cn_end_percents = components.get(f'h3_controlnet_end_percents_{prefix}', [])
|
| 341 |
+
cn_filepaths = components.get(f'h3_controlnet_filepaths_{prefix}', [])
|
| 342 |
+
|
| 343 |
+
guide_images = components.get(f'h3_guide_images_{prefix}', [])
|
| 344 |
+
guide_videos = components.get(f'h3_guide_videos_{prefix}', [])
|
| 345 |
+
guide_audios = components.get(f'h3_guide_audios_{prefix}', [])
|
| 346 |
+
guide_times = components.get(f'h3_guide_times_{prefix}', [])
|
| 347 |
+
guide_frames = components.get(f'h3_guide_frames_{prefix}', [])
|
| 348 |
+
|
| 349 |
+
inputs_list = [
|
| 350 |
+
components['task'],
|
| 351 |
+
components['first_frame'],
|
| 352 |
+
components['last_frame'],
|
| 353 |
+
components['prompt'],
|
| 354 |
+
components['resolution'],
|
| 355 |
+
components['aspect_ratio'],
|
| 356 |
+
components['width'],
|
| 357 |
+
components['height'],
|
| 358 |
+
components['duration'],
|
| 359 |
+
components['sampler'],
|
| 360 |
+
components['scheduler'],
|
| 361 |
+
components['steps'],
|
| 362 |
+
components['cfg_scale'],
|
| 363 |
+
components['seed'],
|
| 364 |
+
components['zero_gpu_duration']
|
| 365 |
+
] + ref_image_inputs + ref_video_inputs + ref_audio_inputs + lora_sources + lora_ids + lora_scales + cn_videos + cn_types + cn_series + cn_strengths + cn_start_percents + cn_end_percents + cn_filepaths + guide_images + guide_videos + guide_audios + guide_times + guide_frames
|
| 366 |
+
|
| 367 |
+
def on_run_click(*args, progress=gr.Progress(track_tqdm=True)):
|
| 368 |
+
task, first_frame, last_frame, prompt, resolution, aspect_ratio, width, height, duration, sampler, scheduler, steps, cfg_scale, seed, zero_gpu_duration = args[:15]
|
| 369 |
+
idx = 15
|
| 370 |
+
imgs = list(args[idx : idx + len(ref_image_inputs)])
|
| 371 |
+
idx += len(ref_image_inputs)
|
| 372 |
+
vids = list(args[idx : idx + len(ref_video_inputs)])
|
| 373 |
+
idx += len(ref_video_inputs)
|
| 374 |
+
auds = list(args[idx : idx + len(ref_audio_inputs)])
|
| 375 |
+
idx += len(ref_audio_inputs)
|
| 376 |
+
|
| 377 |
+
num_loras = len(lora_sources)
|
| 378 |
+
l_sources = args[idx : idx + num_loras]
|
| 379 |
+
l_ids = args[idx + num_loras : idx + 2*num_loras]
|
| 380 |
+
l_scales = args[idx + 2*num_loras : idx + 3*num_loras]
|
| 381 |
+
idx += 3 * num_loras
|
| 382 |
+
|
| 383 |
+
num_cns = len(cn_videos)
|
| 384 |
+
c_vids = args[idx : idx + num_cns]
|
| 385 |
+
c_types = args[idx + num_cns : idx + 2*num_cns]
|
| 386 |
+
c_series = args[idx + 2*num_cns : idx + 3*num_cns]
|
| 387 |
+
c_strengths = args[idx + 3*num_cns : idx + 4*num_cns]
|
| 388 |
+
c_starts = args[idx + 4*num_cns : idx + 5*num_cns]
|
| 389 |
+
c_ends = args[idx + 5*num_cns : idx + 6*num_cns]
|
| 390 |
+
c_fps = args[idx + 6*num_cns : idx + 7*num_cns]
|
| 391 |
+
idx += 7 * num_cns
|
| 392 |
+
|
| 393 |
+
num_guides = len(guide_images)
|
| 394 |
+
g_imgs = args[idx : idx + num_guides]
|
| 395 |
+
g_vids = args[idx + num_guides : idx + 2*num_guides]
|
| 396 |
+
g_auds = args[idx + 2*num_guides : idx + 3*num_guides]
|
| 397 |
+
g_times = args[idx + 3*num_guides : idx + 4*num_guides]
|
| 398 |
+
g_frames = args[idx + 4*num_guides : idx + 5*num_guides] if guide_frames else []
|
| 399 |
+
|
| 400 |
+
ui_values = {
|
| 401 |
+
'task': task,
|
| 402 |
+
'first_frame': first_frame,
|
| 403 |
+
'last_frame': last_frame,
|
| 404 |
+
'prompt': prompt,
|
| 405 |
+
'resolution': resolution,
|
| 406 |
+
'aspect_ratio': aspect_ratio,
|
| 407 |
+
'width': width,
|
| 408 |
+
'height': height,
|
| 409 |
+
'duration': duration,
|
| 410 |
+
'sampler_name': sampler,
|
| 411 |
+
'scheduler': scheduler,
|
| 412 |
+
'steps': steps,
|
| 413 |
+
'cfg_scale': cfg_scale,
|
| 414 |
+
'seed': seed,
|
| 415 |
+
'zero_gpu_duration': zero_gpu_duration,
|
| 416 |
+
'batch_count': 1,
|
| 417 |
+
'ref_images': imgs,
|
| 418 |
+
'ref_videos': vids,
|
| 419 |
+
'ref_audios': auds,
|
| 420 |
+
f'lora_sources_{prefix}': list(l_sources),
|
| 421 |
+
f'lora_ids_{prefix}': list(l_ids),
|
| 422 |
+
f'lora_scales_{prefix}': list(l_scales),
|
| 423 |
+
f'h3_controlnet_videos_{prefix}': list(c_vids),
|
| 424 |
+
f'h3_controlnet_types_{prefix}': list(c_types),
|
| 425 |
+
f'h3_controlnet_series_{prefix}': list(c_series),
|
| 426 |
+
f'h3_controlnet_strengths_{prefix}': list(c_strengths),
|
| 427 |
+
f'h3_controlnet_start_percents_{prefix}': list(c_starts),
|
| 428 |
+
f'h3_controlnet_end_percents_{prefix}': list(c_ends),
|
| 429 |
+
f'h3_controlnet_filepaths_{prefix}': list(c_fps),
|
| 430 |
+
f'h3_guide_images_{prefix}': list(g_imgs),
|
| 431 |
+
f'h3_guide_videos_{prefix}': list(g_vids),
|
| 432 |
+
f'h3_guide_audios_{prefix}': list(g_auds),
|
| 433 |
+
f'h3_guide_times_{prefix}': list(g_times),
|
| 434 |
+
f'h3_guide_frames_{prefix}': list(g_frames),
|
| 435 |
+
}
|
| 436 |
+
return generate_h3_video_wrapper(process_inputs, ui_values, progress=progress)
|
| 437 |
+
|
| 438 |
+
components['run_button'].click(
|
| 439 |
+
fn=on_run_click,
|
| 440 |
+
inputs=inputs_list,
|
| 441 |
+
outputs=[components['output_video']],
|
| 442 |
+
api_name=False
|
| 443 |
+
)
|
ui/layout.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from core.settings import *
|
| 4 |
+
|
| 5 |
+
from .h3_ui import create_ui as create_h3_ui
|
| 6 |
+
|
| 7 |
+
MAX_DYNAMIC_CONTROLS = 10
|
| 8 |
+
|
| 9 |
+
def build_ui(event_handler_function):
|
| 10 |
+
ui_components = {}
|
| 11 |
+
|
| 12 |
+
with gr.Blocks() as demo:
|
| 13 |
+
gr.Markdown("# MiniMax-H3")
|
| 14 |
+
gr.Markdown(
|
| 15 |
+
"This demo is a trimmed [MiniMax-H3](https://huggingface.co/spaces/RioShiina/MiniMax-H3) module within the VideoGen module of the [Comfy web UI](https://github.com/RioShiina47/comfy-webui). Supports [High-Level MCP](https://rioshiina-minimax-h3.hf.space/gradio_api/mcp/)."
|
| 16 |
+
)
|
| 17 |
+
ui_components.update(create_h3_ui())
|
| 18 |
+
|
| 19 |
+
gr.Markdown("<div style='text-align: left; margin-top: 20px;'>Made by RioShiina with ❤️<br><a href='https://github.com/RioShiina47' target='_blank'>GitHub</a> | <a href='https://huggingface.co/RioShiina' target='_blank'>Hugging Face</a> | <a href='https://civitai.com/user/RioShiina' target='_blank'>Civitai</a></div>")
|
| 20 |
+
|
| 21 |
+
event_handler_function(ui_components, demo)
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
import mcp_tools as mcp
|
| 25 |
+
if hasattr(mcp, "register_high_level_mcp_apis"):
|
| 26 |
+
mcp.register_high_level_mcp_apis(demo)
|
| 27 |
+
mcp.cleanup_dependencies_api_names(demo)
|
| 28 |
+
elif hasattr(mcp, 'MCP_FUNCTIONS') and isinstance(mcp.MCP_FUNCTIONS, list):
|
| 29 |
+
for func in mcp.MCP_FUNCTIONS:
|
| 30 |
+
gr.api(func)
|
| 31 |
+
print(f"✅ Registered MCP API endpoint: '{func.__name__}'")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"⚠️ Warning registering MCP functions: {e}")
|
| 34 |
+
|
| 35 |
+
# Disable API exposure for all atomic UI event handlers
|
| 36 |
+
high_level_names = getattr(mcp, "HIGH_LEVEL_MCP_API_NAMES", set())
|
| 37 |
+
for fn in demo.fns.values():
|
| 38 |
+
if getattr(fn, "api_name", None) not in high_level_names:
|
| 39 |
+
fn.show_api = False
|
| 40 |
+
fn.api_name = False
|
| 41 |
+
|
| 42 |
+
return demo
|
ui/shared/h3_fl2va_logic.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from core.workflow_assembler import WorkflowAssembler
|
| 5 |
+
from utils.app_utils import (
|
| 6 |
+
handle_seed,
|
| 7 |
+
save_temp_image,
|
| 8 |
+
get_filename_prefix,
|
| 9 |
+
process_lora_inputs,
|
| 10 |
+
process_h3_controlnet_inputs,
|
| 11 |
+
process_h3_guide_inputs
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
WORKFLOW_RECIPE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "h3_fl2va_recipe.yaml")
|
| 15 |
+
|
| 16 |
+
RESOLUTION_PRESETS = {
|
| 17 |
+
"1080p": {
|
| 18 |
+
"16:9 (Landscape)": (1920, 1088),
|
| 19 |
+
"9:16 (Portrait)": (1088, 1920),
|
| 20 |
+
"1:1 (Square)": (1440, 1440),
|
| 21 |
+
"4:3 (Classic TV)": (1664, 1248),
|
| 22 |
+
"3:4 (Classic Portrait)": (1248, 1664),
|
| 23 |
+
"3:2 (Landscape)": (1760, 1184),
|
| 24 |
+
"2:3 (Portrait)": (1184, 1760),
|
| 25 |
+
},
|
| 26 |
+
"768p": {
|
| 27 |
+
"16:9 (Landscape)": (1344, 768),
|
| 28 |
+
"9:16 (Portrait)": (768, 1344),
|
| 29 |
+
"1:1 (Square)": (1024, 1024),
|
| 30 |
+
"4:3 (Classic TV)": (1152, 864),
|
| 31 |
+
"3:4 (Classic Portrait)": (864, 1152),
|
| 32 |
+
"3:2 (Landscape)": (1248, 832),
|
| 33 |
+
"2:3 (Portrait)": (832, 1248),
|
| 34 |
+
},
|
| 35 |
+
"544p": {
|
| 36 |
+
"16:9 (Landscape)": (960, 544),
|
| 37 |
+
"9:16 (Portrait)": (544, 960),
|
| 38 |
+
"1:1 (Square)": (736, 736),
|
| 39 |
+
"4:3 (Classic TV)": (832, 640),
|
| 40 |
+
"3:4 (Classic Portrait)": (640, 832),
|
| 41 |
+
"3:2 (Landscape)": (864, 576),
|
| 42 |
+
"2:3 (Portrait)": (576, 864),
|
| 43 |
+
},
|
| 44 |
+
"720p": {
|
| 45 |
+
"16:9 (Landscape)": (1344, 768),
|
| 46 |
+
"9:16 (Portrait)": (768, 1344),
|
| 47 |
+
"1:1 (Square)": (1024, 1024),
|
| 48 |
+
"4:3 (Classic TV)": (1152, 864),
|
| 49 |
+
"3:4 (Classic Portrait)": (864, 1152),
|
| 50 |
+
"3:2 (Landscape)": (1248, 832),
|
| 51 |
+
"2:3 (Portrait)": (832, 1248),
|
| 52 |
+
},
|
| 53 |
+
"480p": {
|
| 54 |
+
"16:9 (Landscape)": (960, 544),
|
| 55 |
+
"9:16 (Portrait)": (544, 960),
|
| 56 |
+
"1:1 (Square)": (736, 736),
|
| 57 |
+
"4:3 (Classic TV)": (832, 640),
|
| 58 |
+
"3:4 (Classic Portrait)": (640, 832),
|
| 59 |
+
"3:2 (Landscape)": (864, 576),
|
| 60 |
+
"2:3 (Portrait)": (576, 864),
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
ASPECT_RATIO_PRESETS = RESOLUTION_PRESETS["544p"]
|
| 65 |
+
|
| 66 |
+
def calculate_h3_frame_length(duration_seconds: float) -> int:
|
| 67 |
+
"""
|
| 68 |
+
Converts duration (seconds) at 24fps to a valid frame length
|
| 69 |
+
snapped up to the model's 17-frame-per-block (17k+5) grid.
|
| 70 |
+
Grid sequence: 5, 22, 39, 56, 73, 90, 107, 124, 141...
|
| 71 |
+
"""
|
| 72 |
+
raw_frames = int(round(duration_seconds * 24))
|
| 73 |
+
if raw_frames <= 5:
|
| 74 |
+
return 5
|
| 75 |
+
return 5 + 17 * math.ceil((raw_frames - 5) / 17)
|
| 76 |
+
|
| 77 |
+
def process_inputs(ui_values, seed_override=None, progress=None):
|
| 78 |
+
local_ui_values = ui_values.copy()
|
| 79 |
+
|
| 80 |
+
width = int(local_ui_values.get('width') or 0)
|
| 81 |
+
height = int(local_ui_values.get('height') or 0)
|
| 82 |
+
|
| 83 |
+
if width <= 0 or height <= 0:
|
| 84 |
+
resolution = local_ui_values.get('resolution', '544p')
|
| 85 |
+
selected_ratio = local_ui_values.get('aspect_ratio', "16:9 (Landscape)")
|
| 86 |
+
width, height = RESOLUTION_PRESETS.get(resolution, {}).get(selected_ratio, (960, 544))
|
| 87 |
+
|
| 88 |
+
local_ui_values['width'] = width
|
| 89 |
+
local_ui_values['height'] = height
|
| 90 |
+
local_ui_values['sampler_name'] = local_ui_values.get('sampler_name') or local_ui_values.get('sampler') or 'res_multistep'
|
| 91 |
+
local_ui_values['scheduler'] = local_ui_values.get('scheduler') or 'simple'
|
| 92 |
+
local_ui_values['steps'] = int(local_ui_values.get('steps') or 20)
|
| 93 |
+
|
| 94 |
+
duration = float(local_ui_values.get('duration', 3.0))
|
| 95 |
+
local_ui_values['length'] = calculate_h3_frame_length(duration)
|
| 96 |
+
|
| 97 |
+
seed = seed_override if seed_override is not None else int(local_ui_values.get('seed', -1))
|
| 98 |
+
local_ui_values['seed'] = handle_seed(seed)
|
| 99 |
+
|
| 100 |
+
filename_prefix = get_filename_prefix()
|
| 101 |
+
local_ui_values['filename_prefix'] = f"video/{filename_prefix}"
|
| 102 |
+
|
| 103 |
+
local_ui_values['loras'] = process_lora_inputs(ui_values, 'h3_fl2va', progress=progress)
|
| 104 |
+
local_ui_values['h3_controlnets'] = process_h3_controlnet_inputs(ui_values, 'h3_fl2va', progress=progress)
|
| 105 |
+
local_ui_values['h3_guides'] = process_h3_guide_inputs(ui_values, 'h3_fl2va', progress=progress)
|
| 106 |
+
|
| 107 |
+
assembler = WorkflowAssembler(WORKFLOW_RECIPE_PATH)
|
| 108 |
+
final_workflow = assembler.assemble(local_ui_values)
|
| 109 |
+
|
| 110 |
+
first_frame_img = local_ui_values.get('first_frame')
|
| 111 |
+
if first_frame_img is not None:
|
| 112 |
+
saved_first_img = save_temp_image(first_frame_img)
|
| 113 |
+
if saved_first_img:
|
| 114 |
+
ff_loader_id = assembler.add_node("LoadImage", {"image": saved_first_img}, title="Load Image")
|
| 115 |
+
ff_scale_id = assembler.add_node("ImageScale", {
|
| 116 |
+
"image": [ff_loader_id, 0],
|
| 117 |
+
"width": width,
|
| 118 |
+
"height": height,
|
| 119 |
+
"upscale_method": "nearest-exact",
|
| 120 |
+
"crop": "center"
|
| 121 |
+
}, title="Upscale Image")
|
| 122 |
+
assembler.connect(ff_scale_id, 0, "minimax_h3", "first_frame")
|
| 123 |
+
|
| 124 |
+
last_frame_img = local_ui_values.get('last_frame')
|
| 125 |
+
if last_frame_img is not None:
|
| 126 |
+
saved_last_img = save_temp_image(last_frame_img)
|
| 127 |
+
if saved_last_img:
|
| 128 |
+
lf_loader_id = assembler.add_node("LoadImage", {"image": saved_last_img}, title="Load Image")
|
| 129 |
+
lf_scale_id = assembler.add_node("ImageScale", {
|
| 130 |
+
"image": [lf_loader_id, 0],
|
| 131 |
+
"width": width,
|
| 132 |
+
"height": height,
|
| 133 |
+
"upscale_method": "nearest-exact",
|
| 134 |
+
"crop": "center"
|
| 135 |
+
}, title="Upscale Image")
|
| 136 |
+
assembler.connect(lf_scale_id, 0, "minimax_h3", "last_frame")
|
| 137 |
+
|
| 138 |
+
return final_workflow, None
|
ui/shared/h3_fl2va_recipe.yaml
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
nodes:
|
| 2 |
+
unet_loader:
|
| 3 |
+
class_type: UNETLoader
|
| 4 |
+
title: "Load Diffusion Model"
|
| 5 |
+
params:
|
| 6 |
+
unet_name: "minimax_h3_fl2va_pruned_nvfp4.safetensors"
|
| 7 |
+
weight_dtype: "default"
|
| 8 |
+
clip_loader:
|
| 9 |
+
class_type: CLIPLoader
|
| 10 |
+
title: "Load CLIP"
|
| 11 |
+
params:
|
| 12 |
+
clip_name: "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors"
|
| 13 |
+
type: "minimax"
|
| 14 |
+
device: "default"
|
| 15 |
+
video_vae_loader:
|
| 16 |
+
class_type: VAELoader
|
| 17 |
+
title: "Load Video VAE"
|
| 18 |
+
params:
|
| 19 |
+
vae_name: "minimax_h3_video_vae_fp16.safetensors"
|
| 20 |
+
audio_vae_loader:
|
| 21 |
+
class_type: VAELoader
|
| 22 |
+
title: "Load Audio VAE"
|
| 23 |
+
params:
|
| 24 |
+
vae_name: "minimax_h3_audio_vae_fp32.safetensors"
|
| 25 |
+
minimax_h3:
|
| 26 |
+
class_type: MiniMaxH3ImageToVideo
|
| 27 |
+
title: "MiniMax H3 Image to Video"
|
| 28 |
+
params:
|
| 29 |
+
width: 1344
|
| 30 |
+
height: 768
|
| 31 |
+
length: 73
|
| 32 |
+
basic_guider:
|
| 33 |
+
class_type: BasicGuider
|
| 34 |
+
title: "Basic Guider"
|
| 35 |
+
ksampler_select:
|
| 36 |
+
class_type: KSamplerSelect
|
| 37 |
+
title: "KSamplerSelect"
|
| 38 |
+
params:
|
| 39 |
+
sampler_name: "res_multistep"
|
| 40 |
+
basic_scheduler:
|
| 41 |
+
class_type: BasicScheduler
|
| 42 |
+
title: "BasicScheduler"
|
| 43 |
+
params:
|
| 44 |
+
scheduler: "simple"
|
| 45 |
+
steps: 20
|
| 46 |
+
denoise: 1.0
|
| 47 |
+
random_noise:
|
| 48 |
+
class_type: RandomNoise
|
| 49 |
+
title: "RandomNoise"
|
| 50 |
+
params:
|
| 51 |
+
noise_seed: 1
|
| 52 |
+
sampler_custom_advanced:
|
| 53 |
+
class_type: SamplerCustomAdvanced
|
| 54 |
+
title: "SamplerCustomAdvanced"
|
| 55 |
+
vae_decode:
|
| 56 |
+
class_type: VAEDecode
|
| 57 |
+
title: "VAE Decode"
|
| 58 |
+
vae_decode_audio:
|
| 59 |
+
class_type: VAEDecodeAudio
|
| 60 |
+
title: "VAE Decode Audio"
|
| 61 |
+
create_video:
|
| 62 |
+
class_type: CreateVideo
|
| 63 |
+
title: "Create Video"
|
| 64 |
+
params:
|
| 65 |
+
fps: 24
|
| 66 |
+
bit_depth: 8
|
| 67 |
+
save_video:
|
| 68 |
+
class_type: SaveVideo
|
| 69 |
+
title: "Save Video"
|
| 70 |
+
params:
|
| 71 |
+
filename_prefix: "video/MiniMax_H3"
|
| 72 |
+
format: "mp4"
|
| 73 |
+
codec:
|
| 74 |
+
codec: "h264"
|
| 75 |
+
|
| 76 |
+
dynamic_lora_chains:
|
| 77 |
+
loras:
|
| 78 |
+
template: LoraLoader
|
| 79 |
+
output_map:
|
| 80 |
+
"unet_loader:0": model
|
| 81 |
+
"clip_loader:0": clip
|
| 82 |
+
input_map:
|
| 83 |
+
model: model
|
| 84 |
+
clip: clip
|
| 85 |
+
template_output_map:
|
| 86 |
+
"0": model
|
| 87 |
+
"1": clip
|
| 88 |
+
end_input_map:
|
| 89 |
+
model:
|
| 90 |
+
- "basic_guider:model"
|
| 91 |
+
- "basic_scheduler:model"
|
| 92 |
+
clip:
|
| 93 |
+
- "minimax_h3:clip"
|
| 94 |
+
|
| 95 |
+
dynamic_h3_controlnet_chains:
|
| 96 |
+
h3_controlnets:
|
| 97 |
+
template: MiniMaxH3FunControlNetApply
|
| 98 |
+
vae_source: "video_vae_loader:0"
|
| 99 |
+
target_nodes:
|
| 100 |
+
- "basic_guider:model"
|
| 101 |
+
- "basic_scheduler:model"
|
| 102 |
+
|
| 103 |
+
dynamic_h3_guide_chains:
|
| 104 |
+
h3_guides:
|
| 105 |
+
template: MiniMaxH3AddGuide
|
| 106 |
+
source_node: "minimax_h3"
|
| 107 |
+
vae_source: "video_vae_loader:0"
|
| 108 |
+
audio_vae_source: "audio_vae_loader:0"
|
| 109 |
+
target_nodes:
|
| 110 |
+
- "basic_guider:conditioning"
|
| 111 |
+
|
| 112 |
+
connections:
|
| 113 |
+
- from: "clip_loader:0"
|
| 114 |
+
to: "minimax_h3:clip"
|
| 115 |
+
- from: "video_vae_loader:0"
|
| 116 |
+
to: "minimax_h3:vae"
|
| 117 |
+
- from: "unet_loader:0"
|
| 118 |
+
to: "basic_guider:model"
|
| 119 |
+
- from: "minimax_h3:0"
|
| 120 |
+
to: "basic_guider:conditioning"
|
| 121 |
+
- from: "unet_loader:0"
|
| 122 |
+
to: "basic_scheduler:model"
|
| 123 |
+
- from: "random_noise:0"
|
| 124 |
+
to: "sampler_custom_advanced:noise"
|
| 125 |
+
- from: "basic_guider:0"
|
| 126 |
+
to: "sampler_custom_advanced:guider"
|
| 127 |
+
- from: "ksampler_select:0"
|
| 128 |
+
to: "sampler_custom_advanced:sampler"
|
| 129 |
+
- from: "basic_scheduler:0"
|
| 130 |
+
to: "sampler_custom_advanced:sigmas"
|
| 131 |
+
- from: "minimax_h3:1"
|
| 132 |
+
to: "sampler_custom_advanced:latent_image"
|
| 133 |
+
- from: "sampler_custom_advanced:0"
|
| 134 |
+
to: "vae_decode:samples"
|
| 135 |
+
- from: "video_vae_loader:0"
|
| 136 |
+
to: "vae_decode:vae"
|
| 137 |
+
- from: "sampler_custom_advanced:0"
|
| 138 |
+
to: "vae_decode_audio:samples"
|
| 139 |
+
- from: "audio_vae_loader:0"
|
| 140 |
+
to: "vae_decode_audio:vae"
|
| 141 |
+
- from: "vae_decode:0"
|
| 142 |
+
to: "create_video:images"
|
| 143 |
+
- from: "vae_decode_audio:0"
|
| 144 |
+
to: "create_video:audio"
|
| 145 |
+
- from: "create_video:0"
|
| 146 |
+
to: "save_video:video"
|
| 147 |
+
|
| 148 |
+
ui_map:
|
| 149 |
+
prompt: "minimax_h3:prompt"
|
| 150 |
+
width: "minimax_h3:width"
|
| 151 |
+
height: "minimax_h3:height"
|
| 152 |
+
length: "minimax_h3:length"
|
| 153 |
+
seed: "random_noise:noise_seed"
|
| 154 |
+
filename_prefix: "save_video:filename_prefix"
|
| 155 |
+
sampler_name: "ksampler_select:sampler_name"
|
| 156 |
+
scheduler: "basic_scheduler:scheduler"
|
| 157 |
+
steps: "basic_scheduler:steps"
|
ui/shared/h3_fl2va_ui.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from .h3_fl2va_logic import process_inputs, RESOLUTION_PRESETS
|
| 3 |
+
from .ui_components import create_lora_settings_ui, create_h3_controlnet_ui, create_h3_guide_ui
|
| 4 |
+
from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES
|
| 5 |
+
from core.generation_logic import generate_h3_video_wrapper
|
| 6 |
+
|
| 7 |
+
UI_INFO = {
|
| 8 |
+
"workflow_recipe": "h3_fl2va_recipe.yaml",
|
| 9 |
+
"main_tab": "VideoGen",
|
| 10 |
+
"sub_tab": "H3 FL2VA",
|
| 11 |
+
"run_button_text": "🎬 Generate H3 Video"
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
def create_ui():
|
| 15 |
+
components = {}
|
| 16 |
+
with gr.Column():
|
| 17 |
+
gr.Markdown("## MiniMax H3 Video Generation")
|
| 18 |
+
gr.Markdown("💡 **Tip:** No image for T2VA; upload First Frame for I2VA; upload First Frame & Last Frame for FL2VA. Under the default ZeroGPU Duration (s) of 120s, tasks with 544p resolution, 20 steps, and 5s duration pass successfully.")
|
| 19 |
+
|
| 20 |
+
with gr.Row():
|
| 21 |
+
components['first_frame'] = gr.Image(type="pil", label="First Frame (Optional)", height=220)
|
| 22 |
+
components['last_frame'] = gr.Image(type="pil", label="Last Frame (Optional)", height=220)
|
| 23 |
+
|
| 24 |
+
components['prompt'] = gr.Textbox(label="Prompt", lines=5)
|
| 25 |
+
|
| 26 |
+
with gr.Row():
|
| 27 |
+
with gr.Column(scale=1):
|
| 28 |
+
with gr.Row():
|
| 29 |
+
components['resolution'] = gr.Radio(
|
| 30 |
+
label="Resolution",
|
| 31 |
+
choices=["544p", "768p", "1080p"],
|
| 32 |
+
value="544p",
|
| 33 |
+
interactive=True
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
with gr.Row():
|
| 37 |
+
components['aspect_ratio'] = gr.Dropdown(
|
| 38 |
+
label="Aspect Ratio",
|
| 39 |
+
choices=list(RESOLUTION_PRESETS["544p"].keys()),
|
| 40 |
+
value="16:9 (Landscape)",
|
| 41 |
+
interactive=True
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
with gr.Row():
|
| 45 |
+
components['width'] = gr.Number(label="Width", value=960, precision=0)
|
| 46 |
+
components['height'] = gr.Number(label="Height", value=544, precision=0)
|
| 47 |
+
|
| 48 |
+
with gr.Row(visible=False):
|
| 49 |
+
components['sampler'] = gr.Dropdown(
|
| 50 |
+
label="Sampler",
|
| 51 |
+
choices=SAMPLER_CHOICES,
|
| 52 |
+
value="res_multistep" if "res_multistep" in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else "res_multistep"),
|
| 53 |
+
interactive=True,
|
| 54 |
+
visible=False
|
| 55 |
+
)
|
| 56 |
+
components['scheduler'] = gr.Dropdown(
|
| 57 |
+
label="Scheduler",
|
| 58 |
+
choices=SCHEDULER_CHOICES,
|
| 59 |
+
value="simple" if "simple" in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else "simple"),
|
| 60 |
+
interactive=True,
|
| 61 |
+
visible=False
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
with gr.Row(visible=False):
|
| 65 |
+
components['cfg_scale'] = gr.Slider(
|
| 66 |
+
label="CFG Scale",
|
| 67 |
+
minimum=1.0,
|
| 68 |
+
maximum=20.0,
|
| 69 |
+
step=0.1,
|
| 70 |
+
value=1.0,
|
| 71 |
+
interactive=True,
|
| 72 |
+
visible=False
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
with gr.Row():
|
| 76 |
+
components['steps'] = gr.Slider(
|
| 77 |
+
label="Steps",
|
| 78 |
+
minimum=1,
|
| 79 |
+
maximum=50,
|
| 80 |
+
step=1,
|
| 81 |
+
value=20,
|
| 82 |
+
interactive=True
|
| 83 |
+
)
|
| 84 |
+
components['duration'] = gr.Slider(
|
| 85 |
+
label="Duration (s)",
|
| 86 |
+
minimum=0.2,
|
| 87 |
+
maximum=15.0,
|
| 88 |
+
step=0.1,
|
| 89 |
+
value=5.0,
|
| 90 |
+
interactive=True
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
with gr.Row():
|
| 94 |
+
components['seed'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)
|
| 95 |
+
components['zero_gpu_duration'] = gr.Number(
|
| 96 |
+
label="ZeroGPU Duration (s)",
|
| 97 |
+
value=120,
|
| 98 |
+
precision=0
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Column(scale=1):
|
| 102 |
+
components['output_video'] = gr.Video(
|
| 103 |
+
label="Result Video",
|
| 104 |
+
interactive=False,
|
| 105 |
+
height=492
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
components.update(create_lora_settings_ui("h3_fl2va"))
|
| 109 |
+
components.update(create_h3_guide_ui("h3_fl2va"))
|
| 110 |
+
components.update(create_h3_controlnet_ui("h3_fl2va"))
|
| 111 |
+
|
| 112 |
+
components['run_button'] = gr.Button(UI_INFO["run_button_text"], variant="primary", elem_classes=["run-shortcut"])
|
| 113 |
+
|
| 114 |
+
return components
|
| 115 |
+
|
| 116 |
+
def create_event_handlers(components: dict, demo: gr.Blocks):
|
| 117 |
+
def update_dimensions(resolution, aspect_ratio):
|
| 118 |
+
w, h = RESOLUTION_PRESETS.get(resolution, {}).get(aspect_ratio, (960, 544))
|
| 119 |
+
return w, h
|
| 120 |
+
|
| 121 |
+
components['resolution'].change(
|
| 122 |
+
fn=update_dimensions,
|
| 123 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 124 |
+
outputs=[components['width'], components['height']],
|
| 125 |
+
api_name=False
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
components['aspect_ratio'].change(
|
| 129 |
+
fn=update_dimensions,
|
| 130 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 131 |
+
outputs=[components['width'], components['height']],
|
| 132 |
+
api_name=False
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
lora_sources = components.get('lora_sources_h3_fl2va', [])
|
| 136 |
+
lora_ids = components.get('lora_ids_h3_fl2va', [])
|
| 137 |
+
lora_scales = components.get('lora_scales_h3_fl2va', [])
|
| 138 |
+
|
| 139 |
+
cn_videos = components.get('h3_controlnet_videos_h3_fl2va', [])
|
| 140 |
+
cn_types = components.get('h3_controlnet_types_h3_fl2va', [])
|
| 141 |
+
cn_series = components.get('h3_controlnet_series_h3_fl2va', [])
|
| 142 |
+
cn_strengths = components.get('h3_controlnet_strengths_h3_fl2va', [])
|
| 143 |
+
cn_start_percents = components.get('h3_controlnet_start_percents_h3_fl2va', [])
|
| 144 |
+
cn_end_percents = components.get('h3_controlnet_end_percents_h3_fl2va', [])
|
| 145 |
+
cn_filepaths = components.get('h3_controlnet_filepaths_h3_fl2va', [])
|
| 146 |
+
|
| 147 |
+
guide_images = components.get('h3_guide_images_h3_fl2va', [])
|
| 148 |
+
guide_videos = components.get('h3_guide_videos_h3_fl2va', [])
|
| 149 |
+
guide_audios = components.get('h3_guide_audios_h3_fl2va', [])
|
| 150 |
+
guide_times = components.get('h3_guide_times_h3_fl2va', [])
|
| 151 |
+
guide_frames = components.get('h3_guide_frames_h3_fl2va', [])
|
| 152 |
+
|
| 153 |
+
inputs_list = [
|
| 154 |
+
components['first_frame'],
|
| 155 |
+
components['last_frame'],
|
| 156 |
+
components['prompt'],
|
| 157 |
+
components['resolution'],
|
| 158 |
+
components['aspect_ratio'],
|
| 159 |
+
components['width'],
|
| 160 |
+
components['height'],
|
| 161 |
+
components['duration'],
|
| 162 |
+
components['sampler'],
|
| 163 |
+
components['scheduler'],
|
| 164 |
+
components['steps'],
|
| 165 |
+
components['cfg_scale'],
|
| 166 |
+
components['seed'],
|
| 167 |
+
components['zero_gpu_duration']
|
| 168 |
+
] + lora_sources + lora_ids + lora_scales + cn_videos + cn_types + cn_series + cn_strengths + cn_start_percents + cn_end_percents + cn_filepaths + guide_images + guide_videos + guide_audios + guide_times + guide_frames
|
| 169 |
+
|
| 170 |
+
def on_run_click(*args, progress=gr.Progress(track_tqdm=True)):
|
| 171 |
+
first_frame, last_frame, prompt, resolution, aspect_ratio, width, height, duration, sampler, scheduler, steps, cfg_scale, seed, zero_gpu_duration = args[:14]
|
| 172 |
+
rest = args[14:]
|
| 173 |
+
num_loras = len(lora_sources)
|
| 174 |
+
l_sources = rest[:num_loras]
|
| 175 |
+
l_ids = rest[num_loras:2*num_loras]
|
| 176 |
+
l_scales = rest[2*num_loras:3*num_loras]
|
| 177 |
+
|
| 178 |
+
rest_cn = rest[3*num_loras:]
|
| 179 |
+
num_cns = len(cn_videos)
|
| 180 |
+
c_vids = rest_cn[:num_cns]
|
| 181 |
+
c_types = rest_cn[num_cns:2*num_cns]
|
| 182 |
+
c_series = rest_cn[2*num_cns:3*num_cns]
|
| 183 |
+
c_strengths = rest_cn[3*num_cns:4*num_cns]
|
| 184 |
+
c_starts = rest_cn[4*num_cns:5*num_cns]
|
| 185 |
+
c_ends = rest_cn[5*num_cns:6*num_cns]
|
| 186 |
+
c_fps = rest_cn[6*num_cns:7*num_cns]
|
| 187 |
+
|
| 188 |
+
rest_guide = rest_cn[7*num_cns:]
|
| 189 |
+
num_guides = len(guide_images)
|
| 190 |
+
g_imgs = rest_guide[:num_guides]
|
| 191 |
+
g_vids = rest_guide[num_guides:2*num_guides]
|
| 192 |
+
g_auds = rest_guide[2*num_guides:3*num_guides]
|
| 193 |
+
g_times = rest_guide[3*num_guides:4*num_guides]
|
| 194 |
+
g_frames = rest_guide[4*num_guides:5*num_guides] if guide_frames else []
|
| 195 |
+
|
| 196 |
+
ui_values = {
|
| 197 |
+
'first_frame': first_frame,
|
| 198 |
+
'last_frame': last_frame,
|
| 199 |
+
'prompt': prompt,
|
| 200 |
+
'resolution': resolution,
|
| 201 |
+
'aspect_ratio': aspect_ratio,
|
| 202 |
+
'width': width,
|
| 203 |
+
'height': height,
|
| 204 |
+
'duration': duration,
|
| 205 |
+
'sampler_name': sampler,
|
| 206 |
+
'scheduler': scheduler,
|
| 207 |
+
'steps': steps,
|
| 208 |
+
'cfg_scale': cfg_scale,
|
| 209 |
+
'seed': seed,
|
| 210 |
+
'zero_gpu_duration': zero_gpu_duration,
|
| 211 |
+
'batch_count': 1,
|
| 212 |
+
'lora_sources_h3_fl2va': list(l_sources),
|
| 213 |
+
'lora_ids_h3_fl2va': list(l_ids),
|
| 214 |
+
'lora_scales_h3_fl2va': list(l_scales),
|
| 215 |
+
'h3_controlnet_videos_h3_fl2va': list(c_vids),
|
| 216 |
+
'h3_controlnet_types_h3_fl2va': list(c_types),
|
| 217 |
+
'h3_controlnet_series_h3_fl2va': list(c_series),
|
| 218 |
+
'h3_controlnet_strengths_h3_fl2va': list(c_strengths),
|
| 219 |
+
'h3_controlnet_start_percents_h3_fl2va': list(c_starts),
|
| 220 |
+
'h3_controlnet_end_percents_h3_fl2va': list(c_ends),
|
| 221 |
+
'h3_controlnet_filepaths_h3_fl2va': list(c_fps),
|
| 222 |
+
'h3_guide_images_h3_fl2va': list(g_imgs),
|
| 223 |
+
'h3_guide_videos_h3_fl2va': list(g_vids),
|
| 224 |
+
'h3_guide_audios_h3_fl2va': list(g_auds),
|
| 225 |
+
'h3_guide_times_h3_fl2va': list(g_times),
|
| 226 |
+
'h3_guide_frames_h3_fl2va': list(g_frames),
|
| 227 |
+
}
|
| 228 |
+
return generate_h3_video_wrapper(process_inputs, ui_values, progress=progress)
|
| 229 |
+
|
| 230 |
+
components['run_button'].click(
|
| 231 |
+
fn=on_run_click,
|
| 232 |
+
inputs=inputs_list,
|
| 233 |
+
outputs=[components['output_video']],
|
| 234 |
+
api_name=False
|
| 235 |
+
)
|
ui/shared/h3_ref2va_logic.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import math
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from core.workflow_assembler import WorkflowAssembler
|
| 5 |
+
from utils.app_utils import (
|
| 6 |
+
handle_seed, save_temp_image, save_temp_video, save_temp_audio,
|
| 7 |
+
get_filename_prefix, process_lora_inputs, process_h3_controlnet_inputs,
|
| 8 |
+
process_h3_guide_inputs
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
WORKFLOW_RECIPE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "h3_ref2va_recipe.yaml")
|
| 12 |
+
|
| 13 |
+
RESOLUTION_PRESETS = {
|
| 14 |
+
"1080p": {
|
| 15 |
+
"16:9 (Landscape)": (1920, 1088),
|
| 16 |
+
"9:16 (Portrait)": (1088, 1920),
|
| 17 |
+
"1:1 (Square)": (1440, 1440),
|
| 18 |
+
"4:3 (Classic TV)": (1664, 1248),
|
| 19 |
+
"3:4 (Classic Portrait)": (1248, 1664),
|
| 20 |
+
"3:2 (Landscape)": (1760, 1184),
|
| 21 |
+
"2:3 (Portrait)": (1184, 1760),
|
| 22 |
+
},
|
| 23 |
+
"768p": {
|
| 24 |
+
"16:9 (Landscape)": (1344, 768),
|
| 25 |
+
"9:16 (Portrait)": (768, 1344),
|
| 26 |
+
"1:1 (Square)": (1024, 1024),
|
| 27 |
+
"4:3 (Classic TV)": (1152, 864),
|
| 28 |
+
"3:4 (Classic Portrait)": (864, 1152),
|
| 29 |
+
"3:2 (Landscape)": (1248, 832),
|
| 30 |
+
"2:3 (Portrait)": (832, 1248),
|
| 31 |
+
},
|
| 32 |
+
"544p": {
|
| 33 |
+
"16:9 (Landscape)": (960, 544),
|
| 34 |
+
"9:16 (Portrait)": (544, 960),
|
| 35 |
+
"1:1 (Square)": (736, 736),
|
| 36 |
+
"4:3 (Classic TV)": (832, 640),
|
| 37 |
+
"3:4 (Classic Portrait)": (640, 832),
|
| 38 |
+
"3:2 (Landscape)": (864, 576),
|
| 39 |
+
"2:3 (Portrait)": (576, 864),
|
| 40 |
+
},
|
| 41 |
+
"720p": {
|
| 42 |
+
"16:9 (Landscape)": (1344, 768),
|
| 43 |
+
"9:16 (Portrait)": (768, 1344),
|
| 44 |
+
"1:1 (Square)": (1024, 1024),
|
| 45 |
+
"4:3 (Classic TV)": (1152, 864),
|
| 46 |
+
"3:4 (Classic Portrait)": (864, 1152),
|
| 47 |
+
"3:2 (Landscape)": (1248, 832),
|
| 48 |
+
"2:3 (Portrait)": (832, 1248),
|
| 49 |
+
},
|
| 50 |
+
"480p": {
|
| 51 |
+
"16:9 (Landscape)": (960, 544),
|
| 52 |
+
"9:16 (Portrait)": (544, 960),
|
| 53 |
+
"1:1 (Square)": (736, 736),
|
| 54 |
+
"4:3 (Classic TV)": (832, 640),
|
| 55 |
+
"3:4 (Classic Portrait)": (640, 832),
|
| 56 |
+
"3:2 (Landscape)": (864, 576),
|
| 57 |
+
"2:3 (Portrait)": (576, 864),
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
ASPECT_RATIO_PRESETS = RESOLUTION_PRESETS["544p"]
|
| 62 |
+
|
| 63 |
+
def calculate_h3_frame_length(duration_seconds: float) -> int:
|
| 64 |
+
"""
|
| 65 |
+
Converts duration (seconds) at 24fps to a valid frame length
|
| 66 |
+
snapped up to the model's 17-frame-per-block (17k+5) grid.
|
| 67 |
+
Grid sequence: 5, 22, 39, 56, 73, 90, 107, 124, 141...
|
| 68 |
+
"""
|
| 69 |
+
raw_frames = int(round(duration_seconds * 24))
|
| 70 |
+
if raw_frames <= 5:
|
| 71 |
+
return 5
|
| 72 |
+
return 5 + 17 * math.ceil((raw_frames - 5) / 17)
|
| 73 |
+
|
| 74 |
+
def process_inputs(ui_values, seed_override=None, progress=None):
|
| 75 |
+
local_ui_values = ui_values.copy()
|
| 76 |
+
|
| 77 |
+
width = int(local_ui_values.get('width') or 0)
|
| 78 |
+
height = int(local_ui_values.get('height') or 0)
|
| 79 |
+
|
| 80 |
+
if width <= 0 or height <= 0:
|
| 81 |
+
resolution = local_ui_values.get('resolution', '544p')
|
| 82 |
+
selected_ratio = local_ui_values.get('aspect_ratio', "16:9 (Landscape)")
|
| 83 |
+
width, height = RESOLUTION_PRESETS.get(resolution, {}).get(selected_ratio, (960, 544))
|
| 84 |
+
|
| 85 |
+
local_ui_values['width'] = width
|
| 86 |
+
local_ui_values['height'] = height
|
| 87 |
+
local_ui_values['sampler_name'] = local_ui_values.get('sampler_name') or local_ui_values.get('sampler') or 'res_multistep'
|
| 88 |
+
local_ui_values['scheduler'] = local_ui_values.get('scheduler') or 'simple'
|
| 89 |
+
local_ui_values['steps'] = int(local_ui_values.get('steps') or 20)
|
| 90 |
+
|
| 91 |
+
ref_images_input = local_ui_values.get('ref_images', [])
|
| 92 |
+
saved_ref_images = []
|
| 93 |
+
if isinstance(ref_images_input, list):
|
| 94 |
+
for img in ref_images_input:
|
| 95 |
+
if img is not None:
|
| 96 |
+
saved = save_temp_image(img)
|
| 97 |
+
if saved:
|
| 98 |
+
saved_ref_images.append(saved)
|
| 99 |
+
local_ui_values['ref_images'] = saved_ref_images
|
| 100 |
+
|
| 101 |
+
ref_videos_input = local_ui_values.get('ref_videos', [])
|
| 102 |
+
saved_ref_videos = []
|
| 103 |
+
if isinstance(ref_videos_input, list):
|
| 104 |
+
for video_path in ref_videos_input:
|
| 105 |
+
if video_path:
|
| 106 |
+
saved_vid = save_temp_video(video_path)
|
| 107 |
+
if saved_vid:
|
| 108 |
+
saved_ref_videos.append(saved_vid)
|
| 109 |
+
local_ui_values['ref_videos'] = saved_ref_videos
|
| 110 |
+
|
| 111 |
+
ref_audios_input = local_ui_values.get('ref_audios', [])
|
| 112 |
+
saved_ref_audios = []
|
| 113 |
+
if isinstance(ref_audios_input, list):
|
| 114 |
+
for audio_path in ref_audios_input:
|
| 115 |
+
if audio_path:
|
| 116 |
+
saved_aud = save_temp_audio(audio_path)
|
| 117 |
+
if saved_aud:
|
| 118 |
+
saved_ref_audios.append(saved_aud)
|
| 119 |
+
local_ui_values['ref_audios'] = saved_ref_audios
|
| 120 |
+
|
| 121 |
+
duration = float(local_ui_values.get('duration', 3.0))
|
| 122 |
+
local_ui_values['length'] = calculate_h3_frame_length(duration)
|
| 123 |
+
|
| 124 |
+
seed = seed_override if seed_override is not None else int(local_ui_values.get('seed', -1))
|
| 125 |
+
local_ui_values['seed'] = handle_seed(seed)
|
| 126 |
+
|
| 127 |
+
filename_prefix = get_filename_prefix()
|
| 128 |
+
local_ui_values['filename_prefix'] = f"video/{filename_prefix}"
|
| 129 |
+
|
| 130 |
+
local_ui_values['loras'] = process_lora_inputs(ui_values, 'h3_ref2va', progress=progress)
|
| 131 |
+
local_ui_values['h3_controlnets'] = process_h3_controlnet_inputs(ui_values, 'h3_ref2va', progress=progress)
|
| 132 |
+
local_ui_values['h3_guides'] = process_h3_guide_inputs(ui_values, 'h3_ref2va', progress=progress)
|
| 133 |
+
|
| 134 |
+
assembler = WorkflowAssembler(WORKFLOW_RECIPE_PATH)
|
| 135 |
+
final_workflow = assembler.assemble(local_ui_values)
|
| 136 |
+
|
| 137 |
+
return final_workflow, None
|
ui/shared/h3_ref2va_recipe.yaml
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
nodes:
|
| 2 |
+
unet_loader:
|
| 3 |
+
class_type: UNETLoader
|
| 4 |
+
title: "Load Diffusion Model"
|
| 5 |
+
params:
|
| 6 |
+
unet_name: "minimax_h3_ref2va_pruned_nvfp4.safetensors"
|
| 7 |
+
weight_dtype: "default"
|
| 8 |
+
clip_loader:
|
| 9 |
+
class_type: CLIPLoader
|
| 10 |
+
title: "Load CLIP"
|
| 11 |
+
params:
|
| 12 |
+
clip_name: "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors"
|
| 13 |
+
type: "minimax"
|
| 14 |
+
device: "default"
|
| 15 |
+
video_vae_loader:
|
| 16 |
+
class_type: VAELoader
|
| 17 |
+
title: "Load Video VAE"
|
| 18 |
+
params:
|
| 19 |
+
vae_name: "minimax_h3_video_vae_fp16.safetensors"
|
| 20 |
+
audio_vae_loader:
|
| 21 |
+
class_type: VAELoader
|
| 22 |
+
title: "Load Audio VAE"
|
| 23 |
+
params:
|
| 24 |
+
vae_name: "minimax_h3_audio_vae_fp32.safetensors"
|
| 25 |
+
minimax_h3:
|
| 26 |
+
class_type: MiniMaxH3ReferenceToVideo
|
| 27 |
+
title: "MiniMax H3 Reference to Video"
|
| 28 |
+
params:
|
| 29 |
+
width: 1344
|
| 30 |
+
height: 768
|
| 31 |
+
length: 73
|
| 32 |
+
ref_image_size: "match"
|
| 33 |
+
basic_guider:
|
| 34 |
+
class_type: BasicGuider
|
| 35 |
+
title: "Basic Guider"
|
| 36 |
+
ksampler_select:
|
| 37 |
+
class_type: KSamplerSelect
|
| 38 |
+
title: "KSamplerSelect"
|
| 39 |
+
params:
|
| 40 |
+
sampler_name: "res_multistep"
|
| 41 |
+
basic_scheduler:
|
| 42 |
+
class_type: BasicScheduler
|
| 43 |
+
title: "BasicScheduler"
|
| 44 |
+
params:
|
| 45 |
+
scheduler: "simple"
|
| 46 |
+
steps: 20
|
| 47 |
+
denoise: 1.0
|
| 48 |
+
random_noise:
|
| 49 |
+
class_type: RandomNoise
|
| 50 |
+
title: "RandomNoise"
|
| 51 |
+
params:
|
| 52 |
+
noise_seed: 1
|
| 53 |
+
sampler_custom_advanced:
|
| 54 |
+
class_type: SamplerCustomAdvanced
|
| 55 |
+
title: "SamplerCustomAdvanced"
|
| 56 |
+
vae_decode:
|
| 57 |
+
class_type: VAEDecode
|
| 58 |
+
title: "VAE Decode"
|
| 59 |
+
vae_decode_audio:
|
| 60 |
+
class_type: VAEDecodeAudio
|
| 61 |
+
title: "VAE Decode Audio"
|
| 62 |
+
create_video:
|
| 63 |
+
class_type: CreateVideo
|
| 64 |
+
title: "Create Video"
|
| 65 |
+
params:
|
| 66 |
+
fps: 24
|
| 67 |
+
bit_depth: 8
|
| 68 |
+
save_video:
|
| 69 |
+
class_type: SaveVideo
|
| 70 |
+
title: "Save Video"
|
| 71 |
+
params:
|
| 72 |
+
filename_prefix: "video/MiniMax_H3"
|
| 73 |
+
format: "mp4"
|
| 74 |
+
codec:
|
| 75 |
+
codec: "h264"
|
| 76 |
+
|
| 77 |
+
dynamic_lora_chains:
|
| 78 |
+
loras:
|
| 79 |
+
template: LoraLoader
|
| 80 |
+
output_map:
|
| 81 |
+
"unet_loader:0": model
|
| 82 |
+
"clip_loader:0": clip
|
| 83 |
+
input_map:
|
| 84 |
+
model: model
|
| 85 |
+
clip: clip
|
| 86 |
+
template_output_map:
|
| 87 |
+
"0": model
|
| 88 |
+
"1": clip
|
| 89 |
+
end_input_map:
|
| 90 |
+
model:
|
| 91 |
+
- "basic_guider:model"
|
| 92 |
+
- "basic_scheduler:model"
|
| 93 |
+
clip:
|
| 94 |
+
- "minimax_h3:clip"
|
| 95 |
+
|
| 96 |
+
dynamic_h3_ref_img_chains:
|
| 97 |
+
ref_images:
|
| 98 |
+
target_node: "minimax_h3"
|
| 99 |
+
|
| 100 |
+
dynamic_h3_ref_video_chains:
|
| 101 |
+
ref_videos:
|
| 102 |
+
target_node: "minimax_h3"
|
| 103 |
+
|
| 104 |
+
dynamic_h3_ref_audio_chains:
|
| 105 |
+
ref_audios:
|
| 106 |
+
target_node: "minimax_h3"
|
| 107 |
+
|
| 108 |
+
dynamic_h3_controlnet_chains:
|
| 109 |
+
h3_controlnets:
|
| 110 |
+
template: MiniMaxH3FunControlNetApply
|
| 111 |
+
vae_source: "video_vae_loader:0"
|
| 112 |
+
target_nodes:
|
| 113 |
+
- "basic_guider:model"
|
| 114 |
+
- "basic_scheduler:model"
|
| 115 |
+
|
| 116 |
+
dynamic_h3_guide_chains:
|
| 117 |
+
h3_guides:
|
| 118 |
+
template: MiniMaxH3AddGuide
|
| 119 |
+
source_node: "minimax_h3"
|
| 120 |
+
vae_source: "video_vae_loader:0"
|
| 121 |
+
audio_vae_source: "audio_vae_loader:0"
|
| 122 |
+
target_nodes:
|
| 123 |
+
- "basic_guider:conditioning"
|
| 124 |
+
|
| 125 |
+
connections:
|
| 126 |
+
- from: "clip_loader:0"
|
| 127 |
+
to: "minimax_h3:clip"
|
| 128 |
+
- from: "video_vae_loader:0"
|
| 129 |
+
to: "minimax_h3:vae"
|
| 130 |
+
- from: "audio_vae_loader:0"
|
| 131 |
+
to: "minimax_h3:audio_vae"
|
| 132 |
+
- from: "unet_loader:0"
|
| 133 |
+
to: "basic_guider:model"
|
| 134 |
+
- from: "minimax_h3:0"
|
| 135 |
+
to: "basic_guider:conditioning"
|
| 136 |
+
- from: "unet_loader:0"
|
| 137 |
+
to: "basic_scheduler:model"
|
| 138 |
+
- from: "random_noise:0"
|
| 139 |
+
to: "sampler_custom_advanced:noise"
|
| 140 |
+
- from: "basic_guider:0"
|
| 141 |
+
to: "sampler_custom_advanced:guider"
|
| 142 |
+
- from: "ksampler_select:0"
|
| 143 |
+
to: "sampler_custom_advanced:sampler"
|
| 144 |
+
- from: "basic_scheduler:0"
|
| 145 |
+
to: "sampler_custom_advanced:sigmas"
|
| 146 |
+
- from: "minimax_h3:1"
|
| 147 |
+
to: "sampler_custom_advanced:latent_image"
|
| 148 |
+
- from: "sampler_custom_advanced:0"
|
| 149 |
+
to: "vae_decode:samples"
|
| 150 |
+
- from: "video_vae_loader:0"
|
| 151 |
+
to: "vae_decode:vae"
|
| 152 |
+
- from: "sampler_custom_advanced:0"
|
| 153 |
+
to: "vae_decode_audio:samples"
|
| 154 |
+
- from: "audio_vae_loader:0"
|
| 155 |
+
to: "vae_decode_audio:vae"
|
| 156 |
+
- from: "vae_decode:0"
|
| 157 |
+
to: "create_video:images"
|
| 158 |
+
- from: "vae_decode_audio:0"
|
| 159 |
+
to: "create_video:audio"
|
| 160 |
+
- from: "create_video:0"
|
| 161 |
+
to: "save_video:video"
|
| 162 |
+
|
| 163 |
+
ui_map:
|
| 164 |
+
prompt: "minimax_h3:prompt"
|
| 165 |
+
width: "minimax_h3:width"
|
| 166 |
+
height: "minimax_h3:height"
|
| 167 |
+
length: "minimax_h3:length"
|
| 168 |
+
seed: "random_noise:noise_seed"
|
| 169 |
+
filename_prefix: "save_video:filename_prefix"
|
| 170 |
+
sampler_name: "ksampler_select:sampler_name"
|
| 171 |
+
scheduler: "basic_scheduler:scheduler"
|
| 172 |
+
steps: "basic_scheduler:steps"
|
ui/shared/h3_ref2va_ui.py
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from .h3_ref2va_logic import process_inputs, RESOLUTION_PRESETS
|
| 3 |
+
from .ui_components import create_lora_settings_ui, create_h3_controlnet_ui, create_h3_guide_ui
|
| 4 |
+
from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES
|
| 5 |
+
from core.generation_logic import generate_h3_video_wrapper
|
| 6 |
+
|
| 7 |
+
UI_INFO = {
|
| 8 |
+
"workflow_recipe": "h3_ref2va_recipe.yaml",
|
| 9 |
+
"main_tab": "VideoGen",
|
| 10 |
+
"sub_tab": "H3 REF2VA",
|
| 11 |
+
"run_button_text": "🎬 Generate H3 Video"
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
MAX_REF_IMAGES = 9
|
| 15 |
+
MAX_REF_VIDEOS = 3
|
| 16 |
+
MAX_REF_AUDIOS = 3
|
| 17 |
+
|
| 18 |
+
def create_ui():
|
| 19 |
+
components = {}
|
| 20 |
+
with gr.Column():
|
| 21 |
+
gr.Markdown("## MiniMax H3 Reference Video Generation")
|
| 22 |
+
gr.Markdown("💡 **Tip:** Supports uploading up to 9 reference images, 3 reference videos with audio, and 3 reference audio files. Under the default ZeroGPU Duration (s) of 120s, tasks with 544p resolution, 20 steps, 5s duration, and 3 reference images pass successfully.")
|
| 23 |
+
|
| 24 |
+
components['prompt'] = gr.Textbox(label="Prompt", lines=5)
|
| 25 |
+
|
| 26 |
+
with gr.Row():
|
| 27 |
+
with gr.Column(scale=1):
|
| 28 |
+
with gr.Row():
|
| 29 |
+
components['resolution'] = gr.Radio(
|
| 30 |
+
label="Resolution",
|
| 31 |
+
choices=["544p", "768p", "1080p"],
|
| 32 |
+
value="544p",
|
| 33 |
+
interactive=True
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
with gr.Row():
|
| 37 |
+
components['aspect_ratio'] = gr.Dropdown(
|
| 38 |
+
label="Aspect Ratio",
|
| 39 |
+
choices=list(RESOLUTION_PRESETS["544p"].keys()),
|
| 40 |
+
value="16:9 (Landscape)",
|
| 41 |
+
interactive=True
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
with gr.Row():
|
| 45 |
+
components['width'] = gr.Number(label="Width", value=960, precision=0)
|
| 46 |
+
components['height'] = gr.Number(label="Height", value=544, precision=0)
|
| 47 |
+
|
| 48 |
+
with gr.Row(visible=False):
|
| 49 |
+
components['sampler'] = gr.Dropdown(
|
| 50 |
+
label="Sampler",
|
| 51 |
+
choices=SAMPLER_CHOICES,
|
| 52 |
+
value="res_multistep" if "res_multistep" in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else "res_multistep"),
|
| 53 |
+
interactive=True,
|
| 54 |
+
visible=False
|
| 55 |
+
)
|
| 56 |
+
components['scheduler'] = gr.Dropdown(
|
| 57 |
+
label="Scheduler",
|
| 58 |
+
choices=SCHEDULER_CHOICES,
|
| 59 |
+
value="simple" if "simple" in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else "simple"),
|
| 60 |
+
interactive=True,
|
| 61 |
+
visible=False
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
with gr.Row(visible=False):
|
| 65 |
+
components['cfg_scale'] = gr.Slider(
|
| 66 |
+
label="CFG Scale",
|
| 67 |
+
minimum=1.0,
|
| 68 |
+
maximum=20.0,
|
| 69 |
+
step=0.1,
|
| 70 |
+
value=1.0,
|
| 71 |
+
interactive=True,
|
| 72 |
+
visible=False
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
with gr.Row():
|
| 76 |
+
components['steps'] = gr.Slider(
|
| 77 |
+
label="Steps",
|
| 78 |
+
minimum=1,
|
| 79 |
+
maximum=50,
|
| 80 |
+
step=1,
|
| 81 |
+
value=20,
|
| 82 |
+
interactive=True
|
| 83 |
+
)
|
| 84 |
+
components['duration'] = gr.Slider(
|
| 85 |
+
label="Duration (s)",
|
| 86 |
+
minimum=0.2,
|
| 87 |
+
maximum=15.0,
|
| 88 |
+
step=0.1,
|
| 89 |
+
value=5.0,
|
| 90 |
+
interactive=True
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
with gr.Row():
|
| 94 |
+
components['seed'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)
|
| 95 |
+
components['zero_gpu_duration'] = gr.Number(
|
| 96 |
+
label="ZeroGPU Duration (s)",
|
| 97 |
+
value=120,
|
| 98 |
+
precision=0
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
with gr.Column(scale=1):
|
| 102 |
+
components['output_video'] = gr.Video(
|
| 103 |
+
label="Result Video",
|
| 104 |
+
interactive=False,
|
| 105 |
+
height=492
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
components.update(create_lora_settings_ui("h3_ref2va"))
|
| 109 |
+
|
| 110 |
+
with gr.Accordion("Reference Image Settings", open=False):
|
| 111 |
+
ref_image_groups = []
|
| 112 |
+
ref_image_inputs = []
|
| 113 |
+
with gr.Row():
|
| 114 |
+
for i in range(MAX_REF_IMAGES):
|
| 115 |
+
with gr.Column(visible=(i < 1), min_width=160) as img_col:
|
| 116 |
+
img_comp = gr.Image(
|
| 117 |
+
type="pil",
|
| 118 |
+
label=f"Ref Image {i+1}",
|
| 119 |
+
sources=["upload"],
|
| 120 |
+
height=160
|
| 121 |
+
)
|
| 122 |
+
ref_image_groups.append(img_col)
|
| 123 |
+
ref_image_inputs.append(img_comp)
|
| 124 |
+
components['ref_image_groups'] = ref_image_groups
|
| 125 |
+
components['ref_image_inputs'] = ref_image_inputs
|
| 126 |
+
components['ref_images'] = ref_image_inputs
|
| 127 |
+
|
| 128 |
+
with gr.Row():
|
| 129 |
+
components['add_ref_button'] = gr.Button("✚ Add Reference Image")
|
| 130 |
+
components['delete_ref_button'] = gr.Button("➖ Delete Reference Image", visible=True)
|
| 131 |
+
components['ref_count_state'] = gr.State(1)
|
| 132 |
+
|
| 133 |
+
with gr.Accordion("Reference Video Settings", open=False):
|
| 134 |
+
ref_video_groups = []
|
| 135 |
+
ref_video_inputs = []
|
| 136 |
+
with gr.Row():
|
| 137 |
+
for i in range(MAX_REF_VIDEOS):
|
| 138 |
+
with gr.Column(visible=(i < 1), min_width=200) as vid_col:
|
| 139 |
+
vid_comp = gr.Video(
|
| 140 |
+
label=f"Ref Video {i+1}",
|
| 141 |
+
sources=["upload"],
|
| 142 |
+
height=200
|
| 143 |
+
)
|
| 144 |
+
ref_video_groups.append(vid_col)
|
| 145 |
+
ref_video_inputs.append(vid_comp)
|
| 146 |
+
components['ref_video_groups'] = ref_video_groups
|
| 147 |
+
components['ref_video_inputs'] = ref_video_inputs
|
| 148 |
+
components['ref_videos'] = ref_video_inputs
|
| 149 |
+
|
| 150 |
+
with gr.Row():
|
| 151 |
+
components['add_ref_video_button'] = gr.Button("✚ Add Reference Video")
|
| 152 |
+
components['delete_ref_video_button'] = gr.Button("➖ Delete Reference Video", visible=True)
|
| 153 |
+
components['ref_video_count_state'] = gr.State(1)
|
| 154 |
+
|
| 155 |
+
with gr.Accordion("Reference Audio Settings", open=False):
|
| 156 |
+
ref_audio_groups = []
|
| 157 |
+
ref_audio_inputs = []
|
| 158 |
+
with gr.Row():
|
| 159 |
+
for i in range(MAX_REF_AUDIOS):
|
| 160 |
+
with gr.Column(visible=(i < 1), min_width=200) as aud_col:
|
| 161 |
+
aud_comp = gr.Audio(
|
| 162 |
+
label=f"Ref Audio {i+1}",
|
| 163 |
+
sources=["upload"],
|
| 164 |
+
type="filepath"
|
| 165 |
+
)
|
| 166 |
+
ref_audio_groups.append(aud_col)
|
| 167 |
+
ref_audio_inputs.append(aud_comp)
|
| 168 |
+
components['ref_audio_groups'] = ref_audio_groups
|
| 169 |
+
components['ref_audio_inputs'] = ref_audio_inputs
|
| 170 |
+
components['ref_audios'] = ref_audio_inputs
|
| 171 |
+
|
| 172 |
+
with gr.Row():
|
| 173 |
+
components['add_ref_audio_button'] = gr.Button("✚ Add Reference Audio")
|
| 174 |
+
components['delete_ref_audio_button'] = gr.Button("➖ Delete Reference Audio", visible=True)
|
| 175 |
+
components['ref_audio_count_state'] = gr.State(1)
|
| 176 |
+
|
| 177 |
+
components.update(create_h3_guide_ui("h3_ref2va"))
|
| 178 |
+
components.update(create_h3_controlnet_ui("h3_ref2va"))
|
| 179 |
+
|
| 180 |
+
components['run_button'] = gr.Button(UI_INFO["run_button_text"], variant="primary", elem_classes=["run-shortcut"])
|
| 181 |
+
|
| 182 |
+
return components
|
| 183 |
+
|
| 184 |
+
def create_event_handlers(components: dict, demo: gr.Blocks):
|
| 185 |
+
def update_dimensions(resolution, aspect_ratio):
|
| 186 |
+
w, h = RESOLUTION_PRESETS.get(resolution, {}).get(aspect_ratio, (960, 544))
|
| 187 |
+
return w, h
|
| 188 |
+
|
| 189 |
+
components['resolution'].change(
|
| 190 |
+
fn=update_dimensions,
|
| 191 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 192 |
+
outputs=[components['width'], components['height']],
|
| 193 |
+
api_name=False
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
components['aspect_ratio'].change(
|
| 197 |
+
fn=update_dimensions,
|
| 198 |
+
inputs=[components['resolution'], components['aspect_ratio']],
|
| 199 |
+
outputs=[components['width'], components['height']],
|
| 200 |
+
api_name=False
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
ref_count_state = components['ref_count_state']
|
| 204 |
+
add_ref_btn = components['add_ref_button']
|
| 205 |
+
del_ref_btn = components['delete_ref_button']
|
| 206 |
+
ref_image_groups = components['ref_image_groups']
|
| 207 |
+
ref_image_inputs = components['ref_image_inputs']
|
| 208 |
+
|
| 209 |
+
def add_ref_row(count):
|
| 210 |
+
count += 1
|
| 211 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_IMAGES))
|
| 212 |
+
return (count, gr.update(visible=count < MAX_REF_IMAGES), gr.update(visible=count > 0)) + visibility_updates
|
| 213 |
+
|
| 214 |
+
def delete_ref_row(count):
|
| 215 |
+
count -= 1
|
| 216 |
+
image_clear_updates = [gr.update()] * MAX_REF_IMAGES
|
| 217 |
+
if count >= 0:
|
| 218 |
+
image_clear_updates[count] = None
|
| 219 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_IMAGES))
|
| 220 |
+
return (count, gr.update(visible=count < MAX_REF_IMAGES), gr.update(visible=count > 0)) + visibility_updates + tuple(image_clear_updates)
|
| 221 |
+
|
| 222 |
+
add_ref_outputs = [ref_count_state, add_ref_btn, del_ref_btn] + ref_image_groups
|
| 223 |
+
del_ref_outputs = [ref_count_state, add_ref_btn, del_ref_btn] + ref_image_groups + ref_image_inputs
|
| 224 |
+
|
| 225 |
+
add_ref_btn.click(
|
| 226 |
+
fn=add_ref_row,
|
| 227 |
+
inputs=[ref_count_state],
|
| 228 |
+
outputs=add_ref_outputs,
|
| 229 |
+
show_progress=False,
|
| 230 |
+
api_name=False
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
del_ref_btn.click(
|
| 234 |
+
fn=delete_ref_row,
|
| 235 |
+
inputs=[ref_count_state],
|
| 236 |
+
outputs=del_ref_outputs,
|
| 237 |
+
show_progress=False,
|
| 238 |
+
api_name=False
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
ref_video_count_state = components['ref_video_count_state']
|
| 242 |
+
add_ref_vid_btn = components['add_ref_video_button']
|
| 243 |
+
del_ref_vid_btn = components['delete_ref_video_button']
|
| 244 |
+
ref_video_groups = components['ref_video_groups']
|
| 245 |
+
ref_video_inputs = components['ref_video_inputs']
|
| 246 |
+
|
| 247 |
+
def add_ref_video_row(count):
|
| 248 |
+
count += 1
|
| 249 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_VIDEOS))
|
| 250 |
+
return (count, gr.update(visible=count < MAX_REF_VIDEOS), gr.update(visible=count > 0)) + visibility_updates
|
| 251 |
+
|
| 252 |
+
def delete_ref_video_row(count):
|
| 253 |
+
count -= 1
|
| 254 |
+
video_clear_updates = [gr.update()] * MAX_REF_VIDEOS
|
| 255 |
+
if count >= 0:
|
| 256 |
+
video_clear_updates[count] = None
|
| 257 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_VIDEOS))
|
| 258 |
+
return (count, gr.update(visible=count < MAX_REF_VIDEOS), gr.update(visible=count > 0)) + visibility_updates + tuple(video_clear_updates)
|
| 259 |
+
|
| 260 |
+
add_ref_vid_outputs = [ref_video_count_state, add_ref_vid_btn, del_ref_vid_btn] + ref_video_groups
|
| 261 |
+
del_ref_vid_outputs = [ref_video_count_state, add_ref_vid_btn, del_ref_vid_btn] + ref_video_groups + ref_video_inputs
|
| 262 |
+
|
| 263 |
+
add_ref_vid_btn.click(
|
| 264 |
+
fn=add_ref_video_row,
|
| 265 |
+
inputs=[ref_video_count_state],
|
| 266 |
+
outputs=add_ref_vid_outputs,
|
| 267 |
+
show_progress=False,
|
| 268 |
+
api_name=False
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
del_ref_vid_btn.click(
|
| 272 |
+
fn=delete_ref_video_row,
|
| 273 |
+
inputs=[ref_video_count_state],
|
| 274 |
+
outputs=del_ref_vid_outputs,
|
| 275 |
+
show_progress=False,
|
| 276 |
+
api_name=False
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
ref_audio_count_state = components['ref_audio_count_state']
|
| 280 |
+
add_ref_aud_btn = components['add_ref_audio_button']
|
| 281 |
+
del_ref_aud_btn = components['delete_ref_audio_button']
|
| 282 |
+
ref_audio_groups = components['ref_audio_groups']
|
| 283 |
+
ref_audio_inputs = components['ref_audio_inputs']
|
| 284 |
+
|
| 285 |
+
def add_ref_audio_row(count):
|
| 286 |
+
count += 1
|
| 287 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_AUDIOS))
|
| 288 |
+
return (count, gr.update(visible=count < MAX_REF_AUDIOS), gr.update(visible=count > 0)) + visibility_updates
|
| 289 |
+
|
| 290 |
+
def delete_ref_audio_row(count):
|
| 291 |
+
count -= 1
|
| 292 |
+
audio_clear_updates = [gr.update()] * MAX_REF_AUDIOS
|
| 293 |
+
if count >= 0:
|
| 294 |
+
audio_clear_updates[count] = None
|
| 295 |
+
visibility_updates = tuple(gr.update(visible=i < count) for i in range(MAX_REF_AUDIOS))
|
| 296 |
+
return (count, gr.update(visible=count < MAX_REF_AUDIOS), gr.update(visible=count > 0)) + visibility_updates + tuple(audio_clear_updates)
|
| 297 |
+
|
| 298 |
+
add_ref_aud_outputs = [ref_audio_count_state, add_ref_aud_btn, del_ref_aud_btn] + ref_audio_groups
|
| 299 |
+
del_ref_aud_outputs = [ref_audio_count_state, add_ref_aud_btn, del_ref_aud_btn] + ref_audio_groups + ref_audio_inputs
|
| 300 |
+
|
| 301 |
+
add_ref_aud_btn.click(
|
| 302 |
+
fn=add_ref_audio_row,
|
| 303 |
+
inputs=[ref_audio_count_state],
|
| 304 |
+
outputs=add_ref_aud_outputs,
|
| 305 |
+
show_progress=False,
|
| 306 |
+
api_name=False
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
del_ref_aud_btn.click(
|
| 310 |
+
fn=delete_ref_audio_row,
|
| 311 |
+
inputs=[ref_audio_count_state],
|
| 312 |
+
outputs=del_ref_aud_outputs,
|
| 313 |
+
show_progress=False,
|
| 314 |
+
api_name=False
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
lora_sources = components.get('lora_sources_h3_ref2va', [])
|
| 318 |
+
lora_ids = components.get('lora_ids_h3_ref2va', [])
|
| 319 |
+
lora_scales = components.get('lora_scales_h3_ref2va', [])
|
| 320 |
+
|
| 321 |
+
cn_videos = components.get('h3_controlnet_videos_h3_ref2va', [])
|
| 322 |
+
cn_types = components.get('h3_controlnet_types_h3_ref2va', [])
|
| 323 |
+
cn_series = components.get('h3_controlnet_series_h3_ref2va', [])
|
| 324 |
+
cn_strengths = components.get('h3_controlnet_strengths_h3_ref2va', [])
|
| 325 |
+
cn_start_percents = components.get('h3_controlnet_start_percents_h3_ref2va', [])
|
| 326 |
+
cn_end_percents = components.get('h3_controlnet_end_percents_h3_ref2va', [])
|
| 327 |
+
cn_filepaths = components.get('h3_controlnet_filepaths_h3_ref2va', [])
|
| 328 |
+
|
| 329 |
+
guide_images = components.get('h3_guide_images_h3_ref2va', [])
|
| 330 |
+
guide_videos = components.get('h3_guide_videos_h3_ref2va', [])
|
| 331 |
+
guide_audios = components.get('h3_guide_audios_h3_ref2va', [])
|
| 332 |
+
guide_times = components.get('h3_guide_times_h3_ref2va', [])
|
| 333 |
+
guide_frames = components.get('h3_guide_frames_h3_ref2va', [])
|
| 334 |
+
|
| 335 |
+
inputs_list = [
|
| 336 |
+
components['prompt'],
|
| 337 |
+
components['resolution'],
|
| 338 |
+
components['aspect_ratio'],
|
| 339 |
+
components['width'],
|
| 340 |
+
components['height'],
|
| 341 |
+
components['duration'],
|
| 342 |
+
components['sampler'],
|
| 343 |
+
components['scheduler'],
|
| 344 |
+
components['steps'],
|
| 345 |
+
components['cfg_scale'],
|
| 346 |
+
components['seed'],
|
| 347 |
+
components['zero_gpu_duration']
|
| 348 |
+
] + ref_image_inputs + ref_video_inputs + ref_audio_inputs + lora_sources + lora_ids + lora_scales + cn_videos + cn_types + cn_series + cn_strengths + cn_start_percents + cn_end_percents + cn_filepaths + guide_images + guide_videos + guide_audios + guide_times + guide_frames
|
| 349 |
+
|
| 350 |
+
def on_run_click(*args, progress=gr.Progress(track_tqdm=True)):
|
| 351 |
+
prompt, resolution, aspect_ratio, width, height, duration, sampler, scheduler, steps, cfg_scale, seed, zero_gpu_duration = args[:12]
|
| 352 |
+
idx = 12
|
| 353 |
+
imgs = list(args[idx : idx + len(ref_image_inputs)])
|
| 354 |
+
idx += len(ref_image_inputs)
|
| 355 |
+
vids = list(args[idx : idx + len(ref_video_inputs)])
|
| 356 |
+
idx += len(ref_video_inputs)
|
| 357 |
+
auds = list(args[idx : idx + len(ref_audio_inputs)])
|
| 358 |
+
idx += len(ref_audio_inputs)
|
| 359 |
+
|
| 360 |
+
num_loras = len(lora_sources)
|
| 361 |
+
l_sources = args[idx : idx + num_loras]
|
| 362 |
+
l_ids = args[idx + num_loras : idx + 2*num_loras]
|
| 363 |
+
l_scales = args[idx + 2*num_loras : idx + 3*num_loras]
|
| 364 |
+
idx += 3 * num_loras
|
| 365 |
+
|
| 366 |
+
num_cns = len(cn_videos)
|
| 367 |
+
c_vids = args[idx : idx + num_cns]
|
| 368 |
+
c_types = args[idx + num_cns : idx + 2*num_cns]
|
| 369 |
+
c_series = args[idx + 2*num_cns : idx + 3*num_cns]
|
| 370 |
+
c_strengths = args[idx + 3*num_cns : idx + 4*num_cns]
|
| 371 |
+
c_starts = args[idx + 4*num_cns : idx + 5*num_cns]
|
| 372 |
+
c_ends = args[idx + 5*num_cns : idx + 6*num_cns]
|
| 373 |
+
c_fps = args[idx + 6*num_cns : idx + 7*num_cns]
|
| 374 |
+
idx += 7 * num_cns
|
| 375 |
+
|
| 376 |
+
num_guides = len(guide_images)
|
| 377 |
+
g_imgs = args[idx : idx + num_guides]
|
| 378 |
+
g_vids = args[idx + num_guides : idx + 2*num_guides]
|
| 379 |
+
g_auds = args[idx + 2*num_guides : idx + 3*num_guides]
|
| 380 |
+
g_times = args[idx + 3*num_guides : idx + 4*num_guides]
|
| 381 |
+
g_frames = args[idx + 4*num_guides : idx + 5*num_guides] if guide_frames else []
|
| 382 |
+
|
| 383 |
+
ui_values = {
|
| 384 |
+
'prompt': prompt,
|
| 385 |
+
'resolution': resolution,
|
| 386 |
+
'aspect_ratio': aspect_ratio,
|
| 387 |
+
'width': width,
|
| 388 |
+
'height': height,
|
| 389 |
+
'duration': duration,
|
| 390 |
+
'sampler_name': sampler,
|
| 391 |
+
'scheduler': scheduler,
|
| 392 |
+
'steps': steps,
|
| 393 |
+
'cfg_scale': cfg_scale,
|
| 394 |
+
'seed': seed,
|
| 395 |
+
'zero_gpu_duration': zero_gpu_duration,
|
| 396 |
+
'batch_count': 1,
|
| 397 |
+
'ref_images': imgs,
|
| 398 |
+
'ref_videos': vids,
|
| 399 |
+
'ref_audios': auds,
|
| 400 |
+
'lora_sources_h3_ref2va': list(l_sources),
|
| 401 |
+
'lora_ids_h3_ref2va': list(l_ids),
|
| 402 |
+
'lora_scales_h3_ref2va': list(l_scales),
|
| 403 |
+
'h3_controlnet_videos_h3_ref2va': list(c_vids),
|
| 404 |
+
'h3_controlnet_types_h3_ref2va': list(c_types),
|
| 405 |
+
'h3_controlnet_series_h3_ref2va': list(c_series),
|
| 406 |
+
'h3_controlnet_strengths_h3_ref2va': list(c_strengths),
|
| 407 |
+
'h3_controlnet_start_percents_h3_ref2va': list(c_starts),
|
| 408 |
+
'h3_controlnet_end_percents_h3_ref2va': list(c_ends),
|
| 409 |
+
'h3_controlnet_filepaths_h3_ref2va': list(c_fps),
|
| 410 |
+
'h3_guide_images_h3_ref2va': list(g_imgs),
|
| 411 |
+
'h3_guide_videos_h3_ref2va': list(g_vids),
|
| 412 |
+
'h3_guide_audios_h3_ref2va': list(g_auds),
|
| 413 |
+
'h3_guide_times_h3_ref2va': list(g_times),
|
| 414 |
+
'h3_guide_frames_h3_ref2va': list(g_frames),
|
| 415 |
+
}
|
| 416 |
+
return generate_h3_video_wrapper(process_inputs, ui_values, progress=progress)
|
| 417 |
+
|
| 418 |
+
components['run_button'].click(
|
| 419 |
+
fn=on_run_click,
|
| 420 |
+
inputs=inputs_list,
|
| 421 |
+
outputs=[components['output_video']],
|
| 422 |
+
api_name=False
|
| 423 |
+
)
|
ui/shared/ui_components.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES
|
| 3 |
+
from core.settings import (
|
| 4 |
+
MAX_LORAS, MAX_CONTROLNETS, MAX_H3_GUIDES, LORA_SOURCE_CHOICES, RESOLUTION_MAP, MODEL_DEFAULTS_CONFIG
|
| 5 |
+
)
|
| 6 |
+
from utils.app_utils import get_h3_cn_defaults
|
| 7 |
+
|
| 8 |
+
default_vals = MODEL_DEFAULTS_CONFIG.get('Default', {})
|
| 9 |
+
DEFAULT_STEPS = default_vals.get('steps', 20)
|
| 10 |
+
DEFAULT_CFG = default_vals.get('cfg', 5.0)
|
| 11 |
+
DEFAULT_SAMPLER = default_vals.get('sampler_name', 'euler')
|
| 12 |
+
DEFAULT_SCHEDULER = default_vals.get('scheduler', 'simple')
|
| 13 |
+
DEFAULT_POS_PROMPT = default_vals.get('positive_prompt', '')
|
| 14 |
+
DEFAULT_NEG_PROMPT = default_vals.get('negative_prompt', '')
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def create_base_parameter_ui(prefix, defaults=None):
|
| 18 |
+
if defaults is None:
|
| 19 |
+
defaults = {}
|
| 20 |
+
|
| 21 |
+
components = {}
|
| 22 |
+
|
| 23 |
+
with gr.Row():
|
| 24 |
+
components[f'aspect_ratio_{prefix}'] = gr.Dropdown(
|
| 25 |
+
label="Aspect Ratio",
|
| 26 |
+
choices=list(RESOLUTION_MAP.get('sdxl', {}).keys()),
|
| 27 |
+
value="1:1 (Square)",
|
| 28 |
+
interactive=True,
|
| 29 |
+
allow_custom_value=True
|
| 30 |
+
)
|
| 31 |
+
with gr.Row():
|
| 32 |
+
components[f'width_{prefix}'] = gr.Number(label="Width", value=defaults.get('w', 1024), interactive=True)
|
| 33 |
+
components[f'height_{prefix}'] = gr.Number(label="Height", value=defaults.get('h', 1024), interactive=True)
|
| 34 |
+
with gr.Row():
|
| 35 |
+
components[f'sampler_{prefix}'] = gr.Dropdown(
|
| 36 |
+
label="Sampler",
|
| 37 |
+
choices=SAMPLER_CHOICES,
|
| 38 |
+
value=DEFAULT_SAMPLER if DEFAULT_SAMPLER in SAMPLER_CHOICES else (SAMPLER_CHOICES[0] if SAMPLER_CHOICES else 'euler')
|
| 39 |
+
)
|
| 40 |
+
components[f'scheduler_{prefix}'] = gr.Dropdown(
|
| 41 |
+
label="Scheduler",
|
| 42 |
+
choices=SCHEDULER_CHOICES,
|
| 43 |
+
value=DEFAULT_SCHEDULER if DEFAULT_SCHEDULER in SCHEDULER_CHOICES else (SCHEDULER_CHOICES[0] if SCHEDULER_CHOICES else 'simple')
|
| 44 |
+
)
|
| 45 |
+
with gr.Row():
|
| 46 |
+
components[f'steps_{prefix}'] = gr.Slider(label="Steps", minimum=1, maximum=100, step=1, value=DEFAULT_STEPS)
|
| 47 |
+
components[f'cfg_{prefix}'] = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, step=0.1, value=DEFAULT_CFG)
|
| 48 |
+
with gr.Row():
|
| 49 |
+
components[f'seed_{prefix}'] = gr.Number(label="Seed (-1 for random)", value=-1, precision=0)
|
| 50 |
+
components[f'batch_size_{prefix}'] = gr.Slider(label="Batch Size", minimum=1, maximum=16, step=1, value=1)
|
| 51 |
+
with gr.Row():
|
| 52 |
+
components[f'guidance_{prefix}'] = gr.Slider(label="Guidance (FLUX)", minimum=1.0, maximum=10.0, step=0.1, value=3.5, visible=False, interactive=True)
|
| 53 |
+
components[f'zero_gpu_{prefix}'] = gr.Number(label="ZeroGPU Duration (s)", value=None, placeholder="Default: 60s, Max: 120s", info="Optional: Set how long to reserve the GPU.")
|
| 54 |
+
|
| 55 |
+
return components
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def create_lora_settings_ui(prefix: str):
|
| 59 |
+
components = {}
|
| 60 |
+
|
| 61 |
+
lora_rows, lora_sources, lora_ids, lora_scales, lora_uploads = [], [], [], [], []
|
| 62 |
+
|
| 63 |
+
with gr.Accordion("LoRA Settings", open=False, visible=True) as lora_accordion:
|
| 64 |
+
components[f'lora_accordion_{prefix}'] = lora_accordion
|
| 65 |
+
gr.Markdown("💡 **Tip:** When downloading from Civitai, please use the **Version ID**, not the Model ID. You can find the Version ID in the URL (e.g., `civitai.com/models/123?modelVersionId=456`) or under the model's download button. When downloading from Hugging Face, please use the format: `repo_id/filename.extension` or `repo_id/folder_path/filename.extension` (e.g., `Comfy-Org/MiniMax-H3/loras/minimax_h3_fl2v_turbo_4step_v1.0_768p_comfyui_bf16.safetensors` or `Comfy-Org/MiniMax-H3/loras/minimax_h3_ref2v_turbo_4step_v0.1_comfyui_bf16.safetensors`).")
|
| 66 |
+
components[f'lora_count_state_{prefix}'] = gr.State(1)
|
| 67 |
+
|
| 68 |
+
for i in range(MAX_LORAS):
|
| 69 |
+
with gr.Row(visible=i==0) as row:
|
| 70 |
+
source = gr.Dropdown(label=f"LoRA Source {i+1}", choices=LORA_SOURCE_CHOICES, value=LORA_SOURCE_CHOICES[0], scale=1)
|
| 71 |
+
lora_id = gr.Textbox(label="Civitai Version ID / HF file / Upload File", scale=2, type="text")
|
| 72 |
+
scale = gr.Slider(label=f"Scale", minimum=0.0, maximum=2.0, step=0.05, value=1.0, scale=1)
|
| 73 |
+
upload = gr.UploadButton(label="Upload", file_types=[".safetensors"], scale=1)
|
| 74 |
+
|
| 75 |
+
lora_rows.append(row)
|
| 76 |
+
lora_sources.append(source)
|
| 77 |
+
lora_ids.append(lora_id)
|
| 78 |
+
lora_scales.append(scale)
|
| 79 |
+
lora_uploads.append(upload)
|
| 80 |
+
|
| 81 |
+
with gr.Row():
|
| 82 |
+
components[f'add_lora_button_{prefix}'] = gr.Button("Add LoRA", variant="secondary")
|
| 83 |
+
components[f'delete_lora_button_{prefix}'] = gr.Button("Remove LoRA", variant="secondary", visible=False)
|
| 84 |
+
|
| 85 |
+
components[f'lora_rows_{prefix}'] = lora_rows
|
| 86 |
+
components[f'lora_sources_{prefix}'] = lora_sources
|
| 87 |
+
components[f'lora_ids_{prefix}'] = lora_ids
|
| 88 |
+
components[f'lora_scales_{prefix}'] = lora_scales
|
| 89 |
+
components[f'lora_uploads_{prefix}'] = lora_uploads
|
| 90 |
+
|
| 91 |
+
all_lora_components_flat = []
|
| 92 |
+
for i in range(MAX_LORAS):
|
| 93 |
+
all_lora_components_flat.extend([lora_sources[i], lora_ids[i], lora_scales[i], lora_uploads[i]])
|
| 94 |
+
components[f'all_lora_components_flat_{prefix}'] = all_lora_components_flat
|
| 95 |
+
|
| 96 |
+
return components
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def create_h3_guide_ui(prefix: str, max_units=MAX_H3_GUIDES):
|
| 100 |
+
components = {}
|
| 101 |
+
key = lambda name: f"{name}_{prefix}"
|
| 102 |
+
|
| 103 |
+
with gr.Accordion("Keyframe Guide Settings", open=False, visible=True) as accordion:
|
| 104 |
+
components[key('h3_guide_accordion')] = accordion
|
| 105 |
+
gr.Markdown(
|
| 106 |
+
"💡 **Tip:** You can anchor keyframe guides (image, video clip, or audio) "
|
| 107 |
+
"at arbitrary positions along the continuous timeline (not limited to first/last frames). "
|
| 108 |
+
"Specify the position via **Time (seconds)**."
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
guide_rows = []
|
| 112 |
+
images = []
|
| 113 |
+
videos = []
|
| 114 |
+
audios = []
|
| 115 |
+
times = []
|
| 116 |
+
frames = []
|
| 117 |
+
|
| 118 |
+
components.update({
|
| 119 |
+
key('h3_guide_rows'): guide_rows,
|
| 120 |
+
key('h3_guide_images'): images,
|
| 121 |
+
key('h3_guide_videos'): videos,
|
| 122 |
+
key('h3_guide_audios'): audios,
|
| 123 |
+
key('h3_guide_times'): times,
|
| 124 |
+
key('h3_guide_frames'): frames,
|
| 125 |
+
})
|
| 126 |
+
|
| 127 |
+
for i in range(max_units):
|
| 128 |
+
with gr.Row(visible=(i < 1)) as row:
|
| 129 |
+
with gr.Column(scale=1):
|
| 130 |
+
images.append(gr.Image(label=f"Guide Image {i+1}", type="pil", sources=["upload"], height=200))
|
| 131 |
+
with gr.Column(scale=1):
|
| 132 |
+
videos.append(gr.Video(label=f"Guide Video (Opt) {i+1}", sources=["upload"], height=200))
|
| 133 |
+
with gr.Column(scale=1):
|
| 134 |
+
audios.append(gr.Audio(label=f"Guide Audio (Opt) {i+1}", sources=["upload"], type="filepath"))
|
| 135 |
+
times.append(gr.Slider(label=f"Time (s) {i+1}", minimum=0.0, maximum=15.0, step=0.5, value=float(i * 1.5), interactive=True))
|
| 136 |
+
guide_rows.append(row)
|
| 137 |
+
|
| 138 |
+
with gr.Row():
|
| 139 |
+
components[key('add_h3_guide_button')] = gr.Button("✚ Add Guide", variant="secondary")
|
| 140 |
+
components[key('delete_h3_guide_button')] = gr.Button("➖ Delete Guide", variant="secondary", visible=False)
|
| 141 |
+
components[key('h3_guide_count_state')] = gr.State(1)
|
| 142 |
+
|
| 143 |
+
all_guide_components_flat = []
|
| 144 |
+
for i in range(max_units):
|
| 145 |
+
all_guide_components_flat.extend([
|
| 146 |
+
images[i], videos[i], audios[i], times[i]
|
| 147 |
+
])
|
| 148 |
+
components[key('all_h3_guide_components_flat')] = all_guide_components_flat
|
| 149 |
+
|
| 150 |
+
return components
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def create_h3_controlnet_ui(prefix: str, max_units=MAX_CONTROLNETS):
|
| 154 |
+
components = {}
|
| 155 |
+
key = lambda name: f"{name}_{prefix}"
|
| 156 |
+
|
| 157 |
+
default_types, default_type, default_series, default_serie, default_fp = get_h3_cn_defaults()
|
| 158 |
+
|
| 159 |
+
with gr.Accordion("H3 ControlNet Settings", open=False, visible=True) as accordion:
|
| 160 |
+
components[key('h3_controlnet_accordion')] = accordion
|
| 161 |
+
gr.Markdown(
|
| 162 |
+
"💡 **Tip:** This feature does not perform preprocessing on uploaded videos. "
|
| 163 |
+
"Please upload the corresponding preprocessed control video (e.g., Canny edges, Depth, Pose) rather than raw/unprocessed video footage."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
cn_rows, videos, series, types, strengths, start_percents, end_percents, filepaths = [], [], [], [], [], [], [], []
|
| 167 |
+
components.update({
|
| 168 |
+
key('h3_controlnet_rows'): cn_rows,
|
| 169 |
+
key('h3_controlnet_videos'): videos,
|
| 170 |
+
key('h3_controlnet_series'): series,
|
| 171 |
+
key('h3_controlnet_types'): types,
|
| 172 |
+
key('h3_controlnet_strengths'): strengths,
|
| 173 |
+
key('h3_controlnet_start_percents'): start_percents,
|
| 174 |
+
key('h3_controlnet_end_percents'): end_percents,
|
| 175 |
+
key('h3_controlnet_filepaths'): filepaths,
|
| 176 |
+
})
|
| 177 |
+
|
| 178 |
+
for i in range(max_units):
|
| 179 |
+
with gr.Row(visible=(i < 1)) as row:
|
| 180 |
+
with gr.Column(scale=1):
|
| 181 |
+
videos.append(gr.Video(label=f"Control Video {i+1}", sources=["upload"], height=220))
|
| 182 |
+
with gr.Column(scale=2):
|
| 183 |
+
types.append(gr.Dropdown(label="Type", choices=default_types, value=default_type, interactive=True, allow_custom_value=True))
|
| 184 |
+
series.append(gr.Dropdown(label="Series", choices=default_series, value=default_serie, interactive=True, allow_custom_value=True))
|
| 185 |
+
strengths.append(gr.Slider(label="Strength", minimum=0.0, maximum=2.0, step=0.05, value=1.0, interactive=True))
|
| 186 |
+
start_percents.append(gr.State(0.0))
|
| 187 |
+
end_percents.append(gr.State(1.0))
|
| 188 |
+
filepaths.append(gr.State(default_fp))
|
| 189 |
+
cn_rows.append(row)
|
| 190 |
+
|
| 191 |
+
with gr.Row():
|
| 192 |
+
components[key('add_h3_controlnet_button')] = gr.Button("✚ Add H3 ControlNet", variant="secondary")
|
| 193 |
+
components[key('delete_h3_controlnet_button')] = gr.Button("➖ Delete H3 ControlNet", variant="secondary", visible=False)
|
| 194 |
+
components[key('h3_controlnet_count_state')] = gr.State(1)
|
| 195 |
+
|
| 196 |
+
all_cn_components_flat = []
|
| 197 |
+
for i in range(max_units):
|
| 198 |
+
all_cn_components_flat.extend([
|
| 199 |
+
videos[i], types[i], series[i], strengths[i], start_percents[i], end_percents[i], filepaths[i]
|
| 200 |
+
])
|
| 201 |
+
components[key('all_h3_controlnet_components_flat')] = all_cn_components_flat
|
| 202 |
+
|
| 203 |
+
return components
|