Files
fls-eugene-ComfyUI_TextRand…/file_loader.py
T
2026-07-17 00:31:36 +02:00

80 lines
2.6 KiB
Python

import os
import random
from .randomizer import MultilineRandomChanceNode
class WildcardFileLoaderNode:
@classmethod
def get_wildcard_files(cls):
"""Scans the wildcards directory recursively to find all text files, preserving folder structures."""
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "wildcards")
)
os.makedirs(base_dir, exist_ok=True)
file_list = []
for root, _, files in os.walk(base_dir):
for file in files:
if file.endswith(".txt"):
full_path = os.path.join(root, file)
rel_path = os.path.relpath(full_path, base_dir)
file_list.append(rel_path.replace("\\", "/"))
if not file_list:
return ["No .txt files found in ComfyUI/wildcards/"]
return sorted(file_list)
@classmethod
def INPUT_TYPES(cls):
file_list = cls.get_wildcard_files()
return {
"required": {
"wildcard_file": (file_list,),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFFFFFFFFFFFF}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("selected_text",)
FUNCTION = "load_and_randomize_file"
CATEGORY = "TextRandomizer/Text"
def load_and_randomize_file(self, wildcard_file, seed):
base_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "wildcards")
)
file_path = os.path.join(base_dir, wildcard_file)
if not os.path.exists(file_path) or wildcard_file.startswith("No .txt files"):
return ("",)
try:
with open(file_path, "r", encoding="utf-8") as f:
raw_lines = f.readlines()
except Exception:
return ("",)
# Filter out comments and blank lines
clean_text_block = "\n".join(
[
line.strip()
for line in raw_lines
if line.strip() and not line.startswith("#")
]
)
if not clean_text_block:
return ("",)
# 1. Fetch the raw tuple output generated by the randomizer module code
randomizer = MultilineRandomChanceNode()
final_string_tuple = randomizer.process_random_text(clean_text_block, seed)
# 2. Extract index 0 to strip away the internal tuple container structure
pure_extracted_string = final_string_tuple[0]
# 3. Return the pure string packaged cleanly inside ComfyUI's mandatory outer node tuple wrapper
return (pure_extracted_string,)