malcolmrey commited on
Commit
fef8668
·
1 Parent(s): d0d1821

generation guide

Browse files
h3-center/docs/MINIMAX_H3_REFMOD_CREATION_GUIDE.md ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MiniMax-H3 RefMod Creation & Extraction Guide
2
+
3
+ _Version: 1.0.0_
4
+ _Last Updated: September 2026_
5
+ _Target Architecture: MiniMax-H3 (T2V & C2V) + `ComfyUI-MiniMaxH3Mod`_
6
+
7
+ ---
8
+
9
+ ## 1. Overview: What Is a RefMod?
10
+
11
+ A **RefMod (Reference Latent Adapter)** is a lightweight, pre-encoded `.safetensors` file (~1.1 MB – 1.6 MB) that stores compressed conditioning latents extracted through the MiniMax-H3 3D Video VAE.
12
+
13
+ Instead of resizing, transmitting, and VAE-encoding 8+ raw image files on every single generation step (which causes VRAM spikes, latency, and restricts multi-character scaling), a RefMod is **pre-encoded once** from a dataset and loaded instantaneously into `MiniMaxH3RefModsLoader`.
14
+
15
+ ### Key Specifications
16
+ | Parameter | Value / Recommendation | Description |
17
+ |---|---|---|
18
+ | **File Format** | `.safetensors` | Self-contained latent tensor + JSON header metadata |
19
+ | **File Size** | **~1.1 MB – 1.6 MB** | Highly compact, portable across GPU hosts |
20
+ | **Token Budget** | **Up to 8,192 tokens** | Automatically fits within cross-attention limit |
21
+ | **Short-Edge Resolution** | **1024px** (multiples of 32) | Optimized for MiniMax-H3 DiT patch resolution |
22
+ | **Concept Types** | `identity` (default), `style`, `general` | Isolates facial geometry and biometric features |
23
+ | **Target Directory** | `ComfyUI/models/refmods/` | Standard directory scanned by ComfyUI loader |
24
+
25
+ ---
26
+
27
+ ## 2. Prerequisites & Environment Setup
28
+
29
+ To create RefMods, you need:
30
+
31
+ 1. **ComfyUI Installation**: Standard ComfyUI setup.
32
+ 2. **`ComfyUI-MiniMaxH3Mod` Custom Node**:
33
+ ```bash
34
+ cd ComfyUI/custom_nodes
35
+ git clone https://github.com/Luisacaotica/ComfyUI-MiniMaxH3Mod.git
36
+ pip install -r ComfyUI-MiniMaxH3Mod/requirements.txt
37
+ ```
38
+ 3. **MiniMax-H3 Video VAE**:
39
+ - Location: `ComfyUI/models/vae/minimax_h3_video_vae_fp16.safetensors`
40
+ 4. **RefMods Output Folder**:
41
+ - Location: `ComfyUI/models/refmods/` (created automatically if missing).
42
+
43
+ ---
44
+
45
+ ## 3. Dataset Preparation Guidelines
46
+
47
+ The quality and fidelity of a RefMod directly depend on dataset curation:
48
+
49
+ ### A. Persona / Character Identity RefMods
50
+ - **Image Count**: **8 to 20 high-quality images**.
51
+ - **Angles & Views**:
52
+ - 40% Straight-on / front portraits (clear eye contact, neutral and smiling).
53
+ - 30% Three-quarter angle views (left and right).
54
+ - 20% Profile angles.
55
+ - 10% Full-body or waist-up framing.
56
+ - **Lighting & Backgrounds**: Use diverse lighting (daylight, warm indoor, dramatic) with uncluttered or varied backgrounds so the latent extractor focuses on invariant facial and biometric geometry.
57
+ - **Resolution**: High-res originals (1024x1024 or higher). The extractor will automatically downsample/rescale the short edge to 1024px.
58
+ - **Supported Formats**: `.png`, `.jpg`, `.jpeg`, `.webp`, `.bmp`.
59
+
60
+ ### B. Booster RefMods (e.g. `tattoo`)
61
+ - **Image Count**: **6 to 12 targeted close-up images**.
62
+ - **Consistency**: High-detail, sharp focus on target features, clean lighting, free from digital artifacts or extreme motion blur.
63
+
64
+ ---
65
+
66
+ ## 4. Method 1: The Automated Backend Tool (Recommended)
67
+
68
+ The project includes an end-to-end generator CLI located at `sd-backend/scripts/generate_refmod.py` (accessible via npm scripts).
69
+
70
+ ### Basic Command
71
+ ```bash
72
+ # Using npm from the project root:
73
+ npm run datasets:refmod -- <dataset_name_or_folder_path>
74
+
75
+ # Or running Python directly:
76
+ python scripts/generate_refmod.py <dataset_name_or_folder_path>
77
+ ```
78
+
79
+ ### Examples
80
+ ```bash
81
+ # 1. Generate by dataset name located in C:\Development\ai-toolkit\datasets\
82
+ npm run datasets:refmod -- feliciaday
83
+
84
+ # 2. Generate by absolute folder path
85
+ npm run datasets:refmod -- C:\Development\ai-toolkit\datasets\feliciaday
86
+
87
+ # 3. Dry-run to inspect discovered images and exact execution command
88
+ npm run datasets:refmod -- feliciaday --dry-run
89
+
90
+ # 4. Custom RefMod name and description
91
+ npm run datasets:refmod -- feliciaday --name minimaxh3_agusia_v2_refmod --description "Felicia Day updated 2026 likeness"
92
+ ```
93
+
94
+ ### What Method 1 Handles Automatically:
95
+ 1. **Auto-Discovery**: Scans the dataset directory for all supported images, videos, and audio clips (including dedicated `clips/` and `audio/` subfolders).
96
+ 2. **Environment Discovery**: Automatically detects ComfyUI root, ComfyUI virtualenv Python, `extract_mod.py`, and `minimax_h3_video_vae_fp16.safetensors`.
97
+ 3. **Encoding & Token Fitting**: Executes the VAE encoding pipeline and truncates/pools latents to the 8192 token budget.
98
+ 4. **Dual Output Distribution**: Saves the compiled `.safetensors` into `ComfyUI/models/refmods/` for instant live use, and also copies a backup into the source dataset directory.
99
+
100
+ ### CLI Options Reference
101
+ | Flag | Default | Description |
102
+ |---|---|---|
103
+ | `--name <string>` | Auto-derived | Custom name (e.g. `minimaxh3_persona_v1_refmod`) |
104
+ | `--resolution <int>` | `1024` | Short-edge pixel resolution cap |
105
+ | `--max-tokens <int>` | `8192` | Maximum conditioning token budget |
106
+ | `--concept-type <type>` | `identity` | Concept type (`identity`, `style`, `general`) |
107
+ | `--mode <mode>` | `encode` | Extraction mode (`encode`, `optimize`, `svd`) |
108
+ | `--recursive` | `False` | Recursively scan subfolders for images |
109
+ | `--no-copy` | `False` | Do not copy `.safetensors` back into dataset folder |
110
+ | `--dry-run` | `False` | Print discovery summary and command without running |
111
+
112
+ ---
113
+
114
+ ## 5. Method 2: Direct Command-Line Extraction via `extract_mod.py`
115
+
116
+ If you are working directly in the ComfyUI directory or custom scripts, invoke `extract_mod.py` from `ComfyUI-MiniMaxH3Mod`:
117
+
118
+ ```bash
119
+ # Activate ComfyUI virtual environment
120
+ cd C:\Development\ComfyUI
121
+ .\venv\Scripts\activate
122
+
123
+ # Run extraction
124
+ python custom_nodes/ComfyUI-MiniMaxH3Mod/extract_mod.py \
125
+ --vae models/vae/minimax_h3_video_vae_fp16.safetensors \
126
+ --name minimaxh3_feliciaday_v1_refmod \
127
+ --mode encode \
128
+ --concept-type identity \
129
+ --resolution 1024 \
130
+ --max-tokens 8192 \
131
+ --output models/refmods \
132
+ --description "Felicia Day primary persona RefMod" \
133
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\01.png" \
134
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\02.png" \
135
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\03.png" \
136
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\04.png" \
137
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\05.png" \
138
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\06.png" \
139
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\07.png" \
140
+ --image "C:\Development\ai-toolkit\datasets\feliciaday\08.png"
141
+ ```
142
+
143
+ ---
144
+
145
+ ## 6. Method 3: High-Speed In-Memory Batch Extraction
146
+
147
+ When generating dozens of RefMods in bulk across many dataset folders, re-launching Python and re-loading the 3D VAE for each dataset creates unnecessary overhead.
148
+
149
+ Use the Python in-memory batch extraction pattern (`fox_local/scripts/batch_extract_all_datasets_refmod.py`), which **loads the VAE once into VRAM** and processes all datasets sequentially:
150
+
151
+ ```python
152
+ import os
153
+ import sys
154
+ import torch
155
+
156
+ COMFY_ROOT = r"C:\Development\ComfyUI"
157
+ CUSTOM_NODE_DIR = os.path.join(COMFY_ROOT, "custom_nodes", "ComfyUI-MiniMaxH3Mod")
158
+ sys.path.insert(0, CUSTOM_NODE_DIR)
159
+ sys.path.insert(0, COMFY_ROOT)
160
+
161
+ import comfy.model_management
162
+ import comfy.sd
163
+ import comfy.utils
164
+ from common import load_image_file
165
+ from core import H3RefMod, fit_token_budget
166
+
167
+ DATASETS_ROOT = r"C:\Development\ai-toolkit\datasets"
168
+ VAE_PATH = os.path.join(COMFY_ROOT, "models", "vae", "minimax_h3_video_vae_fp16.safetensors")
169
+ OUTPUT_DIR = os.path.join(COMFY_ROOT, "models", "refmods")
170
+
171
+ RESOLUTION = 1024
172
+ MAX_TOKENS = 8192
173
+ device = comfy.model_management.get_torch_device()
174
+
175
+ # 1. Load VAE model ONCE into GPU memory
176
+ sd, metadata = comfy.utils.load_torch_file(VAE_PATH, return_metadata=True)
177
+ vae = comfy.sd.VAE(sd=sd, metadata=metadata, device=device)
178
+
179
+ # 2. Iterate through datasets
180
+ for entry in sorted(os.listdir(DATASETS_ROOT)):
181
+ folder = os.path.join(DATASETS_ROOT, entry)
182
+ if not os.path.isdir(folder):
183
+ continue
184
+
185
+ images = [os.path.join(folder, f) for f in sorted(os.listdir(folder)) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
186
+ if not images:
187
+ continue
188
+
189
+ mod_name = f"minimaxh3_{entry}_v1_refmod"
190
+ out_file = os.path.join(OUTPUT_DIR, f"{mod_name}.safetensors")
191
+ if os.path.exists(out_file):
192
+ continue
193
+
194
+ frames = []
195
+ shapes = []
196
+ # Load and encode images
197
+ for img_path in images:
198
+ src = load_image_file(img_path, RESOLUTION * 2)
199
+ # upscale / rescale
200
+ samples = src[..., :3].movedim(-1, 1)
201
+ samples = comfy.utils.common_upscale(samples, 1024, 1024, "lanczos", "disabled").movedim(1, -1)
202
+ with torch.no_grad():
203
+ z = vae.encode(samples.to(device)).float().cpu()
204
+ frames.append(z.to(torch.float16))
205
+ shapes.append(f"{z.shape[2]}x{z.shape[3]}x{z.shape[4]}")
206
+
207
+ # Concatenate temporal latent frames and fit token budget
208
+ latent = torch.cat(frames, dim=2)
209
+ latent = fit_token_budget(latent, MAX_TOKENS, mod_name)
210
+
211
+ # Instantiate RefMod container and save .safetensors
212
+ mod = H3RefMod(
213
+ name=mod_name,
214
+ kind="video" if latent.shape[2] > 1 else "image",
215
+ latent=latent,
216
+ latent_h=latent.shape[3],
217
+ latent_w=latent.shape[4],
218
+ latent_t=latent.shape[2],
219
+ mode="encode",
220
+ source="stack",
221
+ source_shape=" +".join(shapes),
222
+ pool=f"full-res {latent.shape[4]*16}x{latent.shape[3]*16}px",
223
+ optimize_steps=0,
224
+ tags=[f"{len(frames)} img"],
225
+ description=f"RefMod for {entry}",
226
+ concept_type="identity",
227
+ )
228
+ mod.save(os.path.join(OUTPUT_DIR, mod_name))
229
+ print(f"Generated {mod_name} ({len(frames)} images, {mod.token_count} tokens)")
230
+ ```
231
+
232
+ ---
233
+
234
+ ## 7. Verifying & Validating Created RefMods
235
+
236
+ Once extracted, verify your RefMod file integrity:
237
+
238
+ 1. **Check Output Location**:
239
+ - Ensure the file exists in `ComfyUI/models/refmods/<mod_name>.safetensors`.
240
+ 2. **File Size Check**:
241
+ - File size should be between **1.0 MB and 1.7 MB**. Files smaller than 100 KB indicate empty latents or encoding failures.
242
+ 3. **Metadata Inspection**:
243
+ ```python
244
+ from safetensors import safe_open
245
+ with safe_open("ComfyUI/models/refmods/minimaxh3_feliciaday_v1_refmod.safetensors", framework="pt") as f:
246
+ metadata = f.metadata()
247
+ print("Metadata:", metadata)
248
+ for k in f.keys():
249
+ tensor = f.get_tensor(k)
250
+ print(f"Tensor {k}: shape {tensor.shape}, dtype {tensor.dtype}")
251
+ ```
252
+
253
+ ---
254
+
255
+ ## 8. Utilizing Created RefMods in ComfyUI
256
+
257
+ ### A. Single Persona Setup
258
+ In your ComfyUI workflow (`workflow_api_minimaxh3_t2v.json` or `workflow_api_minimaxh3_c2v.json`):
259
+ - **Node `MiniMaxH3RefModsLoader` (Node 200)**:
260
+ - `mod_1`: Select your created RefMod (e.g. `minimaxh3_feliciaday_v1_refmod`)
261
+ - `strength_1`: `1.0`
262
+ - `copies_1`: `1` (or `2` for stronger face lock)
263
+ - **Node `MiniMaxH3RefModApply` (Node 201)**:
264
+ - Connects `REFMODS` output from Node 200 into the DiT conditioning chain.
265
+
266
+ ### B. Dual-Stack Setup (Persona + Anatomy Booster)
267
+ To combine persona likeness with enhanced lower anatomical definition:
268
+ - `mod_1`: `minimaxh3_mileycyrus_v1_refmod` (strength: `1.0`, copies: `1`)
269
+ - `mod_2`: `minimaxh3_tattoos_v1_refmod` or `minimaxh3_tattoos_v1_refmod` (strength: `0.75`, copies: `1`)
270
+
271
+ ### C. Multi-Character Setup (Up to 8 Personas)
272
+ To render multiple distinct characters in one scene without image count restrictions:
273
+ - `mod_1`: `minimaxh3_feliciaday_v1_refmod` (strength: `1.0`)
274
+ - `mod_2`: `minimaxh3_mileycyrus_v1_refmod` (strength: `1.0`)
275
+ - `mod_3`: `minimaxh3_bradpitt_v1_refmod` (strength: `1.0`)
276
+
277
+ ---
278
+
279
+ ## 9. Troubleshooting & FAQ
280
+
281
+ ### Q: Why did extraction fail with `CUDA out of memory` during VAE encoding?
282
+ **A:** If dataset images are huge (e.g. 4K/8K uncompressed PNGs), loading many simultaneous full-res images into PyTorch can fill VRAM. Set `--resolution 1024`, which caps the image short-edge before VAE tensor transfer, or encode on CPU and transfer latents to GPU.
283
+
284
+ ### Q: Why did the token count get capped at 8192?
285
+ **A:** 8192 tokens is the hardware/architecture cross-attention limit for MiniMax-H3 conditioning. `fit_token_budget()` automatically downsamples or pools the latent stack so it fits into the attention window without exceeding context memory.
286
+
287
+ ### Q: Does adding more images to the dataset always improve the RefMod?
288
+ **A:** Up to 12–16 images provides diminishing returns. Quality and variety (different lighting, clean angles) matter far more than sheer quantity. 8–12 pristine, diverse crops will outperform 50 blurry, repetitive screenshots.
289
+
290
+ ### Q: Where do I distribute RefMods?
291
+ **A:** Open-weight RefMods can be uploaded directly to Hugging Face Hub repositories (e.g. `huggingface.co/malcolmrey`) under standard safetensors model cards.
h3-center/docs/scripts/generate_refmod.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate MiniMax H3 RefMod (.safetensors) from a dataset folder.
2
+
3
+ Automatically scans the dataset directory for reference images, videos, and
4
+ audio clips, invokes ComfyUI's extract_mod.py pipeline with optimal identity
5
+ settings, and saves/copies the resulting RefMod to both ComfyUI's model tree
6
+ and the dataset folder.
7
+
8
+ Usage:
9
+ python scripts/generate_refmod.py <folder_or_dataset_name> [options]
10
+ npm run datasets:generate-refmod -- <folder_or_dataset_name> [options]
11
+ npm run datasets:refmod -- <folder_or_dataset_name> [options]
12
+
13
+ Examples:
14
+ # Generate RefMod for a dataset folder (auto-discovers images & video clips)
15
+ npm run datasets:refmod -- C:\\Development\\ai-toolkit\\datasets\\feliciadaymoviesimages
16
+
17
+ # Generate by dataset name under C:\\Development\\ai-toolkit\\datasets
18
+ npm run datasets:refmod -- feliciadaymoviesimages
19
+
20
+ # Preview media discovered and execution command without encoding
21
+ npm run datasets:refmod -- feliciadaymoviesimages --dry-run
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import os
28
+ import re
29
+ import shutil
30
+ import subprocess # nosec B404
31
+ import sys
32
+ import unicodedata
33
+ from collections.abc import Sequence
34
+ from dataclasses import dataclass, field
35
+ from pathlib import Path
36
+ from typing import NamedTuple
37
+
38
+ # Ensure UTF-8 output on Windows consoles
39
+ reconfig_out = getattr(sys.stdout, "reconfigure", None)
40
+ if callable(reconfig_out):
41
+ reconfig_out(encoding="utf-8", errors="replace")
42
+ reconfig_err = getattr(sys.stderr, "reconfigure", None)
43
+ if callable(reconfig_err):
44
+ reconfig_err(encoding="utf-8", errors="replace")
45
+
46
+ SUPPORTED_IMAGE_EXTENSIONS = {
47
+ ".png",
48
+ ".jpg",
49
+ ".jpeg",
50
+ ".webp",
51
+ ".bmp",
52
+ ".tiff",
53
+ }
54
+
55
+ SUPPORTED_VIDEO_EXTENSIONS = {
56
+ ".mp4",
57
+ ".mkv",
58
+ ".webm",
59
+ ".mov",
60
+ ".avi",
61
+ ".m4v",
62
+ ".flv",
63
+ ".wmv",
64
+ ".ts",
65
+ }
66
+
67
+ SUPPORTED_AUDIO_EXTENSIONS = {
68
+ ".wav",
69
+ ".mp3",
70
+ ".flac",
71
+ ".aac",
72
+ ".m4a",
73
+ ".ogg",
74
+ ".opus",
75
+ }
76
+
77
+ DEFAULT_DATASETS_ROOTS = [
78
+ Path("C:/Development/ai-toolkit/datasets"),
79
+ Path("datasets"),
80
+ ]
81
+
82
+ DEFAULT_COMFYUI_ROOTS = [
83
+ Path("C:/Development/ComfyUI"),
84
+ Path("../ComfyUI"),
85
+ Path("../../ComfyUI"),
86
+ ]
87
+
88
+
89
+ class DatasetMedia(NamedTuple):
90
+ images: list[Path]
91
+ videos: list[Path]
92
+ audios: list[Path]
93
+
94
+
95
+ class ComfyUIEnvironment(NamedTuple):
96
+ comfy_dir: Path
97
+ python_exe: Path
98
+ extract_mod_script: Path
99
+ vae_path: Path
100
+ refmods_dir: Path
101
+
102
+
103
+ class RefModResult(NamedTuple):
104
+ name: str
105
+ comfy_output_path: Path
106
+ dataset_output_path: Path | None
107
+ images_count: int
108
+ videos_count: int
109
+ audios_count: int
110
+ token_count: int | None
111
+ size_mb: float | None
112
+
113
+
114
+ def sanitize_stem(stem: str) -> str:
115
+ """Create a clean, filesystem-safe identifier from a folder or file name."""
116
+ normalized = unicodedata.normalize("NFKD", stem)
117
+ cleaned = re.sub(r"\[[^\]]*\]", "", normalized)
118
+ cleaned = re.sub(r"\([^\)]*\)", "", cleaned)
119
+ cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", cleaned)
120
+ cleaned = re.sub(r"_+", "_", cleaned).strip("_").lower()
121
+ return cleaned if cleaned else "concept"
122
+
123
+
124
+ def resolve_dataset_folder(folder_input: str | Path) -> Path:
125
+ """Resolve dataset folder from absolute, relative, or known dataset roots."""
126
+ path = Path(folder_input).resolve()
127
+ if path.exists() and path.is_dir():
128
+ return path
129
+
130
+ folder_str = str(folder_input).strip("\"'")
131
+ direct_path = Path(folder_str)
132
+ if direct_path.exists() and direct_path.is_dir():
133
+ return direct_path.resolve()
134
+
135
+ # If it's a short name, search standard dataset directories
136
+ for root in DEFAULT_DATASETS_ROOTS:
137
+ candidate = root / folder_str
138
+ if candidate.exists() and candidate.is_dir():
139
+ return candidate.resolve()
140
+
141
+ raise ValueError(f"Dataset directory not found: '{folder_input}'")
142
+
143
+
144
+ def _first_existing(candidates: Sequence[Path]) -> Path | None:
145
+ """Return the first candidate path that exists, resolved, or None."""
146
+ for candidate in candidates:
147
+ if candidate.exists():
148
+ return candidate.resolve()
149
+ return None
150
+
151
+
152
+ def _resolve_comfy_dir(comfy_dir: Path | None) -> Path:
153
+ if comfy_dir is not None and comfy_dir.exists():
154
+ return comfy_dir
155
+
156
+ env_comfy = os.environ.get("COMFYUI_PATH")
157
+ if env_comfy and Path(env_comfy).exists():
158
+ return Path(env_comfy).resolve()
159
+
160
+ resolved = _first_existing([c for c in DEFAULT_COMFYUI_ROOTS if c.is_dir()])
161
+ if resolved is not None:
162
+ return resolved
163
+
164
+ raise ValueError(
165
+ "Could not locate ComfyUI installation directory. "
166
+ "Please specify --comfy-dir or set COMFYUI_PATH environment variable."
167
+ )
168
+
169
+
170
+ def _resolve_python_exe(comfy_dir: Path, python_exe: Path | None) -> Path:
171
+ if python_exe is not None and python_exe.exists():
172
+ return python_exe
173
+
174
+ candidates = [
175
+ comfy_dir / "venv" / "Scripts" / "python.exe",
176
+ comfy_dir / "venv" / "bin" / "python",
177
+ Path(sys.executable),
178
+ ]
179
+ return _first_existing(candidates) or Path(sys.executable)
180
+
181
+
182
+ def _resolve_extract_mod_script(comfy_dir: Path, extract_mod_script: Path | None) -> Path:
183
+ if extract_mod_script is not None and extract_mod_script.exists():
184
+ return extract_mod_script
185
+
186
+ candidates = [
187
+ comfy_dir / "custom_nodes" / "ComfyUI-MiniMaxH3Mod" / "extract_mod.py",
188
+ Path("custom_nodes/ComfyUI-MiniMaxH3Mod/extract_mod.py"),
189
+ ]
190
+ resolved = _first_existing(candidates)
191
+ if resolved is None:
192
+ raise ValueError(
193
+ f"Could not locate extract_mod.py under ComfyUI custom_nodes: {comfy_dir}. "
194
+ "Ensure ComfyUI-MiniMaxH3Mod is installed."
195
+ )
196
+ return resolved
197
+
198
+
199
+ def _resolve_vae_path(comfy_dir: Path, vae_path: Path | None) -> Path:
200
+ if vae_path is not None and vae_path.exists():
201
+ return vae_path
202
+
203
+ candidates = [
204
+ comfy_dir / "models" / "vae" / "minimax_h3_video_vae_fp16.safetensors",
205
+ comfy_dir / "models" / "vae" / "minimax_h3_video_vae.safetensors",
206
+ comfy_dir / "models" / "vae" / "h3_video_vae_fp16.safetensors",
207
+ ]
208
+ resolved = _first_existing(candidates)
209
+ if resolved is None:
210
+ raise ValueError(
211
+ f"Could not locate MiniMax H3 Video VAE in {comfy_dir / 'models' / 'vae'}. "
212
+ "Please provide --vae path explicitly."
213
+ )
214
+ return resolved
215
+
216
+
217
+ def discover_comfyui_environment(
218
+ comfy_dir: Path | None = None,
219
+ python_exe: Path | None = None,
220
+ extract_mod_script: Path | None = None,
221
+ vae_path: Path | None = None,
222
+ refmods_dir: Path | None = None,
223
+ ) -> ComfyUIEnvironment:
224
+ """Discover ComfyUI installation, Python virtualenv, extract_mod.py script, and H3 VAE."""
225
+ resolved_comfy = _resolve_comfy_dir(comfy_dir)
226
+ resolved_python = _resolve_python_exe(resolved_comfy, python_exe)
227
+ resolved_script = _resolve_extract_mod_script(resolved_comfy, extract_mod_script)
228
+ resolved_vae = _resolve_vae_path(resolved_comfy, vae_path)
229
+
230
+ resolved_refmods = refmods_dir or (resolved_comfy / "models" / "refmods").resolve()
231
+ resolved_refmods.mkdir(parents=True, exist_ok=True)
232
+
233
+ return ComfyUIEnvironment(
234
+ comfy_dir=resolved_comfy,
235
+ python_exe=resolved_python,
236
+ extract_mod_script=resolved_script,
237
+ vae_path=resolved_vae,
238
+ refmods_dir=resolved_refmods,
239
+ )
240
+
241
+
242
+ def natural_sort_key(s: str | Path) -> list[int | str]:
243
+ """Sort strings containing numbers in human/natural order."""
244
+ return [int(t) if t.isdigit() else t.lower() for t in re.split(r"(\d+)", str(s))]
245
+
246
+
247
+ @dataclass
248
+ class _MediaBuckets:
249
+ images: list[Path] = field(default_factory=list)
250
+ videos: list[Path] = field(default_factory=list)
251
+ audios: list[Path] = field(default_factory=list)
252
+
253
+
254
+ def _classify_file(file_path: Path, buckets: _MediaBuckets) -> None:
255
+ ext = file_path.suffix.lower()
256
+ if ext in SUPPORTED_IMAGE_EXTENSIONS:
257
+ buckets.images.append(file_path)
258
+ elif ext in SUPPORTED_VIDEO_EXTENSIONS:
259
+ buckets.videos.append(file_path)
260
+ elif ext in SUPPORTED_AUDIO_EXTENSIONS:
261
+ buckets.audios.append(file_path)
262
+
263
+
264
+ def _scan_recursive(folder: Path, buckets: _MediaBuckets) -> None:
265
+ for entry in folder.rglob("*"):
266
+ if entry.is_file():
267
+ _classify_file(entry, buckets)
268
+
269
+
270
+ def _scan_top_level(folder: Path, buckets: _MediaBuckets) -> None:
271
+ for entry in folder.iterdir():
272
+ if entry.is_file():
273
+ _classify_file(entry, buckets)
274
+
275
+
276
+ def _scan_subfolder_by_extension(subfolder: Path, extensions: set[str]) -> list[Path]:
277
+ """Files directly under subfolder whose extension is in extensions, if it exists at all."""
278
+ if not subfolder.is_dir():
279
+ return []
280
+ return [
281
+ entry
282
+ for entry in subfolder.iterdir()
283
+ if entry.is_file() and entry.suffix.lower() in extensions
284
+ ]
285
+
286
+
287
+ def _fill_missing_from_subfolders(folder: Path, buckets: _MediaBuckets) -> None:
288
+ """A non-recursive scan misses clips/audio kept in dedicated subfolders — fill from those."""
289
+ if not buckets.videos:
290
+ buckets.videos.extend(
291
+ _scan_subfolder_by_extension(folder / "clips", SUPPORTED_VIDEO_EXTENSIONS)
292
+ )
293
+
294
+ if not buckets.audios:
295
+ for sub in ("audio", "clips_audio"):
296
+ buckets.audios.extend(
297
+ _scan_subfolder_by_extension(folder / sub, SUPPORTED_AUDIO_EXTENSIONS)
298
+ )
299
+
300
+
301
+ def scan_dataset_media(folder: Path, recursive: bool = False) -> DatasetMedia:
302
+ """Scan folder for reference images, video clips, and audio files."""
303
+ buckets = _MediaBuckets()
304
+
305
+ if recursive:
306
+ _scan_recursive(folder, buckets)
307
+ else:
308
+ _scan_top_level(folder, buckets)
309
+ _fill_missing_from_subfolders(folder, buckets)
310
+
311
+ buckets.images.sort(key=natural_sort_key)
312
+ buckets.videos.sort(key=natural_sort_key)
313
+ buckets.audios.sort(key=natural_sort_key)
314
+
315
+ return DatasetMedia(images=buckets.images, videos=buckets.videos, audios=buckets.audios)
316
+
317
+
318
+ def derive_refmod_name(folder: Path, explicit_name: str | None = None) -> str:
319
+ """Derive standard RefMod identifier (e.g. minimaxh3_<persona>_v1_refmod)."""
320
+ if explicit_name:
321
+ clean = explicit_name.strip()
322
+ if clean.lower().endswith(".safetensors"):
323
+ clean = clean[:-12]
324
+ return clean
325
+
326
+ stem = sanitize_stem(folder.name)
327
+ if stem.startswith("minimaxh3_") and stem.endswith("_refmod"):
328
+ return stem
329
+ return f"minimaxh3_{stem}_v1_refmod"
330
+
331
+
332
+ @dataclass
333
+ class ComfyUIEnvOverrides:
334
+ """Explicit overrides for discover_comfyui_environment; a field left None auto-discovers."""
335
+
336
+ comfy_dir: Path | None = None
337
+ python_exe: Path | None = None
338
+ extract_mod_script: Path | None = None
339
+ vae_path: Path | None = None
340
+ refmods_dir: Path | None = None
341
+
342
+
343
+ def generate_refmod(
344
+ folder_input: str | Path,
345
+ name: str | None = None,
346
+ mode: str = "encode",
347
+ concept_type: str = "identity",
348
+ resolution: int = 1024,
349
+ max_tokens: int = 8192,
350
+ description: str | None = None,
351
+ env_overrides: ComfyUIEnvOverrides | None = None,
352
+ copy_to_dataset: bool = True,
353
+ recursive: bool = False,
354
+ dry_run: bool = False,
355
+ ) -> RefModResult:
356
+ """Scan dataset media and invoke extract_mod.py to generate RefMod."""
357
+ overrides = env_overrides or ComfyUIEnvOverrides()
358
+ folder = resolve_dataset_folder(folder_input)
359
+ env = discover_comfyui_environment(
360
+ comfy_dir=overrides.comfy_dir,
361
+ python_exe=overrides.python_exe,
362
+ extract_mod_script=overrides.extract_mod_script,
363
+ vae_path=overrides.vae_path,
364
+ refmods_dir=overrides.refmods_dir,
365
+ )
366
+
367
+ media = scan_dataset_media(folder, recursive=recursive)
368
+ total_visual_refs = len(media.images) + len(media.videos)
369
+
370
+ print("\n========================================================")
371
+ print(" MiniMax H3 RefMod Generator")
372
+ print("========================================================")
373
+ print(f"Dataset Folder: {folder}")
374
+ print("Found Media:")
375
+ print(f" - Images: {len(media.images)}")
376
+ print(f" - Videos: {len(media.videos)}")
377
+ print(f" - Audios: {len(media.audios)}")
378
+
379
+ if total_visual_refs == 0:
380
+ raise ValueError(
381
+ f"No supported images or videos found in '{folder}'. "
382
+ "MiniMax H3 RefMod extraction requires at least one image or video reference."
383
+ )
384
+
385
+ mod_name = derive_refmod_name(folder, name)
386
+ mod_desc = description or f"{folder.name} persona reference mod"
387
+
388
+ print("\nRefMod Configuration:")
389
+ print(f" Name: {mod_name}")
390
+ print(f" Mode: {mode}")
391
+ print(f" Concept Type: {concept_type}")
392
+ print(f" Resolution: {resolution}px short-edge")
393
+ print(f" Max Tokens: {max_tokens}")
394
+ print(f" Description: {mod_desc}")
395
+ print(f" VAE: {env.vae_path.name}")
396
+ print(f" Output Dir: {env.refmods_dir}")
397
+
398
+ cmd_args: list[str] = [
399
+ str(env.extract_mod_script),
400
+ "--vae",
401
+ str(env.vae_path),
402
+ "--name",
403
+ mod_name,
404
+ "--mode",
405
+ mode,
406
+ "--concept-type",
407
+ concept_type,
408
+ "--resolution",
409
+ str(resolution),
410
+ "--max-tokens",
411
+ str(max_tokens),
412
+ "--output",
413
+ str(env.refmods_dir),
414
+ "--description",
415
+ mod_desc,
416
+ ]
417
+
418
+ for img in media.images:
419
+ cmd_args.extend(["--image", str(img)])
420
+ for vid in media.videos:
421
+ cmd_args.extend(["--video", str(vid)])
422
+
423
+ full_cmd = [str(env.python_exe), *cmd_args]
424
+
425
+ if dry_run:
426
+ print(
427
+ f"\n[DRY RUN] Would execute command with {len(media.images)} image(s) and {len(media.videos)} video(s):"
428
+ )
429
+ print(f" {' '.join(full_cmd[:10])} ... [+{total_visual_refs} media paths]")
430
+ return RefModResult(
431
+ name=mod_name,
432
+ comfy_output_path=env.refmods_dir / f"{mod_name}.safetensors",
433
+ dataset_output_path=folder / f"{mod_name}.safetensors" if copy_to_dataset else None,
434
+ images_count=len(media.images),
435
+ videos_count=len(media.videos),
436
+ audios_count=len(media.audios),
437
+ token_count=None,
438
+ size_mb=None,
439
+ )
440
+
441
+ print("\nExtracting RefMod latents with ComfyUI H3 VAE...")
442
+ proc = subprocess.run( # nosec B603
443
+ full_cmd,
444
+ check=True,
445
+ text=True,
446
+ )
447
+
448
+ if proc.returncode != 0:
449
+ raise RuntimeError(f"extract_mod.py failed with exit code {proc.returncode}")
450
+
451
+ comfy_mod_file = env.refmods_dir / f"{mod_name}.safetensors"
452
+ dataset_mod_file: Path | None = None
453
+
454
+ if not comfy_mod_file.exists():
455
+ raise RuntimeError(f"Expected output file was not created: {comfy_mod_file}")
456
+
457
+ size_bytes = comfy_mod_file.stat().st_size
458
+ size_mb = size_bytes / (1024 * 1024)
459
+
460
+ if copy_to_dataset:
461
+ dataset_mod_file = folder / f"{mod_name}.safetensors"
462
+ shutil.copy2(comfy_mod_file, dataset_mod_file)
463
+ print(f"\nCopied RefMod to dataset folder:\n -> {dataset_mod_file}")
464
+
465
+ print("\nRefMod generated successfully!")
466
+ print(f" File: {comfy_mod_file} ({size_mb:.2f} MB)")
467
+ print(f" Ready for use with 'Load H3 RefMods' (dropdown '{mod_name}')")
468
+
469
+ return RefModResult(
470
+ name=mod_name,
471
+ comfy_output_path=comfy_mod_file,
472
+ dataset_output_path=dataset_mod_file,
473
+ images_count=len(media.images),
474
+ videos_count=len(media.videos),
475
+ audios_count=len(media.audios),
476
+ token_count=None,
477
+ size_mb=size_mb,
478
+ )
479
+
480
+
481
+ def build_parser() -> argparse.ArgumentParser:
482
+ parser = argparse.ArgumentParser(
483
+ description="Generate MiniMax H3 RefMod (.safetensors) from a dataset folder."
484
+ )
485
+ parser.add_argument(
486
+ "folder",
487
+ help="Path or name of the dataset folder containing reference images, videos, and audio.",
488
+ )
489
+ parser.add_argument(
490
+ "--name",
491
+ default=None,
492
+ help="Output RefMod name (default: minimaxh3_<folder_stem>_v1_refmod).",
493
+ )
494
+ parser.add_argument(
495
+ "--mode",
496
+ choices=["encode", "training"],
497
+ default="encode",
498
+ help="RefMod mode: 'encode' = full VAE identity encode (recommended for persons), 'training' = pooled grid.",
499
+ )
500
+ parser.add_argument(
501
+ "--concept-type",
502
+ default="identity",
503
+ choices=[
504
+ "identity",
505
+ "generic",
506
+ "style",
507
+ "action",
508
+ "object",
509
+ "scene",
510
+ "pose",
511
+ "outfit",
512
+ ],
513
+ help="Concept type (default: identity).",
514
+ )
515
+ parser.add_argument(
516
+ "--resolution",
517
+ type=int,
518
+ default=1024,
519
+ help="Target short-edge resolution in px (default: 1024).",
520
+ )
521
+ parser.add_argument(
522
+ "--max-tokens",
523
+ type=int,
524
+ default=8192,
525
+ help="Maximum injected token budget (default: 8192).",
526
+ )
527
+ parser.add_argument(
528
+ "--description",
529
+ default=None,
530
+ help="Text description of the concept embedded into RefMod metadata.",
531
+ )
532
+ parser.add_argument(
533
+ "--comfy-dir",
534
+ type=Path,
535
+ default=None,
536
+ help="ComfyUI root directory (auto-detected if omitted).",
537
+ )
538
+ parser.add_argument(
539
+ "--vae",
540
+ type=Path,
541
+ default=None,
542
+ help="Path to minimax_h3_video_vae_fp16.safetensors (auto-detected if omitted).",
543
+ )
544
+ parser.add_argument(
545
+ "--output",
546
+ type=Path,
547
+ default=None,
548
+ help="Destination directory for RefMod file (default: ComfyUI/models/refmods).",
549
+ )
550
+ parser.add_argument(
551
+ "--no-copy",
552
+ action="store_true",
553
+ help="Do not copy the generated RefMod into the dataset directory.",
554
+ )
555
+ parser.add_argument(
556
+ "--recursive",
557
+ action="store_true",
558
+ help="Recursively search subdirectories for images, videos, and audio files.",
559
+ )
560
+ parser.add_argument(
561
+ "--dry-run",
562
+ action="store_true",
563
+ help="Scan files and display configuration without running extraction.",
564
+ )
565
+ return parser
566
+
567
+
568
+ def main(argv: Sequence[str] | None = None) -> int:
569
+ parser = build_parser()
570
+ args = parser.parse_args(argv)
571
+
572
+ try:
573
+ generate_refmod(
574
+ folder_input=args.folder,
575
+ name=args.name,
576
+ mode=args.mode,
577
+ concept_type=args.concept_type,
578
+ resolution=args.resolution,
579
+ max_tokens=args.max_tokens,
580
+ description=args.description,
581
+ env_overrides=ComfyUIEnvOverrides(
582
+ comfy_dir=args.comfy_dir,
583
+ vae_path=args.vae,
584
+ refmods_dir=args.output,
585
+ ),
586
+ copy_to_dataset=not args.no_copy,
587
+ recursive=args.recursive,
588
+ dry_run=args.dry_run,
589
+ )
590
+ return 0
591
+ except Exception as err: # pylint: disable=broad-except
592
+ print(f"\n[ERROR] {err}", file=sys.stderr)
593
+ return 1
594
+
595
+
596
+ if __name__ == "__main__":
597
+ sys.exit(main())