File size: 32,108 Bytes
7e61d08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#!/usr/bin/env python3
"""PPE · MiniMax-H3 ref2va 换装工作流:节点插件安装 + 模型补齐 + 校验 + 工作流整理(RunPod 用)

只做准备和静态检查,不启动生成或训练。

用法(在装了 ComfyUI 的 RunPod 机器终端里):
    python3 /workspace/ppe_models.py --workflow /workspace/1111_api.json
可选:
    --with-full      另外下载 B200 满血版(ref2va bf16 66 GB、官方文本模型 bf16 52 GB、视频 VAE fp16 5 GB)
    --models-dir D   手动指定模型目录(默认 ComfyUI/models,必须在持久化存储上)
    --check-only     只检查,不安装、不下载
    --force          模型目录不在持久化存储上也继续(不建议)

大小和 SHA256 已于 2026-11-03 在 Hugging Face 接口上逐个核对。
"""
from __future__ import annotations

import argparse
import copy
import datetime as dt
import hashlib
import json
import os
import re
import shutil
import struct
import subprocess
import sys
import urllib.request

HF = "https://huggingface.co"


def u(repo, path, rev="main"):
    return f"{HF}/{repo}/resolve/{rev}/{path}"


# ---------------------------------------------------------------------------
# 模型:name, 子目录, 地址, 大小, SHA256, 分组, 说明
#   exact   = 与工作流引用同名同文件
#   renamed = 作者改了名,按作者记录是同一文件(工作流引用会改成新名)
#   chosen  = 你指定的替代文件(工作流引用会改成它)
#   full    = 满血版,加 --with-full 才下载
# ---------------------------------------------------------------------------
MODELS = [
    ("sam3.1_multiplex_fp16.safetensors", "checkpoints", u("Comfy-Org/sam3.1", "checkpoints/sam3.1_multiplex_fp16.safetensors"),
     1745546848, "9ba99c92703c2e8b4f47de2d34a539bb8e18923049e238b780d70dbe6368eb03", "exact", "人物识别 SAM3.1"),
    ("minimax_h3_ref2va_int8_convrot.safetensors", "diffusion_models", u("Comfy-Org/MiniMax-H3", "diffusion_models/minimax_h3_ref2va_int8_convrot.safetensors"),
     34038894550, "9eef934046a0671bc8a5daf87100705e1478419c574cfde70c50fbe6885f76a9", "exact", "前半段主模型 int8"),
    ("minimax_h3_ref2va_pruned_w4a8_mixed.safetensors", "diffusion_models", u("Kijai/MiniMax-H3-experimental", "minimax_h3_ref2va_pruned_w4a8_mixed.safetensors"),
     11770657048, "de2c6c29c4ee702b45e48e40daae3834aeee58ab681c732d9152589a87c89910", "exact", "后半段主模型 w4a8"),
    ("qwen3vl_32b_h3_ultra_uncensored_heretic_int8_convrot.safetensors", "text_encoders",
     u("ethanfel/Qwen3-VL-32B-Ultra-Heretic-H3-ComfyUI-INT8-ConvRot", "qwen3vl_32b_h3_ultra_uncensored_heretic_int8_convrot.safetensors"),
     26363476151, "d84547412144b7c50a6ec77437a889b869d3ace88da77ef1775d3d2a4901c192", "exact", "文本模型(社区改版)"),
    ("minimax_h3_video_vae_int8_convrot.safetensors", "vae", u("Comfy-Org/MiniMax-H3", "vae/minimax_h3_video_vae_int8_convrot.safetensors"),
     2811065184, "52a2c8c73583c86e4f41cdcce3a6ad0ea562987bc0bf3d60a0cef5f5c8e60c0e", "exact", "视频 VAE int8"),
    ("minimax_h3_audio_vae_fp32.safetensors", "vae", u("Comfy-Org/MiniMax-H3", "vae/minimax_h3_audio_vae_fp32.safetensors"),
     605254808, "8e505d95dd1561d47abd43d4238fd40d9bb1ae9e147ed0a4cba778d76ae4db48", "exact", "音频 VAE"),
    ("taeh3.safetensors", "vae_approx", u("OzzyGT/taeh3", "taeh3.safetensors"),
     22709752, "4fd022bfcab08772fe0536b17ea1a3bbb5625be11e397868d1c5d891863d4c13", "exact", "预览小 VAE"),
    ("dmad_minimax_h3_4step_full_critic_comfyui.safetensors", "loras", u("ZhengmingYu/DMAD", "minimax_h3/dmad_minimax_h3_4step_full_critic_comfyui.safetensors"),
     1956195976, "d3ee9f599ef1ac2d76850e90372ce9064fdc2c16e7f3de6a7ba9bc90cb91eb1b", "exact", "4 步加速 LoRA"),
    ("h3_character_swap_pro4500_1000.safetensors", "loras", u("akatz-ai/MiniMax-H3-Character-Swap-LoRA", "h3_character_swap_pro4500_1000.safetensors"),
     155110320, "4b2a3f420ae804c0aa3422761ff84dbd1bf52eef6900ffab6d2e66df63cb4e79", "exact", "换人 LoRA"),
    ("MMH3-ExposureSlider-V1.safetensors", "loras", u("Kutches/minmax", "MMH3-ExposureSlider-V1.safetensors"),
     217896, "530334bb668fc222a179d55097632ef398288e497728518b096fb69e38c8d9f7", "exact", "曝光 LoRA(镜像仓库,原作者 alcaitiff)"),
    ("h3_upscaler_lms_v0.1_fp32.safetensors", "latent_upscale_models", u("Alissonerdx/Minimax-H3-ComfyUI", "latent_upscaler/h3_upscaler_lms_v0.1_fp32.safetensors"),
     1381153616, "7b70711ebf13051bac4b637247f2e6f0db5e1c6da88af3f28ad0165c6483c8c4", "renamed",
     "放大模型;工作流旧名 h3_upscaler_sharpness_2000steps_v0.1_fp32(按作者记录为同一文件)"),
    ("minimax_h3_lms_v1.0_r64.safetensors", "loras", u("Alissonerdx/Minimax-H3-ComfyUI", "loras/minimax_h3_lms_v1.0_r64.safetensors"),
     1239664536, "16f3195bc6bffa431c0598dc2031e520ba058b4fcbc9f104db9e3fdfdeacf60c", "chosen",
     "LMS 作者原版,你指定替代节点 610 的 _r2(不是同一文件)"),
    ("MysticXXX_MMH3-V4-ref2va.safetensors", "loras",
     u("jinksa77/Minimax_H3", "MysticXXX_MMH3-V4-ref2va.safetensors", "21a3da2332b977f756a001192b106fe95f020277"),
     137654280, "106243744bb11cf962d66a92fd837f9744431ecdf2d4ebd63ff5385afec11b59", "chosen",
     "你指定替代节点 636/660 的 MysticXXX-ref2va-V4(成人向 LoRA;与旧名文件是否同一文件未确认)"),
    ("minimax_h3_ref2va_bf16.safetensors", "diffusion_models", u("Comfy-Org/MiniMax-H3", "diffusion_models/minimax_h3_ref2va_bf16.safetensors"),
     66280487368, "e32c54c1a7b4f5f397f195cea267ccb18806303bb665678c4bee60953bdf3026", "full", "满血版主模型 bf16(B200 测试用)"),
    ("qwen3vl_32b_minimax_h3_bf16.safetensors", "text_encoders", u("Comfy-Org/MiniMax-H3", "text_encoders/qwen3vl_32b_minimax_h3_bf16.safetensors"),
     51506295256, "600d567f6a9629c8574e8e7041b199bdd9c59a986afa7906910a81919610607d", "full", "官方文本模型 bf16(B200 测试用)"),
    ("minimax_h3_video_vae_fp16.safetensors", "vae", u("Comfy-Org/MiniMax-H3", "vae/minimax_h3_video_vae_fp16.safetensors"),
     5207808496, "7c1f131492e7eddacaac9069a61b81bdd39de5cc96561e677c5eab1cdce5e522", "full", "视频 VAE fp16(B200 测试用)"),
]
GROUP = {"exact": "完全匹配", "renamed": "改名同文件", "chosen": "指定替代", "full": "满血版"}

