Spaces:
Running on Zero
Running on Zero
Strip to the I2VA/FLF2VA path with a single generate_video API
Browse filesDrop T2VA, REF2VA, keyframe guides, ControlNet, LoRA chains, the MCP tool
server and the YAML recipe/injector framework. One app.py builds the
MiniMaxH3ImageToVideo graph directly, declares a per-job ZeroGPU budget
(mirrored in protocol-generator), and persists finished videos to the
igitagoz/h3-job-outputs dataset keyed by job_id. ComfyUI is pinned to
c75d8c9 and requirements.txt carries that commit's own pins.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitignore +1 -16
- README.md +82 -20
- app.py +613 -94
- chain_injectors/__init__.py +0 -50
- chain_injectors/h3_controlnet_injector.py +0 -115
- chain_injectors/h3_guide_injector.py +0 -152
- chain_injectors/h3_ref_audio_injector.py +0 -27
- chain_injectors/h3_ref_img_injector.py +0 -35
- chain_injectors/h3_ref_video_injector.py +0 -32
- chain_injectors/lora_injector.py +0 -76
- comfy_integration/__init__.py +0 -0
- comfy_integration/nodes.py +0 -44
- comfy_integration/setup.py +0 -63
- core/__init__.py +0 -0
- core/generation_logic.py +0 -131
- core/model_manager.py +0 -32
- core/pipelines/__init__.py +0 -0
- core/pipelines/base_pipeline.py +0 -55
- core/pipelines/pipeline_input_processor.py +0 -36
- core/pipelines/workflow_executor.py +0 -125
- core/settings.py +0 -134
- core/shared_state.py +0 -1
- core/workflow_assembler.py +0 -202
- mcp_tools/__init__.py +0 -41
- mcp_tools/common.py +0 -610
- mcp_tools/error_schema.py +0 -85
- mcp_tools/get_task_list.py +0 -11
- mcp_tools/get_task_status.py +0 -21
- mcp_tools/mcp_gradio_integration.py +0 -122
- mcp_tools/run.py +0 -94
- mcp_tools/tool_handlers.py +0 -19
- requirements.txt +45 -43
- tests/test_h3_guide.py +0 -373
- ui/__init__.py +0 -0
- ui/events/__init__.py +0 -1
- ui/events/chain_handlers.py +0 -222
- ui/events/main.py +0 -22
- ui/h3_logic.py +0 -198
- ui/h3_ui.py +0 -443
- ui/layout.py +0 -42
- ui/shared/h3_fl2va_logic.py +0 -138
- ui/shared/h3_fl2va_recipe.yaml +0 -157
- ui/shared/h3_fl2va_ui.py +0 -235
- ui/shared/h3_ref2va_logic.py +0 -137
- ui/shared/h3_ref2va_recipe.yaml +0 -172
- ui/shared/h3_ref2va_ui.py +0 -423
- ui/shared/ui_components.py +0 -203
- utils/__init__.py +0 -0
- utils/app_utils.py +0 -805
- workflow_recipes/h3_fl2va_recipe.yaml +0 -194
.gitignore
CHANGED
|
@@ -1,18 +1,3 @@
|
|
|
|
|
| 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 |
-
|
|
|
|
| 1 |
+
ComfyUI/
|
| 2 |
__pycache__/
|
| 3 |
*.py[cod]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
CHANGED
|
@@ -1,20 +1,82 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: MiniMax-H3
|
| 3 |
-
emoji: 🎬
|
| 4 |
-
colorFrom: purple
|
| 5 |
-
colorTo: red
|
| 6 |
-
sdk: gradio
|
| 7 |
-
|
| 8 |
-
python_version: 3.12
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: MiniMax-H3
|
| 3 |
+
emoji: 🎬
|
| 4 |
+
colorFrom: purple
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.27.0
|
| 8 |
+
python_version: '3.12'
|
| 9 |
+
app_file: app.py
|
| 10 |
+
startup_duration_timeout: 1h
|
| 11 |
+
short_description: MiniMax-H3 I2V / FLF2V with native audio (ZeroGPU)
|
| 12 |
+
models:
|
| 13 |
+
- Comfy-Org/MiniMax-H3
|
| 14 |
+
- lilcheaty/MiniMax-H3-NVFP4
|
| 15 |
+
- MiniMaxAI/MiniMax-H3
|
| 16 |
+
---
|
| 17 |
+
|
| 18 |
+
# MiniMax-H3 · I2V (`igitagoz`)
|
| 19 |
+
|
| 20 |
+
Stripped-down fork of [RioShiina/MiniMax-H3](https://huggingface.co/spaces/RioShiina/MiniMax-H3)
|
| 21 |
+
for [protocol-generator](https://github.com/): **only the image-to-video path**
|
| 22 |
+
(I2VA with a start frame, FLF2VA when a last frame is also given), run through
|
| 23 |
+
ComfyUI's `MiniMaxH3ImageToVideo` node on the NVFP4-pruned FL2VA checkpoint.
|
| 24 |
+
Output is an mp4 with H3's native audio track.
|
| 25 |
+
|
| 26 |
+
Dropped from upstream: T2VA (no image), REF2VA (reference images / videos /
|
| 27 |
+
audio), the timeline keyframe guide, ControlNet, LoRA chains, the MCP tool
|
| 28 |
+
server and the YAML recipe / injector framework. Everything lives in `app.py`.
|
| 29 |
+
|
| 30 |
+
## App API
|
| 31 |
+
|
| 32 |
+
Named endpoint: **`generate_video`**
|
| 33 |
+
|
| 34 |
+
Positional inputs (after the uploaded start image):
|
| 35 |
+
|
| 36 |
+
| # | name | notes |
|
| 37 |
+
|---|---|---|
|
| 38 |
+
| 1 | last_frame | optional last-frame keyframe (FLF2VA); `null` for plain I2VA |
|
| 39 |
+
| 2 | prompt | |
|
| 40 |
+
| 3 | max_dim | longest side in px; short side follows the start image's AR, snapped to 32 |
|
| 41 |
+
| 4 | seconds | clip length at 24 fps, snapped up to the 17k+5 frame grid (5s → 124 frames) |
|
| 42 |
+
| 5 | steps | sampling steps (res_multistep / simple) |
|
| 43 |
+
| 6 | seed | |
|
| 44 |
+
| 7 | randomize_seed | |
|
| 45 |
+
| 8 | job_id | durable dataset key |
|
| 46 |
+
|
| 47 |
+
Outputs: `[video, used_seed, job_id, duration_ms]`.
|
| 48 |
+
|
| 49 |
+
## ZeroGPU budget
|
| 50 |
+
|
| 51 |
+
`estimate_gpu_seconds(width, height, frames, steps)` is declared to `@spaces.GPU`
|
| 52 |
+
per job and mirrored in the app (`estimateH3SpaceAllocSecs` in
|
| 53 |
+
`src/shared/pipelineCost.ts`). Keep the two in lockstep — the declaration is also
|
| 54 |
+
ZeroGPU's kill timeout. Jobs whose estimate exceeds `MAX_GPU_SECONDS` (1800) are
|
| 55 |
+
refused up front instead of being killed mid-run with the quota billed.
|
| 56 |
+
|
| 57 |
+
The formula is anchored on upstream's note that 960×544 / 20 steps / 5s finishes
|
| 58 |
+
inside its 120s default; the app calibrates the *cost* figure from measured jobs,
|
| 59 |
+
but the Space-side constants only change by editing `app.py`.
|
| 60 |
+
|
| 61 |
+
`H3_PRELOAD_MODELS=1` (Space variable) loads the four checkpoints into CPU RAM at
|
| 62 |
+
startup so the GPU worker inherits them instead of re-reading ~34 GB from disk
|
| 63 |
+
inside every job's GPU window. Off by default — untested on this hardware tier.
|
| 64 |
+
|
| 65 |
+
## Durable outputs
|
| 66 |
+
|
| 67 |
+
When `job_id` is set and Space secret `HF_TOKEN` has write access, the finished
|
| 68 |
+
`{job_id}.mp4` (+ `{job_id}.json`) are uploaded to dataset
|
| 69 |
+
`igitagoz/h3-job-outputs` (override with `H3_JOB_DATASET`).
|
| 70 |
+
|
| 71 |
+
## Models
|
| 72 |
+
|
| 73 |
+
| role | file | repo |
|
| 74 |
+
|---|---|---|
|
| 75 |
+
| diffusion model | `minimax_h3_fl2va_pruned_nvfp4.safetensors` (12.5 GB) | `lilcheaty/MiniMax-H3-NVFP4` |
|
| 76 |
+
| text encoder | `qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors` (15.7 GB) | `Comfy-Org/MiniMax-H3` |
|
| 77 |
+
| video VAE | `minimax_h3_video_vae_fp16.safetensors` (5.2 GB) | `Comfy-Org/MiniMax-H3` |
|
| 78 |
+
| audio VAE | `minimax_h3_audio_vae_fp32.safetensors` (0.6 GB) | `Comfy-Org/MiniMax-H3` |
|
| 79 |
+
|
| 80 |
+
ComfyUI is cloned at startup and pinned to `COMFYUI_COMMIT` in `app.py`;
|
| 81 |
+
`requirements.txt` carries that commit's own requirements so no runtime pip step
|
| 82 |
+
is needed.
|
app.py
CHANGED
|
@@ -1,94 +1,613 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""MiniMax-H3 image-to-video (I2VA / FLF2VA) — slim ZeroGPU Space for protocol-generator.
|
| 2 |
+
|
| 3 |
+
Stripped from RioShiina/MiniMax-H3: one Gradio endpoint (`generate_video`) that runs
|
| 4 |
+
ComfyUI's `MiniMaxH3ImageToVideo` graph on the NVFP4-pruned FL2VA checkpoint. A start
|
| 5 |
+
frame is required; an optional last frame turns the job into FLF2VA. No T2VA, REF2VA,
|
| 6 |
+
keyframe guides, ControlNet, LoRA chains or MCP server — see README.md.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import spaces # noqa: F401 — must be imported before torch (ZeroGPU patches CUDA)
|
| 10 |
+
|
| 11 |
+
import asyncio
|
| 12 |
+
import glob
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
+
import os
|
| 16 |
+
import pathlib
|
| 17 |
+
import random
|
| 18 |
+
import shutil
|
| 19 |
+
import subprocess
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
import uuid
|
| 23 |
+
from typing import Any
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
from huggingface_hub import HfApi, hf_hub_download
|
| 27 |
+
from PIL import Image, ImageOps
|
| 28 |
+
|
| 29 |
+
# ── Paths / pins ─────────────────────────────────────────────────────────────
|
| 30 |
+
|
| 31 |
+
APP_DIR = pathlib.Path(__file__).resolve().parent
|
| 32 |
+
COMFY = APP_DIR / "ComfyUI"
|
| 33 |
+
COMFY_MODELS = COMFY / "models"
|
| 34 |
+
COMFY_INPUT = COMFY / "input"
|
| 35 |
+
COMFY_OUTPUT = COMFY / "output"
|
| 36 |
+
|
| 37 |
+
# ComfyUI master on 2026-09-12; requirements.txt mirrors this commit's own pins.
|
| 38 |
+
COMFYUI_COMMIT = os.environ.get("COMFYUI_COMMIT", "c75d8c966c29cb0392259af791f43373315b72db")
|
| 39 |
+
|
| 40 |
+
# (models/<subdir>, local filename, HF repo, path in repo)
|
| 41 |
+
DOWNLOADS = [
|
| 42 |
+
("diffusion_models", "minimax_h3_fl2va_pruned_nvfp4.safetensors",
|
| 43 |
+
"lilcheaty/MiniMax-H3-NVFP4", "minimax_h3_fl2va_pruned_nvfp4.safetensors"),
|
| 44 |
+
("text_encoders", "qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors",
|
| 45 |
+
"Comfy-Org/MiniMax-H3", "text_encoders/qwen3vl_32b_minimax_h3_nvfp4_awq.safetensors"),
|
| 46 |
+
("vae", "minimax_h3_video_vae_fp16.safetensors",
|
| 47 |
+
"Comfy-Org/MiniMax-H3", "vae/minimax_h3_video_vae_fp16.safetensors"),
|
| 48 |
+
("vae", "minimax_h3_audio_vae_fp32.safetensors",
|
| 49 |
+
"Comfy-Org/MiniMax-H3", "vae/minimax_h3_audio_vae_fp32.safetensors"),
|
| 50 |
+
]
|
| 51 |
+
UNET_NAME = DOWNLOADS[0][1]
|
| 52 |
+
CLIP_NAME = DOWNLOADS[1][1]
|
| 53 |
+
VIDEO_VAE_NAME = DOWNLOADS[2][1]
|
| 54 |
+
AUDIO_VAE_NAME = DOWNLOADS[3][1]
|
| 55 |
+
|
| 56 |
+
# Override with Space secret/variable H3_JOB_DATASET. Requires HF_TOKEN (write) on the Space.
|
| 57 |
+
H3_JOB_DATASET = os.environ.get("H3_JOB_DATASET", "igitagoz/h3-job-outputs").strip()
|
| 58 |
+
|
| 59 |
+
# Load the checkpoints into CPU RAM once at startup so the forked GPU worker inherits
|
| 60 |
+
# them instead of re-reading ~34 GB from disk inside every job's GPU window.
|
| 61 |
+
# Opt-in: untested on the ZeroGPU tier this Space runs on.
|
| 62 |
+
PRELOAD_MODELS = os.environ.get("H3_PRELOAD_MODELS", "0").strip() in ("1", "true", "yes")
|
| 63 |
+
|
| 64 |
+
# ── Model geometry (mirrored in src/shared/pipelineCost.ts — keep in lockstep) ──
|
| 65 |
+
|
| 66 |
+
FPS = 24
|
| 67 |
+
CANVAS_MULTIPLE = 32
|
| 68 |
+
MIN_SECONDS = 1.0
|
| 69 |
+
MAX_SECONDS = 15.0
|
| 70 |
+
MIN_STEPS = 1
|
| 71 |
+
MAX_STEPS = 50
|
| 72 |
+
MIN_MAX_DIM = 256
|
| 73 |
+
MAX_MAX_DIM = 1920
|
| 74 |
+
|
| 75 |
+
# ZeroGPU declaration = kill timeout. Anchored on upstream's note that 960×544 /
|
| 76 |
+
# 20 steps / 5s completes inside its 120s default, then padded (model load happens
|
| 77 |
+
# inside the GPU window). The app fits a residual on top for the *cost* figure.
|
| 78 |
+
MIN_GPU_SECONDS = int(os.environ.get("MIN_GPU_SECONDS", "60"))
|
| 79 |
+
MAX_GPU_SECONDS = int(os.environ.get("MAX_GPU_SECONDS", "1800"))
|
| 80 |
+
H3_REF_WORK = 960 * 544 * 124
|
| 81 |
+
H3_BASE_SECS = 40.0
|
| 82 |
+
H3_PER_STEP_SECS = 5.0
|
| 83 |
+
H3_WORK_EXPONENT = 1.3
|
| 84 |
+
H3_SAFETY = 1.25
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def frame_count(seconds: float) -> int:
|
| 88 |
+
"""24 fps frame count snapped *up* to the model's 17k+5 grid: 5, 22, …, 124 (≈5s), 362 (≈15s)."""
|
| 89 |
+
raw = int(round(float(seconds) * FPS))
|
| 90 |
+
if raw <= 5:
|
| 91 |
+
return 5
|
| 92 |
+
return 5 + 17 * math.ceil((raw - 5) / 17)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def fit_canvas(image_w: int, image_h: int, max_dim: int) -> tuple[int, int]:
|
| 96 |
+
"""Longest side = max_dim, short side follows the input aspect ratio, both snapped to 32."""
|
| 97 |
+
long_side = max(CANVAS_MULTIPLE, int(max_dim))
|
| 98 |
+
scale = long_side / max(image_w, image_h)
|
| 99 |
+
|
| 100 |
+
def snap(v: float) -> int:
|
| 101 |
+
return max(CANVAS_MULTIPLE, round(v * scale / CANVAS_MULTIPLE) * CANVAS_MULTIPLE)
|
| 102 |
+
|
| 103 |
+
return snap(image_w), snap(image_h)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def estimate_gpu_seconds(width: int, height: int, frames: int, steps: int) -> int:
|
| 107 |
+
work = (width * height * frames) / H3_REF_WORK
|
| 108 |
+
est = (H3_BASE_SECS + H3_PER_STEP_SECS * steps * work ** H3_WORK_EXPONENT) * H3_SAFETY
|
| 109 |
+
return max(MIN_GPU_SECONDS, int(math.ceil(est)))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ── SageAttention (optional; wheel from RioShiina's ZeroGPU build) ───────────
|
| 113 |
+
|
| 114 |
+
if "--use-sage-attention" not in sys.argv:
|
| 115 |
+
sys.argv.append("--use-sage-attention")
|
| 116 |
+
|
| 117 |
+
_sage_patched = False
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def apply_sage_attention_patch() -> str:
|
| 121 |
+
global _sage_patched
|
| 122 |
+
if _sage_patched:
|
| 123 |
+
return "sage attention already enabled"
|
| 124 |
+
try:
|
| 125 |
+
from comfy import model_management
|
| 126 |
+
import sageattention # noqa: F401
|
| 127 |
+
|
| 128 |
+
model_management.sage_attention_enabled = lambda: True
|
| 129 |
+
model_management.pytorch_attention_enabled = lambda: False
|
| 130 |
+
_sage_patched = True
|
| 131 |
+
return "sage attention enabled"
|
| 132 |
+
except ImportError:
|
| 133 |
+
return "sageattention not installed — default attention"
|
| 134 |
+
except Exception as exc: # pragma: no cover
|
| 135 |
+
return f"sage attention patch failed: {exc}"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# ── ComfyUI bootstrap ────────────────────────────────────────────────────────
|
| 139 |
+
|
| 140 |
+
def _run(cmd: list[str], cwd: pathlib.Path | None = None, check: bool = True) -> None:
|
| 141 |
+
print(f"[setup] $ {' '.join(cmd)}", flush=True)
|
| 142 |
+
subprocess.run(cmd, cwd=str(cwd) if cwd else None, check=check)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def ensure_comfy() -> None:
|
| 146 |
+
if not COMFY.exists():
|
| 147 |
+
_run(["git", "clone", "--depth", "1", "https://github.com/comfyanonymous/ComfyUI.git", str(COMFY)])
|
| 148 |
+
_run(["git", "fetch", "--depth", "1", "origin", COMFYUI_COMMIT], cwd=COMFY, check=False)
|
| 149 |
+
_run(["git", "checkout", COMFYUI_COMMIT], cwd=COMFY, check=False)
|
| 150 |
+
for sub in {d[0] for d in DOWNLOADS}:
|
| 151 |
+
(COMFY_MODELS / sub).mkdir(parents=True, exist_ok=True)
|
| 152 |
+
COMFY_INPUT.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
COMFY_OUTPUT.mkdir(parents=True, exist_ok=True)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def ensure_models(progress: gr.Progress | None = None) -> None:
|
| 157 |
+
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
| 158 |
+
for index, (sub, name, repo, repo_path) in enumerate(DOWNLOADS):
|
| 159 |
+
dest = COMFY_MODELS / sub / name
|
| 160 |
+
if dest.is_symlink() and not dest.exists():
|
| 161 |
+
dest.unlink()
|
| 162 |
+
if dest.exists():
|
| 163 |
+
continue
|
| 164 |
+
if progress:
|
| 165 |
+
progress(index / len(DOWNLOADS), desc=f"downloading {name}")
|
| 166 |
+
print(f"[setup] downloading {repo}/{repo_path}", flush=True)
|
| 167 |
+
cached = hf_hub_download(repo_id=repo, filename=repo_path, token=token)
|
| 168 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 169 |
+
os.symlink(cached, dest)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
_nodes_ready = False
|
| 173 |
+
NODE_CLASS_MAPPINGS: dict[str, Any] = {}
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def init_comfy_nodes() -> None:
|
| 177 |
+
"""Import ComfyUI in-process (cwd = ComfyUI/ so folder_paths resolves models/, input/, output/)."""
|
| 178 |
+
global _nodes_ready, NODE_CLASS_MAPPINGS
|
| 179 |
+
if _nodes_ready:
|
| 180 |
+
return
|
| 181 |
+
comfy_path = str(COMFY)
|
| 182 |
+
sys.path = [p for p in sys.path if p != comfy_path]
|
| 183 |
+
sys.path.insert(0, comfy_path)
|
| 184 |
+
for module_name in list(sys.modules):
|
| 185 |
+
if module_name == "utils" or module_name.startswith("utils."):
|
| 186 |
+
del sys.modules[module_name]
|
| 187 |
+
os.chdir(COMFY)
|
| 188 |
+
|
| 189 |
+
import execution
|
| 190 |
+
import nodes
|
| 191 |
+
import server
|
| 192 |
+
|
| 193 |
+
loop = asyncio.new_event_loop()
|
| 194 |
+
asyncio.set_event_loop(loop)
|
| 195 |
+
server_instance = server.PromptServer(loop)
|
| 196 |
+
execution.PromptQueue(server_instance)
|
| 197 |
+
loop.run_until_complete(nodes.init_extra_nodes())
|
| 198 |
+
NODE_CLASS_MAPPINGS = nodes.NODE_CLASS_MAPPINGS
|
| 199 |
+
for required in ("MiniMaxH3ImageToVideo", "VAEDecodeAudio", "CreateVideo", "SaveVideo"):
|
| 200 |
+
if required not in NODE_CLASS_MAPPINGS:
|
| 201 |
+
raise RuntimeError(f"ComfyUI @ {COMFYUI_COMMIT} has no '{required}' node")
|
| 202 |
+
_nodes_ready = True
|
| 203 |
+
print("[setup] ComfyUI nodes ready", flush=True)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
# ── Workflow (the FL2VA recipe, inlined) ────────────────────────────────────
|
| 207 |
+
|
| 208 |
+
class _DummyHidden:
|
| 209 |
+
extra_pnginfo = None
|
| 210 |
+
prompt = None
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def node_template(class_type: str) -> dict[str, Any]:
|
| 214 |
+
"""Node dict pre-filled with every input's declared default, like the ComfyUI API format."""
|
| 215 |
+
if class_type not in NODE_CLASS_MAPPINGS:
|
| 216 |
+
raise ValueError(f"node class '{class_type}' not found")
|
| 217 |
+
node_class = NODE_CLASS_MAPPINGS[class_type]
|
| 218 |
+
input_types = node_class.INPUT_TYPES()
|
| 219 |
+
inputs: dict[str, Any] = {}
|
| 220 |
+
for name, details in {**input_types.get("required", {}), **input_types.get("optional", {})}.items():
|
| 221 |
+
config = details[1] if len(details) > 1 and isinstance(details[1], dict) else {}
|
| 222 |
+
inputs[name] = config.get("default")
|
| 223 |
+
return {"inputs": inputs, "class_type": class_type, "_meta": {"title": class_type}}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def build_workflow(
|
| 227 |
+
*,
|
| 228 |
+
prompt: str,
|
| 229 |
+
width: int,
|
| 230 |
+
height: int,
|
| 231 |
+
frames: int,
|
| 232 |
+
steps: int,
|
| 233 |
+
seed: int,
|
| 234 |
+
first_frame_name: str,
|
| 235 |
+
last_frame_name: str | None,
|
| 236 |
+
filename_prefix: str,
|
| 237 |
+
) -> dict[str, Any]:
|
| 238 |
+
wf: dict[str, Any] = {}
|
| 239 |
+
|
| 240 |
+
def add(node_id: str, class_type: str, title: str, **inputs: Any) -> str:
|
| 241 |
+
node = node_template(class_type)
|
| 242 |
+
node["_meta"]["title"] = title
|
| 243 |
+
node["inputs"].update(inputs)
|
| 244 |
+
wf[node_id] = node
|
| 245 |
+
return node_id
|
| 246 |
+
|
| 247 |
+
add("unet", "UNETLoader", "Load Diffusion Model", unet_name=UNET_NAME, weight_dtype="default")
|
| 248 |
+
add("clip", "CLIPLoader", "Load CLIP", clip_name=CLIP_NAME, type="minimax", device="default")
|
| 249 |
+
add("vvae", "VAELoader", "Load Video VAE", vae_name=VIDEO_VAE_NAME)
|
| 250 |
+
add("avae", "VAELoader", "Load Audio VAE", vae_name=AUDIO_VAE_NAME)
|
| 251 |
+
|
| 252 |
+
add("ff_load", "LoadImage", "Load First Frame", image=first_frame_name)
|
| 253 |
+
add("ff_scale", "ImageScale", "Scale First Frame", image=["ff_load", 0],
|
| 254 |
+
upscale_method="nearest-exact", width=width, height=height, crop="center")
|
| 255 |
+
h3_inputs: dict[str, Any] = dict(
|
| 256 |
+
clip=["clip", 0], vae=["vvae", 0], prompt=prompt,
|
| 257 |
+
width=width, height=height, length=frames, first_frame=["ff_scale", 0],
|
| 258 |
+
)
|
| 259 |
+
if last_frame_name:
|
| 260 |
+
add("lf_load", "LoadImage", "Load Last Frame", image=last_frame_name)
|
| 261 |
+
add("lf_scale", "ImageScale", "Scale Last Frame", image=["lf_load", 0],
|
| 262 |
+
upscale_method="nearest-exact", width=width, height=height, crop="center")
|
| 263 |
+
h3_inputs["last_frame"] = ["lf_scale", 0]
|
| 264 |
+
add("h3", "MiniMaxH3ImageToVideo", "MiniMax H3 Image to Video", **h3_inputs)
|
| 265 |
+
|
| 266 |
+
add("guider", "BasicGuider", "Basic Guider", model=["unet", 0], conditioning=["h3", 0])
|
| 267 |
+
add("sampler", "KSamplerSelect", "KSamplerSelect", sampler_name="res_multistep")
|
| 268 |
+
add("sigmas", "BasicScheduler", "BasicScheduler", model=["unet", 0],
|
| 269 |
+
scheduler="simple", steps=steps, denoise=1.0)
|
| 270 |
+
add("noise", "RandomNoise", "RandomNoise", noise_seed=seed)
|
| 271 |
+
add("sample", "SamplerCustomAdvanced", "SamplerCustomAdvanced", noise=["noise", 0],
|
| 272 |
+
guider=["guider", 0], sampler=["sampler", 0], sigmas=["sigmas", 0], latent_image=["h3", 1])
|
| 273 |
+
add("vdec", "VAEDecode", "VAE Decode", samples=["sample", 0], vae=["vvae", 0])
|
| 274 |
+
add("adec", "VAEDecodeAudio", "VAE Decode Audio", samples=["sample", 0], vae=["avae", 0])
|
| 275 |
+
add("video", "CreateVideo", "Create Video", images=["vdec", 0], audio=["adec", 0], fps=FPS)
|
| 276 |
+
add("save", "SaveVideo", "Save Video", video=["video", 0], filename_prefix=filename_prefix,
|
| 277 |
+
format="mp4", codec={"codec": "h264"})
|
| 278 |
+
return wf
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
# ── Executor (upstream's minimal topological runner — no PromptServer round-trip) ──
|
| 282 |
+
|
| 283 |
+
def _value_at(obj: Any, index: int) -> Any:
|
| 284 |
+
try:
|
| 285 |
+
return obj[index]
|
| 286 |
+
except (KeyError, IndexError, TypeError):
|
| 287 |
+
try:
|
| 288 |
+
return obj["result"][index]
|
| 289 |
+
except (KeyError, IndexError, TypeError):
|
| 290 |
+
return None
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _topological_order(workflow: dict[str, Any]) -> list[str]:
|
| 294 |
+
from collections import defaultdict, deque
|
| 295 |
+
|
| 296 |
+
graph: dict[str, list[str]] = defaultdict(list)
|
| 297 |
+
in_degree = {node_id: 0 for node_id in workflow}
|
| 298 |
+
for node_id, node in workflow.items():
|
| 299 |
+
for value in node.get("inputs", {}).values():
|
| 300 |
+
if isinstance(value, list) and len(value) == 2 and isinstance(value[0], str) and value[0] in workflow:
|
| 301 |
+
graph[value[0]].append(node_id)
|
| 302 |
+
in_degree[node_id] += 1
|
| 303 |
+
queue = deque(n for n, d in in_degree.items() if d == 0)
|
| 304 |
+
ordered: list[str] = []
|
| 305 |
+
while queue:
|
| 306 |
+
current = queue.popleft()
|
| 307 |
+
ordered.append(current)
|
| 308 |
+
for nxt in graph[current]:
|
| 309 |
+
in_degree[nxt] -= 1
|
| 310 |
+
if in_degree[nxt] == 0:
|
| 311 |
+
queue.append(nxt)
|
| 312 |
+
if len(ordered) != len(workflow):
|
| 313 |
+
raise RuntimeError("workflow contains a cycle")
|
| 314 |
+
return ordered
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def execute_workflow(workflow: dict[str, Any], initial_objects: dict[str, Any] | None = None) -> Any:
|
| 318 |
+
import torch
|
| 319 |
+
|
| 320 |
+
computed: dict[str, Any] = dict(initial_objects or {})
|
| 321 |
+
with torch.no_grad():
|
| 322 |
+
order = _topological_order(workflow)
|
| 323 |
+
for node_id in order:
|
| 324 |
+
if node_id in computed:
|
| 325 |
+
continue
|
| 326 |
+
node = workflow[node_id]
|
| 327 |
+
node_class = NODE_CLASS_MAPPINGS.get(node["class_type"])
|
| 328 |
+
if node_class is None:
|
| 329 |
+
raise RuntimeError(f"unknown node class '{node['class_type']}'")
|
| 330 |
+
instance = node_class()
|
| 331 |
+
for target in (node_class, instance):
|
| 332 |
+
if getattr(target, "hidden", None) is None:
|
| 333 |
+
try:
|
| 334 |
+
setattr(target, "hidden", _DummyHidden())
|
| 335 |
+
except Exception:
|
| 336 |
+
pass
|
| 337 |
+
|
| 338 |
+
kwargs: dict[str, Any] = {}
|
| 339 |
+
for name, value in node["inputs"].items():
|
| 340 |
+
if isinstance(value, list) and len(value) == 2 and isinstance(value[0], str) and value[0] in workflow:
|
| 341 |
+
src_id, out_idx = value
|
| 342 |
+
if src_id not in computed:
|
| 343 |
+
raise RuntimeError(f"output of node {src_id} needed by {node_id} but not computed")
|
| 344 |
+
actual = _value_at(computed[src_id], out_idx)
|
| 345 |
+
else:
|
| 346 |
+
actual = value
|
| 347 |
+
if "." in name:
|
| 348 |
+
parent, child = name.split(".", 1)
|
| 349 |
+
kwargs.setdefault(parent, {})[child] = actual
|
| 350 |
+
else:
|
| 351 |
+
kwargs[name] = actual
|
| 352 |
+
|
| 353 |
+
fn = getattr(instance, getattr(node_class, "FUNCTION"))
|
| 354 |
+
print(f"[run] {node_id} ({node['class_type']})", flush=True)
|
| 355 |
+
computed[node_id] = fn(**kwargs)
|
| 356 |
+
return computed.get("save")
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def extract_video_path(out: Any) -> str | None:
|
| 360 |
+
"""Locate the mp4 SaveVideo wrote (ui payload, object attrs, or newest file in output/)."""
|
| 361 |
+
found: list[str] = []
|
| 362 |
+
|
| 363 |
+
def visit(item: Any) -> None:
|
| 364 |
+
if item is None or found:
|
| 365 |
+
return
|
| 366 |
+
if isinstance(item, (list, tuple)):
|
| 367 |
+
for sub in item:
|
| 368 |
+
visit(sub)
|
| 369 |
+
return
|
| 370 |
+
if isinstance(item, str):
|
| 371 |
+
if os.path.exists(item):
|
| 372 |
+
found.append(item)
|
| 373 |
+
return
|
| 374 |
+
if isinstance(item, dict):
|
| 375 |
+
for key in ("images", "videos", "video"):
|
| 376 |
+
for sub in item.get("ui", {}).get(key, []):
|
| 377 |
+
if isinstance(sub, dict) and sub.get("filename"):
|
| 378 |
+
candidate = COMFY_OUTPUT / sub.get("subfolder", "") / sub["filename"]
|
| 379 |
+
if candidate.exists():
|
| 380 |
+
found.append(str(candidate))
|
| 381 |
+
return
|
| 382 |
+
return
|
| 383 |
+
ui = getattr(item, "ui", None)
|
| 384 |
+
if ui is not None:
|
| 385 |
+
visit(ui if isinstance(ui, dict) else getattr(ui, "as_dict", lambda: None)())
|
| 386 |
+
for attr in ("path", "saved_path", "filepath", "filename", "full_path"):
|
| 387 |
+
val = getattr(item, attr, None)
|
| 388 |
+
if isinstance(val, str):
|
| 389 |
+
for candidate in (pathlib.Path(val), COMFY_OUTPUT / val):
|
| 390 |
+
if candidate.exists():
|
| 391 |
+
found.append(str(candidate))
|
| 392 |
+
return
|
| 393 |
+
|
| 394 |
+
visit(out)
|
| 395 |
+
if found:
|
| 396 |
+
return found[0]
|
| 397 |
+
files = glob.glob(str(COMFY_OUTPUT / "**" / "*.mp4"), recursive=True)
|
| 398 |
+
if not files:
|
| 399 |
+
return None
|
| 400 |
+
files.sort(key=os.path.getmtime, reverse=True)
|
| 401 |
+
return files[0]
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
# ── Optional CPU preload of the four loaders (see PRELOAD_MODELS) ───────────
|
| 405 |
+
|
| 406 |
+
PRELOADED: dict[str, Any] = {}
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def preload_models() -> None:
|
| 410 |
+
template = build_workflow(prompt="", width=960, height=544, frames=124, steps=1, seed=0,
|
| 411 |
+
first_frame_name="", last_frame_name=None, filename_prefix="")
|
| 412 |
+
for node_id in ("unet", "clip", "vvae", "avae"):
|
| 413 |
+
node = template[node_id]
|
| 414 |
+
node_class = NODE_CLASS_MAPPINGS[node["class_type"]]
|
| 415 |
+
instance = node_class()
|
| 416 |
+
fn = getattr(instance, getattr(node_class, "FUNCTION"))
|
| 417 |
+
print(f"[setup] preloading {node_id} ({node['class_type']})", flush=True)
|
| 418 |
+
PRELOADED[node_id] = fn(**node["inputs"])
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
# ── Durable outputs (same scheme as the Wan / LTX Spaces) ───────────────────
|
| 422 |
+
|
| 423 |
+
def persist_job_output(job_id: str, video_path: str, seed: int) -> None:
|
| 424 |
+
"""Upload the finished mp4 (+ tiny sidecar) to a Hub dataset keyed by job_id so a
|
| 425 |
+
client that lost the SSE stream can later download `{job_id}.mp4`."""
|
| 426 |
+
job_id = (job_id or "").strip()
|
| 427 |
+
if not job_id or not video_path or not os.path.isfile(video_path):
|
| 428 |
+
return
|
| 429 |
+
token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
| 430 |
+
if not token:
|
| 431 |
+
print(f"[persist] skip {job_id}: no HF_TOKEN on Space", flush=True)
|
| 432 |
+
return
|
| 433 |
+
if not H3_JOB_DATASET:
|
| 434 |
+
print(f"[persist] skip {job_id}: H3_JOB_DATASET empty", flush=True)
|
| 435 |
+
return
|
| 436 |
+
try:
|
| 437 |
+
api = HfApi(token=token)
|
| 438 |
+
api.upload_file(path_or_fileobj=video_path, path_in_repo=f"{job_id}.mp4",
|
| 439 |
+
repo_id=H3_JOB_DATASET, repo_type="dataset")
|
| 440 |
+
meta = json.dumps({"job_id": job_id, "seed": int(seed)}, separators=(",", ":"))
|
| 441 |
+
api.upload_file(path_or_fileobj=meta.encode("utf-8"), path_in_repo=f"{job_id}.json",
|
| 442 |
+
repo_id=H3_JOB_DATASET, repo_type="dataset")
|
| 443 |
+
print(f"[persist] uploaded {job_id} → dataset {H3_JOB_DATASET}", flush=True)
|
| 444 |
+
except Exception as exc:
|
| 445 |
+
print(f"[persist] failed for {job_id}: {exc}", flush=True)
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# ── Job helpers ──────────────────────────────────────────────────────────────
|
| 449 |
+
|
| 450 |
+
def stage_input_image(path: str, tag: str) -> tuple[str, int, int]:
|
| 451 |
+
"""Copy an upload into ComfyUI/input as an oriented RGB PNG; returns (name, w, h)."""
|
| 452 |
+
with Image.open(path) as img:
|
| 453 |
+
img = ImageOps.exif_transpose(img).convert("RGB")
|
| 454 |
+
name = f"h3_{tag}_{uuid.uuid4().hex}.png"
|
| 455 |
+
img.save(COMFY_INPUT / name, "PNG")
|
| 456 |
+
return name, img.width, img.height
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def prune_old_files(directory: pathlib.Path, max_age_secs: int) -> None:
|
| 460 |
+
cutoff = time.time() - max_age_secs
|
| 461 |
+
for p in directory.rglob("*"):
|
| 462 |
+
try:
|
| 463 |
+
if p.is_file() and p.stat().st_mtime < cutoff:
|
| 464 |
+
p.unlink()
|
| 465 |
+
except OSError:
|
| 466 |
+
pass
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _gpu_budget(workflow: dict[str, Any], budget: int, initial_objects: dict[str, Any] | None = None,
|
| 470 |
+
progress: gr.Progress | None = None) -> int:
|
| 471 |
+
return int(budget)
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
@spaces.GPU(duration=_gpu_budget)
|
| 475 |
+
def run_workflow_gpu(workflow: dict[str, Any], budget: int, initial_objects: dict[str, Any] | None = None,
|
| 476 |
+
progress: gr.Progress | None = None) -> str | None:
|
| 477 |
+
print(f"[gpu] {apply_sage_attention_patch()} — budget {budget}s", flush=True)
|
| 478 |
+
out = execute_workflow(workflow, initial_objects)
|
| 479 |
+
return extract_video_path(out)
|
| 480 |
+
|
| 481 |
+
|
| 482 |
+
def generate_video(
|
| 483 |
+
first_frame: str | None,
|
| 484 |
+
last_frame: str | None,
|
| 485 |
+
prompt: str,
|
| 486 |
+
max_dim: float,
|
| 487 |
+
seconds: float,
|
| 488 |
+
steps: float,
|
| 489 |
+
seed: float,
|
| 490 |
+
randomize_seed: bool,
|
| 491 |
+
job_id: str = "",
|
| 492 |
+
progress: gr.Progress = gr.Progress(track_tqdm=True),
|
| 493 |
+
) -> tuple[str, int, str, int]:
|
| 494 |
+
"""api_name=generate_video — returns (video, used_seed, job_id, duration_ms)."""
|
| 495 |
+
t0 = time.time()
|
| 496 |
+
if not first_frame:
|
| 497 |
+
raise gr.Error("upload a start image first")
|
| 498 |
+
if not str(prompt or "").strip():
|
| 499 |
+
raise gr.Error("write a prompt first")
|
| 500 |
+
|
| 501 |
+
try:
|
| 502 |
+
max_dim_i = int(max_dim)
|
| 503 |
+
seconds_f = float(seconds)
|
| 504 |
+
steps_i = int(steps)
|
| 505 |
+
except (TypeError, ValueError):
|
| 506 |
+
raise gr.Error("max_dim, seconds and steps must be numbers")
|
| 507 |
+
if not (MIN_MAX_DIM <= max_dim_i <= MAX_MAX_DIM):
|
| 508 |
+
raise gr.Error(f"max_dim must be between {MIN_MAX_DIM} and {MAX_MAX_DIM}")
|
| 509 |
+
if not (MIN_SECONDS <= seconds_f <= MAX_SECONDS):
|
| 510 |
+
raise gr.Error(f"seconds must be between {MIN_SECONDS:g} and {MAX_SECONDS:g}")
|
| 511 |
+
if not (MIN_STEPS <= steps_i <= MAX_STEPS):
|
| 512 |
+
raise gr.Error(f"steps must be between {MIN_STEPS} and {MAX_STEPS}")
|
| 513 |
+
|
| 514 |
+
used_seed = random.randint(0, 2**32 - 1) if randomize_seed or int(seed) < 0 else int(seed)
|
| 515 |
+
|
| 516 |
+
progress(0.02, desc="Preparing inputs")
|
| 517 |
+
prune_old_files(COMFY_INPUT, 6 * 3600)
|
| 518 |
+
prune_old_files(COMFY_OUTPUT, 6 * 3600)
|
| 519 |
+
ff_name, in_w, in_h = stage_input_image(first_frame, "first")
|
| 520 |
+
lf_name = stage_input_image(last_frame, "last")[0] if last_frame else None
|
| 521 |
+
|
| 522 |
+
width, height = fit_canvas(in_w, in_h, max_dim_i)
|
| 523 |
+
frames = frame_count(seconds_f)
|
| 524 |
+
budget = estimate_gpu_seconds(width, height, frames, steps_i)
|
| 525 |
+
if budget > MAX_GPU_SECONDS:
|
| 526 |
+
raise gr.Error(
|
| 527 |
+
f"this job needs ~{budget}s of GPU time, above the Space cap of {MAX_GPU_SECONDS}s — "
|
| 528 |
+
f"lower the resolution ({width}×{height}), duration ({frames} frames) or steps ({steps_i})"
|
| 529 |
+
)
|
| 530 |
+
print(f"[job] {job_id or '-'} {width}x{height} frames={frames} steps={steps_i} seed={used_seed} "
|
| 531 |
+
f"last_frame={'yes' if lf_name else 'no'} budget={budget}s", flush=True)
|
| 532 |
+
|
| 533 |
+
progress(0.05, desc="Checking models")
|
| 534 |
+
ensure_models(progress)
|
| 535 |
+
|
| 536 |
+
workflow = build_workflow(
|
| 537 |
+
prompt=str(prompt), width=width, height=height, frames=frames, steps=steps_i, seed=used_seed,
|
| 538 |
+
first_frame_name=ff_name, last_frame_name=lf_name,
|
| 539 |
+
filename_prefix=f"video/h3_{job_id.strip() or uuid.uuid4().hex}",
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
progress(0.1, desc=f"Generating ({width}×{height}, {frames} frames, {steps_i} steps)")
|
| 543 |
+
try:
|
| 544 |
+
video = run_workflow_gpu(workflow, budget, PRELOADED or None, progress=progress)
|
| 545 |
+
finally:
|
| 546 |
+
for name in (ff_name, lf_name):
|
| 547 |
+
if name:
|
| 548 |
+
try:
|
| 549 |
+
(COMFY_INPUT / name).unlink()
|
| 550 |
+
except OSError:
|
| 551 |
+
pass
|
| 552 |
+
if not video:
|
| 553 |
+
raise gr.Error("generation finished without an output video — check the Space logs")
|
| 554 |
+
|
| 555 |
+
persist_job_output(job_id, video, used_seed)
|
| 556 |
+
duration_ms = int((time.time() - t0) * 1000)
|
| 557 |
+
print(f"[job] {job_id or '-'} done in {duration_ms}ms → {video}", flush=True)
|
| 558 |
+
return video, int(used_seed), job_id or "", duration_ms
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
# ── Startup ──────────────────────────────────────────────────────────────────
|
| 562 |
+
|
| 563 |
+
print("[setup] ComfyUI bootstrap", flush=True)
|
| 564 |
+
ensure_comfy()
|
| 565 |
+
ensure_models()
|
| 566 |
+
init_comfy_nodes()
|
| 567 |
+
print(f"[setup] {apply_sage_attention_patch()}", flush=True)
|
| 568 |
+
if PRELOAD_MODELS:
|
| 569 |
+
try:
|
| 570 |
+
preload_models()
|
| 571 |
+
except Exception as exc: # fall back to loading inside the GPU window
|
| 572 |
+
PRELOADED.clear()
|
| 573 |
+
print(f"[setup] preload failed, loaders will run on GPU: {exc}", flush=True)
|
| 574 |
+
|
| 575 |
+
# ── UI (the visible form IS the API — inputs are positional in this order) ──
|
| 576 |
+
|
| 577 |
+
with gr.Blocks(title="MiniMax-H3 I2V") as demo:
|
| 578 |
+
gr.Markdown(
|
| 579 |
+
"# MiniMax-H3 · image-to-video\n"
|
| 580 |
+
"Start image required; add a last image for first-to-last-frame. Native audio. "
|
| 581 |
+
"Slim fork of [RioShiina/MiniMax-H3](https://huggingface.co/spaces/RioShiina/MiniMax-H3) "
|
| 582 |
+
"for protocol-generator — I2VA / FLF2VA only."
|
| 583 |
+
)
|
| 584 |
+
with gr.Row():
|
| 585 |
+
first_frame = gr.Image(type="filepath", label="Start image", height=240)
|
| 586 |
+
last_frame = gr.Image(type="filepath", label="Last image (optional)", height=240)
|
| 587 |
+
prompt = gr.Textbox(label="Prompt", lines=4)
|
| 588 |
+
with gr.Row():
|
| 589 |
+
max_dim = gr.Number(label="Longest side (px, ×32)", value=960, precision=0,
|
| 590 |
+
info="960 ≈ 544p at 16:9 · 1344 ≈ 768p · 1920 ≈ 1080p")
|
| 591 |
+
seconds = gr.Slider(label="Duration (s)", minimum=MIN_SECONDS, maximum=MAX_SECONDS, step=0.5, value=5.0)
|
| 592 |
+
steps = gr.Slider(label="Steps", minimum=MIN_STEPS, maximum=MAX_STEPS, step=1, value=20)
|
| 593 |
+
with gr.Row():
|
| 594 |
+
seed = gr.Number(label="Seed (-1 = random)", value=-1, precision=0)
|
| 595 |
+
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 596 |
+
job_id = gr.Textbox(label="job_id", value="", visible=False)
|
| 597 |
+
run_btn = gr.Button("Generate", variant="primary")
|
| 598 |
+
video = gr.Video(label="Result", interactive=False)
|
| 599 |
+
used_seed = gr.Number(label="used_seed", precision=0, visible=False)
|
| 600 |
+
job_id_out = gr.Textbox(label="job_id", visible=False)
|
| 601 |
+
duration_ms = gr.Number(label="duration_ms", precision=0, visible=False)
|
| 602 |
+
|
| 603 |
+
run_btn.click(
|
| 604 |
+
fn=generate_video,
|
| 605 |
+
inputs=[first_frame, last_frame, prompt, max_dim, seconds, steps, seed, randomize_seed, job_id],
|
| 606 |
+
outputs=[video, used_seed, job_id_out, duration_ms],
|
| 607 |
+
api_name="generate_video",
|
| 608 |
+
)
|
| 609 |
+
|
| 610 |
+
demo.queue()
|
| 611 |
+
|
| 612 |
+
if __name__ == "__main__":
|
| 613 |
+
demo.launch()
|
chain_injectors/__init__.py
DELETED
|
@@ -1,50 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,115 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,152 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,27 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,35 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,32 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,76 +0,0 @@
|
|
| 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
DELETED
|
File without changes
|
comfy_integration/nodes.py
DELETED
|
@@ -1,44 +0,0 @@
|
|
| 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 |
-
server_instance = server.PromptServer(loop)
|
| 15 |
-
execution.PromptQueue(server_instance)
|
| 16 |
-
|
| 17 |
-
loop.run_until_complete(init_extra_nodes())
|
| 18 |
-
|
| 19 |
-
import_custom_nodes()
|
| 20 |
-
|
| 21 |
-
CLIPTextEncode = NODE_CLASS_MAPPINGS['CLIPTextEncode']
|
| 22 |
-
CLIPTextEncodeSDXL = NODE_CLASS_MAPPINGS['CLIPTextEncodeSDXL']
|
| 23 |
-
LoraLoader = NODE_CLASS_MAPPINGS['LoraLoader']
|
| 24 |
-
CLIPSetLastLayer = NODE_CLASS_MAPPINGS['CLIPSetLastLayer']
|
| 25 |
-
|
| 26 |
-
if 'EmptyHunyuanImageLatent' in NODE_CLASS_MAPPINGS:
|
| 27 |
-
EmptyHunyuanImageLatent = NODE_CLASS_MAPPINGS['EmptyHunyuanImageLatent']
|
| 28 |
-
else:
|
| 29 |
-
print("⚠️ Warning: 'EmptyHunyuanImageLatent' not found in NODE_CLASS_MAPPINGS. HunyuanImage txt2img may fail if this node is required.")
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
KSamplerNode = NODE_CLASS_MAPPINGS['KSampler']
|
| 33 |
-
SAMPLER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["sampler_name"][0]
|
| 34 |
-
SCHEDULER_CHOICES = KSamplerNode.INPUT_TYPES()["required"]["scheduler"][0]
|
| 35 |
-
except Exception:
|
| 36 |
-
print("⚠️ Could not dynamically get sampler/scheduler choices, using fallback list.")
|
| 37 |
-
SAMPLER_CHOICES = ['euler', 'dpmpp_2m_sde_gpu']
|
| 38 |
-
SCHEDULER_CHOICES = ['normal', 'karras']
|
| 39 |
-
|
| 40 |
-
checkpointloadersimple = CheckpointLoaderSimple()
|
| 41 |
-
loraloader = LoraLoader()
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
print("✅ ComfyUI custom nodes and class mappings are ready.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
comfy_integration/setup.py
DELETED
|
@@ -1,63 +0,0 @@
|
|
| 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 |
-
import comfy.model_management
|
| 53 |
-
print("--- Environment Ready ---")
|
| 54 |
-
|
| 55 |
-
print("✅ ComfyUI initialized with default attention mechanism.")
|
| 56 |
-
|
| 57 |
-
for dir_path in CATEGORY_TO_DIR_MAP.values():
|
| 58 |
-
os.makedirs(os.path.join(APP_DIR, dir_path), exist_ok=True)
|
| 59 |
-
|
| 60 |
-
os.makedirs(os.path.join(APP_DIR, INPUT_DIR), exist_ok=True)
|
| 61 |
-
os.makedirs(os.path.join(APP_DIR, OUTPUT_DIR), exist_ok=True)
|
| 62 |
-
|
| 63 |
-
print("✅ All required model directories are present.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
core/__init__.py
DELETED
|
File without changes
|
core/generation_logic.py
DELETED
|
@@ -1,131 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,32 +0,0 @@
|
|
| 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
DELETED
|
File without changes
|
core/pipelines/base_pipeline.py
DELETED
|
@@ -1,55 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,36 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,125 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,134 +0,0 @@
|
|
| 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', 5)
|
| 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 = 5, 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
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
INVALID_MODEL_URLS = {}
|
|
|
|
|
|
core/workflow_assembler.py
DELETED
|
@@ -1,202 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,41 +0,0 @@
|
|
| 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 .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 .error_schema import make_error, make_validation_error, make_not_found_error
|
| 10 |
-
try:
|
| 11 |
-
from .mcp_gradio_integration import (
|
| 12 |
-
register_high_level_mcp_apis,
|
| 13 |
-
cleanup_dependencies_api_names,
|
| 14 |
-
patch_gradio_api_suppression,
|
| 15 |
-
HIGH_LEVEL_MCP_API_NAMES,
|
| 16 |
-
)
|
| 17 |
-
except ImportError:
|
| 18 |
-
register_high_level_mcp_apis = None
|
| 19 |
-
cleanup_dependencies_api_names = None
|
| 20 |
-
patch_gradio_api_suppression = None
|
| 21 |
-
HIGH_LEVEL_MCP_API_NAMES = set()
|
| 22 |
-
|
| 23 |
-
MCP_FUNCTIONS = [
|
| 24 |
-
handle_get_task_list,
|
| 25 |
-
handle_run,
|
| 26 |
-
handle_get_task_status,
|
| 27 |
-
]
|
| 28 |
-
|
| 29 |
-
__all__ = [
|
| 30 |
-
"handle_get_task_list",
|
| 31 |
-
"handle_run",
|
| 32 |
-
"handle_get_task_status",
|
| 33 |
-
"make_error",
|
| 34 |
-
"make_validation_error",
|
| 35 |
-
"make_not_found_error",
|
| 36 |
-
"register_high_level_mcp_apis",
|
| 37 |
-
"cleanup_dependencies_api_names",
|
| 38 |
-
"patch_gradio_api_suppression",
|
| 39 |
-
"HIGH_LEVEL_MCP_API_NAMES",
|
| 40 |
-
"MCP_FUNCTIONS",
|
| 41 |
-
]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
mcp_tools/common.py
DELETED
|
@@ -1,610 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,11 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,21 +0,0 @@
|
|
| 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/mcp_gradio_integration.py
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,94 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,19 +0,0 @@
|
|
| 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
CHANGED
|
@@ -1,43 +1,45 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
comfyui-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# ComfyUI's own requirements.txt at the pinned commit (COMFYUI_COMMIT in app.py) —
|
| 2 |
+
# the Space installs these at build time so the runtime clone needs no pip step.
|
| 3 |
+
comfyui-frontend-package==1.52.7
|
| 4 |
+
comfyui-workflow-templates==0.11.59
|
| 5 |
+
comfyui-embedded-docs==0.5.11
|
| 6 |
+
torch
|
| 7 |
+
torchsde
|
| 8 |
+
torchvision
|
| 9 |
+
torchaudio
|
| 10 |
+
numpy>=1.25.0
|
| 11 |
+
einops
|
| 12 |
+
transformers>=4.50.3
|
| 13 |
+
tokenizers>=0.13.3
|
| 14 |
+
sentencepiece
|
| 15 |
+
safetensors>=0.4.2
|
| 16 |
+
aiohttp>=3.11.8
|
| 17 |
+
yarl>=1.18.0
|
| 18 |
+
pyyaml
|
| 19 |
+
Pillow
|
| 20 |
+
scipy
|
| 21 |
+
tqdm
|
| 22 |
+
psutil
|
| 23 |
+
alembic
|
| 24 |
+
SQLAlchemy>=2.0.0
|
| 25 |
+
filelock
|
| 26 |
+
av>=17.0.0
|
| 27 |
+
comfy-kitchen==0.2.33
|
| 28 |
+
comfy-aimdo==0.5.3
|
| 29 |
+
requests
|
| 30 |
+
simpleeval>=1.0.0
|
| 31 |
+
blake3
|
| 32 |
+
|
| 33 |
+
#non essential dependencies:
|
| 34 |
+
kornia>=0.7.1
|
| 35 |
+
spandrel
|
| 36 |
+
pydantic~=2.0
|
| 37 |
+
pydantic-settings~=2.0
|
| 38 |
+
PyOpenGL>=3.1.8
|
| 39 |
+
comfy-angle
|
| 40 |
+
|
| 41 |
+
# Space-side
|
| 42 |
+
huggingface-hub
|
| 43 |
+
imageio
|
| 44 |
+
spaces
|
| 45 |
+
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
DELETED
|
@@ -1,373 +0,0 @@
|
|
| 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
DELETED
|
File without changes
|
ui/events/__init__.py
DELETED
|
@@ -1 +0,0 @@
|
|
| 1 |
-
from .main import attach_event_handlers
|
|
|
|
|
|
ui/events/chain_handlers.py
DELETED
|
@@ -1,222 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,22 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,198 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,443 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,42 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,138 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,157 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,235 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,137 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,172 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,423 +0,0 @@
|
|
| 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
DELETED
|
@@ -1,203 +0,0 @@
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
utils/__init__.py
DELETED
|
File without changes
|
utils/app_utils.py
DELETED
|
@@ -1,805 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import random
|
| 3 |
-
import requests
|
| 4 |
-
import hashlib
|
| 5 |
-
import re
|
| 6 |
-
from typing import Sequence, Mapping, Any, Union, Set
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
import shutil
|
| 9 |
-
|
| 10 |
-
import gradio as gr
|
| 11 |
-
from huggingface_hub import hf_hub_download, constants as hf_constants
|
| 12 |
-
import torch
|
| 13 |
-
import numpy as np
|
| 14 |
-
from PIL import Image, ImageChops
|
| 15 |
-
import yaml
|
| 16 |
-
|
| 17 |
-
from core.settings import *
|
| 18 |
-
|
| 19 |
-
MODELS_ROOT_DIR = "ComfyUI/models"
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
class UniqueKeyLoader(yaml.SafeLoader):
|
| 23 |
-
"""
|
| 24 |
-
A custom YAML loader that handles duplicate keys by grouping their values into a list.
|
| 25 |
-
"""
|
| 26 |
-
def construct_mapping(self, node, deep=False):
|
| 27 |
-
mapping = []
|
| 28 |
-
for key_node, value_node in node.value:
|
| 29 |
-
key = self.construct_object(key_node, deep=deep)
|
| 30 |
-
value = self.construct_object(value_node, deep=deep)
|
| 31 |
-
mapping.append((key, value))
|
| 32 |
-
|
| 33 |
-
result = {}
|
| 34 |
-
for k, v in mapping:
|
| 35 |
-
if k in result:
|
| 36 |
-
if isinstance(result[k], list):
|
| 37 |
-
result[k].append(v)
|
| 38 |
-
else:
|
| 39 |
-
result[k] = [result[k], v]
|
| 40 |
-
else:
|
| 41 |
-
result[k] = v
|
| 42 |
-
return result
|
| 43 |
-
|
| 44 |
-
UniqueKeyLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, UniqueKeyLoader.construct_mapping)
|
| 45 |
-
|
| 46 |
-
def save_uploaded_file_with_hash(file_obj: gr.File, target_dir: str) -> str:
|
| 47 |
-
if not file_obj:
|
| 48 |
-
return ""
|
| 49 |
-
|
| 50 |
-
temp_path = file_obj.name
|
| 51 |
-
|
| 52 |
-
sha256 = hashlib.sha256()
|
| 53 |
-
with open(temp_path, 'rb') as f:
|
| 54 |
-
for block in iter(lambda: f.read(65536), b''):
|
| 55 |
-
sha256.update(block)
|
| 56 |
-
|
| 57 |
-
file_hash = sha256.hexdigest()
|
| 58 |
-
_, extension = os.path.splitext(temp_path)
|
| 59 |
-
hashed_filename = f"{file_hash}{extension.lower()}"
|
| 60 |
-
|
| 61 |
-
dest_path = os.path.join(target_dir, hashed_filename)
|
| 62 |
-
|
| 63 |
-
os.makedirs(target_dir, exist_ok=True)
|
| 64 |
-
if not os.path.exists(dest_path):
|
| 65 |
-
shutil.copy(temp_path, dest_path)
|
| 66 |
-
print(f"✅ Saved uploaded file as: {dest_path}")
|
| 67 |
-
else:
|
| 68 |
-
print(f"ℹ️ File already exists (deduplicated): {dest_path}")
|
| 69 |
-
|
| 70 |
-
return hashed_filename
|
| 71 |
-
|
| 72 |
-
def bytes_to_gb(byte_size: int) -> float:
|
| 73 |
-
if byte_size is None or byte_size == 0:
|
| 74 |
-
return 0.0
|
| 75 |
-
return round(byte_size / (1024 ** 3), 2)
|
| 76 |
-
|
| 77 |
-
def get_directory_size(path: str) -> int:
|
| 78 |
-
total_size = 0
|
| 79 |
-
if not os.path.exists(path):
|
| 80 |
-
return 0
|
| 81 |
-
try:
|
| 82 |
-
for dirpath, _, filenames in os.walk(path):
|
| 83 |
-
for f in filenames:
|
| 84 |
-
fp = os.path.join(dirpath, f)
|
| 85 |
-
if os.path.isfile(fp) and not os.path.islink(fp):
|
| 86 |
-
total_size += os.path.getsize(fp)
|
| 87 |
-
except OSError as e:
|
| 88 |
-
print(f"Warning: Could not access {path} to calculate size: {e}")
|
| 89 |
-
return total_size
|
| 90 |
-
|
| 91 |
-
def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
|
| 92 |
-
try:
|
| 93 |
-
return obj[index]
|
| 94 |
-
except (KeyError, IndexError):
|
| 95 |
-
try:
|
| 96 |
-
return obj["result"][index]
|
| 97 |
-
except (KeyError, IndexError):
|
| 98 |
-
return None
|
| 99 |
-
|
| 100 |
-
def sanitize_prompt(prompt: str) -> str:
|
| 101 |
-
if not isinstance(prompt, str):
|
| 102 |
-
return ""
|
| 103 |
-
return "".join(char for char in prompt if char.isprintable() or char in ('\n', '\t'))
|
| 104 |
-
|
| 105 |
-
def sanitize_id(input_id: str) -> str:
|
| 106 |
-
if not isinstance(input_id, str):
|
| 107 |
-
return ""
|
| 108 |
-
input_id = input_id.strip()
|
| 109 |
-
if "civitai" in input_id.lower():
|
| 110 |
-
version_match = re.search(r'modelVersionId=(\d+)', input_id)
|
| 111 |
-
if version_match:
|
| 112 |
-
return version_match.group(1)
|
| 113 |
-
model_match = re.search(r'/models/(\d+)', input_id)
|
| 114 |
-
if model_match:
|
| 115 |
-
return model_match.group(1)
|
| 116 |
-
return re.sub(r'[^0-9]', '', input_id)
|
| 117 |
-
|
| 118 |
-
def sanitize_url(url: str) -> str:
|
| 119 |
-
if not isinstance(url, str):
|
| 120 |
-
raise ValueError("URL must be a string.")
|
| 121 |
-
url = url.strip()
|
| 122 |
-
if not re.match(r'^https?://[^\s/$.?#].[^\s]*$', url):
|
| 123 |
-
raise ValueError("Invalid URL format or scheme. Only HTTP and HTTPS are allowed.")
|
| 124 |
-
return url
|
| 125 |
-
|
| 126 |
-
def sanitize_filename(filename: str) -> str:
|
| 127 |
-
if not isinstance(filename, str):
|
| 128 |
-
return ""
|
| 129 |
-
sanitized = filename.replace('..', '')
|
| 130 |
-
sanitized = re.sub(r'[^\w\.\-]', '_', sanitized)
|
| 131 |
-
return sanitized.lstrip('/\\')
|
| 132 |
-
|
| 133 |
-
def get_civitai_file_info(version_id: str) -> dict | None:
|
| 134 |
-
api_url = f"https://civitai.com/api/v1/model-versions/{version_id}"
|
| 135 |
-
try:
|
| 136 |
-
response = requests.get(api_url, timeout=10)
|
| 137 |
-
response.raise_for_status()
|
| 138 |
-
data = response.json()
|
| 139 |
-
|
| 140 |
-
model_type = data.get('model', {}).get('type')
|
| 141 |
-
|
| 142 |
-
result_file = None
|
| 143 |
-
for file_data in data.get('files', []):
|
| 144 |
-
if file_data.get('type') == 'Model' and file_data['name'].endswith(('.safetensors', '.pt', '.bin')):
|
| 145 |
-
result_file = file_data.copy()
|
| 146 |
-
break
|
| 147 |
-
|
| 148 |
-
if not result_file and data.get('files'):
|
| 149 |
-
result_file = data['files'][0].copy()
|
| 150 |
-
|
| 151 |
-
if result_file:
|
| 152 |
-
result_file['model_type'] = model_type
|
| 153 |
-
return result_file
|
| 154 |
-
except Exception:
|
| 155 |
-
return None
|
| 156 |
-
|
| 157 |
-
def download_file(url: str, save_path: str, api_key: str = None, progress=None, desc: str = "") -> str:
|
| 158 |
-
if os.path.exists(save_path):
|
| 159 |
-
return f"File already exists: {os.path.basename(save_path)}"
|
| 160 |
-
|
| 161 |
-
headers = {'Authorization': f'Bearer {api_key}'} if api_key and api_key.strip() else {}
|
| 162 |
-
try:
|
| 163 |
-
if progress:
|
| 164 |
-
progress(0, desc=desc)
|
| 165 |
-
|
| 166 |
-
response = requests.get(url, stream=True, headers=headers, timeout=15)
|
| 167 |
-
response.raise_for_status()
|
| 168 |
-
total_size = int(response.headers.get('content-length', 0))
|
| 169 |
-
|
| 170 |
-
with open(save_path, "wb") as f:
|
| 171 |
-
downloaded = 0
|
| 172 |
-
for chunk in response.iter_content(chunk_size=8192):
|
| 173 |
-
f.write(chunk)
|
| 174 |
-
if progress and total_size > 0:
|
| 175 |
-
downloaded += len(chunk)
|
| 176 |
-
progress(downloaded / total_size, desc=desc)
|
| 177 |
-
return f"Successfully downloaded: {os.path.basename(save_path)}"
|
| 178 |
-
except Exception as e:
|
| 179 |
-
if os.path.exists(save_path):
|
| 180 |
-
os.remove(save_path)
|
| 181 |
-
return f"Download failed for {os.path.basename(save_path)}: {e}"
|
| 182 |
-
|
| 183 |
-
def get_lora_path(source: str, id_or_url: str, civitai_key: str, progress) -> tuple[str | None, str]:
|
| 184 |
-
if not id_or_url or not id_or_url.strip():
|
| 185 |
-
return None, "No ID/URL provided."
|
| 186 |
-
|
| 187 |
-
try:
|
| 188 |
-
if source == "Civitai":
|
| 189 |
-
version_id = sanitize_id(id_or_url)
|
| 190 |
-
if not version_id:
|
| 191 |
-
return None, "Invalid Civitai ID provided. Must be numeric."
|
| 192 |
-
|
| 193 |
-
file_info = get_civitai_file_info(version_id)
|
| 194 |
-
if file_info:
|
| 195 |
-
model_type = file_info.get('model_type')
|
| 196 |
-
if model_type and model_type.lower() == 'checkpoint':
|
| 197 |
-
return None, f"Invalid Civitai model type '{model_type}' for LoRA. Checkpoint models are not allowed."
|
| 198 |
-
|
| 199 |
-
filename = sanitize_filename(f"civitai_{version_id}.safetensors")
|
| 200 |
-
local_path = os.path.join(LORA_DIR, filename)
|
| 201 |
-
api_key_to_use = civitai_key
|
| 202 |
-
source_name = f"Civitai ID {version_id}"
|
| 203 |
-
elif source == "Hugging Face":
|
| 204 |
-
parts = id_or_url.strip().split('/')
|
| 205 |
-
if len(parts) < 3:
|
| 206 |
-
return None, "Invalid Hugging Face path. Format: repo_owner/repo_name/filename"
|
| 207 |
-
repo_id = f"{parts[0]}/{parts[1]}"
|
| 208 |
-
repo_file_path = "/".join(parts[2:])
|
| 209 |
-
unique_name = id_or_url.strip().replace('/', '_')
|
| 210 |
-
filename = sanitize_filename(unique_name)
|
| 211 |
-
local_path = os.path.join(LORA_DIR, filename)
|
| 212 |
-
source_name = f"HF {repo_file_path}"
|
| 213 |
-
else:
|
| 214 |
-
return None, "Invalid source."
|
| 215 |
-
|
| 216 |
-
except ValueError as e:
|
| 217 |
-
return None, f"Input validation failed: {e}"
|
| 218 |
-
|
| 219 |
-
if os.path.lexists(local_path):
|
| 220 |
-
if not os.path.exists(local_path):
|
| 221 |
-
os.remove(local_path)
|
| 222 |
-
else:
|
| 223 |
-
return local_path, "File already exists."
|
| 224 |
-
|
| 225 |
-
if source == "Civitai":
|
| 226 |
-
if not file_info or not file_info.get('downloadUrl'):
|
| 227 |
-
return None, f"Could not get download link for {source_name}."
|
| 228 |
-
|
| 229 |
-
status = download_file(file_info['downloadUrl'], local_path, api_key_to_use, progress=progress, desc=f"Downloading {source_name}")
|
| 230 |
-
return (local_path, status) if "Successfully" in status else (None, status)
|
| 231 |
-
elif source == "Hugging Face":
|
| 232 |
-
try:
|
| 233 |
-
if progress and callable(progress): progress(0, desc=f"Downloading {source_name}")
|
| 234 |
-
cached_path = hf_hub_download(repo_id=repo_id, filename=repo_file_path, token=os.environ.get("HF_TOKEN"))
|
| 235 |
-
os.makedirs(LORA_DIR, exist_ok=True)
|
| 236 |
-
if os.path.lexists(local_path):
|
| 237 |
-
if not os.path.exists(local_path):
|
| 238 |
-
try:
|
| 239 |
-
os.remove(local_path)
|
| 240 |
-
except OSError:
|
| 241 |
-
pass
|
| 242 |
-
if not os.path.exists(local_path):
|
| 243 |
-
try:
|
| 244 |
-
os.symlink(cached_path, local_path)
|
| 245 |
-
except (OSError, NotImplementedError):
|
| 246 |
-
shutil.copyfile(cached_path, local_path)
|
| 247 |
-
if progress and callable(progress): progress(1.0, desc=f"Downloaded {source_name}")
|
| 248 |
-
return local_path, f"Successfully downloaded: {filename}"
|
| 249 |
-
except Exception as e:
|
| 250 |
-
return None, f"Hugging Face download failed: {e}"
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
def _ensure_model_downloaded(display_name: str, progress=gr.Progress()):
|
| 254 |
-
if display_name not in ALL_MODEL_MAP:
|
| 255 |
-
for cat_dir in CATEGORY_TO_DIR_MAP.values():
|
| 256 |
-
check_path = os.path.join(cat_dir, display_name)
|
| 257 |
-
if os.path.exists(check_path):
|
| 258 |
-
return display_name
|
| 259 |
-
raise ValueError(f"Model '{display_name}' not found in configuration.")
|
| 260 |
-
|
| 261 |
-
model_info = ALL_MODEL_MAP[display_name]
|
| 262 |
-
repo_filename = model_info[1]
|
| 263 |
-
base_filename = os.path.basename(repo_filename)
|
| 264 |
-
|
| 265 |
-
download_info = ALL_FILE_DOWNLOAD_MAP.get(base_filename)
|
| 266 |
-
if not download_info:
|
| 267 |
-
raise gr.Error(f"Model '{base_filename}' not found in file_list.yaml. Cannot download.")
|
| 268 |
-
|
| 269 |
-
category = download_info.get("category")
|
| 270 |
-
dest_dir = CATEGORY_TO_DIR_MAP.get(category)
|
| 271 |
-
|
| 272 |
-
if not dest_dir:
|
| 273 |
-
raise ValueError(f"Unknown YAML category '{category}' for '{base_filename}'.")
|
| 274 |
-
|
| 275 |
-
dest_path = os.path.join(dest_dir, base_filename)
|
| 276 |
-
|
| 277 |
-
if os.path.lexists(dest_path):
|
| 278 |
-
if not os.path.exists(dest_path):
|
| 279 |
-
print(f"⚠️ Found and removed broken symlink: {dest_path}")
|
| 280 |
-
os.remove(dest_path)
|
| 281 |
-
else:
|
| 282 |
-
return base_filename
|
| 283 |
-
|
| 284 |
-
source = download_info.get("source")
|
| 285 |
-
try:
|
| 286 |
-
progress(0, desc=f"Downloading: {base_filename}")
|
| 287 |
-
|
| 288 |
-
if source == "hf":
|
| 289 |
-
repo_id = download_info.get("repo_id")
|
| 290 |
-
hf_filename = download_info.get("repository_file_path", base_filename)
|
| 291 |
-
if not repo_id:
|
| 292 |
-
raise ValueError(f"repo_id is missing for HF model '{base_filename}'")
|
| 293 |
-
|
| 294 |
-
cached_path = hf_hub_download(repo_id=repo_id, filename=hf_filename, token=os.environ.get("HF_TOKEN"))
|
| 295 |
-
os.makedirs(dest_dir, exist_ok=True)
|
| 296 |
-
os.symlink(cached_path, dest_path)
|
| 297 |
-
print(f"✅ Symlinked '{cached_path}' to '{dest_path}'")
|
| 298 |
-
|
| 299 |
-
elif source == "civitai":
|
| 300 |
-
model_version_id = download_info.get("model_version_id")
|
| 301 |
-
if not model_version_id:
|
| 302 |
-
raise ValueError(f"model_version_id is missing for Civitai model '{base_filename}'")
|
| 303 |
-
|
| 304 |
-
file_info = get_civitai_file_info(model_version_id)
|
| 305 |
-
if not file_info or not file_info.get('downloadUrl'):
|
| 306 |
-
raise ConnectionError(f"Could not get download URL for Civitai model version ID {model_version_id}")
|
| 307 |
-
|
| 308 |
-
status = download_file(
|
| 309 |
-
file_info['downloadUrl'], dest_path, api_key=os.environ.get("CIVITAI_API_KEY", ""), progress=progress, desc=f"Downloading: {base_filename}"
|
| 310 |
-
)
|
| 311 |
-
if "Failed" in status:
|
| 312 |
-
raise ConnectionError(status)
|
| 313 |
-
else:
|
| 314 |
-
raise NotImplementedError(f"Download source '{source}' is not implemented for '{base_filename}'")
|
| 315 |
-
|
| 316 |
-
progress(1.0, desc=f"Downloaded: {base_filename}")
|
| 317 |
-
|
| 318 |
-
except Exception as e:
|
| 319 |
-
if os.path.lexists(dest_path):
|
| 320 |
-
try:
|
| 321 |
-
os.remove(dest_path)
|
| 322 |
-
except OSError: pass
|
| 323 |
-
raise gr.Error(f"Failed to download and link '{display_name}': {e}")
|
| 324 |
-
|
| 325 |
-
return base_filename
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
def ensure_file_downloaded(filename: str, progress=None):
|
| 329 |
-
if not filename or filename == "None":
|
| 330 |
-
return
|
| 331 |
-
|
| 332 |
-
download_info = ALL_FILE_DOWNLOAD_MAP.get(filename)
|
| 333 |
-
if not download_info:
|
| 334 |
-
print(f"⚠️ Warning: File '{filename}' not found in configuration (file_list.yaml). Cannot download.")
|
| 335 |
-
return
|
| 336 |
-
|
| 337 |
-
category = download_info.get("category", "loras")
|
| 338 |
-
dest_dir = CATEGORY_TO_DIR_MAP.get(category, LORA_DIR)
|
| 339 |
-
dest_path = os.path.join(dest_dir, filename)
|
| 340 |
-
|
| 341 |
-
if os.path.lexists(dest_path):
|
| 342 |
-
if not os.path.exists(dest_path):
|
| 343 |
-
print(f"⚠️ Found and removed broken symlink: {dest_path}")
|
| 344 |
-
os.remove(dest_path)
|
| 345 |
-
else:
|
| 346 |
-
return
|
| 347 |
-
|
| 348 |
-
source = download_info.get("source")
|
| 349 |
-
try:
|
| 350 |
-
if source == "hf":
|
| 351 |
-
repo_id = download_info.get("repo_id")
|
| 352 |
-
repo_filename = download_info.get("repository_file_path", filename)
|
| 353 |
-
if not repo_id:
|
| 354 |
-
raise ValueError("repo_id is missing for Hugging Face download.")
|
| 355 |
-
|
| 356 |
-
if progress and callable(progress):
|
| 357 |
-
progress(0, desc=f"Downloading: {filename}")
|
| 358 |
-
cached_path = hf_hub_download(repo_id=repo_id, filename=repo_filename, token=os.environ.get("HF_TOKEN"))
|
| 359 |
-
os.makedirs(dest_dir, exist_ok=True)
|
| 360 |
-
os.symlink(cached_path, dest_path)
|
| 361 |
-
print(f"✅ Symlinked '{cached_path}' to '{dest_path}'")
|
| 362 |
-
if progress and callable(progress):
|
| 363 |
-
progress(1.0, desc=f"Downloaded: {filename}")
|
| 364 |
-
|
| 365 |
-
elif source == "civitai":
|
| 366 |
-
model_version_id = download_info.get("model_version_id")
|
| 367 |
-
if not model_version_id:
|
| 368 |
-
raise ValueError("model_version_id is missing for Civitai download.")
|
| 369 |
-
|
| 370 |
-
file_info = get_civitai_file_info(model_version_id)
|
| 371 |
-
if not file_info or not file_info.get('downloadUrl'):
|
| 372 |
-
raise ConnectionError(f"Could not get download URL for Civitai model version ID {model_version_id}")
|
| 373 |
-
|
| 374 |
-
status = download_file(
|
| 375 |
-
file_info['downloadUrl'],
|
| 376 |
-
dest_path,
|
| 377 |
-
api_key=os.environ.get("CIVITAI_API_KEY", ""),
|
| 378 |
-
progress=progress,
|
| 379 |
-
desc=f"Downloading: {filename}"
|
| 380 |
-
)
|
| 381 |
-
if "Failed" in status:
|
| 382 |
-
raise ConnectionError(status)
|
| 383 |
-
else:
|
| 384 |
-
raise NotImplementedError(f"Download source '{source}' is not implemented for '{filename}'.")
|
| 385 |
-
|
| 386 |
-
except Exception as e:
|
| 387 |
-
if os.path.lexists(dest_path):
|
| 388 |
-
try:
|
| 389 |
-
os.remove(dest_path)
|
| 390 |
-
except OSError:
|
| 391 |
-
pass
|
| 392 |
-
raise gr.Error(f"Failed to download file '{filename}': {e}")
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
def get_model_generation_defaults(model_display_name: str, model_type: str, defaults_config: dict):
|
| 396 |
-
final_defaults = {
|
| 397 |
-
'steps': 25, 'cfg': 7.0, 'sampler_name': 'euler', 'scheduler': 'simple',
|
| 398 |
-
'positive_prompt': '', 'negative_prompt': ''
|
| 399 |
-
}
|
| 400 |
-
|
| 401 |
-
if 'Default' in defaults_config:
|
| 402 |
-
final_defaults.update(defaults_config['Default'])
|
| 403 |
-
|
| 404 |
-
model_type_key = next((key for key in defaults_config if key.lower().replace(" ", "-").replace(".", "") == model_type.lower()), None)
|
| 405 |
-
if model_type_key:
|
| 406 |
-
model_type_config = defaults_config[model_type_key]
|
| 407 |
-
if '_defaults' in model_type_config:
|
| 408 |
-
final_defaults.update(model_type_config['_defaults'])
|
| 409 |
-
|
| 410 |
-
if model_display_name in model_type_config:
|
| 411 |
-
final_defaults.update(model_type_config[model_display_name])
|
| 412 |
-
|
| 413 |
-
return final_defaults
|
| 414 |
-
|
| 415 |
-
def get_filename_prefix() -> str:
|
| 416 |
-
import time
|
| 417 |
-
return f"H3_{int(time.time())}"
|
| 418 |
-
|
| 419 |
-
def save_temp_image(img):
|
| 420 |
-
if img is None:
|
| 421 |
-
return None
|
| 422 |
-
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 423 |
-
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 424 |
-
os.makedirs(input_dir, exist_ok=True)
|
| 425 |
-
if isinstance(img, Image.Image):
|
| 426 |
-
filename = f"temp_image_{random.randint(10000, 99999)}.png"
|
| 427 |
-
filepath = os.path.join(input_dir, filename)
|
| 428 |
-
img.save(filepath, "PNG")
|
| 429 |
-
return os.path.basename(filepath)
|
| 430 |
-
elif isinstance(img, str):
|
| 431 |
-
if not img:
|
| 432 |
-
return None
|
| 433 |
-
if os.path.exists(img):
|
| 434 |
-
ext = os.path.splitext(img)[1] or ".png"
|
| 435 |
-
filename = f"temp_image_{random.randint(10000, 99999)}{ext}"
|
| 436 |
-
save_path = os.path.join(input_dir, filename)
|
| 437 |
-
shutil.copy(img, save_path)
|
| 438 |
-
return os.path.basename(save_path)
|
| 439 |
-
if os.path.exists(os.path.join(input_dir, img)):
|
| 440 |
-
return img
|
| 441 |
-
return os.path.basename(img)
|
| 442 |
-
return None
|
| 443 |
-
|
| 444 |
-
def save_temp_audio(audio_path):
|
| 445 |
-
if not audio_path:
|
| 446 |
-
return None
|
| 447 |
-
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 448 |
-
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 449 |
-
os.makedirs(input_dir, exist_ok=True)
|
| 450 |
-
if os.path.exists(audio_path):
|
| 451 |
-
ext = os.path.splitext(audio_path)[1] or ".wav"
|
| 452 |
-
filename = f"temp_audio_{random.randint(10000, 99999)}{ext}"
|
| 453 |
-
save_path = os.path.join(input_dir, filename)
|
| 454 |
-
shutil.copy(audio_path, save_path)
|
| 455 |
-
return os.path.basename(filename)
|
| 456 |
-
if os.path.exists(os.path.join(input_dir, audio_path)):
|
| 457 |
-
return audio_path
|
| 458 |
-
return os.path.basename(audio_path)
|
| 459 |
-
|
| 460 |
-
def save_temp_video(video_path):
|
| 461 |
-
if not video_path:
|
| 462 |
-
return None
|
| 463 |
-
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 464 |
-
input_dir = os.path.join(_PROJECT_ROOT, "input")
|
| 465 |
-
os.makedirs(input_dir, exist_ok=True)
|
| 466 |
-
if os.path.exists(video_path):
|
| 467 |
-
ext = os.path.splitext(video_path)[1] or ".mp4"
|
| 468 |
-
filename = f"temp_video_{random.randint(10000, 99999)}{ext}"
|
| 469 |
-
save_path = os.path.join(input_dir, filename)
|
| 470 |
-
shutil.copy(video_path, save_path)
|
| 471 |
-
return os.path.basename(filename)
|
| 472 |
-
if os.path.exists(os.path.join(input_dir, video_path)):
|
| 473 |
-
return video_path
|
| 474 |
-
return os.path.basename(video_path)
|
| 475 |
-
|
| 476 |
-
def handle_seed(seed_value: int, max_val: int = 2**32 - 1) -> int:
|
| 477 |
-
if seed_value == -1 or seed_value is None:
|
| 478 |
-
return random.randint(0, max_val)
|
| 479 |
-
return int(seed_value)
|
| 480 |
-
|
| 481 |
-
def process_lora_inputs(ui_values: dict, prefix: str = "", progress=None) -> list:
|
| 482 |
-
active_loras_for_gpu = []
|
| 483 |
-
|
| 484 |
-
# 1. Check direct prefix format (e.g. lora_sources_h3_fl2va)
|
| 485 |
-
lora_sources = ui_values.get(f'lora_sources_{prefix}', []) if prefix else []
|
| 486 |
-
lora_ids = ui_values.get(f'lora_ids_{prefix}', []) if prefix else []
|
| 487 |
-
lora_scales = ui_values.get(f'lora_scales_{prefix}', []) if prefix else []
|
| 488 |
-
|
| 489 |
-
if isinstance(lora_sources, list) and isinstance(lora_ids, list):
|
| 490 |
-
for source, val, scale in zip(lora_sources, lora_ids, lora_scales):
|
| 491 |
-
scale_val = float(scale) if scale is not None else 1.0
|
| 492 |
-
if scale_val > 0 and val and str(val).strip():
|
| 493 |
-
lora_id = str(val).strip()
|
| 494 |
-
lora_filename = None
|
| 495 |
-
if source == "File":
|
| 496 |
-
lora_filename = sanitize_filename(lora_id)
|
| 497 |
-
local_path = os.path.join(LORA_DIR, lora_filename)
|
| 498 |
-
if not os.path.exists(local_path):
|
| 499 |
-
raise gr.Error(f"Uploaded LoRA file '{lora_id}' no longer exists on server. Please re-upload it.")
|
| 500 |
-
elif source in ("Civitai", "Hugging Face"):
|
| 501 |
-
local_path, status = get_lora_path(source, lora_id, os.environ.get("CIVITAI_API_KEY", ""), progress)
|
| 502 |
-
if local_path:
|
| 503 |
-
lora_filename = os.path.basename(local_path)
|
| 504 |
-
else:
|
| 505 |
-
raise gr.Error(f"Failed to prepare LoRA {lora_id}: {status}")
|
| 506 |
-
|
| 507 |
-
if lora_filename:
|
| 508 |
-
active_loras_for_gpu.append({
|
| 509 |
-
"lora_name": lora_filename,
|
| 510 |
-
"strength_model": scale_val,
|
| 511 |
-
"strength_clip": scale_val
|
| 512 |
-
})
|
| 513 |
-
|
| 514 |
-
# 2. Check lora_data flat list format (e.g. [source1, id1, scale1, upload1, ...])
|
| 515 |
-
lora_data = ui_values.get('lora_data', [])
|
| 516 |
-
if lora_data and not active_loras_for_gpu:
|
| 517 |
-
sources, ids, scales, files = lora_data[0::4], lora_data[1::4], lora_data[2::4], lora_data[3::4]
|
| 518 |
-
for source, lora_id, scale, _ in zip(sources, ids, scales, files):
|
| 519 |
-
scale_val = float(scale) if scale is not None else 1.0
|
| 520 |
-
if scale_val > 0 and lora_id and str(lora_id).strip():
|
| 521 |
-
lora_id_str = str(lora_id).strip()
|
| 522 |
-
lora_filename = None
|
| 523 |
-
if source == "File":
|
| 524 |
-
lora_filename = sanitize_filename(lora_id_str)
|
| 525 |
-
local_path = os.path.join(LORA_DIR, lora_filename)
|
| 526 |
-
if not os.path.exists(local_path):
|
| 527 |
-
raise gr.Error(f"Uploaded LoRA file '{lora_id_str}' no longer exists on server. Please re-upload it.")
|
| 528 |
-
elif source in ("Civitai", "Hugging Face"):
|
| 529 |
-
local_path, status = get_lora_path(source, lora_id_str, os.environ.get("CIVITAI_API_KEY", ""), progress)
|
| 530 |
-
if local_path:
|
| 531 |
-
lora_filename = os.path.basename(local_path)
|
| 532 |
-
else:
|
| 533 |
-
raise gr.Error(f"Failed to prepare LoRA {lora_id_str}: {status}")
|
| 534 |
-
|
| 535 |
-
if lora_filename:
|
| 536 |
-
active_loras_for_gpu.append({
|
| 537 |
-
"lora_name": lora_filename,
|
| 538 |
-
"strength_model": scale_val,
|
| 539 |
-
"strength_clip": scale_val
|
| 540 |
-
})
|
| 541 |
-
|
| 542 |
-
# 3. Check direct 'loras' list of dicts (from MCP or custom payload)
|
| 543 |
-
raw_loras = ui_values.get('loras', [])
|
| 544 |
-
if raw_loras and not active_loras_for_gpu and isinstance(raw_loras, list):
|
| 545 |
-
for item in raw_loras:
|
| 546 |
-
if isinstance(item, dict):
|
| 547 |
-
if "lora_name" in item:
|
| 548 |
-
active_loras_for_gpu.append(item)
|
| 549 |
-
else:
|
| 550 |
-
src = item.get("source", "Hugging Face")
|
| 551 |
-
val = item.get("lora_value") or item.get("id_or_url") or item.get("lora_id")
|
| 552 |
-
scale = item.get("scale", 1.0)
|
| 553 |
-
scale_val = float(scale) if scale is not None else 1.0
|
| 554 |
-
if scale_val > 0 and val and str(val).strip():
|
| 555 |
-
lora_id_str = str(val).strip()
|
| 556 |
-
lora_filename = None
|
| 557 |
-
if src == "File":
|
| 558 |
-
lora_filename = sanitize_filename(lora_id_str)
|
| 559 |
-
local_path = os.path.join(LORA_DIR, lora_filename)
|
| 560 |
-
if not os.path.exists(local_path):
|
| 561 |
-
raise gr.Error(f"Uploaded LoRA file '{lora_id_str}' no longer exists on server. Please re-upload it.")
|
| 562 |
-
elif src in ("Civitai", "Hugging Face"):
|
| 563 |
-
local_path, status = get_lora_path(src, lora_id_str, os.environ.get("CIVITAI_API_KEY", ""), progress)
|
| 564 |
-
if local_path:
|
| 565 |
-
lora_filename = os.path.basename(local_path)
|
| 566 |
-
else:
|
| 567 |
-
raise gr.Error(f"Failed to prepare LoRA {lora_id_str}: {status}")
|
| 568 |
-
if lora_filename:
|
| 569 |
-
active_loras_for_gpu.append({
|
| 570 |
-
"lora_name": lora_filename,
|
| 571 |
-
"strength_model": scale_val,
|
| 572 |
-
"strength_clip": scale_val
|
| 573 |
-
})
|
| 574 |
-
|
| 575 |
-
return active_loras_for_gpu
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
def load_h3_controlnet_config():
|
| 579 |
-
_PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 580 |
-
_CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'h3_controlnet_models.yaml')
|
| 581 |
-
try:
|
| 582 |
-
with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f:
|
| 583 |
-
config = yaml.safe_load(f)
|
| 584 |
-
return config.get("H3_ControlNet", {}) if isinstance(config, dict) else {}
|
| 585 |
-
except Exception as e:
|
| 586 |
-
print(f"Error loading h3_controlnet_models.yaml: {e}")
|
| 587 |
-
return {}
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
def get_h3_cn_defaults(arch_val="MiniMax-H3"):
|
| 591 |
-
cn_full_config = load_h3_controlnet_config()
|
| 592 |
-
cn_config = cn_full_config.get(arch_val, [])
|
| 593 |
-
if not cn_config and cn_full_config:
|
| 594 |
-
cn_config = next(iter(cn_full_config.values()), [])
|
| 595 |
-
|
| 596 |
-
if not cn_config:
|
| 597 |
-
return ["Canny", "Depth", "HED", "MLSD", "Pose"], "Canny", ["alibaba-pai/MiniMax-H3-Fun-Controlnet-Union"], "alibaba-pai/MiniMax-H3-Fun-Controlnet-Union", "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 598 |
-
|
| 599 |
-
all_types = []
|
| 600 |
-
for model in cn_config:
|
| 601 |
-
for t in model.get("Type", []):
|
| 602 |
-
if t not in all_types:
|
| 603 |
-
all_types.append(t)
|
| 604 |
-
default_type = all_types[0] if all_types else "Canny"
|
| 605 |
-
|
| 606 |
-
series_choices = []
|
| 607 |
-
if default_type:
|
| 608 |
-
for model in cn_config:
|
| 609 |
-
if default_type in model.get("Type", []):
|
| 610 |
-
s = model.get("Series", "Default")
|
| 611 |
-
if s not in series_choices:
|
| 612 |
-
series_choices.append(s)
|
| 613 |
-
default_series = series_choices[0] if series_choices else ""
|
| 614 |
-
|
| 615 |
-
filepath = ""
|
| 616 |
-
if default_series and default_type:
|
| 617 |
-
for model in cn_config:
|
| 618 |
-
if model.get("Series") == default_series and default_type in model.get("Type", []):
|
| 619 |
-
filepath = model.get("Filepath", "")
|
| 620 |
-
break
|
| 621 |
-
|
| 622 |
-
return all_types, default_type, series_choices, default_series, filepath
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
def process_h3_controlnet_inputs(ui_values: dict, prefix: str = "", progress=None) -> list:
|
| 626 |
-
active_cns = []
|
| 627 |
-
|
| 628 |
-
# 1. Check direct prefix format (e.g. h3_controlnet_videos_h3_fl2va)
|
| 629 |
-
videos = ui_values.get(f'h3_controlnet_videos_{prefix}', []) if prefix else []
|
| 630 |
-
types = ui_values.get(f'h3_controlnet_types_{prefix}', []) if prefix else []
|
| 631 |
-
series = ui_values.get(f'h3_controlnet_series_{prefix}', []) if prefix else []
|
| 632 |
-
strengths = ui_values.get(f'h3_controlnet_strengths_{prefix}', []) if prefix else []
|
| 633 |
-
start_percents = ui_values.get(f'h3_controlnet_start_percents_{prefix}', []) if prefix else []
|
| 634 |
-
end_percents = ui_values.get(f'h3_controlnet_end_percents_{prefix}', []) if prefix else []
|
| 635 |
-
filepaths = ui_values.get(f'h3_controlnet_filepaths_{prefix}', []) if prefix else []
|
| 636 |
-
|
| 637 |
-
if isinstance(videos, list) and isinstance(types, list):
|
| 638 |
-
for idx, vid in enumerate(videos):
|
| 639 |
-
if vid:
|
| 640 |
-
saved_vid_name = save_temp_video(vid) if isinstance(vid, str) and os.path.exists(vid) else vid
|
| 641 |
-
if not saved_vid_name:
|
| 642 |
-
continue
|
| 643 |
-
|
| 644 |
-
fp = filepaths[idx] if idx < len(filepaths) and filepaths[idx] and filepaths[idx] != "None" else None
|
| 645 |
-
if not fp:
|
| 646 |
-
fp = "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 647 |
-
|
| 648 |
-
ensure_file_downloaded(fp, progress=progress)
|
| 649 |
-
|
| 650 |
-
st = float(strengths[idx]) if idx < len(strengths) and strengths[idx] is not None else 1.0
|
| 651 |
-
sp = float(start_percents[idx]) if idx < len(start_percents) and start_percents[idx] is not None else 0.0
|
| 652 |
-
ep = float(end_percents[idx]) if idx < len(end_percents) and end_percents[idx] is not None else 1.0
|
| 653 |
-
|
| 654 |
-
active_cns.append({
|
| 655 |
-
"video": saved_vid_name,
|
| 656 |
-
"control_net_name": fp,
|
| 657 |
-
"strength": st,
|
| 658 |
-
"start_percent": sp,
|
| 659 |
-
"end_percent": ep
|
| 660 |
-
})
|
| 661 |
-
|
| 662 |
-
# 2. Check flat component list (e.g. [video1, type1, series1, strength1, start1, end1, filepath1, ...])
|
| 663 |
-
cn_data = ui_values.get(f'h3_controlnet_data_{prefix}', []) or ui_values.get('h3_controlnet_data', [])
|
| 664 |
-
if cn_data and not active_cns and isinstance(cn_data, list):
|
| 665 |
-
stride = 7
|
| 666 |
-
for i in range(0, len(cn_data), stride):
|
| 667 |
-
chunk = cn_data[i:i+stride]
|
| 668 |
-
if len(chunk) >= 1 and chunk[0]:
|
| 669 |
-
vid = chunk[0]
|
| 670 |
-
saved_vid_name = save_temp_video(vid) if isinstance(vid, str) and os.path.exists(vid) else vid
|
| 671 |
-
if not saved_vid_name:
|
| 672 |
-
continue
|
| 673 |
-
fp = chunk[6] if len(chunk) > 6 and chunk[6] and chunk[6] != "None" else "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 674 |
-
ensure_file_downloaded(fp, progress=progress)
|
| 675 |
-
st = float(chunk[3]) if len(chunk) > 3 and chunk[3] is not None else 1.0
|
| 676 |
-
sp = float(chunk[4]) if len(chunk) > 4 and chunk[4] is not None else 0.0
|
| 677 |
-
ep = float(chunk[5]) if len(chunk) > 5 and chunk[5] is not None else 1.0
|
| 678 |
-
active_cns.append({
|
| 679 |
-
"video": saved_vid_name,
|
| 680 |
-
"control_net_name": fp,
|
| 681 |
-
"strength": st,
|
| 682 |
-
"start_percent": sp,
|
| 683 |
-
"end_percent": ep
|
| 684 |
-
})
|
| 685 |
-
|
| 686 |
-
# 3. Check direct 'h3_controlnets' list of dicts (from MCP or custom payload)
|
| 687 |
-
raw_cns = ui_values.get('h3_controlnets', [])
|
| 688 |
-
if raw_cns and not active_cns and isinstance(raw_cns, list):
|
| 689 |
-
for item in raw_cns:
|
| 690 |
-
if isinstance(item, dict):
|
| 691 |
-
vid = item.get('video') or item.get('control_video') or item.get('file')
|
| 692 |
-
if vid:
|
| 693 |
-
saved_vid_name = save_temp_video(vid) if isinstance(vid, str) and os.path.exists(vid) else vid
|
| 694 |
-
if not saved_vid_name:
|
| 695 |
-
continue
|
| 696 |
-
fp = item.get('control_net_name') or item.get('filepath') or item.get('name') or "minimax_h3_fun_controlnet_union_pruned_int8_convrot.safetensors"
|
| 697 |
-
ensure_file_downloaded(fp, progress=progress)
|
| 698 |
-
active_cns.append({
|
| 699 |
-
"video": saved_vid_name,
|
| 700 |
-
"control_net_name": fp,
|
| 701 |
-
"strength": float(item.get('strength', 1.0)),
|
| 702 |
-
"start_percent": float(item.get('start_percent', 0.0)),
|
| 703 |
-
"end_percent": float(item.get('end_percent', 1.0))
|
| 704 |
-
})
|
| 705 |
-
|
| 706 |
-
return active_cns
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
def process_h3_guide_inputs(ui_values: dict, prefix: str = "", progress=None) -> list:
|
| 710 |
-
"""
|
| 711 |
-
Parses and prepares MiniMax H3 keyframe guide inputs.
|
| 712 |
-
Supports:
|
| 713 |
-
1. Direct prefix format (e.g. h3_guide_images_h3_ref2va, h3_guide_times_h3_ref2va, etc.)
|
| 714 |
-
2. Direct 'h3_guides' or 'guides' list of dictionaries (from MCP or custom payload)
|
| 715 |
-
Returns:
|
| 716 |
-
List of guide dicts: [{'frame_idx': int, 'image': str, 'video': str, 'audio': str}, ...]
|
| 717 |
-
"""
|
| 718 |
-
active_guides = []
|
| 719 |
-
|
| 720 |
-
# 1. Direct prefix format from Gradio UI
|
| 721 |
-
images = ui_values.get(f'h3_guide_images_{prefix}', []) if prefix else []
|
| 722 |
-
videos = ui_values.get(f'h3_guide_videos_{prefix}', []) if prefix else []
|
| 723 |
-
audios = ui_values.get(f'h3_guide_audios_{prefix}', []) if prefix else []
|
| 724 |
-
times = ui_values.get(f'h3_guide_times_{prefix}', []) if prefix else []
|
| 725 |
-
frames = ui_values.get(f'h3_guide_frames_{prefix}', []) if prefix else []
|
| 726 |
-
|
| 727 |
-
if images or videos or audios:
|
| 728 |
-
max_len = max(len(images), len(videos), len(audios), len(times), len(frames))
|
| 729 |
-
for i in range(max_len):
|
| 730 |
-
img = images[i] if i < len(images) else None
|
| 731 |
-
vid = videos[i] if i < len(videos) else None
|
| 732 |
-
aud = audios[i] if i < len(audios) else None
|
| 733 |
-
t_val = times[i] if i < len(times) else None
|
| 734 |
-
f_val = frames[i] if i < len(frames) else None
|
| 735 |
-
|
| 736 |
-
saved_img = save_temp_image(img) if img is not None else None
|
| 737 |
-
saved_vid = save_temp_video(vid) if vid else None
|
| 738 |
-
saved_aud = save_temp_audio(aud) if aud else None
|
| 739 |
-
|
| 740 |
-
if not (saved_img or saved_vid or saved_aud):
|
| 741 |
-
continue
|
| 742 |
-
|
| 743 |
-
if f_val is not None and str(f_val).strip() != "":
|
| 744 |
-
try:
|
| 745 |
-
frame_idx = int(round(float(f_val)))
|
| 746 |
-
except (ValueError, TypeError):
|
| 747 |
-
frame_idx = 0
|
| 748 |
-
elif t_val is not None and str(t_val).strip() != "":
|
| 749 |
-
try:
|
| 750 |
-
frame_idx = int(round(float(t_val) * 24))
|
| 751 |
-
except (ValueError, TypeError):
|
| 752 |
-
frame_idx = 0
|
| 753 |
-
else:
|
| 754 |
-
frame_idx = 0
|
| 755 |
-
|
| 756 |
-
guide_dict = {"frame_idx": max(0, frame_idx)}
|
| 757 |
-
if saved_img:
|
| 758 |
-
guide_dict["image"] = saved_img
|
| 759 |
-
if saved_vid:
|
| 760 |
-
guide_dict["video"] = saved_vid
|
| 761 |
-
if saved_aud:
|
| 762 |
-
guide_dict["audio"] = saved_aud
|
| 763 |
-
active_guides.append(guide_dict)
|
| 764 |
-
|
| 765 |
-
# 2. Check direct 'h3_guides' or 'guides' list of dicts (from MCP or custom payload)
|
| 766 |
-
raw_guides = ui_values.get(f'h3_guides_{prefix}') or ui_values.get('h3_guides') or ui_values.get('guides', [])
|
| 767 |
-
if raw_guides and not active_guides and isinstance(raw_guides, list):
|
| 768 |
-
for item in raw_guides:
|
| 769 |
-
if isinstance(item, dict):
|
| 770 |
-
img = item.get('image')
|
| 771 |
-
vid = item.get('video')
|
| 772 |
-
aud = item.get('audio')
|
| 773 |
-
|
| 774 |
-
saved_img = save_temp_image(img) if img is not None else None
|
| 775 |
-
saved_vid = save_temp_video(vid) if vid else None
|
| 776 |
-
saved_aud = save_temp_audio(aud) if aud else None
|
| 777 |
-
|
| 778 |
-
if not (saved_img or saved_vid or saved_aud):
|
| 779 |
-
continue
|
| 780 |
-
|
| 781 |
-
if item.get('frame_idx') is not None:
|
| 782 |
-
try:
|
| 783 |
-
frame_idx = int(round(float(item['frame_idx'])))
|
| 784 |
-
except (ValueError, TypeError):
|
| 785 |
-
frame_idx = 0
|
| 786 |
-
elif item.get('time_seconds') is not None or item.get('time') is not None:
|
| 787 |
-
try:
|
| 788 |
-
raw_t = item.get('time_seconds') if item.get('time_seconds') is not None else item.get('time')
|
| 789 |
-
frame_idx = int(round(float(raw_t) * 24))
|
| 790 |
-
except (ValueError, TypeError):
|
| 791 |
-
frame_idx = 0
|
| 792 |
-
else:
|
| 793 |
-
frame_idx = 0
|
| 794 |
-
|
| 795 |
-
guide_dict = {"frame_idx": max(0, frame_idx)}
|
| 796 |
-
if saved_img:
|
| 797 |
-
guide_dict["image"] = saved_img
|
| 798 |
-
if saved_vid:
|
| 799 |
-
guide_dict["video"] = saved_vid
|
| 800 |
-
if saved_aud:
|
| 801 |
-
guide_dict["audio"] = saved_aud
|
| 802 |
-
active_guides.append(guide_dict)
|
| 803 |
-
|
| 804 |
-
active_guides.sort(key=lambda x: x['frame_idx'])
|
| 805 |
-
return active_guides
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
workflow_recipes/h3_fl2va_recipe.yaml
DELETED
|
@@ -1,194 +0,0 @@
|
|
| 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 |
-
first_frame_loader:
|
| 77 |
-
class_type: "{{ first_frame_loader_class }}"
|
| 78 |
-
title: "Load Image"
|
| 79 |
-
first_frame_scale:
|
| 80 |
-
class_type: "{{ first_frame_scale_class }}"
|
| 81 |
-
title: "Upscale Image"
|
| 82 |
-
params:
|
| 83 |
-
upscale_method: "nearest-exact"
|
| 84 |
-
crop: "center"
|
| 85 |
-
|
| 86 |
-
last_frame_loader:
|
| 87 |
-
class_type: "{{ last_frame_loader_class }}"
|
| 88 |
-
title: "Load Image"
|
| 89 |
-
last_frame_scale:
|
| 90 |
-
class_type: "{{ last_frame_scale_class }}"
|
| 91 |
-
title: "Upscale Image"
|
| 92 |
-
params:
|
| 93 |
-
upscale_method: "nearest-exact"
|
| 94 |
-
crop: "center"
|
| 95 |
-
|
| 96 |
-
dynamic_lora_chains:
|
| 97 |
-
loras:
|
| 98 |
-
template: LoraLoader
|
| 99 |
-
output_map:
|
| 100 |
-
"unet_loader:0": model
|
| 101 |
-
"clip_loader:0": clip
|
| 102 |
-
input_map:
|
| 103 |
-
model: model
|
| 104 |
-
clip: clip
|
| 105 |
-
template_output_map:
|
| 106 |
-
"0": model
|
| 107 |
-
"1": clip
|
| 108 |
-
end_input_map:
|
| 109 |
-
model:
|
| 110 |
-
- "basic_guider:model"
|
| 111 |
-
- "basic_scheduler:model"
|
| 112 |
-
clip:
|
| 113 |
-
- "minimax_h3:clip"
|
| 114 |
-
|
| 115 |
-
dynamic_h3_controlnet_chains:
|
| 116 |
-
h3_controlnets:
|
| 117 |
-
template: MiniMaxH3FunControlNetApply
|
| 118 |
-
vae_source: "video_vae_loader:0"
|
| 119 |
-
target_nodes:
|
| 120 |
-
- "basic_guider:model"
|
| 121 |
-
- "basic_scheduler:model"
|
| 122 |
-
|
| 123 |
-
dynamic_h3_guide_chains:
|
| 124 |
-
h3_guides:
|
| 125 |
-
template: MiniMaxH3AddGuide
|
| 126 |
-
source_node: "minimax_h3"
|
| 127 |
-
source_output: 0
|
| 128 |
-
vae_source: "video_vae_loader:0"
|
| 129 |
-
audio_vae_source: "audio_vae_loader:0"
|
| 130 |
-
target_nodes:
|
| 131 |
-
- "basic_guider:conditioning"
|
| 132 |
-
|
| 133 |
-
connections:
|
| 134 |
-
- from: "clip_loader:0"
|
| 135 |
-
to: "minimax_h3:clip"
|
| 136 |
-
- from: "video_vae_loader:0"
|
| 137 |
-
to: "minimax_h3:vae"
|
| 138 |
-
- from: "unet_loader:0"
|
| 139 |
-
to: "basic_guider:model"
|
| 140 |
-
- from: "minimax_h3:0"
|
| 141 |
-
to: "basic_guider:conditioning"
|
| 142 |
-
- from: "unet_loader:0"
|
| 143 |
-
to: "basic_scheduler:model"
|
| 144 |
-
- from: "random_noise:0"
|
| 145 |
-
to: "sampler_custom_advanced:noise"
|
| 146 |
-
- from: "basic_guider:0"
|
| 147 |
-
to: "sampler_custom_advanced:guider"
|
| 148 |
-
- from: "ksampler_select:0"
|
| 149 |
-
to: "sampler_custom_advanced:sampler"
|
| 150 |
-
- from: "basic_scheduler:0"
|
| 151 |
-
to: "sampler_custom_advanced:sigmas"
|
| 152 |
-
- from: "minimax_h3:1"
|
| 153 |
-
to: "sampler_custom_advanced:latent_image"
|
| 154 |
-
- from: "sampler_custom_advanced:0"
|
| 155 |
-
to: "vae_decode:samples"
|
| 156 |
-
- from: "video_vae_loader:0"
|
| 157 |
-
to: "vae_decode:vae"
|
| 158 |
-
- from: "sampler_custom_advanced:0"
|
| 159 |
-
to: "vae_decode_audio:samples"
|
| 160 |
-
- from: "audio_vae_loader:0"
|
| 161 |
-
to: "vae_decode_audio:vae"
|
| 162 |
-
- from: "vae_decode:0"
|
| 163 |
-
to: "create_video:images"
|
| 164 |
-
- from: "vae_decode_audio:0"
|
| 165 |
-
to: "create_video:audio"
|
| 166 |
-
- from: "create_video:0"
|
| 167 |
-
to: "save_video:video"
|
| 168 |
-
|
| 169 |
-
- from: "first_frame_loader:0"
|
| 170 |
-
to: "first_frame_scale:image"
|
| 171 |
-
- from: "first_frame_scale:0"
|
| 172 |
-
to: "minimax_h3:first_frame"
|
| 173 |
-
|
| 174 |
-
- from: "last_frame_loader:0"
|
| 175 |
-
to: "last_frame_scale:image"
|
| 176 |
-
- from: "last_frame_scale:0"
|
| 177 |
-
to: "minimax_h3:last_frame"
|
| 178 |
-
|
| 179 |
-
ui_map:
|
| 180 |
-
prompt: "minimax_h3:prompt"
|
| 181 |
-
width:
|
| 182 |
-
- "minimax_h3:width"
|
| 183 |
-
- "first_frame_scale:width"
|
| 184 |
-
- "last_frame_scale:width"
|
| 185 |
-
height:
|
| 186 |
-
- "minimax_h3:height"
|
| 187 |
-
- "first_frame_scale:height"
|
| 188 |
-
- "last_frame_scale:height"
|
| 189 |
-
length: "minimax_h3:length"
|
| 190 |
-
seed: "random_noise:noise_seed"
|
| 191 |
-
filename_prefix: "save_video:filename_prefix"
|
| 192 |
-
first_frame_image: "first_frame_loader:image"
|
| 193 |
-
last_frame_image: "last_frame_loader:image"
|
| 194 |
-
steps: "basic_scheduler:steps"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|