ACCC1380/molab-checkpoints / patch_bsk_six_inputs.py
ACCC1380's picture
download
raw
4.15 kB
#!/usr/bin/env python3
"""Expand BSK StringMergeWithSwitch to six inputs for an older ComfyUI workflow.
Run from anywhere: python3 patch_bsk_six_inputs.py
Optional: python3 patch_bsk_six_inputs.py /path/to/ComfyUI_bsk_UI/__init__.py
Only rewrites the named class, saves a timestamped backup, and validates syntax.
"""
import ast
import os
from pathlib import Path
import shutil
import sys
import tempfile
from datetime import datetime, timezone
DEFAULT_PATH = Path('/marimo/ComfyUI/custom_nodes/ComfyUI_bsk_UI/__init__.py')
TARGET = Path(sys.argv[1] if len(sys.argv) > 1 else DEFAULT_PATH)
REPLACEMENT = '''class bsk_StringMergeWithSwitch:
"""Merge six optional string inputs, gated by corresponding switches."""
@classmethod
def INPUT_TYPES(cls):
optional = {}
for number in range(1, 7):
optional[f"input{number}"] = ("STRING", {"default": "", "forceInput": False})
optional[f"switch{number}"] = ("BOOLEAN", {"default": True})
return {"required": {}, "optional": optional}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("merged_string",)
FUNCTION = "merge_strings"
CATEGORY = "utils/text"
def merge_strings(self, input1="", switch1=True, input2="", switch2=True,
input3="", switch3=True, input4="", switch4=True,
input5="", switch5=True, input6="", switch6=True):
parts = []
for value, enabled in ((input1, switch1), (input2, switch2),
(input3, switch3), (input4, switch4),
(input5, switch5), (input6, switch6)):
if enabled and value:
cleaned = value.strip().rstrip(", ")
if cleaned:
parts.append(cleaned)
return (", ".join(parts),)
'''
def main():
if not TARGET.is_file():
raise SystemExit(f'找不到 BSK 插件源码:{TARGET}')
original = TARGET.read_text(encoding='utf-8')
tree = ast.parse(original, filename=str(TARGET))
found = [node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == 'bsk_StringMergeWithSwitch']
if len(found) != 1:
raise SystemExit(f'预期恰好一个 bsk_StringMergeWithSwitch 类,实际找到 {len(found)} 个;未修改。')
cls = found[0]
source_bytes = original.encode('utf-8')
starts = [0]
for line in source_bytes.splitlines(keepends=True):
starts.append(starts[-1] + len(line))
start = starts[cls.lineno - 1] + cls.col_offset
end = starts[cls.end_lineno - 1] + cls.end_col_offset
current = source_bytes[start:end]
if b'Merge six optional string inputs, gated' in current:
print('BSK 六路合并节点已修复,无需重复修改。')
return
# Refuse to replace unrelated code after upstream refactors.
method_names = {node.name for node in cls.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))}
if not {'INPUT_TYPES', 'merge_strings'}.issubset(method_names):
raise SystemExit('现有类结构不符合预期,停止修改。')
changed = source_bytes[:start] + REPLACEMENT.encode('utf-8') + source_bytes[end:]
ast.parse(changed.decode('utf-8'), filename=str(TARGET))
stat = TARGET.stat()
timestamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
backup = TARGET.with_name(TARGET.name + f'.backup-bsk-{timestamp}')
shutil.copy2(TARGET, backup)
fd, tempname = tempfile.mkstemp(prefix='.bsk-fix-', dir=str(TARGET.parent))
try:
with os.fdopen(fd, 'wb') as f:
f.write(changed)
f.flush()
os.fsync(f.fileno())
os.chmod(tempname, stat.st_mode & 0o777)
if os.geteuid() == 0:
os.chown(tempname, stat.st_uid, stat.st_gid)
os.replace(tempname, TARGET)
finally:
if os.path.exists(tempname):
os.unlink(tempname)
print('修复成功:bsk_StringMergeWithSwitch 已支持 input1~input6 / switch1~switch6')
print('备份文件:', backup)
print('请完整重启 ComfyUI,再运行工作流。')
if __name__ == '__main__':
main()

Xet Storage Details

Size:
4.15 kB
·
Xet hash:
28260ee1904740a57a00e5f6e37b03376082b8f76c7000433380da92d41243b2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.