# 工作流里要改的模型引用(旧名 → 新名)
RENAME = {
    "h3_upscaler_sharpness_2000steps_v0.1_fp32.safetensors": "h3_upscaler_lms_v0.1_fp32.safetensors",   # 节点 645
    "minimax_h3_lms_v1.0_r64_r2.safetensors": "minimax_h3_lms_v1.0_r64.safetensors",                     # 节点 610
    "MysticXXX-ref2va-V4.safetensors": "MysticXXX_MMH3-V4-ref2va.safetensors",                           # 节点 636 / 660
}
REMOVE_BRIDGE = [632]        # jamie LoRA:删除节点,上游模型直接接到下游
REMOVE_NODES = [650, 651]    # 已静音的打包节点(VideoCombineNode 找不到来源,CompressImages 用不上)

# ---------------------------------------------------------------------------
# 节点插件:目录名, 地址, 提供的节点
# ---------------------------------------------------------------------------
NODE_PACKS = [
    ("ComfyUI-KJNodes", "https://github.com/kijai/ComfyUI-KJNodes",
     ["GetImageSizeAndCount", "ImageConcatMulti", "ModelPreviewOverrideKJ", "MiniMaxChunkFeedForward",
      "MiniMaxLowVRAMAttention", "MiniMaxH3MemoryEfficientSageAttentionPatch"]),
    ("ComfyUI-Easy-Use", "https://github.com/yolain/ComfyUI-Easy-Use", ["easy ifElse", "easy int", "easy positive", "easy showAnything"]),
    ("ComfyUI-VideoHelperSuite", "https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite", ["VHS_LoadVideo", "VHS_VideoCombine"]),
    ("ComfyUI_LayerStyle", "https://github.com/chflame163/ComfyUI_LayerStyle", ["LayerUtility: ImageScaleByAspectRatio V2"]),
    ("ComfyUI_Comfyroll_CustomNodes", "https://github.com/Suzie1/ComfyUI_Comfyroll_CustomNodes", ["CR Prompt Text"]),
    ("ComfyUI-utils-nodes", "https://github.com/zhangp365/ComfyUI-utils-nodes", ["ConcatTextOfUtils"]),
    ("ComfyUI_SwiftCut", "https://github.com/yichengup/ComfyUI_SwiftCut", ["YCImageBatchBlend"]),
    ("Comfyui_Minimax_h3_latent_Upscaler", "https://github.com/LBH-123-AI/Comfyui_Minimax_h3_latent_Upscaler", ["MinimaxH3LatentUpscaler3D"]),
]
# 单文件节点:SolAttnMiniMax(Sol 稀疏注意力),放在 custom_nodes 根目录
SINGLE_FILE_NODES = [
    ("sol_attn_minimax_v2.py",
     "https://raw.githubusercontent.com/xm6018924/BSAI-ComfyUI-Sol-H3/bd05744bd2c98a9cfd62daac1ccfece4f8ee5521/sol_attn_minimax_v2.py",
     ["SolAttnMiniMax"]),
]
# ComfyUI 本体需要有的新节点(太旧要更新 ComfyUI)
CORE_NEEDED = ["SAM3_VideoTrack", "SCAIL2ColoredMask", "MiniMaxH3ReferenceToVideo", "MiniMaxH3SigmaShift", "EmptyAudio",
               "ComfyMathExpression", "ModelAttentionBackend", "LoraLoaderBypassModelOnly", "LTXVConcatAVLatent", "ManualSigmas"]

