Skip to content

Instantly share code, notes, and snippets.

@CoffeeVampir3
Last active March 12, 2024 20:16
Show Gist options
  • Save CoffeeVampir3/f5470e16b723140434a059d3b35b908a to your computer and use it in GitHub Desktop.
Save CoffeeVampir3/f5470e16b723140434a059d3b35b908a to your computer and use it in GitHub Desktop.
Mutate clip
import re, os, random, csv
class WildCLIP:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"text": ("STRING", {"multiline": True}), "clip": ("CLIP", )
}
}
RETURN_TYPES = ("CONDITIONING",)
FUNCTION = "encode"
CATEGORY = "conditioning"
def pattern_replace(self, text):
pattern = r'<([^>]+)>'
matches = re.findall(pattern, text)
choices = []
for match in matches:
sub_matches = match.split('|')
for sm in sub_matches:
if sm.startswith('%') and sm.endswith('%'):
filename = sm[1:-1] # Remove the leading and trailing '%' characters
file_path = os.path.join('wildcards', filename + '.csv')
absolute_path = os.path.abspath(file_path)
try:
with open(absolute_path, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
choices.extend(row)
except FileNotFoundError:
print(f"File '{absolute_path}' not found.")
else:
choices.append(sm)
print(choices)
if choices is not None:
selected_option = random.choice(choices)
text = text.replace('<' + match + '>', selected_option)
return text
def encode(self, clip, text):
text = self.pattern_replace(text)
print(text)
tokens = clip.tokenize(text)
tokens["l"] = clip.tokenize(text)["l"]
if len(tokens["l"]) != len(tokens["g"]):
empty = clip.tokenize("")
while len(tokens["l"]) < len(tokens["g"]):
tokens["l"] += empty["l"]
while len(tokens["l"]) > len(tokens["g"]):
tokens["g"] += empty["g"]
cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
return ([[cond, {"pooled_output": pooled}]], )
NODE_CLASS_MAPPINGS = {
"WildCLIP": WildCLIP
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"WildCLIP": "Wild Clip"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment