HEL-892: add pinned H3 loader decoder and video reference contracts
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -21,6 +21,7 @@ except ModuleNotFoundError:
|
||||
|
||||
from calliope.comfyui.companions import load_companions
|
||||
from calliope.comfyui.delivery_scope import exclusion_for
|
||||
from calliope.comfyui.h3_chain_reference import CHAIN_PROFILE
|
||||
from calliope.comfyui.h3_core_reference import CORE_PROFILE
|
||||
from calliope.comfyui.serialization_reference import (
|
||||
ASR_PROFILE,
|
||||
@@ -309,6 +310,7 @@ REFERENCE_PROFILES = (
|
||||
GRID_PROFILE,
|
||||
H3_PROFILE,
|
||||
CORE_PROFILE,
|
||||
CHAIN_PROFILE,
|
||||
)
|
||||
|
||||
|
||||
@@ -603,10 +605,21 @@ def h3_field_evidence(source, prompt):
|
||||
return fields
|
||||
|
||||
|
||||
def core_field_evidence(source):
|
||||
def core_field_evidence(source, profile=CORE_PROFILE):
|
||||
"""Node diagnostics only, including rejected layouts; never a partial prompt."""
|
||||
from calliope.comfyui.h3_core_reference import LAYOUTS, saved_values, serialize_node
|
||||
|
||||
layouts = LAYOUTS
|
||||
if profile == CHAIN_PROFILE:
|
||||
from calliope.comfyui.h3_chain_reference import (
|
||||
LAYOUTS as CHAIN_LAYOUTS,
|
||||
)
|
||||
from calliope.comfyui.h3_chain_reference import (
|
||||
saved_values,
|
||||
serialize_node,
|
||||
)
|
||||
|
||||
layouts = {**layouts, **CHAIN_LAYOUTS}
|
||||
evidence = []
|
||||
links = {
|
||||
e[0]: (i, e)
|
||||
@@ -615,7 +628,7 @@ def core_field_evidence(source):
|
||||
}
|
||||
for i, node in enumerate(source.get("nodes", [])):
|
||||
ct = node.get("type")
|
||||
if ct not in LAYOUTS:
|
||||
if ct not in layouts:
|
||||
continue
|
||||
fields, reasons = [], []
|
||||
try:
|
||||
@@ -624,7 +637,7 @@ def core_field_evidence(source):
|
||||
saved = {}
|
||||
reasons.append(str(exc))
|
||||
for name, value in saved.items():
|
||||
wi = LAYOUTS[ct].index(name)
|
||||
wi = layouts[ct].index(name)
|
||||
fields.append(
|
||||
{
|
||||
"field": name,
|
||||
@@ -657,7 +670,7 @@ def core_field_evidence(source):
|
||||
"declared_type": edge[5],
|
||||
"source_endpoint_only": True,
|
||||
"upstream_type_in_public_profile": any(
|
||||
n.get("id") == edge[1] and n.get("type") in LAYOUTS
|
||||
n.get("id") == edge[1] and n.get("type") in layouts
|
||||
for n in source.get("nodes", [])
|
||||
),
|
||||
}
|
||||
@@ -679,10 +692,44 @@ def core_field_evidence(source):
|
||||
}
|
||||
if ct == "RandomNoise" and saved
|
||||
else None,
|
||||
"contract_manifest": "h3-core-reference/sources.json",
|
||||
"contract_manifest": "h3-chain-reference/sources.json"
|
||||
if profile == CHAIN_PROFILE
|
||||
else "h3-core-reference/sources.json",
|
||||
"not_a_submittable_node_or_partial_prompt": True,
|
||||
}
|
||||
)
|
||||
if profile == CHAIN_PROFILE:
|
||||
# Rejected arrays remain opaque evidence; never drop or name an
|
||||
# unproved third CreateVideo value to make the instance pass.
|
||||
evidence[-1]["raw_saved_values"] = [
|
||||
{
|
||||
"pointer": f"/nodes/{i}/widgets_values/{wi}",
|
||||
"value": value,
|
||||
"json_type": type(value).__name__,
|
||||
}
|
||||
for wi, value in enumerate(node.get("widgets_values", []))
|
||||
]
|
||||
evidence[-1]["effective_field_evidence"] = [
|
||||
{
|
||||
"field": field["field"],
|
||||
"value": field["value"],
|
||||
"json_type": field["json_type"],
|
||||
"pointer": field["source_value_pointer"],
|
||||
"origin": "saved_value",
|
||||
}
|
||||
for field in fields
|
||||
if field["field"] not in {p["input"] for p in physical}
|
||||
] + [
|
||||
{
|
||||
"field": edge["input"],
|
||||
"value": edge["endpoint"],
|
||||
"json_type": "list",
|
||||
"pointer": edge["link_pointer"],
|
||||
"origin": "physical_edge_overrides_saved_value",
|
||||
"endpoint_not_execution_eligibility": True,
|
||||
}
|
||||
for edge in physical
|
||||
]
|
||||
return evidence
|
||||
|
||||
|
||||
@@ -694,6 +741,7 @@ def profile_attempt(source, profile):
|
||||
GRID_PROFILE: "1.41.20",
|
||||
H3_PROFILE: "1.53.10",
|
||||
CORE_PROFILE: "1.53.10",
|
||||
CHAIN_PROFILE: "1.53.10",
|
||||
**VHS_PROFILES,
|
||||
**SETGET_PROFILES,
|
||||
**VIDEOINFO_PROFILES,
|
||||
@@ -874,7 +922,7 @@ def profile_attempt(source, profile):
|
||||
if profile in VHS_PROFILES
|
||||
else "crop-split-reference/verified-facts.json"
|
||||
)
|
||||
if profile == CORE_PROFILE:
|
||||
if profile in (CORE_PROFILE, CHAIN_PROFILE):
|
||||
assumptions.update(
|
||||
{
|
||||
"reference_sources": [
|
||||
@@ -891,6 +939,14 @@ def profile_attempt(source, profile):
|
||||
"random_seed_bound": "core_uint64_intersect_JS_safe_integer",
|
||||
}
|
||||
)
|
||||
if profile == CHAIN_PROFILE:
|
||||
assumptions["reference_sources"].insert(0, "h3-chain-reference/sources.json")
|
||||
assumptions["dynamic_model_membership"] = (
|
||||
"unknown; preserve source string without path normalization"
|
||||
)
|
||||
assumptions["save_video_branch"] = (
|
||||
"codec=auto only; no context-dependent filename replacement"
|
||||
)
|
||||
if profile == H3_PROFILE:
|
||||
assumptions["h3_contract"] = "h3-reference/sources.json"
|
||||
assumptions["reference_sources"] = ["h3-reference/sources.json"]
|
||||
@@ -924,7 +980,7 @@ def profile_attempt(source, profile):
|
||||
and expected == "1.48.6"
|
||||
):
|
||||
assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6"
|
||||
if profile == CORE_PROFILE:
|
||||
if profile in (CORE_PROFILE, CHAIN_PROFILE):
|
||||
assumptions["missing_frontend_policy"] = "explicit_1.53.10_reference_assumption"
|
||||
assumptions["missing_node_declarations"] = [
|
||||
n["pointer"]
|
||||
@@ -950,6 +1006,7 @@ def profile_attempt(source, profile):
|
||||
AUX_PROFILE,
|
||||
PRIMITIVE_PROFILE,
|
||||
CORE_PROFILE,
|
||||
CHAIN_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
*CROP_SPLIT_PROFILES,
|
||||
@@ -981,8 +1038,8 @@ def profile_attempt(source, profile):
|
||||
"issues": result.issues,
|
||||
"unresolved_boundaries": result.unresolved_boundaries,
|
||||
**(
|
||||
{"supported_node_evidence": core_field_evidence(source)}
|
||||
if profile == CORE_PROFILE
|
||||
{"supported_node_evidence": core_field_evidence(source, profile)}
|
||||
if profile in (CORE_PROFILE, CHAIN_PROFILE)
|
||||
else {}
|
||||
),
|
||||
**(
|
||||
@@ -1002,8 +1059,8 @@ def profile_attempt(source, profile):
|
||||
"candidate_sha256": canonical_sha(result.prompt),
|
||||
"candidate_prompt": result.prompt,
|
||||
**(
|
||||
{"supported_node_evidence": core_field_evidence(source)}
|
||||
if profile == CORE_PROFILE
|
||||
{"supported_node_evidence": core_field_evidence(source, profile)}
|
||||
if profile in (CORE_PROFILE, CHAIN_PROFILE)
|
||||
else {}
|
||||
),
|
||||
**(
|
||||
@@ -1132,7 +1189,9 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
|
||||
}
|
||||
if baseline_profiles is None:
|
||||
excluded_profiles = (
|
||||
(CORE_PROFILE,)
|
||||
(CHAIN_PROFILE,)
|
||||
if CHAIN_PROFILE in profiles
|
||||
else (CORE_PROFILE,)
|
||||
if CORE_PROFILE in profiles
|
||||
else (H3_PROFILE,)
|
||||
if H3_PROFILE in profiles
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
"""Ten core0.33.0 contracts combined with the unchanged first six contracts.
|
||||
|
||||
Explicit reference assumptions only; dynamic model membership stays unknown.
|
||||
No upstream execution, path normalization, media inspection or output mapping.
|
||||
"""
|
||||
|
||||
from . import h3_core_reference as first
|
||||
|
||||
CHAIN_PROFILE = "comfy-frontend-1.53.10-core-0.33.0-h3-second-group-reference"
|
||||
LAYOUTS = {
|
||||
"VAELoader": ("vae_name",),
|
||||
"UNETLoader": ("unet_name", "weight_dtype"),
|
||||
"CLIPLoader": ("clip_name", "type", "device"),
|
||||
"KSamplerSelect": ("sampler_name",),
|
||||
"BasicGuider": (),
|
||||
"SamplerCustomAdvanced": (),
|
||||
"VAEDecode": (),
|
||||
"VAEDecodeAudio": (),
|
||||
"CreateVideo": ("fps", "bit_depth"),
|
||||
"SaveVideo": ("filename_prefix", "format", "codec"),
|
||||
}
|
||||
WEIGHT_DTYPES = ("default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2")
|
||||
CLIP_TYPES = (
|
||||
"stable_diffusion",
|
||||
"stable_cascade",
|
||||
"sd3",
|
||||
"stable_audio",
|
||||
"mochi",
|
||||
"ltxv",
|
||||
"pixart",
|
||||
"cosmos",
|
||||
"lumina2",
|
||||
"wan",
|
||||
"hidream",
|
||||
"chroma",
|
||||
"ace",
|
||||
"omnigen2",
|
||||
"qwen_image",
|
||||
"hunyuan_image",
|
||||
"flux2",
|
||||
"ovis",
|
||||
"longcat_image",
|
||||
"cogvideox",
|
||||
"lens",
|
||||
"pixeldit",
|
||||
"ideogram4",
|
||||
"boogu",
|
||||
"krea2",
|
||||
"joyimage",
|
||||
"mage",
|
||||
"minimax",
|
||||
)
|
||||
SAMPLERS = (
|
||||
"euler",
|
||||
"euler_cfg_pp",
|
||||
"euler_ancestral",
|
||||
"euler_ancestral_cfg_pp",
|
||||
"heun",
|
||||
"heunpp2",
|
||||
"exp_heun_2_x0",
|
||||
"exp_heun_2_x0_sde",
|
||||
"dpm_2",
|
||||
"dpm_2_ancestral",
|
||||
"lms",
|
||||
"dpm_fast",
|
||||
"dpm_adaptive",
|
||||
"dpmpp_2s_ancestral",
|
||||
"dpmpp_2s_ancestral_cfg_pp",
|
||||
"dpmpp_sde",
|
||||
"dpmpp_sde_gpu",
|
||||
"dpmpp_2m",
|
||||
"dpmpp_2m_cfg_pp",
|
||||
"dpmpp_2m_sde",
|
||||
"dpmpp_2m_sde_gpu",
|
||||
"dpmpp_2m_sde_heun",
|
||||
"dpmpp_2m_sde_heun_gpu",
|
||||
"dpmpp_3m_sde",
|
||||
"dpmpp_3m_sde_gpu",
|
||||
"ddpm",
|
||||
"lcm",
|
||||
"ipndm",
|
||||
"ipndm_v",
|
||||
"deis",
|
||||
"res_multistep",
|
||||
"res_multistep_cfg_pp",
|
||||
"res_multistep_ancestral",
|
||||
"res_multistep_ancestral_cfg_pp",
|
||||
"gradient_estimation",
|
||||
"gradient_estimation_cfg_pp",
|
||||
"er_sde",
|
||||
"seeds_2",
|
||||
"seeds_3",
|
||||
"sa_solver",
|
||||
"sa_solver_pece",
|
||||
"ddim",
|
||||
"uni_pc",
|
||||
"uni_pc_bh2",
|
||||
)
|
||||
OUTPUT_NAMES = {
|
||||
"VAELoader": ["VAE"],
|
||||
"UNETLoader": ["MODEL"],
|
||||
"CLIPLoader": ["CLIP"],
|
||||
"KSamplerSelect": ["SAMPLER"],
|
||||
"BasicGuider": ["GUIDER"],
|
||||
"SamplerCustomAdvanced": ["output", "denoised_output"],
|
||||
"VAEDecode": ["IMAGE"],
|
||||
"VAEDecodeAudio": ["AUDIO"],
|
||||
"CreateVideo": ["VIDEO"],
|
||||
"SaveVideo": ["video"],
|
||||
}
|
||||
|
||||
|
||||
def definitions():
|
||||
def spec(required, outputs, optional=None):
|
||||
return {
|
||||
"input": {
|
||||
"required": {k: [v] for k, v in required.items()},
|
||||
"optional": {k: [v] for k, v in (optional or {}).items()},
|
||||
},
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
return {
|
||||
**first.definitions(),
|
||||
"VAELoader": spec({"vae_name": "COMBO"}, ["VAE"]),
|
||||
"UNETLoader": spec({"unet_name": "COMBO", "weight_dtype": "COMBO"}, ["MODEL"]),
|
||||
"CLIPLoader": spec({"clip_name": "COMBO", "type": "COMBO"}, ["CLIP"], {"device": "COMBO"}),
|
||||
"KSamplerSelect": spec({"sampler_name": "COMBO"}, ["SAMPLER"]),
|
||||
"BasicGuider": spec({"model": "MODEL", "conditioning": "CONDITIONING"}, ["GUIDER"]),
|
||||
"SamplerCustomAdvanced": spec(
|
||||
{
|
||||
"noise": "NOISE",
|
||||
"guider": "GUIDER",
|
||||
"sampler": "SAMPLER",
|
||||
"sigmas": "SIGMAS",
|
||||
"latent_image": "LATENT",
|
||||
},
|
||||
["LATENT", "LATENT"],
|
||||
),
|
||||
"VAEDecode": spec({"samples": "LATENT", "vae": "VAE"}, ["IMAGE"]),
|
||||
"VAEDecodeAudio": spec({"samples": "LATENT", "vae": "VAE"}, ["AUDIO"]),
|
||||
"CreateVideo": spec(
|
||||
{"images": "IMAGE", "fps": "FLOAT"}, ["VIDEO"], {"audio": "AUDIO", "bit_depth": "INT"}
|
||||
),
|
||||
# Wire JSON uses flat codec="auto". Core dynamic_paths nests it only at execution.
|
||||
"SaveVideo": spec(
|
||||
{
|
||||
"video": "VIDEO",
|
||||
"filename_prefix": "STRING",
|
||||
"format": "COMBO",
|
||||
"codec": "COMFY_DYNAMICCOMBO_V3",
|
||||
},
|
||||
["VIDEO"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def saved_values(node):
|
||||
ct = node.get("type")
|
||||
if ct in first.LAYOUTS:
|
||||
return first.saved_values(node)
|
||||
if ct not in LAYOUTS:
|
||||
raise ValueError("第二组只覆盖十类及已审第一组六类")
|
||||
props = node.get("properties") or {}
|
||||
for key, value in (("cnr_id", "comfy-core"), ("ver", "0.33.0")):
|
||||
if key in props and props[key] != value:
|
||||
raise ValueError("第二组提供方/core版本声明冲突;缺失仅参考假设")
|
||||
if "aux_id" in props:
|
||||
raise ValueError("第二组不解释其它来源身份")
|
||||
if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0:
|
||||
raise ValueError("第二组仅正常mode=0")
|
||||
first.check_overrides(node)
|
||||
first.check_overrides(props)
|
||||
layout, values = LAYOUTS[ct], node.get("widgets_values")
|
||||
if not isinstance(values, list) or len(values) != len(layout):
|
||||
raise ValueError("第二组控件保存布局缺项/多项;不删未知保存值")
|
||||
if "widgets_values_named" in node:
|
||||
named = node["widgets_values_named"]
|
||||
if not isinstance(named, dict) or set(named) != set(layout):
|
||||
raise ValueError("第二组具名保存缺项/多项")
|
||||
if any(type(named[k]) is not type(v) or named[k] != v for k, v in zip(layout, values)):
|
||||
raise ValueError("第二组具名/数组恢复冲突")
|
||||
result = dict(zip(layout, values))
|
||||
for key in ("vae_name", "unet_name", "clip_name"):
|
||||
if key in result and (type(result[key]) is not str or not result[key]):
|
||||
raise ValueError("第二组动态模型名需非空源字符串;目录成员/存在未知")
|
||||
enums = {
|
||||
"weight_dtype": WEIGHT_DTYPES,
|
||||
"type": CLIP_TYPES,
|
||||
"device": ("default", "cpu"),
|
||||
"sampler_name": SAMPLERS,
|
||||
"format": ("auto", "mp4"),
|
||||
}
|
||||
for key, options in enums.items():
|
||||
if key in result and (type(result[key]) is not str or result[key] not in options):
|
||||
raise ValueError(f"第二组{key}静态枚举不符")
|
||||
if ct == "CreateVideo":
|
||||
fps = result["fps"]
|
||||
if type(fps) not in (int, float) or not 1.0 <= fps <= 120.0:
|
||||
raise ValueError("第二组fps有限JSON数需1..120")
|
||||
if type(result["bit_depth"]) is not int or not 8 <= result["bit_depth"] <= 10:
|
||||
raise ValueError("第二组bit_depth需INT 8..10;step仅UI步进")
|
||||
if ct == "SaveVideo":
|
||||
if result["codec"] != "auto" or type(result["codec"]) is not str:
|
||||
raise ValueError("第二组仅证明codec=auto无子控件分支;其它动态布局拒绝")
|
||||
prefix = result["filename_prefix"]
|
||||
if type(prefix) is not str or "%" in prefix:
|
||||
raise ValueError("第二组仅不含%的固定前缀;日期/节点/尺寸上下文替换拒绝")
|
||||
return result
|
||||
|
||||
|
||||
def serialize_node(node):
|
||||
if node.get("type") in first.LAYOUTS:
|
||||
return first.serialize_node(node)
|
||||
result = saved_values(node)
|
||||
ct, spec = node["type"], definitions()[node["type"]]
|
||||
outputs = node.get("outputs", [])
|
||||
if [s.get("type") for s in outputs] != spec["output"] or [
|
||||
s.get("name") for s in outputs
|
||||
] != OUTPUT_NAMES[ct]:
|
||||
raise ValueError("第二组输出数量/名称/类型不符")
|
||||
if any(
|
||||
"slot_index" in s and (type(s["slot_index"]) is not int or s["slot_index"] != i)
|
||||
for i, s in enumerate(outputs)
|
||||
):
|
||||
raise ValueError("第二组输出slot_index不符")
|
||||
declared = {**spec["input"]["required"], **spec["input"]["optional"]}
|
||||
sockets = node.get("inputs", [])
|
||||
names = [s.get("name") for s in sockets]
|
||||
if len(names) != len(set(names)):
|
||||
raise ValueError("第二组重复输入槽")
|
||||
for s in sockets:
|
||||
name = s.get("name")
|
||||
if name not in declared or s.get("type") != declared[name][0]:
|
||||
raise ValueError("第二组输入名称/类型或动态分支未证明")
|
||||
if "widget" in s and s["widget"] != {"name": name}:
|
||||
raise ValueError("第二组输入控件绑定不符")
|
||||
if "slot_index" in s:
|
||||
raise ValueError("第二组输入slot_index未证明")
|
||||
# Dynamic selector connections could choose another branch after restore.
|
||||
if ct == "SaveVideo" and name == "codec" and s.get("link") is not None:
|
||||
raise ValueError("第二组codec动态外线选择未证明")
|
||||
return result
|
||||
@@ -14,6 +14,7 @@ import json
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
from .h3_chain_reference import CHAIN_PROFILE
|
||||
from .h3_core_reference import CORE_PROFILE
|
||||
from .structure_reference import (
|
||||
GRID_PROFILE,
|
||||
@@ -489,6 +490,10 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
if profile == CHAIN_PROFILE:
|
||||
from .h3_chain_reference import definitions
|
||||
|
||||
return definitions()
|
||||
if profile == CORE_PROFILE:
|
||||
from .h3_core_reference import definitions
|
||||
|
||||
@@ -579,6 +584,10 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
|
||||
def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]:
|
||||
"""Apply only the pinned identity serializers; reject any extra/missing value."""
|
||||
if profile == CHAIN_PROFILE:
|
||||
from .h3_chain_reference import serialize_node
|
||||
|
||||
return serialize_node(node)
|
||||
if profile == CORE_PROFILE:
|
||||
from .h3_core_reference import serialize_node
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .h3_chain_reference import CHAIN_PROFILE
|
||||
from .h3_core_reference import CORE_PROFILE
|
||||
from .serialization_reference import (
|
||||
ASR_PROFILE,
|
||||
@@ -79,6 +80,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
GRID_PROFILE,
|
||||
H3_PROFILE,
|
||||
CORE_PROFILE,
|
||||
CHAIN_PROFILE,
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
@@ -103,7 +105,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
True,
|
||||
)
|
||||
try:
|
||||
if profile == CORE_PROFILE:
|
||||
if profile in (CORE_PROFILE, CHAIN_PROFILE):
|
||||
from .h3_core_reference import validate_structure
|
||||
|
||||
validate_structure(source)
|
||||
@@ -239,13 +241,14 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
result.diagnostic_graph = source
|
||||
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
||||
issue = {"code": "invalid_reference_contract", "message": str(exc)}
|
||||
if profile in (GRID_PROFILE, H3_PROFILE, CORE_PROFILE):
|
||||
if profile in (GRID_PROFILE, H3_PROFILE, CORE_PROFILE, CHAIN_PROFILE):
|
||||
issue["pointer"] = "/"
|
||||
return Conversion(None, [issue], True)
|
||||
result.reference_only = True
|
||||
if profile in (
|
||||
H3_PROFILE,
|
||||
CORE_PROFILE,
|
||||
CHAIN_PROFILE,
|
||||
GRID_PROFILE,
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
@@ -264,7 +267,12 @@ def _convert(
|
||||
|
||||
def fail(code: str, message: str, node_id: Any = "") -> None:
|
||||
issue = {"code": code, "message": message, "node_id": str(node_id)}
|
||||
if reference and reference_profile in (GRID_PROFILE, H3_PROFILE, CORE_PROFILE):
|
||||
if reference and reference_profile in (
|
||||
GRID_PROFILE,
|
||||
H3_PROFILE,
|
||||
CORE_PROFILE,
|
||||
CHAIN_PROFILE,
|
||||
):
|
||||
issue["pointer"] = next(
|
||||
(
|
||||
f"/nodes/{i}"
|
||||
@@ -326,6 +334,7 @@ def _convert(
|
||||
GRID_PROFILE: "1.41.20",
|
||||
H3_PROFILE: "1.53.10",
|
||||
CORE_PROFILE: "1.53.10",
|
||||
CHAIN_PROFILE: "1.53.10",
|
||||
**VHS_PROFILES,
|
||||
**SETGET_PROFILES,
|
||||
**VIDEOINFO_PROFILES,
|
||||
@@ -476,7 +485,7 @@ def _convert(
|
||||
expected != actual
|
||||
and not (
|
||||
reference
|
||||
and reference_profile == CORE_PROFILE
|
||||
and reference_profile in (CORE_PROFILE, CHAIN_PROFILE)
|
||||
and ct == "ComfyMathExpression"
|
||||
and name.startswith("values.")
|
||||
and actual in ("FLOAT", "INT", "BOOLEAN")
|
||||
|
||||
@@ -0,0 +1,558 @@
|
||||
"""Saved state contracts; synthetic upstream helpers confer no public support."""
|
||||
|
||||
import ast
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from scripts import audit_reference_conversion as audit
|
||||
from scripts.verify_frontend_sources import verify
|
||||
|
||||
from calliope.comfyui.h3_chain_reference import (
|
||||
CHAIN_PROFILE,
|
||||
CLIP_TYPES,
|
||||
LAYOUTS,
|
||||
SAMPLERS,
|
||||
WEIGHT_DTYPES,
|
||||
definitions,
|
||||
saved_values,
|
||||
serialize_node,
|
||||
)
|
||||
from calliope.comfyui.h3_core_reference import CORE_PROFILE
|
||||
from calliope.comfyui.ui2api import convert, convert_reference
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATH = next((REPO / "example_ComfyUI_workflows").rglob("minimax-h3文生视频无审核版.json"))
|
||||
IDS = [119, 120, 127, 128, 135, 126, 125, 122, 121, 130, 92]
|
||||
|
||||
|
||||
def real():
|
||||
return json.loads(PATH.read_bytes())
|
||||
|
||||
|
||||
def node(nid):
|
||||
return copy.deepcopy(next(n for n in real()["nodes"] if n["id"] == nid))
|
||||
|
||||
|
||||
def single(nid):
|
||||
n = node(nid)
|
||||
for s in n["inputs"]:
|
||||
s["link"] = None
|
||||
for s in n["outputs"]:
|
||||
s["links"] = None
|
||||
return {"nodes": [n], "links": [], "extra": {}}
|
||||
|
||||
|
||||
def closed(g):
|
||||
old = copy.deepcopy(g)
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is None and r.issues and r.reference_only and g == old
|
||||
assert all("pointer" in i for i in r.issues)
|
||||
return r
|
||||
|
||||
|
||||
def test_actual_main_ten_types_eleven_instances_one_layout_conflict():
|
||||
g = real()
|
||||
nodes = [n for n in g["nodes"] if n["type"] in LAYOUTS]
|
||||
assert len(LAYOUTS) == 10 and len(nodes) == 11 and len(definitions()) == 16
|
||||
for n in nodes:
|
||||
if n["id"] == 130:
|
||||
with pytest.raises(ValueError, match="布局"):
|
||||
serialize_node(n)
|
||||
assert n["widgets_values"] == [24, 8, "sRGB"]
|
||||
else:
|
||||
assert serialize_node(n) == saved_values(n)
|
||||
closed(g)
|
||||
a = audit.profile_attempt(g, CHAIN_PROFILE)
|
||||
es = a["supported_node_evidence"]
|
||||
assert len(es) == 18 and sum(e["layout_accepted"] for e in es) == 15
|
||||
second = [e for e in es if e["type"] in LAYOUTS]
|
||||
assert len(second) == 11 and sum(e["layout_accepted"] for e in second) == 10
|
||||
assert sum(len(e["saved_fields"]) for e in second) == 11
|
||||
rejected = next(e for e in second if e["node_id"] == "130")
|
||||
assert rejected["saved_fields"] == [] and len(rejected["raw_saved_values"]) == 3
|
||||
assert rejected["raw_saved_values"][2]["value"] == "sRGB"
|
||||
assert a["assumptions"]["dynamic_model_membership"].startswith("unknown")
|
||||
assert convert(g).prompt is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nid", IDS)
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"provider",
|
||||
"version",
|
||||
"aux",
|
||||
"mode",
|
||||
"ue",
|
||||
"hook",
|
||||
"short",
|
||||
"long",
|
||||
"named-missing",
|
||||
"named-extra",
|
||||
"named-conflict",
|
||||
],
|
||||
)
|
||||
def test_identity_restore_layout_coverage_conflicts(nid, mutation):
|
||||
g = single(nid)
|
||||
n = g["nodes"][0]
|
||||
if nid == 130:
|
||||
n["widgets_values"] = [24, 8] # synthetic fixed schema layout only
|
||||
if mutation == "provider":
|
||||
n["properties"]["cnr_id"] = "other"
|
||||
elif mutation == "version":
|
||||
n["properties"]["ver"] = "0.30.0"
|
||||
elif mutation == "aux":
|
||||
n["properties"]["aux_id"] = "other"
|
||||
elif mutation == "mode":
|
||||
n["mode"] = True
|
||||
elif mutation == "ue":
|
||||
n["properties"]["ue_properties"] = {}
|
||||
elif mutation == "hook":
|
||||
n["serializeValue"] = "unknown"
|
||||
elif mutation == "short":
|
||||
if n["widgets_values"]:
|
||||
n["widgets_values"].pop()
|
||||
else:
|
||||
n["widgets_values"] = None
|
||||
elif mutation == "long":
|
||||
n["widgets_values"].append("extra")
|
||||
else:
|
||||
n["widgets_values_named"] = dict(zip(LAYOUTS[n["type"]], n["widgets_values"]))
|
||||
if mutation == "named-extra":
|
||||
n["widgets_values_named"]["extra"] = 0
|
||||
elif LAYOUTS[n["type"]]:
|
||||
k = LAYOUTS[n["type"]][0]
|
||||
if mutation == "named-missing":
|
||||
n["widgets_values_named"].pop(k)
|
||||
else:
|
||||
n["widgets_values_named"][k] = True
|
||||
else:
|
||||
n["widgets_values_named"] = None
|
||||
with pytest.raises((ValueError, TypeError)):
|
||||
serialize_node(n)
|
||||
closed(g)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"nid,index,value",
|
||||
[
|
||||
(119, 0, ""),
|
||||
(119, 0, None),
|
||||
(120, 0, True),
|
||||
(127, 0, []),
|
||||
(127, 1, "fp16"),
|
||||
(128, 0, 17),
|
||||
(128, 1, "unknown"),
|
||||
(128, 2, "cuda"),
|
||||
(135, 0, "unknown"),
|
||||
(130, 0, True),
|
||||
(130, 0, 0),
|
||||
(130, 0, 121),
|
||||
(130, 0, float("nan")),
|
||||
(130, 0, float("inf")),
|
||||
(130, 1, 8.0),
|
||||
(130, 1, True),
|
||||
(130, 1, 7),
|
||||
(130, 1, 11),
|
||||
(92, 0, "%date:yyyy%"),
|
||||
(92, 0, "%name.value%"),
|
||||
(92, 0, "%width%"),
|
||||
(92, 0, "%"),
|
||||
(92, 0, 0),
|
||||
(92, 1, "webm"),
|
||||
(92, 2, "h264"),
|
||||
(92, 2, {"codec": "auto"}),
|
||||
],
|
||||
)
|
||||
def test_types_static_enums_ranges_dynamic_branches_and_context_prefix_rejected(nid, index, value):
|
||||
n = node(nid)
|
||||
if nid == 130:
|
||||
n["widgets_values"] = [24, 8]
|
||||
n["widgets_values"][index] = value
|
||||
with pytest.raises(ValueError):
|
||||
saved_values(n)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nid", [119, 120, 127, 128, 135, 126, 125, 122, 121, 92])
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"output-name",
|
||||
"output-type",
|
||||
"output-extra",
|
||||
"output-index",
|
||||
"input-duplicate",
|
||||
"input-unknown",
|
||||
"input-type",
|
||||
"binding",
|
||||
],
|
||||
)
|
||||
def test_all_output_and_input_slots_strict(nid, mutation):
|
||||
n = node(nid)
|
||||
if mutation == "output-name":
|
||||
n["outputs"][0]["name"] = "unknown"
|
||||
elif mutation == "output-type":
|
||||
n["outputs"][0]["type"] = "UNKNOWN"
|
||||
elif mutation == "output-extra":
|
||||
n["outputs"].append(copy.deepcopy(n["outputs"][0]))
|
||||
elif mutation == "output-index":
|
||||
n["outputs"][0]["slot_index"] = True
|
||||
else:
|
||||
spec = definitions()[n["type"]]["input"]
|
||||
name, typ = next(iter({**spec["required"], **spec["optional"]}.items()))
|
||||
n["inputs"] = [{"name": name, "type": typ[0], "link": None}]
|
||||
if mutation == "input-duplicate":
|
||||
n["inputs"] *= 2
|
||||
elif mutation == "input-unknown":
|
||||
n["inputs"][0]["name"] = "unknown"
|
||||
elif mutation == "input-type":
|
||||
n["inputs"][0]["type"] = "UNKNOWN"
|
||||
else:
|
||||
n["inputs"][0]["widget"] = {"name": "unknown"}
|
||||
with pytest.raises(ValueError):
|
||||
serialize_node(n)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("nid", [119, 120, 127, 128, 135])
|
||||
def test_loaders_preserve_opaque_model_strings_and_explicit_identities(nid):
|
||||
g = single(nid)
|
||||
n = g["nodes"][0]
|
||||
if nid != 135:
|
||||
n["widgets_values"][0] = "folder\\literal/../原名.safetensors"
|
||||
before = copy.deepcopy(g)
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is not None and r.reference_only and g == before
|
||||
assert r.prompt[str(nid)]["inputs"] == saved_values(n)
|
||||
n["widgets_values_named"] = dict(zip(LAYOUTS[n["type"]], n["widgets_values"]))
|
||||
n["properties"].update(cnr_id="comfy-core", ver="0.33.0")
|
||||
g["extra"]["frontendVersion"] = "1.53.10"
|
||||
assert convert_reference(g, CHAIN_PROFILE).prompt == r.prompt
|
||||
assert convert_reference(g, CORE_PROFILE).prompt is None
|
||||
|
||||
|
||||
def synthetic_chain(monkeypatch, audio=True):
|
||||
# Only this local test injects a schema+serializer. It is NOT publicly registered.
|
||||
import calliope.comfyui.ui2api as ui
|
||||
|
||||
g = {"nodes": [node(n) for n in [125, 122, 121, 119, 120, 130, 92]], "links": [], "extra": {}}
|
||||
for n in g["nodes"]:
|
||||
for s in n["inputs"]:
|
||||
s["link"] = None
|
||||
for s in n["outputs"]:
|
||||
s["links"] = None
|
||||
if n["id"] == 130:
|
||||
n["widgets_values"] = [24, 8]
|
||||
helper = {
|
||||
"id": 999,
|
||||
"type": "TEST_ONLY_UPSTREAM",
|
||||
"inputs": [],
|
||||
"outputs": [
|
||||
{"name": x, "type": x, "links": None}
|
||||
for x in ["NOISE", "GUIDER", "SAMPLER", "SIGMAS", "LATENT"]
|
||||
],
|
||||
"widgets_values": [],
|
||||
"mode": 0,
|
||||
}
|
||||
g["nodes"].append(helper)
|
||||
|
||||
def connect(src, so, dst, name):
|
||||
a = next(n for n in g["nodes"] if n["id"] == src)
|
||||
b = next(n for n in g["nodes"] if n["id"] == dst)
|
||||
si = next(i for i, s in enumerate(b["inputs"]) if s["name"] == name)
|
||||
lid = len(g["links"]) + 1
|
||||
a["outputs"][so]["links"] = (a["outputs"][so]["links"] or []) + [lid]
|
||||
b["inputs"][si]["link"] = lid
|
||||
g["links"].append([lid, src, so, dst, si, a["outputs"][so]["type"]])
|
||||
|
||||
for si, name in enumerate(["noise", "guider", "sampler", "sigmas", "latent_image"]):
|
||||
connect(999, si, 125, name)
|
||||
connect(125, 1, 122, "samples")
|
||||
connect(119, 0, 122, "vae")
|
||||
connect(125, 0, 121, "samples")
|
||||
connect(120, 0, 121, "vae")
|
||||
connect(122, 0, 130, "images")
|
||||
if audio:
|
||||
connect(121, 0, 130, "audio")
|
||||
else:
|
||||
g["nodes"] = [n for n in g["nodes"] if n["id"] not in [121, 120]]
|
||||
g["links"] = [e for e in g["links"] if e[3] != 121]
|
||||
g["nodes"][0]["outputs"][0]["links"] = None
|
||||
connect(130, 0, 92, "video")
|
||||
# Reject helper before installing local injection.
|
||||
assert convert_reference(g, CHAIN_PROFILE).prompt is None
|
||||
original_defs = ui.reference_definitions
|
||||
original_ser = ui.serialize_reference_widgets
|
||||
|
||||
def defs(profile):
|
||||
d = original_defs(profile)
|
||||
if profile == CHAIN_PROFILE:
|
||||
d["TEST_ONLY_UPSTREAM"] = {
|
||||
"input": {"required": {}},
|
||||
"output": [s["type"] for s in helper["outputs"]],
|
||||
}
|
||||
return d
|
||||
|
||||
monkeypatch.setattr(ui, "reference_definitions", defs)
|
||||
monkeypatch.setattr(
|
||||
ui,
|
||||
"serialize_reference_widgets",
|
||||
lambda n, p: {} if n["type"] == "TEST_ONLY_UPSTREAM" else original_ser(n, p),
|
||||
)
|
||||
return g
|
||||
|
||||
|
||||
@pytest.mark.parametrize("audio", [True, False])
|
||||
def test_synthetic_video_chain_nonzero_slot_optional_audio_and_instance_propagation(
|
||||
monkeypatch, audio
|
||||
):
|
||||
g = synthetic_chain(monkeypatch, audio)
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is not None, r.issues
|
||||
assert r.prompt["122"]["inputs"]["samples"] == ["125", 1]
|
||||
assert ("audio" in r.prompt["130"]["inputs"]) == audio
|
||||
assert r.prompt["92"]["inputs"]["codec"] == "auto"
|
||||
for n in g["nodes"]:
|
||||
if n["id"] == 125:
|
||||
n["id"] = 888
|
||||
for e in g["links"]:
|
||||
if e[1] == 125:
|
||||
e[1] = 888
|
||||
if e[3] == 125:
|
||||
e[3] = 888
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is not None, r.issues
|
||||
assert r.prompt["122"]["inputs"]["samples"] == ["888", 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"frontend",
|
||||
"ue",
|
||||
"mode",
|
||||
"duplicate",
|
||||
"bad-ref",
|
||||
"slot",
|
||||
"type",
|
||||
"reverse",
|
||||
"cycle",
|
||||
"codec-line",
|
||||
],
|
||||
)
|
||||
def test_synthetic_structure_closes_entire_graph(monkeypatch, mutation):
|
||||
g = synthetic_chain(monkeypatch)
|
||||
if mutation == "frontend":
|
||||
g["extra"]["frontendVersion"] = "1.53.6"
|
||||
elif mutation == "ue":
|
||||
g["extra"]["ue_properties"] = {}
|
||||
elif mutation == "mode":
|
||||
g["nodes"][0]["mode"] = 4
|
||||
elif mutation == "duplicate":
|
||||
g["links"].append(g["links"][0])
|
||||
elif mutation == "bad-ref":
|
||||
g["links"][0][1] = 888
|
||||
elif mutation == "slot":
|
||||
g["links"][0][2] = 99
|
||||
elif mutation == "type":
|
||||
g["links"][0][5] = "UNKNOWN"
|
||||
elif mutation == "reverse":
|
||||
g["nodes"][0]["inputs"][0]["link"] = 999
|
||||
elif mutation == "cycle":
|
||||
g["links"].append([999, 125, 0, 125, 0, "LATENT"])
|
||||
else:
|
||||
n = next(n for n in g["nodes"] if n["id"] == 92)
|
||||
n["inputs"].append({"name": "codec", "type": "COMFY_DYNAMICCOMBO_V3", "link": 1})
|
||||
closed(g)
|
||||
|
||||
|
||||
def test_fixed_widget_physical_input_wins(monkeypatch):
|
||||
g = single(133)
|
||||
b = node(130)
|
||||
b["widgets_values"] = [24, 8]
|
||||
b["inputs"] = [{"name": "fps", "type": "FLOAT", "link": 1, "widget": {"name": "fps"}}]
|
||||
# Local helper supplies IMAGE; all physical paths checked by real validator.
|
||||
# First test the serializer/evidence independently of required IMAGE input.
|
||||
assert serialize_node(b) == {"fps": 24, "bit_depth": 8}
|
||||
g["nodes"].append(b)
|
||||
g["nodes"][0]["outputs"][0]["links"] = [1]
|
||||
g["links"] = [[1, 133, 0, 130, 0, "FLOAT"]]
|
||||
a = audit.profile_attempt(g, CHAIN_PROFILE)
|
||||
e = next(e for e in a["supported_node_evidence"] if e["node_id"] == "130")
|
||||
assert next(f for f in e["effective_field_evidence"] if f["field"] == "fps")["value"] == [
|
||||
"133",
|
||||
0,
|
||||
]
|
||||
# Missing images still prevents ANY partial candidate.
|
||||
closed(g)
|
||||
|
||||
|
||||
def test_old_27_profiles_every_attempt_gap_hash_and_comparison_frozen():
|
||||
old = json.loads((REPO / "docs/hel-892/h3-core-evidence/library.json").read_bytes())
|
||||
ps = tuple(old["profiles"])
|
||||
assert len(ps) == 27 and ps == audit.REFERENCE_PROFILES[:27]
|
||||
before = audit.audit_library(REPO, ps)
|
||||
now = audit.audit_library(REPO, baseline_profiles=ps)
|
||||
assert before["gap_groups"] == old["gap_groups"]
|
||||
for a, b, c in zip(old["cases"], before["cases"], now["cases"]):
|
||||
assert a["attempts"] == b["attempts"] == c["attempts"][:27]
|
||||
assert a["candidate_hashes"] == c["candidate_hashes"]
|
||||
assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons")
|
||||
assert now["coverage_delta"]["new_complete_paths"] == []
|
||||
assert len(now["coverage_delta"]["current_complete_paths"]) == 9
|
||||
for p in PATH.parent.glob("*.json"):
|
||||
closed(json.loads(p.read_bytes()))
|
||||
|
||||
|
||||
def test_pinned_manifests_and_literal_enums_without_upstream_execution():
|
||||
assert not verify(REPO / "docs/hel-892/h3-chain-reference")["upstream_code_executed"]
|
||||
tree = ast.parse((REPO / "docs/hel-892/h3-core-reference/core__comfy__samplers.py").read_text())
|
||||
assignment = next(
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.Assign)
|
||||
and any(isinstance(t, ast.Name) and t.id == "KSAMPLER_NAMES" for t in n.targets)
|
||||
)
|
||||
assert tuple(ast.literal_eval(assignment.value)) + ("ddim", "uni_pc", "uni_pc_bh2") == SAMPLERS
|
||||
tree = ast.parse((REPO / "docs/hel-892/h3-core-reference/core__nodes.py").read_text())
|
||||
for clsname, key, expected in [
|
||||
("UNETLoader", "weight_dtype", WEIGHT_DTYPES),
|
||||
("CLIPLoader", "type", CLIP_TYPES),
|
||||
]:
|
||||
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == clsname)
|
||||
fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "INPUT_TYPES")
|
||||
ret = next(n for n in fn.body if isinstance(n, ast.Return)).value
|
||||
required = next(
|
||||
v for k, v in zip(ret.keys, ret.values) if ast.literal_eval(k) == "required"
|
||||
)
|
||||
value = next(
|
||||
v for k, v in zip(required.keys, required.values) if ast.literal_eval(k) == key
|
||||
)
|
||||
assert tuple(ast.literal_eval(value.elts[0])) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", WEIGHT_DTYPES)
|
||||
def test_all_static_precision_options(dtype):
|
||||
n = node(127)
|
||||
n["widgets_values"][1] = dtype
|
||||
assert saved_values(n)["weight_dtype"] == dtype
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", CLIP_TYPES)
|
||||
def test_all_static_clip_types(kind):
|
||||
n = node(128)
|
||||
n["widgets_values"][1] = kind
|
||||
assert saved_values(n)["type"] == kind
|
||||
|
||||
|
||||
@pytest.mark.parametrize("sampler", SAMPLERS)
|
||||
def test_all_fixed_sampler_options(sampler):
|
||||
n = node(135)
|
||||
n["widgets_values"][0] = sampler
|
||||
assert saved_values(n)["sampler_name"] == sampler
|
||||
|
||||
|
||||
def test_complete_synthetic_physical_fps_overrides_save_and_upstream_switch(monkeypatch):
|
||||
g = synthetic_chain(monkeypatch)
|
||||
f = single(133)["nodes"][0]
|
||||
f["widgets_values"] = [60.0]
|
||||
f["outputs"][0]["links"] = [100]
|
||||
g["nodes"].append(f)
|
||||
video = next(n for n in g["nodes"] if n["id"] == 130)
|
||||
video["inputs"].append({"name": "fps", "type": "FLOAT", "link": 100, "widget": {"name": "fps"}})
|
||||
g["links"].append([100, 133, 0, 130, 2, "FLOAT"])
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is not None, r.issues
|
||||
assert r.prompt["130"]["inputs"]["fps"] == ["133", 0]
|
||||
assert video["widgets_values"] == [24, 8]
|
||||
# Replace a LATENT upstream while retaining nonzero source slot semantics.
|
||||
edge = next(e for e in g["links"] if e[3] == 122 and e[4] == 0)
|
||||
sampler = next(n for n in g["nodes"] if n["id"] == 125)
|
||||
helper = next(n for n in g["nodes"] if n["id"] == 999)
|
||||
sampler["outputs"][1]["links"].remove(edge[0])
|
||||
helper["outputs"][4]["links"].append(edge[0])
|
||||
edge[1], edge[2] = 999, 4
|
||||
r = convert_reference(g, CHAIN_PROFILE)
|
||||
assert r.prompt is not None, r.issues
|
||||
assert r.prompt["122"]["inputs"]["samples"] == ["999", 4]
|
||||
|
||||
|
||||
def test_ten_real_class_registrations_and_schema_field_orders_ast_only():
|
||||
root = REPO / "docs/hel-892"
|
||||
modules = {
|
||||
"h3-core-reference/core__nodes.py": {
|
||||
"VAELoader": ["vae_name"],
|
||||
"UNETLoader": ["unet_name", "weight_dtype"],
|
||||
"CLIPLoader": ["clip_name", "type", "device"],
|
||||
"VAEDecode": ["samples", "vae"],
|
||||
},
|
||||
"h3-core-reference/core__comfy_extras__nodes_custom_sampler.py": {
|
||||
"KSamplerSelect": ["sampler_name"],
|
||||
"BasicGuider": ["model", "conditioning"],
|
||||
"SamplerCustomAdvanced": ["noise", "guider", "sampler", "sigmas", "latent_image"],
|
||||
},
|
||||
"h3-chain-reference/core__comfy_extras__nodes_audio.py": {
|
||||
"VAEDecodeAudio": ["samples", "vae"]
|
||||
},
|
||||
"h3-chain-reference/core__comfy_extras__nodes_video.py": {
|
||||
"CreateVideo": ["images", "fps", "audio", "bit_depth"],
|
||||
"SaveVideo": ["video", "filename_prefix", "format", "codec"],
|
||||
},
|
||||
}
|
||||
for path, specs in modules.items():
|
||||
tree = ast.parse((root / path).read_text())
|
||||
if path.endswith("core__nodes.py"):
|
||||
mapping = next(
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.Assign)
|
||||
and any(
|
||||
isinstance(t, ast.Name) and t.id == "NODE_CLASS_MAPPINGS" for t in n.targets
|
||||
)
|
||||
)
|
||||
registered = {
|
||||
ast.literal_eval(k): v.id for k, v in zip(mapping.value.keys, mapping.value.values)
|
||||
}
|
||||
else:
|
||||
fn = next(
|
||||
n
|
||||
for n in ast.walk(tree)
|
||||
if isinstance(n, ast.AsyncFunctionDef) and n.name == "get_node_list"
|
||||
)
|
||||
registered = {
|
||||
n.id: n.id for r in fn.body if isinstance(r, ast.Return) for n in r.value.elts
|
||||
}
|
||||
for name, expected in specs.items():
|
||||
assert registered[name] == name
|
||||
cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name)
|
||||
if path.endswith("core__nodes.py"):
|
||||
fn = next(
|
||||
n
|
||||
for n in cls.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "INPUT_TYPES"
|
||||
)
|
||||
ret = next(n for n in fn.body if isinstance(n, ast.Return)).value
|
||||
fields = [
|
||||
ast.literal_eval(k)
|
||||
for k, v in zip(ret.keys, ret.values)
|
||||
if ast.literal_eval(k) in ("required", "optional")
|
||||
for k in v.keys
|
||||
]
|
||||
else:
|
||||
fn = next(
|
||||
n
|
||||
for n in cls.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "define_schema"
|
||||
)
|
||||
schema = next(
|
||||
n
|
||||
for n in ast.walk(fn)
|
||||
if isinstance(n, ast.Call)
|
||||
and isinstance(n.func, ast.Attribute)
|
||||
and n.func.attr == "Schema"
|
||||
)
|
||||
kw = {k.arg: k.value for k in schema.keywords}
|
||||
assert ast.literal_eval(kw["node_id"]) == name
|
||||
fields = [ast.literal_eval(n.args[0]) for n in kw["inputs"].elts]
|
||||
assert fields == expected
|
||||
@@ -0,0 +1,50 @@
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from fractions import Fraction
|
||||
from typing import Optional
|
||||
from .._input import ImageInput, AudioInput, MaskInput
|
||||
|
||||
class VideoCodec(str, Enum):
|
||||
AUTO = "auto"
|
||||
H264 = "h264"
|
||||
|
||||
@classmethod
|
||||
def as_input(cls) -> list[str]:
|
||||
"""
|
||||
Returns a list of codec names that can be used as node input.
|
||||
"""
|
||||
return [member.value for member in cls]
|
||||
|
||||
class VideoContainer(str, Enum):
|
||||
AUTO = "auto"
|
||||
MP4 = "mp4"
|
||||
|
||||
@classmethod
|
||||
def as_input(cls) -> list[str]:
|
||||
"""
|
||||
Returns a list of container names that can be used as node input.
|
||||
"""
|
||||
return [member.value for member in cls]
|
||||
|
||||
@classmethod
|
||||
def get_extension(cls, value) -> str:
|
||||
"""
|
||||
Returns the file extension for the container.
|
||||
"""
|
||||
if isinstance(value, str):
|
||||
value = cls(value)
|
||||
if value == VideoContainer.MP4 or value == VideoContainer.AUTO:
|
||||
return "mp4"
|
||||
return ""
|
||||
|
||||
@dataclass
|
||||
class VideoComponents:
|
||||
"""
|
||||
Dataclass representing the components of a video.
|
||||
"""
|
||||
|
||||
images: ImageInput
|
||||
frame_rate: Fraction
|
||||
audio: Optional[AudioInput] = None
|
||||
metadata: Optional[dict] = None
|
||||
alpha: Optional[MaskInput] = None
|
||||
@@ -0,0 +1,896 @@
|
||||
import av
|
||||
import torchaudio
|
||||
import torch
|
||||
import comfy.model_management
|
||||
import folder_paths
|
||||
import os
|
||||
import hashlib
|
||||
import node_helpers
|
||||
import logging
|
||||
from typing_extensions import override
|
||||
from comfy_api.latest import ComfyExtension, IO, UI
|
||||
|
||||
class EmptyLatentAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="EmptyLatentAudio",
|
||||
display_name="Empty Latent Audio",
|
||||
category="model/latent",
|
||||
essentials_category="Audio",
|
||||
inputs=[
|
||||
IO.Float.Input("seconds", default=47.6, min=1.0, max=1000.0, step=0.1),
|
||||
IO.Int.Input(
|
||||
"batch_size", default=1, min=1, max=4096, tooltip="The number of latent images in the batch.",
|
||||
),
|
||||
],
|
||||
outputs=[IO.Latent.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, seconds, batch_size) -> IO.NodeOutput:
|
||||
length = round((seconds * 44100 / 2048) / 2) * 2
|
||||
latent = torch.zeros([batch_size, 64, length], device=comfy.model_management.intermediate_device())
|
||||
return IO.NodeOutput({"samples": latent, "type": "audio", "downscale_ratio_temporal": 2048})
|
||||
|
||||
generate = execute # TODO: remove
|
||||
|
||||
|
||||
class ConditioningStableAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ConditioningStableAudio",
|
||||
category="model/conditioning/stable audio",
|
||||
inputs=[
|
||||
IO.Conditioning.Input("positive"),
|
||||
IO.Conditioning.Input("negative"),
|
||||
IO.Float.Input("seconds_start", default=0.0, min=0.0, max=1000.0, step=0.1),
|
||||
IO.Float.Input("seconds_total", default=47.0, min=0.0, max=1000.0, step=0.1),
|
||||
],
|
||||
outputs=[
|
||||
IO.Conditioning.Output(display_name="positive"),
|
||||
IO.Conditioning.Output(display_name="negative"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, positive, negative, seconds_start, seconds_total) -> IO.NodeOutput:
|
||||
positive = node_helpers.conditioning_set_values(positive, {"seconds_start": seconds_start, "seconds_total": seconds_total})
|
||||
negative = node_helpers.conditioning_set_values(negative, {"seconds_start": seconds_start, "seconds_total": seconds_total})
|
||||
return IO.NodeOutput(positive, negative)
|
||||
|
||||
append = execute # TODO: remove
|
||||
|
||||
|
||||
class VAEEncodeAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="VAEEncodeAudio",
|
||||
search_aliases=["audio to latent"],
|
||||
display_name="VAE Encode Audio",
|
||||
category="model/latent",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.Vae.Input("vae"),
|
||||
],
|
||||
outputs=[IO.Latent.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, vae, audio) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
raise ValueError("VAEEncodeAudio: input audio is None (source video may have no audio track).")
|
||||
sample_rate = audio["sample_rate"]
|
||||
vae_sample_rate = getattr(vae, "audio_sample_rate", 44100)
|
||||
if vae_sample_rate != sample_rate:
|
||||
waveform = torchaudio.functional.resample(audio["waveform"], sample_rate, vae_sample_rate)
|
||||
else:
|
||||
waveform = audio["waveform"]
|
||||
|
||||
t = vae.encode(waveform.movedim(1, -1))
|
||||
return IO.NodeOutput({"samples": t})
|
||||
|
||||
encode = execute # TODO: remove
|
||||
|
||||
|
||||
def vae_decode_audio(vae, samples, tile=None, overlap=None):
|
||||
latent = samples["samples"]
|
||||
if latent.is_nested:
|
||||
latent = latent.unbind()[-1]
|
||||
|
||||
if tile is not None:
|
||||
audio = vae.decode_tiled(latent, tile_x=tile, tile_y=tile, overlap=overlap).movedim(-1, 1)
|
||||
else:
|
||||
audio = vae.decode(latent).movedim(-1, 1)
|
||||
|
||||
std = torch.std(audio, dim=[1, 2], keepdim=True) * 5.0
|
||||
std[std < 1.0] = 1.0
|
||||
audio /= std
|
||||
vae_sample_rate = getattr(vae, "audio_sample_rate_output", getattr(vae, "audio_sample_rate", 44100))
|
||||
return {"waveform": audio, "sample_rate": vae_sample_rate if "sample_rate" not in samples else samples["sample_rate"]}
|
||||
|
||||
|
||||
class VAEDecodeAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="VAEDecodeAudio",
|
||||
search_aliases=["latent to audio"],
|
||||
display_name="VAE Decode Audio",
|
||||
category="model/latent",
|
||||
inputs=[
|
||||
IO.Latent.Input("samples"),
|
||||
IO.Vae.Input("vae"),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, vae, samples) -> IO.NodeOutput:
|
||||
return IO.NodeOutput(vae_decode_audio(vae, samples))
|
||||
|
||||
decode = execute # TODO: remove
|
||||
|
||||
|
||||
class VAEDecodeAudioTiled(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="VAEDecodeAudioTiled",
|
||||
search_aliases=["latent to audio"],
|
||||
display_name="VAE Decode Audio (Tiled)",
|
||||
category="model/latent",
|
||||
inputs=[
|
||||
IO.Latent.Input("samples"),
|
||||
IO.Vae.Input("vae"),
|
||||
IO.Int.Input("tile_size", default=512, min=32, max=8192, step=8),
|
||||
IO.Int.Input("overlap", default=64, min=0, max=1024, step=8),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, vae, samples, tile_size, overlap) -> IO.NodeOutput:
|
||||
return IO.NodeOutput(vae_decode_audio(vae, samples, tile_size, overlap))
|
||||
|
||||
|
||||
class SaveAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAudio",
|
||||
search_aliases=["export flac"],
|
||||
display_name="Save Audio (FLAC) (DEPRECATED)",
|
||||
category="audio",
|
||||
essentials_category="Audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.String.Input("filename_prefix", default="audio/ComfyUI"),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_deprecated=True,
|
||||
is_output_node=True,
|
||||
outputs=[IO.Audio.Output("audio")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, filename_prefix="ComfyUI", format="flac") -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
raise ValueError("SaveAudio: input audio is None (source video may have no audio track).")
|
||||
return IO.NodeOutput(
|
||||
audio,
|
||||
ui=UI.AudioSaveHelper.get_save_audio_ui(audio, filename_prefix=filename_prefix, cls=cls, format=format)
|
||||
)
|
||||
|
||||
|
||||
class SaveAudioMP3(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAudioMP3",
|
||||
search_aliases=["export mp3"],
|
||||
display_name="Save Audio (MP3) (DEPRECATED)",
|
||||
category="audio",
|
||||
essentials_category="Audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.String.Input("filename_prefix", default="audio/ComfyUI"),
|
||||
IO.Combo.Input("quality", options=["V0", "128k", "320k"], default="V0"),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_deprecated=True,
|
||||
is_output_node=True,
|
||||
outputs=[IO.Audio.Output("audio")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, filename_prefix="ComfyUI", format="mp3", quality="128k") -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
raise ValueError("SaveAudioMP3: input audio is None (source video may have no audio track).")
|
||||
return IO.NodeOutput(
|
||||
audio,
|
||||
ui=UI.AudioSaveHelper.get_save_audio_ui(
|
||||
audio, filename_prefix=filename_prefix, cls=cls, format=format, quality=quality
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class SaveAudioOpus(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAudioOpus",
|
||||
search_aliases=["export opus"],
|
||||
display_name="Save Audio (Opus) (DEPRECATED)",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.String.Input("filename_prefix", default="audio/ComfyUI"),
|
||||
IO.Combo.Input("quality", options=["64k", "96k", "128k", "192k", "320k"], default="128k"),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_deprecated=True,
|
||||
is_output_node=True,
|
||||
outputs=[IO.Audio.Output("audio")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, filename_prefix="ComfyUI", format="opus", quality="V3") -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
raise ValueError("SaveAudioOpus: input audio is None (source video may have no audio track).")
|
||||
return IO.NodeOutput(
|
||||
audio,
|
||||
ui=UI.AudioSaveHelper.get_save_audio_ui(
|
||||
audio, filename_prefix=filename_prefix, cls=cls, format=format, quality=quality
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class SaveAudioAdvanced(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAudioAdvanced",
|
||||
search_aliases=["save audio", "export audio", "output audio", "write audio", "flac", "mp3", "opus"],
|
||||
display_name="Save Audio (Advanced)",
|
||||
description="Saves the input audio to your ComfyUI output directory.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio", tooltip="The audio to save."),
|
||||
IO.String.Input(
|
||||
"filename_prefix",
|
||||
default="audio/ComfyUI",
|
||||
tooltip=("The prefix for the file to save. May include formatting tokens such as %date:yyyy-MM-dd%."),
|
||||
),
|
||||
IO.DynamicCombo.Input(
|
||||
"format",
|
||||
options=[
|
||||
IO.DynamicCombo.Option("flac", []),
|
||||
IO.DynamicCombo.Option("mp3", [
|
||||
IO.Combo.Input("quality", options=["V0", "128k", "320k"], default="V0"),
|
||||
]),
|
||||
IO.DynamicCombo.Option("opus", [
|
||||
IO.Combo.Input("quality", options=["64k", "96k", "128k", "192k", "320k"], default="128k"),
|
||||
]),
|
||||
],
|
||||
tooltip="The file format in which to save the audio.",
|
||||
),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
outputs=[IO.Audio.Output("audio")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, filename_prefix: str, format: dict) -> IO.NodeOutput:
|
||||
file_format = format.get("format", None)
|
||||
quality = format.get("quality", None)
|
||||
if quality:
|
||||
ui=UI.AudioSaveHelper.get_save_audio_ui(audio, filename_prefix=filename_prefix, cls=cls, format=file_format, quality=quality)
|
||||
else:
|
||||
ui=UI.AudioSaveHelper.get_save_audio_ui(audio, filename_prefix=filename_prefix, cls=cls, format=file_format)
|
||||
return IO.NodeOutput(audio, ui=ui)
|
||||
|
||||
|
||||
class PreviewAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="PreviewAudio",
|
||||
search_aliases=["play audio"],
|
||||
display_name="Preview Audio",
|
||||
category="audio",
|
||||
description="Preview the audio without saving it to the ComfyUI output directory.",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
outputs=[IO.Audio.Output("audio")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
raise ValueError("PreviewAudio: input audio is None (source video may have no audio track).")
|
||||
return IO.NodeOutput(audio, ui=UI.PreviewAudio(audio, cls=cls))
|
||||
|
||||
save_flac = execute # TODO: remove
|
||||
|
||||
|
||||
def f32_pcm(wav: torch.Tensor) -> torch.Tensor:
|
||||
"""Convert audio to float 32 bits PCM format."""
|
||||
if wav.dtype.is_floating_point:
|
||||
return wav
|
||||
elif wav.dtype == torch.int16:
|
||||
return wav.float() / (2 ** 15)
|
||||
elif wav.dtype == torch.int32:
|
||||
return wav.float() / (2 ** 31)
|
||||
raise ValueError(f"Unsupported wav dtype: {wav.dtype}")
|
||||
|
||||
def load(filepath: str) -> tuple[torch.Tensor, int]:
|
||||
with av.open(filepath) as af:
|
||||
if not af.streams.audio:
|
||||
raise ValueError("No audio stream found in the file.")
|
||||
|
||||
stream = af.streams.audio[0]
|
||||
sr = stream.codec_context.sample_rate
|
||||
n_channels = stream.channels
|
||||
|
||||
frames = []
|
||||
length = 0
|
||||
for frame in af.decode(streams=stream.index):
|
||||
buf = torch.from_numpy(frame.to_ndarray())
|
||||
if buf.shape[0] != n_channels:
|
||||
buf = buf.view(-1, n_channels).t()
|
||||
|
||||
frames.append(buf)
|
||||
length += buf.shape[1]
|
||||
|
||||
if not frames:
|
||||
raise ValueError("No audio frames decoded.")
|
||||
|
||||
wav = torch.cat(frames, dim=1)
|
||||
wav = f32_pcm(wav)
|
||||
return wav, sr
|
||||
|
||||
class LoadAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
os.makedirs(input_dir, exist_ok=True)
|
||||
files = folder_paths.filter_files_content_types(os.listdir(input_dir), ["audio", "video"])
|
||||
return IO.Schema(
|
||||
node_id="LoadAudio",
|
||||
search_aliases=["import audio", "open audio", "audio file"],
|
||||
display_name="Load Audio",
|
||||
category="audio",
|
||||
essentials_category="Audio",
|
||||
inputs=[
|
||||
IO.Combo.Input("audio", upload=IO.UploadType.audio, options=sorted(files)),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio) -> IO.NodeOutput:
|
||||
audio_path = folder_paths.get_annotated_filepath(audio)
|
||||
waveform, sample_rate = load(audio_path)
|
||||
audio = {"waveform": waveform.unsqueeze(0), "sample_rate": sample_rate}
|
||||
return IO.NodeOutput(audio)
|
||||
|
||||
@classmethod
|
||||
def fingerprint_inputs(cls, audio):
|
||||
image_path = folder_paths.get_annotated_filepath(audio)
|
||||
m = hashlib.sha256()
|
||||
with open(image_path, 'rb') as f:
|
||||
m.update(f.read())
|
||||
return m.digest().hex()
|
||||
|
||||
@classmethod
|
||||
def validate_inputs(cls, audio):
|
||||
if not folder_paths.exists_annotated_filepath(audio):
|
||||
return "Invalid audio file: {}".format(audio)
|
||||
return True
|
||||
|
||||
load = execute # TODO: remove
|
||||
|
||||
|
||||
class RecordAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="RecordAudio",
|
||||
search_aliases=["microphone input", "audio capture", "voice input"],
|
||||
display_name="Record Audio",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Custom("AUDIO_RECORD").Input("audio"),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio) -> IO.NodeOutput:
|
||||
audio_path = folder_paths.get_annotated_filepath(audio)
|
||||
|
||||
waveform, sample_rate = load(audio_path)
|
||||
audio = {"waveform": waveform.unsqueeze(0), "sample_rate": sample_rate}
|
||||
return IO.NodeOutput(audio)
|
||||
|
||||
load = execute # TODO: remove
|
||||
|
||||
|
||||
class TrimAudioDuration(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="TrimAudioDuration",
|
||||
search_aliases=["cut audio", "audio clip", "shorten audio"],
|
||||
display_name="Trim Audio Duration",
|
||||
description="Trim audio tensor into chosen time range.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.Float.Input(
|
||||
"start_index",
|
||||
default=0.0,
|
||||
min=-0xffffffffffffffff,
|
||||
max=0xffffffffffffffff,
|
||||
step=0.01,
|
||||
tooltip="Start time in seconds, can be negative to count from the end (supports sub-seconds).",
|
||||
),
|
||||
IO.Float.Input(
|
||||
"duration",
|
||||
default=60.0,
|
||||
min=0.0,
|
||||
step=0.01,
|
||||
tooltip="Duration in seconds",
|
||||
),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, start_index, duration) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
return IO.NodeOutput(None)
|
||||
waveform = audio["waveform"]
|
||||
sample_rate = audio["sample_rate"]
|
||||
audio_length = waveform.shape[-1]
|
||||
|
||||
if audio_length == 0:
|
||||
return IO.NodeOutput(audio)
|
||||
|
||||
if start_index < 0:
|
||||
start_frame = audio_length + int(round(start_index * sample_rate))
|
||||
else:
|
||||
start_frame = int(round(start_index * sample_rate))
|
||||
start_frame = max(0, min(start_frame, audio_length))
|
||||
|
||||
end_frame = start_frame + int(round(duration * sample_rate))
|
||||
end_frame = max(0, min(end_frame, audio_length))
|
||||
|
||||
if start_frame >= end_frame:
|
||||
raise ValueError("TrimAudioDuration: Start time must be less than end time and be within the audio length.")
|
||||
|
||||
return IO.NodeOutput({"waveform": waveform[..., start_frame:end_frame], "sample_rate": sample_rate})
|
||||
|
||||
trim = execute # TODO: remove
|
||||
|
||||
|
||||
class SplitAudioChannels(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SplitAudioChannels",
|
||||
search_aliases=["stereo to mono"],
|
||||
display_name="Split Audio Channels",
|
||||
description="Separates the audio into left and right channels.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
],
|
||||
outputs=[
|
||||
IO.Audio.Output(display_name="left"),
|
||||
IO.Audio.Output(display_name="right"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
return IO.NodeOutput(None, None)
|
||||
waveform = audio["waveform"]
|
||||
sample_rate = audio["sample_rate"]
|
||||
|
||||
if waveform.shape[1] != 2:
|
||||
raise ValueError(f"AudioSplit: Input audio must be stereo (2 channels), got {waveform.shape[1]} channel(s).")
|
||||
|
||||
left_channel = waveform[..., 0:1, :]
|
||||
right_channel = waveform[..., 1:2, :]
|
||||
|
||||
return IO.NodeOutput({"waveform": left_channel, "sample_rate": sample_rate}, {"waveform": right_channel, "sample_rate": sample_rate})
|
||||
|
||||
separate = execute # TODO: remove
|
||||
|
||||
class JoinAudioChannels(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="JoinAudioChannels",
|
||||
display_name="Join Audio Channels",
|
||||
description="Joins left and right mono audio channels into a stereo audio.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio_left"),
|
||||
IO.Audio.Input("audio_right"),
|
||||
],
|
||||
outputs=[
|
||||
IO.Audio.Output(display_name="audio"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio_left, audio_right) -> IO.NodeOutput:
|
||||
if audio_left is None and audio_right is None:
|
||||
return IO.NodeOutput(None)
|
||||
if audio_left is None:
|
||||
return IO.NodeOutput(audio_right)
|
||||
if audio_right is None:
|
||||
return IO.NodeOutput(audio_left)
|
||||
waveform_left = audio_left["waveform"]
|
||||
sample_rate_left = audio_left["sample_rate"]
|
||||
waveform_right = audio_right["waveform"]
|
||||
sample_rate_right = audio_right["sample_rate"]
|
||||
|
||||
if waveform_left.shape[1] != 1 or waveform_right.shape[1] != 1:
|
||||
raise ValueError("AudioJoin: Both input audios must be mono.")
|
||||
|
||||
# Handle different sample rates by resampling to the higher rate
|
||||
waveform_left, waveform_right, output_sample_rate = match_audio_sample_rates(
|
||||
waveform_left, sample_rate_left, waveform_right, sample_rate_right
|
||||
)
|
||||
|
||||
# Handle different lengths by trimming to the shorter length
|
||||
length_left = waveform_left.shape[-1]
|
||||
length_right = waveform_right.shape[-1]
|
||||
|
||||
if length_left != length_right:
|
||||
min_length = min(length_left, length_right)
|
||||
if length_left > min_length:
|
||||
logging.info(f"JoinAudioChannels: Trimming left channel from {length_left} to {min_length} samples.")
|
||||
waveform_left = waveform_left[..., :min_length]
|
||||
if length_right > min_length:
|
||||
logging.info(f"JoinAudioChannels: Trimming right channel from {length_right} to {min_length} samples.")
|
||||
waveform_right = waveform_right[..., :min_length]
|
||||
|
||||
# Join the channels into stereo
|
||||
left_channel = waveform_left[..., 0:1, :]
|
||||
right_channel = waveform_right[..., 0:1, :]
|
||||
stereo_waveform = torch.cat([left_channel, right_channel], dim=1)
|
||||
|
||||
return IO.NodeOutput({"waveform": stereo_waveform, "sample_rate": output_sample_rate})
|
||||
|
||||
|
||||
def match_audio_sample_rates(waveform_1, sample_rate_1, waveform_2, sample_rate_2):
|
||||
if sample_rate_1 != sample_rate_2:
|
||||
if sample_rate_1 > sample_rate_2:
|
||||
waveform_2 = torchaudio.functional.resample(waveform_2, sample_rate_2, sample_rate_1)
|
||||
output_sample_rate = sample_rate_1
|
||||
logging.info(f"Resampling audio2 from {sample_rate_2}Hz to {sample_rate_1}Hz for merging.")
|
||||
else:
|
||||
waveform_1 = torchaudio.functional.resample(waveform_1, sample_rate_1, sample_rate_2)
|
||||
output_sample_rate = sample_rate_2
|
||||
logging.info(f"Resampling audio1 from {sample_rate_1}Hz to {sample_rate_2}Hz for merging.")
|
||||
else:
|
||||
output_sample_rate = sample_rate_1
|
||||
return waveform_1, waveform_2, output_sample_rate
|
||||
|
||||
|
||||
class AudioConcat(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="AudioConcat",
|
||||
search_aliases=["join audio", "combine audio", "append audio"],
|
||||
display_name="Concatenate Audio",
|
||||
description="Concatenates the audio1 to audio2 in the specified direction.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio1"),
|
||||
IO.Audio.Input("audio2"),
|
||||
IO.Combo.Input(
|
||||
"direction",
|
||||
options=['after', 'before'],
|
||||
default="after",
|
||||
tooltip="Whether to append audio2 after or before audio1.",
|
||||
)
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio1, audio2, direction) -> IO.NodeOutput:
|
||||
if audio1 is None and audio2 is None:
|
||||
return IO.NodeOutput(None)
|
||||
if audio1 is None:
|
||||
return IO.NodeOutput(audio2)
|
||||
if audio2 is None:
|
||||
return IO.NodeOutput(audio1)
|
||||
waveform_1 = audio1["waveform"]
|
||||
waveform_2 = audio2["waveform"]
|
||||
sample_rate_1 = audio1["sample_rate"]
|
||||
sample_rate_2 = audio2["sample_rate"]
|
||||
|
||||
if waveform_1.shape[1] == 1:
|
||||
waveform_1 = waveform_1.repeat(1, 2, 1)
|
||||
logging.info("AudioConcat: Converted mono audio1 to stereo by duplicating the channel.")
|
||||
if waveform_2.shape[1] == 1:
|
||||
waveform_2 = waveform_2.repeat(1, 2, 1)
|
||||
logging.info("AudioConcat: Converted mono audio2 to stereo by duplicating the channel.")
|
||||
|
||||
waveform_1, waveform_2, output_sample_rate = match_audio_sample_rates(waveform_1, sample_rate_1, waveform_2, sample_rate_2)
|
||||
|
||||
if direction == 'after':
|
||||
concatenated_audio = torch.cat((waveform_1, waveform_2), dim=2)
|
||||
elif direction == 'before':
|
||||
concatenated_audio = torch.cat((waveform_2, waveform_1), dim=2)
|
||||
|
||||
return IO.NodeOutput({"waveform": concatenated_audio, "sample_rate": output_sample_rate})
|
||||
|
||||
concat = execute # TODO: remove
|
||||
|
||||
|
||||
class AudioMerge(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="AudioMerge",
|
||||
search_aliases=["mix audio", "overlay audio", "layer audio"],
|
||||
display_name="Merge Audio",
|
||||
description="Combine two audio tracks by overlaying their waveforms.",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio1"),
|
||||
IO.Audio.Input("audio2"),
|
||||
IO.Combo.Input(
|
||||
"merge_method",
|
||||
options=["add", "mean", "subtract", "multiply"],
|
||||
tooltip="The method used to combine the audio waveforms.",
|
||||
)
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio1, audio2, merge_method) -> IO.NodeOutput:
|
||||
if audio1 is None and audio2 is None:
|
||||
return IO.NodeOutput(None)
|
||||
if audio1 is None:
|
||||
return IO.NodeOutput(audio2)
|
||||
if audio2 is None:
|
||||
return IO.NodeOutput(audio1)
|
||||
waveform_1 = audio1["waveform"]
|
||||
waveform_2 = audio2["waveform"]
|
||||
sample_rate_1 = audio1["sample_rate"]
|
||||
sample_rate_2 = audio2["sample_rate"]
|
||||
|
||||
waveform_1, waveform_2, output_sample_rate = match_audio_sample_rates(waveform_1, sample_rate_1, waveform_2, sample_rate_2)
|
||||
|
||||
length_1 = waveform_1.shape[-1]
|
||||
length_2 = waveform_2.shape[-1]
|
||||
|
||||
if length_1 == 0 or length_2 == 0:
|
||||
return IO.NodeOutput({"waveform": waveform_1, "sample_rate": output_sample_rate})
|
||||
|
||||
if length_2 > length_1:
|
||||
logging.info(f"AudioMerge: Trimming audio2 from {length_2} to {length_1} samples to match audio1 length.")
|
||||
waveform_2 = waveform_2[..., :length_1]
|
||||
elif length_2 < length_1:
|
||||
logging.info(f"AudioMerge: Padding audio2 from {length_2} to {length_1} samples to match audio1 length.")
|
||||
pad_shape = list(waveform_2.shape)
|
||||
pad_shape[-1] = length_1 - length_2
|
||||
pad_tensor = torch.zeros(pad_shape, dtype=waveform_2.dtype, device=waveform_2.device)
|
||||
waveform_2 = torch.cat((waveform_2, pad_tensor), dim=-1)
|
||||
|
||||
if merge_method == "add":
|
||||
waveform = waveform_1 + waveform_2
|
||||
elif merge_method == "subtract":
|
||||
waveform = waveform_1 - waveform_2
|
||||
elif merge_method == "multiply":
|
||||
waveform = waveform_1 * waveform_2
|
||||
elif merge_method == "mean":
|
||||
waveform = (waveform_1 + waveform_2) / 2
|
||||
|
||||
max_val = waveform.abs().max()
|
||||
if max_val > 1.0:
|
||||
waveform = waveform / max_val
|
||||
|
||||
return IO.NodeOutput({"waveform": waveform, "sample_rate": output_sample_rate})
|
||||
|
||||
merge = execute # TODO: remove
|
||||
|
||||
|
||||
class AudioAdjustVolume(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="AudioAdjustVolume",
|
||||
search_aliases=["audio gain", "loudness", "audio level"],
|
||||
display_name="Adjust Audio Volume",
|
||||
category="audio",
|
||||
description="Adjust the volume of the audio by a specified amount in decibels (dB).",
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.Int.Input(
|
||||
"volume",
|
||||
default=1,
|
||||
min=-100,
|
||||
max=100,
|
||||
tooltip="Volume adjustment in decibels (dB). 0 = no change, +6 = double, -6 = half, etc",
|
||||
)
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, volume) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
return IO.NodeOutput(None)
|
||||
if volume == 0:
|
||||
return IO.NodeOutput(audio)
|
||||
waveform = audio["waveform"]
|
||||
sample_rate = audio["sample_rate"]
|
||||
|
||||
gain = 10 ** (volume / 20)
|
||||
waveform = waveform * gain
|
||||
|
||||
return IO.NodeOutput({"waveform": waveform, "sample_rate": sample_rate})
|
||||
|
||||
adjust_volume = execute # TODO: remove
|
||||
|
||||
|
||||
class EmptyAudio(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="EmptyAudio",
|
||||
search_aliases=["blank audio"],
|
||||
display_name="Empty Audio",
|
||||
category="audio",
|
||||
inputs=[
|
||||
IO.Float.Input(
|
||||
"duration",
|
||||
default=60.0,
|
||||
min=0.0,
|
||||
max=0xffffffffffffffff,
|
||||
step=0.01,
|
||||
tooltip="Duration of the empty audio clip in seconds",
|
||||
),
|
||||
IO.Int.Input(
|
||||
"sample_rate",
|
||||
default=44100,
|
||||
tooltip="Sample rate of the empty audio clip.",
|
||||
min=1,
|
||||
max=192000,
|
||||
advanced=True,
|
||||
),
|
||||
IO.Int.Input(
|
||||
"channels",
|
||||
default=2,
|
||||
min=1,
|
||||
max=2,
|
||||
tooltip="Number of audio channels (1 for mono, 2 for stereo).",
|
||||
advanced=True,
|
||||
),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, duration, sample_rate, channels) -> IO.NodeOutput:
|
||||
num_samples = int(round(duration * sample_rate))
|
||||
waveform = torch.zeros((1, channels, num_samples), dtype=torch.float32)
|
||||
return IO.NodeOutput({"waveform": waveform, "sample_rate": sample_rate})
|
||||
|
||||
create_empty_audio = execute # TODO: remove
|
||||
|
||||
|
||||
class AudioEqualizer3Band(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="AudioEqualizer3Band",
|
||||
search_aliases=["eq", "bass boost", "treble boost", "equalizer"],
|
||||
display_name="Audio Equalizer (3-Band)",
|
||||
category="audio",
|
||||
is_experimental=True,
|
||||
inputs=[
|
||||
IO.Audio.Input("audio"),
|
||||
IO.Float.Input("low_gain_dB", default=0.0, min=-24.0, max=24.0, step=0.1, tooltip="Gain for Low frequencies (Bass)"),
|
||||
IO.Int.Input("low_freq", default=100, min=20, max=500, tooltip="Cutoff frequency for Low shelf"),
|
||||
IO.Float.Input("mid_gain_dB", default=0.0, min=-24.0, max=24.0, step=0.1, tooltip="Gain for Mid frequencies"),
|
||||
IO.Int.Input("mid_freq", default=1000, min=200, max=4000, tooltip="Center frequency for Mids"),
|
||||
IO.Float.Input("mid_q", default=0.707, min=0.1, max=10.0, step=0.1, tooltip="Q factor (bandwidth) for Mids"),
|
||||
IO.Float.Input("high_gain_dB", default=0.0, min=-24.0, max=24.0, step=0.1, tooltip="Gain for High frequencies (Treble)"),
|
||||
IO.Int.Input("high_freq", default=5000, min=1000, max=15000, tooltip="Cutoff frequency for High shelf"),
|
||||
],
|
||||
outputs=[IO.Audio.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, audio, low_gain_dB, low_freq, mid_gain_dB, mid_freq, mid_q, high_gain_dB, high_freq) -> IO.NodeOutput:
|
||||
if audio is None:
|
||||
return IO.NodeOutput(None)
|
||||
waveform = audio["waveform"]
|
||||
sample_rate = audio["sample_rate"]
|
||||
|
||||
if waveform.shape[-1] == 0:
|
||||
return IO.NodeOutput(audio)
|
||||
|
||||
eq_waveform = waveform.clone()
|
||||
|
||||
# 1. Apply Low Shelf (Bass)
|
||||
if low_gain_dB != 0:
|
||||
eq_waveform = torchaudio.functional.bass_biquad(
|
||||
eq_waveform,
|
||||
sample_rate,
|
||||
gain=low_gain_dB,
|
||||
central_freq=float(low_freq),
|
||||
Q=0.707
|
||||
)
|
||||
|
||||
# 2. Apply Peaking EQ (Mids)
|
||||
if mid_gain_dB != 0:
|
||||
eq_waveform = torchaudio.functional.equalizer_biquad(
|
||||
eq_waveform,
|
||||
sample_rate,
|
||||
center_freq=float(mid_freq),
|
||||
gain=mid_gain_dB,
|
||||
Q=mid_q
|
||||
)
|
||||
|
||||
# 3. Apply High Shelf (Treble)
|
||||
if high_gain_dB != 0:
|
||||
eq_waveform = torchaudio.functional.treble_biquad(
|
||||
eq_waveform,
|
||||
sample_rate,
|
||||
gain=high_gain_dB,
|
||||
central_freq=float(high_freq),
|
||||
Q=0.707
|
||||
)
|
||||
|
||||
return IO.NodeOutput({"waveform": eq_waveform, "sample_rate": sample_rate})
|
||||
|
||||
|
||||
class AudioExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[IO.ComfyNode]]:
|
||||
return [
|
||||
EmptyLatentAudio,
|
||||
VAEEncodeAudio,
|
||||
VAEDecodeAudio,
|
||||
VAEDecodeAudioTiled,
|
||||
SaveAudio,
|
||||
SaveAudioMP3,
|
||||
SaveAudioOpus,
|
||||
SaveAudioAdvanced,
|
||||
LoadAudio,
|
||||
PreviewAudio,
|
||||
ConditioningStableAudio,
|
||||
RecordAudio,
|
||||
TrimAudioDuration,
|
||||
SplitAudioChannels,
|
||||
JoinAudioChannels,
|
||||
AudioConcat,
|
||||
AudioMerge,
|
||||
AudioAdjustVolume,
|
||||
EmptyAudio,
|
||||
AudioEqualizer3Band,
|
||||
]
|
||||
|
||||
async def comfy_entrypoint() -> AudioExtension:
|
||||
return AudioExtension()
|
||||
@@ -0,0 +1,320 @@
|
||||
import os
|
||||
import av
|
||||
import torch
|
||||
import folder_paths
|
||||
import json
|
||||
from typing import Optional
|
||||
from typing_extensions import override
|
||||
from fractions import Fraction
|
||||
from comfy_api.latest import ComfyExtension, io, ui, Input, InputImpl, Types
|
||||
from comfy.cli_args import args
|
||||
|
||||
class SaveWEBM(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="SaveWEBM",
|
||||
search_aliases=["export webm"],
|
||||
display_name="Save WEBM",
|
||||
category="video",
|
||||
is_experimental=True,
|
||||
inputs=[
|
||||
io.Image.Input("images", tooltip="RGBA images are saved with their alpha channel as transparency (vp9 codec only)."),
|
||||
io.String.Input("filename_prefix", default="ComfyUI"),
|
||||
io.Combo.Input("codec", options=["vp9", "av1"]),
|
||||
io.Float.Input("fps", default=24.0, min=0.01, max=1000.0, step=0.01),
|
||||
io.Float.Input("crf", default=32.0, min=0, max=63.0, step=1, tooltip="Higher crf means lower quality with a smaller file size, lower crf means higher quality higher filesize."),
|
||||
],
|
||||
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
outputs=[io.Image.Output(display_name="images")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images, codec, fps, filename_prefix, crf) -> io.NodeOutput:
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
|
||||
filename_prefix, folder_paths.get_output_directory(), images[0].shape[1], images[0].shape[0]
|
||||
)
|
||||
|
||||
file = f"{filename}_{counter:05}_.webm"
|
||||
container = av.open(os.path.join(full_output_folder, file), mode="w")
|
||||
|
||||
if cls.hidden.prompt is not None:
|
||||
container.metadata["prompt"] = json.dumps(cls.hidden.prompt)
|
||||
|
||||
if cls.hidden.extra_pnginfo is not None:
|
||||
for x in cls.hidden.extra_pnginfo:
|
||||
container.metadata[x] = json.dumps(cls.hidden.extra_pnginfo[x])
|
||||
|
||||
# Save transparency when the images carry an alpha channel (RGBA) and the codec supports it.
|
||||
# vp9 -> yuva420p; other codecs have no usable alpha path, so the alpha is ignored.
|
||||
save_alpha = images.shape[-1] == 4 and codec == "vp9"
|
||||
|
||||
codec_map = {"vp9": "libvpx-vp9", "av1": "libsvtav1"}
|
||||
stream = container.add_stream(codec_map[codec], rate=Fraction(round(fps * 1000), 1000))
|
||||
stream.width = images.shape[-2]
|
||||
stream.height = images.shape[-3]
|
||||
stream.pix_fmt = "yuva420p" if save_alpha else ("yuv420p10le" if codec == "av1" else "yuv420p")
|
||||
stream.bit_rate = 0
|
||||
stream.options = {'crf': str(crf)}
|
||||
if codec == "av1":
|
||||
stream.options["preset"] = "6"
|
||||
|
||||
for frame in images:
|
||||
if save_alpha:
|
||||
frame = av.VideoFrame.from_ndarray(torch.clamp(frame[..., :4] * 255, min=0, max=255).to(device=torch.device("cpu"), dtype=torch.uint8).numpy(), format="rgba")
|
||||
else:
|
||||
frame = av.VideoFrame.from_ndarray(torch.clamp(frame[..., :3] * 255, min=0, max=255).to(device=torch.device("cpu"), dtype=torch.uint8).numpy(), format="rgb24")
|
||||
for packet in stream.encode(frame):
|
||||
container.mux(packet)
|
||||
container.mux(stream.encode())
|
||||
container.close()
|
||||
|
||||
return io.NodeOutput(images, ui=ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.output)]))
|
||||
|
||||
class SaveVideo(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="SaveVideo",
|
||||
search_aliases=["export video"],
|
||||
display_name="Save Video",
|
||||
category="video",
|
||||
essentials_category="Basics",
|
||||
description="Saves the input videos to your ComfyUI output directory.",
|
||||
inputs=[
|
||||
io.Video.Input("video", tooltip="The video to save."),
|
||||
io.String.Input("filename_prefix", default="video/ComfyUI", tooltip="The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."),
|
||||
io.Combo.Input("format", options=Types.VideoContainer.as_input(), default="auto", tooltip="The format to save the video as."),
|
||||
io.DynamicCombo.Input(
|
||||
"codec",
|
||||
options=[
|
||||
io.DynamicCombo.Option("auto", []),
|
||||
io.DynamicCombo.Option(
|
||||
"h264",
|
||||
[
|
||||
io.DynamicCombo.Input(
|
||||
"encoding",
|
||||
display_name="encoding mode",
|
||||
options=[
|
||||
io.DynamicCombo.Option("auto", []),
|
||||
io.DynamicCombo.Option(
|
||||
"re-encode",
|
||||
[io.Float.Input("crf", default=23.0, min=0.0, max=51.0, step=1.0, tooltip="Lower values produce higher quality and larger files.")],
|
||||
),
|
||||
],
|
||||
optional=True,
|
||||
tooltip="Automatic preserves compatible H.264 streams. Re-encode applies a custom CRF.",
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
tooltip="The codec to use for the video.",
|
||||
),
|
||||
],
|
||||
hidden=[io.Hidden.prompt, io.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
outputs=[io.Video.Output("video")],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, video: Input.Video, filename_prefix, format: str, codec: io.DynamicCombo.Type) -> io.NodeOutput:
|
||||
codec_name = codec["codec"]
|
||||
encoding = codec.get("encoding") or {}
|
||||
width, height = video.get_dimensions()
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
folder_paths.get_output_directory(),
|
||||
width,
|
||||
height
|
||||
)
|
||||
saved_metadata = None
|
||||
if not args.disable_metadata:
|
||||
metadata = {}
|
||||
if cls.hidden.extra_pnginfo is not None:
|
||||
metadata.update(cls.hidden.extra_pnginfo)
|
||||
if cls.hidden.prompt is not None:
|
||||
metadata["prompt"] = cls.hidden.prompt
|
||||
if len(metadata) > 0:
|
||||
saved_metadata = metadata
|
||||
file = f"{filename}_{counter:05}_.{Types.VideoContainer.get_extension(format)}"
|
||||
video.save_to(
|
||||
os.path.join(full_output_folder, file),
|
||||
format=Types.VideoContainer(format),
|
||||
codec=codec_name,
|
||||
metadata=saved_metadata,
|
||||
crf=encoding.get("crf"),
|
||||
)
|
||||
|
||||
return io.NodeOutput(video, ui=ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.output)]))
|
||||
|
||||
|
||||
class CreateVideo(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="CreateVideo",
|
||||
search_aliases=["images to video"],
|
||||
display_name="Create Video",
|
||||
category="video",
|
||||
essentials_category="Video Tools",
|
||||
description="Create a video from images.",
|
||||
inputs=[
|
||||
io.Image.Input("images", tooltip="The images to create a video from."),
|
||||
io.Float.Input("fps", default=30.0, min=1.0, max=120.0, step=1.0),
|
||||
io.Audio.Input("audio", optional=True, tooltip="The audio to add to the video."),
|
||||
io.Int.Input(
|
||||
"bit_depth",
|
||||
min=8,
|
||||
max=10,
|
||||
default=8,
|
||||
step=2,
|
||||
tooltip="Bit depth of the created video. 10-bit keeps smoother gradients with less"
|
||||
" banding, but some players and downstream nodes may not support it.",
|
||||
optional=True,
|
||||
display_mode=io.NumberDisplay.number,
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls, images: Input.Image, fps: float, audio: Optional[Input.Audio] = None, bit_depth: int = 8,
|
||||
) -> io.NodeOutput:
|
||||
return io.NodeOutput(
|
||||
InputImpl.VideoFromComponents(
|
||||
Types.VideoComponents(images=images, audio=audio, frame_rate=Fraction(fps)),
|
||||
bit_depth=bit_depth,
|
||||
)
|
||||
)
|
||||
|
||||
class GetVideoComponents(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="GetVideoComponents",
|
||||
search_aliases=["extract frames", "split video", "video to images", "demux"],
|
||||
display_name="Get Video Components",
|
||||
category="video",
|
||||
description="Extracts all components from a video: frames, audio, framerate, and bit depth.",
|
||||
inputs=[
|
||||
io.Video.Input("video", tooltip="The video to extract components from."),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(display_name="images"),
|
||||
io.Audio.Output(display_name="audio"),
|
||||
io.Float.Output(display_name="fps"),
|
||||
io.Int.Output(display_name="bit_depth"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, video: Input.Video) -> io.NodeOutput:
|
||||
components = video.get_components()
|
||||
return io.NodeOutput(components.images, components.audio, float(components.frame_rate), video.get_bit_depth())
|
||||
|
||||
|
||||
class LoadVideo(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
||||
files = folder_paths.filter_files_content_types(files, ["video"])
|
||||
return io.Schema(
|
||||
node_id="LoadVideo",
|
||||
search_aliases=["import video", "open video", "video file"],
|
||||
display_name="Load Video",
|
||||
category="video",
|
||||
essentials_category="Basics",
|
||||
inputs=[
|
||||
io.Combo.Input("file", options=sorted(files), upload=io.UploadType.video),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, file) -> io.NodeOutput:
|
||||
video_path = folder_paths.get_annotated_filepath(file)
|
||||
return io.NodeOutput(InputImpl.VideoFromFile(video_path))
|
||||
|
||||
@classmethod
|
||||
def fingerprint_inputs(s, file):
|
||||
video_path = folder_paths.get_annotated_filepath(file)
|
||||
mod_time = os.path.getmtime(video_path)
|
||||
# Instead of hashing the file, we can just use the modification time to avoid
|
||||
# rehashing large files.
|
||||
return mod_time
|
||||
|
||||
@classmethod
|
||||
def validate_inputs(s, file):
|
||||
if not folder_paths.exists_annotated_filepath(file):
|
||||
return "Invalid video file: {}".format(file)
|
||||
|
||||
return True
|
||||
|
||||
class VideoSlice(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="Video Slice",
|
||||
display_name="Trim Video",
|
||||
search_aliases=["trim video duration", "skip first frames", "frame load cap", "start time"],
|
||||
category="video",
|
||||
essentials_category="Video Tools",
|
||||
inputs=[
|
||||
io.Video.Input("video"),
|
||||
io.Float.Input(
|
||||
"start_time",
|
||||
default=0.0,
|
||||
max=1e5,
|
||||
min=-1e5,
|
||||
step=0.001,
|
||||
tooltip="Start time in seconds",
|
||||
),
|
||||
io.Float.Input(
|
||||
"duration",
|
||||
default=0.0,
|
||||
min=0.0,
|
||||
step=0.001,
|
||||
tooltip="Duration in seconds, or 0 for unlimited duration",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"strict_duration",
|
||||
default=False,
|
||||
tooltip="If True, when the specified duration is not possible, an error will be raised.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, video: io.Video.Type, start_time: float, duration: float, strict_duration: bool) -> io.NodeOutput:
|
||||
trimmed = video.as_trimmed(start_time, duration, strict_duration=strict_duration)
|
||||
if trimmed is not None:
|
||||
return io.NodeOutput(trimmed)
|
||||
raise ValueError(
|
||||
f"Failed to slice video:\nSource duration: {video.get_duration()}\nStart time: {start_time}\nTarget duration: {duration}"
|
||||
)
|
||||
|
||||
|
||||
class VideoExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [
|
||||
SaveWEBM,
|
||||
SaveVideo,
|
||||
CreateVideo,
|
||||
GetVideoComponents,
|
||||
LoadVideo,
|
||||
VideoSlice,
|
||||
]
|
||||
|
||||
async def comfy_entrypoint() -> VideoExtension:
|
||||
return VideoExtension()
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { useExtensionService } from '@/services/extensionService'
|
||||
import { processDynamicPrompt } from '@/utils/formatUtil'
|
||||
|
||||
// Allows for simple dynamic prompt replacement
|
||||
// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued.
|
||||
|
||||
useExtensionService().registerExtension({
|
||||
name: 'Comfy.DynamicPrompts',
|
||||
nodeCreated(node: LGraphNode) {
|
||||
if (node.widgets) {
|
||||
// Locate dynamic prompt text widgets
|
||||
// Include any widgets with dynamicPrompts set to true, and customtext
|
||||
const widgets = node.widgets.filter((w) => w.dynamicPrompts)
|
||||
for (const widget of widgets) {
|
||||
// Override the serialization of the value to resolve dynamic prompts for all widgets supporting it in this node
|
||||
widget.serializeValue = (workflowNode, widgetIndex) => {
|
||||
if (typeof widget.value !== 'string') return widget.value
|
||||
|
||||
const prompt = processDynamicPrompt(widget.value)
|
||||
|
||||
// Overwrite the value in the serialized workflow pnginfo
|
||||
if (workflowNode?.widgets_values)
|
||||
workflowNode.widgets_values[widgetIndex] = prompt
|
||||
|
||||
return prompt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import { isCloud, isNightly } from '@/platform/distribution/types'
|
||||
|
||||
import './clipspace'
|
||||
import './contextMenuFilter'
|
||||
import './createBoundingBoxes'
|
||||
import './customWidgets'
|
||||
import './dynamicPrompts'
|
||||
import './editAttention'
|
||||
import './electronAdapter'
|
||||
import './groupNode'
|
||||
import './groupOptions'
|
||||
import './imageCompare'
|
||||
import './imageCompositor'
|
||||
import './imageCrop'
|
||||
import './layerEditor'
|
||||
// load3d and saveMesh are loaded on-demand to defer THREE.js (~1.8MB)
|
||||
// The lazy loader triggers loading when a 3D node is used
|
||||
import './load3dLazy'
|
||||
import './maskeditor'
|
||||
if (!isCloud) {
|
||||
await import('./nodeTemplates')
|
||||
}
|
||||
import './noteNode'
|
||||
import './painter'
|
||||
import './previewAny'
|
||||
import './saveText'
|
||||
import './rerouteNode'
|
||||
import './saveImageExtraOutput'
|
||||
// saveMesh is loaded on-demand with load3d (see load3dLazy.ts)
|
||||
import './selectionBorder'
|
||||
import './simpleTouchSupport'
|
||||
import './slotDefaults'
|
||||
import './uploadAudio'
|
||||
import './uploadImage'
|
||||
import './webcamCapture'
|
||||
import './widgetInputs'
|
||||
|
||||
// Cloud-only extensions - tree-shaken in OSS builds
|
||||
// The literal __DISTRIBUTION__ comparison (not the isCloud const) is what
|
||||
// dead-code-eliminates this block and its posthog-js import from OSS builds.
|
||||
if (__DISTRIBUTION__ === 'cloud') {
|
||||
await import('./cloudRemoteConfig')
|
||||
const { registerAgentPanelExtension } = await import('./agentPanel')
|
||||
registerAgentPanelExtension()
|
||||
await import('./cloudBadges')
|
||||
await import('./cloudSessionCookie')
|
||||
}
|
||||
|
||||
// Feedback button for cloud and nightly builds
|
||||
if (isCloud || isNightly) {
|
||||
await import('./cloudFeedbackTopbarButton')
|
||||
}
|
||||
|
||||
// Nightly-only extensions
|
||||
if (isNightly && !isCloud) {
|
||||
await import('./nightlyBadges')
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import type { ComfyNodeDef } from '@/schemas/nodeDefSchema'
|
||||
import { applyTextReplacements } from '@/utils/searchAndReplace'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
const saveNodeTypes = new Set([
|
||||
'SaveImage',
|
||||
'SaveImageAdvanced',
|
||||
'SaveSVGNode',
|
||||
'SaveVideo',
|
||||
'SaveAnimatedWEBP',
|
||||
'SaveWEBM',
|
||||
'SaveAudio',
|
||||
'SaveAudioMP3',
|
||||
'SaveAudioOpus',
|
||||
'SaveAudioAdvanced',
|
||||
'SaveGLB',
|
||||
'Save3DAdvanced',
|
||||
'SaveGaussianSplat',
|
||||
'SavePointCloud',
|
||||
'SaveAnimatedPNG',
|
||||
'CLIPSave',
|
||||
'VAESave',
|
||||
'ModelSave',
|
||||
'LoraSave',
|
||||
'SaveLatent'
|
||||
])
|
||||
|
||||
// Use widget values and dates in output filenames
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.SaveImageExtraOutput',
|
||||
async beforeRegisterNodeDef(
|
||||
nodeType: typeof LGraphNode,
|
||||
nodeData: ComfyNodeDef
|
||||
) {
|
||||
if (saveNodeTypes.has(nodeData.name)) {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
// When the SaveImage node is created we want to override the serialization of the output name widget to run our S&R
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? // @ts-expect-error fixme ts strict error
|
||||
onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const widget = this.widgets.find((w) => w.name === 'filename_prefix')
|
||||
// @ts-expect-error fixme ts strict error
|
||||
widget.serializeValue = () => {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
return applyTextReplacements(app.graph, widget.value)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
} else {
|
||||
// When any other node is created add a property to alias the node
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? // @ts-expect-error fixme ts strict error
|
||||
onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
|
||||
if (!this.properties || !('Node name for S&R' in this.properties)) {
|
||||
this.addProperty('Node name for S&R', this.constructor.type, 'string')
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { LGraph, Subgraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { formatDate } from '@/utils/formatUtil'
|
||||
import { collectAllNodes } from '@/utils/graphTraversalUtil'
|
||||
|
||||
export function applyTextReplacements(
|
||||
graph: LGraph | Subgraph,
|
||||
value: string
|
||||
): string {
|
||||
const allNodes = collectAllNodes(graph)
|
||||
|
||||
return value.replace(/%([^%]+)%/g, function (match, text) {
|
||||
const split = text.split('.')
|
||||
if (split.length !== 2) {
|
||||
// Special handling for dates
|
||||
if (split[0].startsWith('date:')) {
|
||||
return formatDate(split[0].substring(5), new Date())
|
||||
}
|
||||
|
||||
if (text !== 'width' && text !== 'height') {
|
||||
// Dont warn on standard replacements
|
||||
console.warn('Invalid replacement pattern', text)
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
// Find node with matching S&R property name
|
||||
let nodes = allNodes.filter(
|
||||
(n) => n.properties?.['Node name for S&R'] === split[0]
|
||||
)
|
||||
// If we can't, see if there is a node with that title
|
||||
if (!nodes.length) {
|
||||
nodes = allNodes.filter((n) => n.title === split[0])
|
||||
}
|
||||
if (!nodes.length) {
|
||||
console.warn('Unable to find node', split[0])
|
||||
return match
|
||||
}
|
||||
|
||||
if (nodes.length > 1) {
|
||||
console.warn('Multiple nodes matched', split[0], 'using first match')
|
||||
}
|
||||
|
||||
const node = nodes[0]
|
||||
|
||||
const widget = node.widgets?.find((w) => w.name === split[1])
|
||||
if (!widget) {
|
||||
console.warn('Unable to find widget', split[1], 'on node', split[0], node)
|
||||
return match
|
||||
}
|
||||
|
||||
return ((widget.value ?? '') + '').replaceAll(
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[/?<>\\:*|"\x00-\x1F\x7F]/g,
|
||||
'_'
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""Inventory immutable core bytes and reuse the SAME pinned frontend identity."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
CORE = "2f35f4a08176d993cded35dac3332be4f7287f41"
|
||||
FRONTEND = "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5"
|
||||
ANCHORS = (
|
||||
"class VAELoader",
|
||||
"class UNETLoader",
|
||||
"class CLIPLoader",
|
||||
"class VAEDecode",
|
||||
"class KSamplerSelect",
|
||||
"class BasicGuider",
|
||||
"class SamplerCustomAdvanced",
|
||||
"class CreateVideo",
|
||||
"class SaveVideo",
|
||||
"VideoContainer",
|
||||
"INPUT_TYPES",
|
||||
"RETURN_TYPES",
|
||||
"NODE_CLASS_MAPPINGS",
|
||||
"get_filename_list",
|
||||
"codec",
|
||||
"filename_prefix",
|
||||
"applyTextReplacements",
|
||||
"serializeValue",
|
||||
"nodes_video.py",
|
||||
"nodes_audio.py",
|
||||
"KSAMPLER_NAMES",
|
||||
"SAMPLER_NAMES",
|
||||
"class StringMultiline",
|
||||
"class Float",
|
||||
"class ResolutionSelector",
|
||||
"class AspectRatio",
|
||||
"class MathExpressionNode",
|
||||
"class RandomNoise",
|
||||
"class BasicScheduler",
|
||||
"def define_schema",
|
||||
"async def get_node_list",
|
||||
"async def comfy_entrypoint",
|
||||
"class MultiType",
|
||||
"class Autogrow",
|
||||
"class TemplateNames",
|
||||
"def as_dict",
|
||||
"def _expand_schema_for_dynamic",
|
||||
"node_id",
|
||||
"get_node_list()",
|
||||
"schema.node_id",
|
||||
"nodes_primitive.py",
|
||||
"nodes_resolution.py",
|
||||
"nodes_math.py",
|
||||
"nodes_custom_sampler.py",
|
||||
"SCHEDULER_HANDLERS =",
|
||||
"SCHEDULER_NAMES =",
|
||||
"def execute",
|
||||
"noise_seed",
|
||||
"control_after_generate",
|
||||
"getRestoredWidgetValue",
|
||||
"createWidgetRestorationState",
|
||||
"restoreNamed",
|
||||
"serializeValue",
|
||||
"widgets_values_named",
|
||||
"serialiseWidgetValues",
|
||||
"widget.options?.serialize",
|
||||
"inputs[input.name]",
|
||||
"applyAutogrow",
|
||||
"addAutogrowGroup",
|
||||
"autogrowOrdinalToName",
|
||||
"onConnectionsChange",
|
||||
"getOrderedInputSpecs",
|
||||
"for (const inputSpec of orderedInputSpecs)",
|
||||
"mode === 'fixed'",
|
||||
"beforeQueued",
|
||||
"afterQueued",
|
||||
"applyDynamicInputs",
|
||||
"RESOLUTION",
|
||||
"serialize: false",
|
||||
"fallbackWidgetsValuesNames",
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
old = json.loads((ROOT.parent / "h3-core-reference/sources.json").read_bytes())
|
||||
rows = []
|
||||
for entry in old["sources"]:
|
||||
row = dict(entry)
|
||||
row["local_file"] = "../h3-core-reference/" + row["local_file"]
|
||||
row["reuse"] = (
|
||||
"same core0.33.0/frontend1.53.10 full identities from first-group manifest"
|
||||
)
|
||||
rows.append(row)
|
||||
existing = {r["id"] for r in rows}
|
||||
for p in sorted(ROOT.glob("*__*")):
|
||||
prefix, _, tail = p.name.partition("__")
|
||||
if prefix not in ("core", "frontend"):
|
||||
continue
|
||||
filename = tail.replace("__", "/")
|
||||
ident = f"{prefix}:{filename}"
|
||||
if ident in existing:
|
||||
# Already references the same full commit original, do not duplicate.
|
||||
continue
|
||||
repo, sha, tag = (
|
||||
("Comfy-Org/ComfyUI", CORE, "v0.33.0")
|
||||
if prefix == "core"
|
||||
else ("Comfy-Org/ComfyUI_frontend", FRONTEND, "v1.53.10")
|
||||
)
|
||||
lines = p.read_text().splitlines()
|
||||
locations = {
|
||||
f"{anchor}@{i}": [i, min(i + 4, len(lines))]
|
||||
for anchor in ANCHORS
|
||||
for i, line in enumerate(lines, 1)
|
||||
if anchor in line
|
||||
}
|
||||
rows.append(
|
||||
{
|
||||
"id": ident,
|
||||
"repository": f"https://github.com/{repo}",
|
||||
"commit": sha,
|
||||
"tag": tag,
|
||||
"file": filename,
|
||||
"lines": [[1, len(lines)]],
|
||||
"rule_locations": locations,
|
||||
"raw_url": f"https://raw.githubusercontent.com/{repo}/{sha}/{filename}",
|
||||
"url": f"https://github.com/{repo}/blob/{sha}/{filename}",
|
||||
"sha256": hashlib.sha256(p.read_bytes()).hexdigest(),
|
||||
"local_file": p.name,
|
||||
"license": "GPL-3.0",
|
||||
"target_version_match": "unknown",
|
||||
}
|
||||
)
|
||||
identities = []
|
||||
for name, repo, ref, expected, local in (
|
||||
(
|
||||
"core-tag",
|
||||
"Comfy-Org/ComfyUI",
|
||||
"v0.33.0",
|
||||
CORE,
|
||||
"../h3-core-reference/core-tag.json",
|
||||
),
|
||||
(
|
||||
"frontend-tag",
|
||||
"Comfy-Org/ComfyUI_frontend",
|
||||
"v1.53.10",
|
||||
FRONTEND,
|
||||
"../h3-reference/ComfyUI_frontend-tag.json",
|
||||
),
|
||||
):
|
||||
raw = (ROOT / local).read_bytes()
|
||||
data = json.loads(raw)
|
||||
assert data["object"]["sha"] == expected and data["object"]["type"] == "commit"
|
||||
identities.append(
|
||||
{
|
||||
"id": name,
|
||||
"raw_url": f"https://api.github.com/repos/{repo}/git/ref/tags/{ref}",
|
||||
"local_file": local,
|
||||
"sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"ref": f"refs/tags/{ref}",
|
||||
"commit": expected,
|
||||
}
|
||||
)
|
||||
(ROOT / "sources.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schema_version": 1,
|
||||
"authority": "public_reference_only_not_object_info",
|
||||
"sources": rows,
|
||||
"identity_observations": identities,
|
||||
"target_installation": "unknown",
|
||||
"source_graph_identity": "unknown",
|
||||
"upstream_code_executed": False,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
"""Recheck mutable tag identity fields; byte SHA is only the saved observation."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((ROOT / "sources.json").read_bytes())
|
||||
rows = []
|
||||
for entry in manifest["identity_observations"]:
|
||||
raw = (ROOT / entry["local_file"]).read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == entry["sha256"]
|
||||
with urlopen(entry["raw_url"], timeout=30) as response:
|
||||
now = json.loads(response.read())
|
||||
assert now["ref"] == entry["ref"] and now["object"]["type"] == "commit"
|
||||
assert now["object"]["sha"] == entry["commit"]
|
||||
rows.append(
|
||||
{
|
||||
"id": entry["id"],
|
||||
"url": entry["raw_url"],
|
||||
"ref": now["ref"],
|
||||
"commit": now["object"]["sha"],
|
||||
"saved_observation_sha256": entry["sha256"],
|
||||
"byte_identity_required": False,
|
||||
}
|
||||
)
|
||||
(ROOT.parent / "h3-chain-evidence/identity-refetched.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"observations": rows,
|
||||
"target_installation": "unknown",
|
||||
"source_graph_identity": "unknown",
|
||||
"upstream_executed": False,
|
||||
},
|
||||
ensure_ascii=False,
|
||||
indent=2,
|
||||
)
|
||||
+ "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user