LICENSE = [
    ("Comfy-Org/MiniMax-H3 官方模型、VAE、文本模型", "以 MiniMax-H3 官方许可为准,未核实商用条款"),
    ("SAM3.1", "以 Meta / Comfy-Org 页面为准,未核实"),
    ("MMH3-ExposureSlider-V1", "未核实独立商用授权(镜像仓库 Kutches/minmax)"),
    ("h3_upscaler_lms_v0.1_fp32", "上游 LBH 为 Apache-2.0;Alissonerdx 微调文件为混合许可,商用条款未确认"),
    ("minimax_h3_lms_v1.0_r64", "混合许可,商用条款未确认"),
    ("MysticXXX_MMH3-V4-ref2va", "成人向;原作者商用许可未核实(jinksa77 为镜像)"),
    ("dmad / character_swap / taeh3 / heretic 文本模型 / w4a8", "未核实"),
    ("各节点插件", "以各 GitHub 仓库的 LICENSE 为准,未逐个核实"),
]

LINES: list[str] = []


def out(s=""):
    print(s, flush=True)
    LINES.append(s)


def sh(cmd, timeout=600):
    try:
        r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
        return (r.stdout + ("\n" + r.stderr if r.returncode else "")).strip(), r.returncode
    except Exception as e:  # noqa: BLE001
        return f"(失败: {e})", 1


def sho(cmd, timeout=120):
    return sh(cmd, timeout)[0]


def human(n):
    for unit in ("B", "KB", "MB", "GB"):
        if n < 1024 or unit == "GB":
            return f"{n:.1f} {unit}" if unit != "B" else f"{n} B"
        n /= 1024
    return str(n)


