import torch import gc class Iter_TextSwitch: def __init__(self): pass @classmethod def INPUT_TYPES(s): return { "required": { # 預設為空字串,允許不接線 "add_text": ("STRING", {"forceInput": True, "default": ""}), "output_index": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}), "input_count": ("INT", {"default": 2, "min": 1, "max": 128, "step": 1}), "use_last_input": ("BOOLEAN", {"default": False}), }, "optional": { # 這裡不需要寫死 text_0,因為 JS 會動態產生所有輸入 } } RETURN_TYPES = ("STRING",) FUNCTION = "switch_and_combine" CATEGORY = "CustomNodes/Logic" def switch_and_combine(self, add_text="", output_index=0, input_count=1, use_last_input=False, **kwargs): """ # 1. 蒐集所有動態傳入的字串 texts = [] for i in range(input_count): val = kwargs.get(f"text_{i}") # 只有當該接點有連線且有值時才加入(避免計算空的接點) if val is not None: texts.append(val) # 2. 安全性檢查:如果完全沒有輸入接點有連線 if not texts: # 如果連 add_text 都沒接,就回傳純空字串 return (add_text if add_text is not None else "",) # 3. 根據索引選取文本(防止除以零) target_index = output_index % len(texts) selected_text = texts[target_index] # 4. 串接並回傳 # 確保兩者皆為字串,避免 NoneType 相加報錯 final_header = add_text if add_text is not None else "" final_selected = selected_text if selected_text is not None else "" gc.collect() torch.cuda.empty_cache() return (final_header + final_selected,) """ # 1. 取得目標索引(對 input_count 取模,確保不溢出) # 這樣 index 0~n 就會嚴格對應到 image_0 ~ image_n target_idx = output_index % input_count # 2. 從目標索引開始「往回」搜尋有效接點 res_txt = None for i in range(target_idx, -1, -1): val = kwargs.get(f"text_{i}") if val is not None or not use_last_input: res_txt = val break #gc.collect() #torch.cuda.empty_cache() return (add_text + res_txt,)