# ---------------- 环境 ----------------
def find_comfy():
    ok = lambda c: c and os.path.isfile(os.path.join(c, "folder_paths.py")) and os.path.isfile(os.path.join(c, "main.py"))
    for c in [os.environ.get("COMFY_DIR", ""), "/workspace/ComfyUI", "/workspace/comfyui", "/ComfyUI", "/opt/ComfyUI", "/root/ComfyUI"]:
        if ok(c):
            return os.path.realpath(c)
    for p in sho("find /workspace /opt /root / -maxdepth 4 -name folder_paths.py -not -path '/proc/*' "
                 "-not -path '*/site-packages/*' 2>/dev/null", timeout=120).splitlines():
        if ok(os.path.dirname(p)):
            return os.path.realpath(os.path.dirname(p))
    return None


def comfy_python(comfy):
    for p in ("venv/bin/python", ".venv/bin/python", "../venv/bin/python", "../.venv/bin/python"):
        f = os.path.join(comfy, p)
        if os.path.isfile(f):
            return os.path.realpath(f)
    return shutil.which("python3") or sys.executable


def mount_of(path):
    return sho(f"df -P '{path}' | tail -1 | awk '{{print $6}}'") or "?"


def is_persistent(path):
    m = mount_of(path)
    return m not in ("/", "?", ""), m


def extra_paths(comfy):
    res = []
    y = os.path.join(comfy, "extra_model_paths.yaml")
    if not os.path.isfile(y):
        return y, None, res
    txt = open(y, encoding="utf-8", errors="replace").read()
    try:
        import yaml
        data = yaml.safe_load(txt) or {}
        for _, sec in data.items():
            if not isinstance(sec, dict):
                continue
            base = sec.get("base_path", "")
            for k, v in sec.items():
                if k in ("base_path", "is_default"):
                    continue
                for line in str(v).splitlines():
                    if line.strip():
                        res.append((k, os.path.normpath(os.path.join(base, line.strip()))))
    except Exception as e:  # noqa: BLE001
        res.append(("解析失败", str(e)))
    return y, txt, res


# ---------------- 校验 / 下载 ----------------
def safetensors_ok(path):
    try:
        with open(path, "rb") as f:
            n = struct.unpack("<Q", f.read(8))[0]
            if not (2 <= n <= 200 * 1024 * 1024):
                return False, f"文件头长度不合理 ({n})"
            head = f.read(n)
        if not head.lstrip().startswith(b"{"):
            return False, "文件头不是 JSON(可能下载到了网页)"
        json.loads(head)
        return True, "文件头正常"
    except Exception as e:  # noqa: BLE001
        return False, f"读不了文件头: {e}"


def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for b in iter(lambda: f.read(16 * 1024 * 1024), b""):
            h.update(b)
    return h.hexdigest()


def verify(path, size, sha):
    if not os.path.isfile(path):
        return False, "不存在"
    real = os.path.getsize(path)
    if real != size:
        return False, f"大小不对:{real} ≠ {size}"
    ok, msg = safetensors_ok(path)
    if not ok:
        return False, msg
    out(f"      计算 SHA256 … ({human(size)})")
    got = sha256(path)
    if got != sha:
        return False, f"SHA256 不对:{got}"
    return True, "大小、文件头、SHA256 全部通过"


def download(url, dst, size, sha):
    os.makedirs(os.path.dirname(dst), exist_ok=True)
    part = dst + ".part"
    hdr = f"-H 'Authorization: Bearer {os.environ['HF_TOKEN']}'" if os.environ.get("HF_TOKEN") else ""
    for attempt in range(1, 4):
        if os.path.exists(part) and os.path.getsize(part) > size:
            os.replace(part, part + f".oversize.{int(dt.datetime.now().timestamp())}")
        res, _ = sh(f"curl -L --fail -C - --retry 5 --retry-delay 5 --retry-all-errors --connect-timeout 30 "
                    f"{hdr} -o '{part}' -w '%{{http_code}}' '{url}' 2>/dev/null; echo \" rc=$?\"", timeout=6 * 3600)
        have = os.path.getsize(part) if os.path.exists(part) else 0
        out(f"      第 {attempt} 次:HTTP {res.splitlines()[0] if res else '?'},已下载 {human(have)} / {human(size)}")
        if have == size:
            break
    ok, msg = verify(part, size, sha)
    if ok:
        os.replace(part, dst)
    return ok, msg


# ---------------- 节点 ----------------
def scan_types(roots, types):
    blob = []
    for root in roots:
        for r, dirs, files in os.walk(root):
            dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "models", "output", "input", "temp", "__pycache__", "tests")]
            for f in files:
                if f.endswith(".py"):
                    try:
                        blob.append(open(os.path.join(r, f), encoding="utf-8", errors="ignore").read())
                    except OSError:
                        pass
    text = "\n".join(blob)
    return {t: (f'"{t}"' in text or f"'{t}'" in text) for t in types}


def running_types():
    try:
        with urllib.request.urlopen("http://127.0.0.1:8188/object_info", timeout=10) as r:
            return set(json.load(r))
    except Exception:  # noqa: BLE001
        return None


def install_nodes(comfy, py, check_only):
    cn = os.path.join(comfy, "custom_nodes")
    os.makedirs(cn, exist_ok=True)
    existing = {d.lower(): d for d in os.listdir(cn)}
    rows = []
    for name, url, types in NODE_PACKS:
        have = existing.get(name.lower())
        if have:
            rows.append((name, "已安装", os.path.join(cn, have)))
            continue
        if check_only:
            rows.append((name, "缺失(只检查)", url))
            continue
        out(f"  安装 {name} ← {url}")
        res, rc = sh(f"git clone --depth 1 '{url}' '{os.path.join(cn, name)}'", timeout=900)
        if rc:
            rows.append((name, "安装失败:" + res[-200:], url))
            continue
        req = os.path.join(cn, name, "requirements.txt")
        if os.path.isfile(req):
            res, rc = sh(f"'{py}' -m pip install -r '{req}'", timeout=1800)
            out(f"      依赖:{'装好了' if rc == 0 else '有报错 → ' + res[-300:]}")
        rows.append((name, "新装", os.path.join(cn, name)))
    for fname, url, types in SINGLE_FILE_NODES:
        dst = os.path.join(cn, fname)
        if os.path.isfile(dst):
            rows.append((fname, "已安装", dst))
        elif check_only:
            rows.append((fname, "缺失(只检查)", url))
        else:
            res, rc = sh(f"curl -L --fail --retry 5 -o '{dst}.part' '{url}' && mv '{dst}.part' '{dst}'", timeout=300)
            rows.append((fname, "新装" if rc == 0 else "安装失败:" + res[-200:], dst))
    return rows


# ---------------- 工作流 ----------------
def wf_refs(wf):
    refs = []
    for n in wf.get("nodes", []):
        vals = n.get("widgets_values")
        vals = vals if isinstance(vals, list) else list((vals or {}).values())
        for v in vals:
            if isinstance(v, str) and re.search(r"\.(safetensors|pt|pth|ckpt|bin|gguf)$", v):
                st = vals[1] if "Lora" in n["type"] and len(vals) > 1 and isinstance(vals[1], (int, float)) else None
                refs.append(dict(id=n["id"], type=n["type"], mode=n.get("mode", 0), name=v, strength=st))
    return refs


MODE = {0: "启用", 2: "静音", 4: "旁路"}


def rename_refs(wf, mapping):
    changed = []
    for n in wf.get("nodes", []):
        for key in ("widgets_values", "widgets_values_named"):
            vals = n.get(key)
            items = list(enumerate(vals)) if isinstance(vals, list) else list((vals or {}).items())
            for k, v in items:
                if isinstance(v, str) and v in mapping:
                    vals[k] = mapping[v]
                    if key == "widgets_values":
                        changed.append(f"节点 {n['id']} {n['type']}:{v} → {mapping[v]}")
    return changed


def _drop_link(wf, lid):
    L = {l[0]: l for l in wf["links"]}
    if lid not in L:
        return
    _, o, os_, t, ts, _ = L[lid]
    N = {n["id"]: n for n in wf["nodes"]}
    if o in N:
        outs = N[o]["outputs"][os_].get("links") or []
        N[o]["outputs"][os_]["links"] = [x for x in outs if x != lid]
    if t in N and N[t]["inputs"][ts].get("link") == lid:
        N[t]["inputs"][ts]["link"] = None
    wf["links"] = [l for l in wf["links"] if l[0] != lid]


def remove_bridge(wf, nid):
    """删掉一个“模型进、模型出”的节点(如 LoRA),把上游直接接到所有下游。"""
    N = {n["id"]: n for n in wf["nodes"]}
    if nid not in N:
        return f"节点 {nid} 不在工作流里,跳过"
    n = N[nid]
    L = {l[0]: l for l in wf["links"]}
    inp = next((i for i in n["inputs"] if i.get("type") == "MODEL" and i.get("link") is not None), None)
    outp = next((o for o in n["outputs"] if o.get("type") == "MODEL"), None)
    if not inp or not outp:
        return f"节点 {nid} 不是模型进出的节点,没有删"
    src = L[inp["link"]]
    downstream = [L[x] for x in (outp.get("links") or [])]
    for lid in [i.get("link") for i in n["inputs"] if i.get("link") is not None] + list(outp.get("links") or []):
        _drop_link(wf, lid)
    N = {x["id"]: x for x in wf["nodes"]}
    for d in downstream:
        wf["last_link_id"] = wf.get("last_link_id", max(l[0] for l in wf["links"])) + 1
        lid = wf["last_link_id"]
        wf["links"].append([lid, src[1], src[2], d[3], d[4], "MODEL"])
        N[src[1]]["outputs"][src[2]].setdefault("links", []).append(lid)
        N[d[3]]["inputs"][d[4]]["link"] = lid
    wf["nodes"] = [x for x in wf["nodes"] if x["id"] != nid]
    tgt = ", ".join(f"{d[3]} {N[d[3]]['type']}" for d in downstream)
    return f"删除节点 {nid} {n['type']}({(n.get('widgets_values') or [''])[0]}),{src[1]} {N[src[1]]['type']} 直接接到 {tgt}"


def remove_nodes(wf, ids):
    msgs = []
    for nid in ids:
        N = {n["id"]: n for n in wf["nodes"]}
        if nid not in N:
            continue
        n = N[nid]
        lids = [i.get("link") for i in n.get("inputs", []) if i.get("link") is not None]
        lids += [x for o in n.get("outputs", []) for x in (o.get("links") or [])]
        for lid in lids:
            _drop_link(wf, lid)
        wf["nodes"] = [x for x in wf["nodes"] if x["id"] != nid]
        msgs.append(f"删除节点 {nid} {n['type']}(原本已静音)")
    return msgs


def check_links(wf):
    N = {n["id"]: n for n in wf["nodes"]}
    bad = 0
    for i, o, os_, t, ts, _ in wf["links"]:
        if o not in N or t not in N or i not in (N[o]["outputs"][os_].get("links") or []) or N[t]["inputs"][ts].get("link") != i:
            bad += 1
    for n in wf["nodes"]:
        for inp in n.get("inputs", []):
            if inp.get("link") is not None and not any(l[0] == inp["link"] for l in wf["links"]):
                bad += 1
    return bad


# ---------------- 主流程 ----------------
def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--workflow", default="")
    ap.add_argument("--models-dir", default="")
    ap.add_argument("--with-full", action="store_true")
    ap.add_argument("--check-only", action="store_true")
    ap.add_argument("--force", action="store_true")
    a = ap.parse_args()
    ts = dt.datetime.now().strftime("%Y%m%d_%H%M%S")

    out("=" * 72)
    out(f"PPE 模型与节点准备  {ts}   (只做准备和静态检查,没有运行生成)")
    out("=" * 72)

    # 1. 环境
    out("\n[1] 环境")
    comfy = find_comfy()
    out(f"  ComfyUI 目录:{comfy or '没找到'}")
    if not comfy:
        out("  !! 这台机器上没有 ComfyUI,停止。请换用装了 ComfyUI 的机器(或先装 ComfyUI)。")
        return finish(ts, 2)
    py = comfy_python(comfy)
    out(f"  ComfyUI 用的 Python:{py}")
    out("  ComfyUI 版本:" + sho(f"cd '{comfy}' && git log -1 --format='%h %cd' --date=short 2>/dev/null"))
    out("  显卡:" + (sho("nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader") or "无"))
    out("  torch / CUDA:" + sho(f"'{py}' -c 'import torch;print(torch.__version__, torch.version.cuda)' 2>&1 | tail -1"))
    out("  comfy-kitchen:" + sho(f"'{py}' -c 'import comfy_kitchen as c;print(getattr(c,\"__version__\",\"?\"), \"sol_attn=\", hasattr(c,\"sol_attn\"))' 2>&1 | tail -1"))
    sage, sage_rc = sh(f"'{py}' -c 'import sageattention as s;print(getattr(s,\"__version__\",\"已安装\"))'")
    sage = sage.splitlines()[-1] if sage else ""
    out(f"  SageAttention:{sage if sage_rc == 0 else '没装'}")
    out("  " + (sho("df -h /workspace 2>/dev/null | tail -1") or "/workspace 不存在"))
    models_dir = os.path.realpath(a.models_dir or os.path.join(comfy, "models"))
    pers, mnt = is_persistent(models_dir)
    out(f"  模型目录:{models_dir}(挂载点 {mnt})→ {'持久化存储 ✓' if pers else '容器临时盘 ✗,删机器就没了'}")
    y, txt, extra = extra_paths(comfy)
    out(f"  extra_model_paths.yaml:{'有' if txt else '没有'}({y})")
    for k, p in extra:
        out(f"      {k}: {p}  [{'持久化' if is_persistent(p)[0] else '临时盘'}]")
    if not pers and not a.force and not a.check_only:
        out("  !! 模型目录不在持久化存储上,停止下载(可用 --models-dir /workspace/... 指定)。")
        a.check_only = True
    comfy_roots = [models_dir] + [p for _, p in extra if os.path.isdir(p)]
    search_roots = list(dict.fromkeys(comfy_roots + ["/workspace"]))

    def locate(name):
        hits = []
        for r in search_roots:
            hits += [x for x in sho(f"find '{r}' \\( -name .venv -o -name venv -o -name .uv -o -name node_modules -o -name .git "
                                    f"-o -name custom_nodes -o -name site-packages \\) -prune -o -name '{name}' -type f -print "
                                    f"2>/dev/null | head -5", timeout=600).splitlines() if x]
        return list(dict.fromkeys(hits))

    # 2. 节点插件
    out("\n[2] 节点插件")
    node_rows = install_nodes(comfy, py, a.check_only)
    for name, st, where in node_rows:
        out(f"  {name:<40}{st}  {where}")

    # 3. 模型
    out("\n[3] 模型")
    want = [m for m in MODELS if m[5] != "full" or a.with_full]
    results = []
    for name, sub, url, size, sha, group, note in want:
        dst = os.path.join(models_dir, sub, name)
        out(f"\n  · {name}  [{GROUP[group]}]")
        status = None
        for c in [dst] + [h for h in locate(name) if h != dst]:
            if not os.path.isfile(c):
                continue
            ok, msg = verify(c, size, sha)
            out(f"      已有 {c}:{msg}")
            if ok:
                status, path = "已有,校验通过", c
                inside = any(os.path.realpath(c).startswith(os.path.realpath(r) + os.sep) for r in comfy_roots)
                if not inside and not os.path.exists(dst) and not a.check_only:
                    os.makedirs(os.path.dirname(dst), exist_ok=True)
                    os.symlink(c, dst)
                    out(f"      在 ComfyUI 读取范围外,已建链接 {dst} → {c}(没有复制)")
                    status, path = "已有(链接),校验通过", dst
                elif not inside:
                    out("      注意:这个位置 ComfyUI 可能读不到")
                break
        if not status:
            if a.check_only:
                status, path = "缺失(只检查,没下载)", dst
            else:
                if os.path.isfile(dst):
                    os.replace(dst, dst + f".bad_{ts}")
                    out(f"      校验不过的旧文件已改名为 {dst}.bad_{ts}")
                out(f"      下载 → {dst}")
                ok, msg = download(url, dst, size, sha)
                out(f"      {msg}")
                status, path = ("下载完成,校验通过" if ok else f"下载失败:{msg}"), dst
        results.append((name, group, status, path, size, sha, note))

    out("\n  本机旧名文件比对(只有哈希一致才算同一文件):")
    for old, h in {"MysticXXX-ref2va-V4.safetensors": "106243744bb11cf962d66a92fd837f9744431ecdf2d4ebd63ff5385afec11b59",
                   "h3_upscaler_sharpness_2000steps_v0.1_fp32.safetensors": "7b70711ebf13051bac4b637247f2e6f0db5e1c6da88af3f28ad0165c6483c8c4"}.items():
        hits = locate(old)
        if not hits:
            out(f"      {old}:本机没有,无法比对")
        for p in hits:
            got = sha256(p)
            out(f"      {p}:{'哈希一致,确认同一文件' if got == h else '哈希不同,不是同一文件 (' + got + ')'}")
    out(f"      minimax_h3_lms_v1.0_r64_r2.safetensors:{'找到 ' + ', '.join(locate('minimax_h3_lms_v1.0_r64_r2.safetensors')) if locate('minimax_h3_lms_v1.0_r64_r2.safetensors') else '本机没有'}")

    # 4. 工作流
    out("\n[4] 工作流")
    wf_path = a.workflow
    if not wf_path:
        c = sho("grep -rl --include=*.json MinimaxH3LatentUpscaler3D /workspace 2>/dev/null | grep -v -e '\\.bak_' -e '_runpod' | head -1")
        wf_path = c.splitlines()[0] if c else ""
    wf_types = []
    if not wf_path or not os.path.isfile(wf_path):
        out("  没找到工作流 JSON(用 --workflow 指定),跳过工作流检查。")
    else:
        wf = json.load(open(wf_path, encoding="utf-8"))
        base, _ = os.path.splitext(wf_path)
        bak = f"{base}.bak_{ts}.json"
        shutil.copyfile(wf_path, bak)
        out(f"  原工作流(不改动):{wf_path}\n  备份:{bak}")
        new = copy.deepcopy(wf)
        changes = rename_refs(new, RENAME)
        for nid in REMOVE_BRIDGE:
            changes.append(remove_bridge(new, nid))
        changes += remove_nodes(new, REMOVE_NODES)
        bad = check_links(new)
        p_new = f"{base}_runpod.json"
        json.dump(new, open(p_new, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
        out(f"  新工作流:{p_new}(连线检查:{'全部正常' if bad == 0 else f'有 {bad} 处异常'})")
        for c in changes:
            out("      " + c)
        have = {r[0] for r in results if "通过" in r[2]}
        out("\n  新工作流里引用的模型:")
        blocking = []
        for r in wf_refs(new):
            ok = r["name"] in have or bool(locate(r["name"]))
            w = f",权重 {r['strength']}" if r["strength"] is not None else ""
            out(f"      节点 {r['id']:>4} {r['type']:<28} {MODE.get(r['mode'], r['mode'])}{w}:{r['name']}  {'✓' if ok else '✗ 缺失'}")
            if not ok and r["mode"] == 0:
                blocking.append(r)
        out("  会阻塞运行的缺失模型:" + ("、".join(f"节点 {r['id']} {r['name']}" for r in blocking) if blocking else "无"))
        wf_types = sorted({n["type"] for n in new["nodes"] if n.get("mode", 0) == 0})
        if sage_rc != 0:
            nos = copy.deepcopy(new)
            for n in nos["nodes"]:
                if n["type"] == "MiniMaxH3MemoryEfficientSageAttentionPatch":
                    n["mode"] = 4
            p2 = f"{base}_runpod_免Sage.json"
            json.dump(nos, open(p2, "w", encoding="utf-8"), ensure_ascii=False, indent=2)
            out(f"  SageAttention 没装:节点 633(KJ Sage 省显存补丁)运行时会报错。"
                f"\n      另存了一份把 633 设为旁路的版本:{p2}(B200 显存够,这个补丁本来就可以不要)")

    # 5. 节点检查
    out("\n[5] 节点检查")
    rt = running_types()
    if rt is not None:
        how = "ComfyUI 正在运行;但新装的插件要重启 ComfyUI 才会加载,下面结果以重启前为准"
        avail = {t: t in rt for t in set(wf_types) | set(CORE_NEEDED)}
    else:
        how = "ComfyUI 没在运行,按代码里能否搜到节点名判断(启动后以界面为准)"
        avail = scan_types([comfy], sorted(set(wf_types) | set(CORE_NEEDED)))
    out(f"  ({how})")
    core_miss = [t for t in CORE_NEEDED if not avail.get(t)]
    out("  ComfyUI 本体缺的节点:" + (", ".join(core_miss) + " → ComfyUI 版本太旧,需要更新(cd ComfyUI && git pull && pip install -r requirements.txt)" if core_miss else "无"))
    miss = [t for t in wf_types if not avail.get(t)]
    out("  工作流用到、仍然缺失的节点:" + (", ".join(miss) if miss else "无"))

    # 6. 汇总
    out("\n[6] 汇总")
    for name, group, status, path, size, sha, note in results:
        out(f"  {name}\n      {GROUP[group]} | {status}\n      {path} | {size} 字节 | sha256 {sha}\n      {note}")
    if not a.with_full:
        out("  满血版没下载(需要时加 --with-full)")
    out("\n  替代说明:")
    out("      节点 610 LMS:_r2 找不到,按你的指定换成作者原版 minimax_h3_lms_v1.0_r64,效果没验证")
    out("      节点 636/660 MysticXXX:按你的指定换成 MysticXXX_MMH3-V4-ref2va(成人向),和原工作流文件是否相同未确认")
    out("      节点 632 jamie:按你的要求已删除,上游模型直接接到下游")
    out("      节点 650/651:原本静音的打包节点,已删除(VideoCombineNode 找不到来源)")
    out("\n  许可(都没有确认可以商用):")
    for k, v in LICENSE:
        out(f"      {k}:{v}")
    out("\n  注意:以上只是安装、下载和静态检查,工作流没有实际运行验证。新装了插件的话要重启 ComfyUI。")
    return finish(ts, 0)


def finish(ts, code):
    d = "/workspace" if os.path.isdir("/workspace") else "."
    p = os.path.join(d, f"ppe_model_report_{ts}.txt")
    with open(p, "w", encoding="utf-8") as f:
        f.write("\n".join(LINES) + "\n")
    print(f"\n报告已保存:{p}")
    return code


if __name__ == "__main__":
    sys.exit(main())