36 Commits
Author SHA1 Message Date
lilly 396256c084 Update README.md 2024-12-21 10:50:03 +09:00
lilly 87d6fd0c35 Update VAELoaderText.py 2023-10-25 00:34:18 +09:00
lilly 70ed2501bb Update LoraLoaderText.py 2023-08-26 00:20:51 +09:00
lilly 4e57039166 clean 2023-08-24 08:23:36 +09:00
lilly 4bc3e21500 Update mypath.py 2023-08-11 18:31:17 +09:00
lilly c34ebf1940 Update CheckpointLoaderSimpleText.py 2023-08-04 23:58:51 +09:00
lilly b4191ce40f Merge pull request #9 from Chubbly/folder_paths
Use ComfyUI folder locations
2023-08-03 16:47:37 +09:00
Chubbly ca5e193b7e Use ComfyUI folder locations 2023-08-01 21:13:25 +12:00
lilly 4b5f62e141 Update README.md 2023-07-18 19:25:37 +09:00
lilly 35f66f5712 wildcard pattern matching
wildcard pattern matching
2023-07-18 19:17:12 +09:00
lilly 1300e6f958 Merge branch 'main' of https://github.com/lilly1987/ComfyUI_node_Lilly 2023-07-18 18:44:38 +09:00
lilly 7186f2c895 Update wildcards.py
https://github.com/lilly1987/ComfyUI_node_Lilly/commit/0545b7e3f39e0f28c02319f96202f0c03413995d
supports .txt files in different encodings.
2023-07-18 18:44:10 +09:00
lilly 4c50ca066b Update README.md 2023-07-18 18:20:05 +09:00
lilly 0c4fe0b7f5 Merge branch 'main' of https://github.com/lilly1987/ComfyUI_node_Lilly 2023-07-18 18:12:00 +09:00
lilly 46d6e4e111 Update wildcards.py
정리
2023-07-18 18:11:58 +09:00
lilly bdb80a3c85 Update README.md 2023-07-18 17:54:07 +09:00
lilly d3667dc022 Update wildcards.py
호환성 추가
2023-07-18 17:49:18 +09:00
lilly 8cadb8a284 Update wildcards.py
https://github.com/lilly1987/ComfyUI_node_Lilly/pull/8/commits/c91e62428f32171aaf10ed6e71138371a1854a19
2023-07-18 17:35:29 +09:00
lilly ed401cb9b8 fix 230711
LoraLoaderTextRandom is not test
2023-07-11 22:27:58 +09:00
lilly ab31903931 fix 2023-06-27 18:27:10 +09:00
lilly 2148bbd6df Update SaveImageSimple.py
fix
2023-04-28 14:59:13 +09:00
lilly c94162bfcd Update SaveImageSimple.py 2023-04-17 00:50:29 +09:00
lilly 60ff0e5b57 Update SaveImageSimple.py 2023-04-17 00:50:12 +09:00
lilly 9ffde08e4d Update README.md 2023-04-13 23:11:27 +09:00
lilly 026ffb291b support wildcard file name 2023-04-13 23:05:35 +09:00
lilly 038ea91985 add VAELoaderText 2023-04-13 00:27:48 +09:00
lilly fe13add535 Update TextWildcards.py
fix
2023-04-12 22:44:26 +09:00
lilly 40ad60ab06 Update __init__.py 2023-04-12 21:44:20 +09:00
lilly 41be495672 Update CheckpointLoaderSimpleText.py 2023-04-06 21:29:47 +09:00
lilly 059d59455c Update LoraLoaderText.py
bug fix
2023-04-05 22:09:37 +09:00
lilly 99a74bee92 Merge branch 'main' of https://github.com/lilly1987/ComfyUI_node_Lilly 2023-04-05 21:52:32 +09:00
lilly 3247eaec7e Update SimpleSampler.py 2023-04-05 21:52:25 +09:00
lilly dd3420d15c Update README.md 2023-04-05 21:25:52 +09:00
lilly eb17b381a6 Update wildcards.py
is_card_Load
2023-04-05 21:24:14 +09:00
lilly 6feccddcba Merge branch 'test' 2023-04-05 20:21:30 +09:00
lilly 7bd85c9544 Update __init__.py 2023-04-05 20:21:21 +09:00
12 changed files with 334 additions and 117 deletions
+1
View File
@@ -1,2 +1,3 @@
*.pyc
**/nppBackup/
+7 -15
View File
@@ -5,10 +5,10 @@ from folder_paths import *
import random
import os
if __name__ == os.path.splitext(os.path.basename(__file__))[0] :
from ConsoleColor import print, console
from ConsoleColor import print, console, ccolor
from mypath import *
else:
from .ConsoleColor import print, console
from .ConsoleColor import print, console, ccolor
from .mypath import *
#print(__file__)
@@ -35,24 +35,16 @@ class CheckpointLoaderSimpleText:
CATEGORY = "loaders"
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
#ckpt_path =check_name_ckpt(name_split_choice(ckpt_name))
print(f"ckpt_name",ckpt_name)
ns=name_split_choice(ckpt_name)
print(f"ns",ns)
ckpt_path =get_full_path("checkpoints",ns)
print(f"ckpt_path",ckpt_path)
print(f"[{ccolor}]ckpt_name : [/{ccolor}]", ckpt_name)
ckpt_path=folder_paths.get_full_path("checkpoints", ckpt_name)
if ckpt_path is None:
print(f"{ckpt_name} is none")
(name,fullpath)=filenameget(os.path.join(models_dir, "checkpoints")+"/**/"+ckpt_name+"*.safetensors")
if fullpath is None:
print(f"{name} is none")
return
ckpt_path=fullpath
ckpt_path=getFullPath(ckpt_name,"checkpoints")
print(f"[{ccolor}]ckpt_path : [/{ccolor}]", ckpt_path)
try:
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
return out
except Exception as e:
print("CheckpointLoaderSimpleText Exception : "+ e)
console.print_exception()
return
+36 -18
View File
@@ -4,11 +4,16 @@ from nodes import *
import folder_paths
if __name__ == os.path.splitext(os.path.basename(__file__))[0] :
from ConsoleColor import print, console
from ConsoleColor import print, console, ccolor
from mypath import *
else:
from .ConsoleColor import print, console
from .ConsoleColor import print, console, ccolor
from .mypath import *
class LoraLoaderText:
def __init__(self):
self.loaded_lora = None
@classmethod
def INPUT_TYPES(s):
return {
@@ -31,25 +36,38 @@ class LoraLoaderText:
def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
if lora_name is None or lora_name =="":
print("[red]No lora_name[/red] : ", lora_name)
return (strength_model, strength_clip)
if lora_name.endswith('.safetensors') or lora_name.endswith('.ckpt') :
lora_path = folder_paths.get_full_path("loras", lora_name)
print(f"[{ccolor}]lora_name : [/{ccolor}]", lora_name)
if strength_model == 0 and strength_clip == 0:
print("[red]strength_model,strength_clip 0[/red] : ", lora_name)
return (model, clip)
else:
lora_path = folder_paths.get_full_path("loras", lora_name+'.safetensors')
print("[green]lora_path : [/green]"+ lora_path)
if lora_name is None or lora_name =="" :
print("[red]No lora_name[/red] : ", lora_name)
return (model, clip)
lora_path = folder_paths.get_full_path("loras", lora_name)
if lora_path is None:
print("[yellow]No lora_path of lora_name [/yellow] : ", lora_name)
lora_path=getFullPath(lora_name,"loras")
if lora_path is None:
lora_path = folder_paths.get_full_path("loras", lora_name+'.ckpt')
print("[green]lora_path : [/green]"+ lora_path)
if lora_path is None:
print("[red]No lora_name[/red] : ", lora_name)
return (model, clip)
print("[red]No lora_path of lora_name [/red] : ", lora_name)
return (model, clip)
lora = None
if self.loaded_lora is not None:
if self.loaded_lora[0] == lora_path:
lora = self.loaded_lora[1]
else:
del self.loaded_lora
if lora is None:
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
self.loaded_lora = (lora_path, lora)
# =========================================
try:
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora_path, strength_model, strength_clip)
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
return (model_lora, clip_lora)
except Exception as e:
console.print_exception()
+30 -7
View File
@@ -48,18 +48,41 @@ class LoraLoaderTextRandom:
strength_model=random.uniform(min(strength_model_min,strength_model_max),max(strength_model_min,strength_model_max))
strength_clip=random.uniform(min(strength_clip_min,strength_clip_max),max(strength_clip_min,strength_clip_max))
lora_path =check_name_pt("loras",name_split_choice(lora_name))
if lora_path is None:
print(f"LoraLoaderTextRandom : {lora_name} is none")
print(f"[{ccolor}]lora_name : [/{ccolor}]", lora_name)
if strength_model == 0 and strength_clip == 0:
print("[red]strength_model,strength_clip 0[/red] : ", lora_name)
return (model, clip)
print(f"LoraLoaderTextRandom : {lora_path} ")
if lora_name is None or lora_name =="" :
print("[red]No lora_name[/red] : ", lora_name)
return (model, clip)
lora_path = folder_paths.get_full_path("loras", lora_name)
if lora_path is None:
#print("[red]No lora_path of lora_name [/red] : ", lora_name)
lora_path=getFullPath(lora_name,"loras")
if lora_path is None:
print("[red]No lora_path of lora_name [/red] : ", lora_name)
return (model, clip)
lora = None
if self.loaded_lora is not None:
if self.loaded_lora[0] == lora_path:
lora = self.loaded_lora[1]
else:
del self.loaded_lora
if lora is None:
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
self.loaded_lora = (lora_path, lora)
# =========================================
try:
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora_path, strength_model, strength_clip)
return (model_lora, clip_lora)
except Exception as e:
print(f"LoraLoaderTextRandom Exception : {e}" )
err_msg = traceback.format_exc()
print(err_msg)
console.print_exception()
return (model, clip)
#NODE_CLASS_MAPPINGS = {
+54 -13
View File
@@ -1,20 +1,30 @@
# ComfyUI-node-Lilly
## No longer maintained.
i use https://github.com/ltdrdata/ComfyUI-extension-tutorials/blob/Main/ComfyUI-Impact-Pack/tutorial/ImpactWildcard.md
## install
ComfyUI_windows_portable\ComfyUI\custom_nodes\ComfyUI_node_Lilly
Go to ./custom_nodes and clone git repo:
```
cd ./custom_nodes
git clone https://github.com/kuriot/ComfyUI_node_Lilly.git
```
or https://github.com/lilly1987/ComfyUI_node_Lilly/archive/refs/heads/main.zip install this like
![2023-03-22 05 54 43](https://user-images.githubusercontent.com/20321215/226738610-c042a51c-8e72-45de-b714-385eaac383af.png)
## wildcards
### ex
### ex - wildcard
- form
- form :
a{__b__|{c|}|{__d__|e|}|f|}g____ __my__
- to
- to :
aeg __quality_my__, __breasts__, { |__character_dress__|__dress_my__}, __shoulder__, {high heels,| } {choker,| } {<lora:__lora_lst__:__rora_num__>,| } NSFW, __NSFW_my__, { |__style_my__,}
```
@@ -28,6 +38,30 @@ ex : {3$$a1|{b2|c3|}|d4|{-$$|f|g}|{-2$$h||i}|{1-$$j|k|}}/{$$l|m|}/{0$$n|}
{-$$a|b|c} -> {0-3$$a|b|c} 0-max
```
### ex - wildcard text file use
- ~/a/b.txt
```
1
```
- ~/b.txt
```
2
```
- __b__ to 1 or 2
- __/b__ to 2
- __/a/b__ to 1
- __?b__ to 2
- __*__ to 1 or 2
### filename pattern matching
- \* is matches everything
- ? is matches any single character
- \[seq\] is matches any character in seq
- \[!seq\] is matches any character not in seq
- reference https://docs.python.org/3/library/fnmatch.html
### run sample
```
@@ -46,18 +80,12 @@ w.card_path=os.path.dirname(__file__)+"\\wildcards\\**\\*.txt"
print(w.run("a{__b__|{c|}|{__d__|e|}|f|}g____ __my__"))
```
###
```
wildcards.py # modul file
wildcards/*.txt # wildcards file
wildcards/**/*.txt # wildcards file
```
### txt file (UTF8)
### txt file (supports .txt files in different encodings.)
from
```
# 주석
# 주석 comment
a,b
{b|c|__anotherfile__}
__anotherfile__
@@ -70,6 +98,12 @@ c
__anotherfile__
```
### reload card
call wildcards.card_load()
or
wildcards.run("{9$$-$$a|b|c}",True)
## for ComfyUI
@@ -102,6 +136,13 @@ __anotherfile__
![SimpleSamplerVAE](https://user-images.githubusercontent.com/20321215/229341040-72d422d5-7904-41c3-a0e7-ac256ea40d0e.png)
### VAELoaderText , LoraLoaderText , CheckpointLoaderSimpleText
- support file name Wildcard(?*)
![2023-04-13 23 07 29](https://user-images.githubusercontent.com/20321215/231785743-a77257b1-6932-4713-8b91-0614aeeb45e8.png)
![2023-04-13 23 07 49](https://user-images.githubusercontent.com/20321215/231785748-b33b5d69-de00-4265-8fdb-405e61ab8758.png)
### random_sampler_node.py
+3 -1
View File
@@ -2,6 +2,7 @@ from PIL import Image
from PIL.PngImagePlugin import PngInfo
import numpy as np
import json
import re
import time
@@ -44,6 +45,7 @@ class SaveImageSimple:
#print("outputdir : " + outputdir , Colors.CYAN)
#print("len(images) : " + str(len(images)) , Colors.CYAN)
filename_prefix=re.sub(r"[*]", "",filename_prefix)
filename_prefix+=time.strftime('_%Y%m%d_%H%M%S')
results = list()
cnt=1
@@ -58,7 +60,7 @@ class SaveImageSimple:
for x in extra_pnginfo:
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
if not os.path.exists(outputdir):
print("makedirs : " + outputdir , Colors.CYAN)
print("makedirs : " + outputdir )
os.makedirs(outputdir)
filename=filename_prefix+f"_{cnt:05}_.png"
filename=os.path.join(outputdir, filename)
+14 -12
View File
@@ -2,7 +2,7 @@ import comfy.samplers
import comfy.sd
import comfy.utils
import comfy_extras.clip_vision
#import comfy_extras.clip_vision
import model_management
import importlib
@@ -27,6 +27,8 @@ import numpy as np
#print(f"SimpleSampler __file__ {os.path.splitext(os.path.basename(__file__))[0]}")
import os
if __name__ == os.path.splitext(os.path.basename(__file__))[0] or __name__ =='__main__':
from ConsoleColor import print, console
from wildcards import wildcards
@@ -37,18 +39,18 @@ else:
#print(os.path.basename(__file__))
#----------------------------
wildcardsOn=True
# wildcards support check
wildcardsOn=False
try:
from wildcards import *
wildcardsOn=True
#wildcards.card_path=os.path.dirname(__file__)+"\\..\\wildcards\\**\\*.txt"
print(f"import wildcards succ", style="bold GREEN" )
except:
print(f"import wildcards fail", style="bold RED")
wildcardsOn=False
err_msg = traceback.format_exc()
print(err_msg)
#wildcardsOn=False
#try:
# wildcardsOn=True
# #wildcards.card_path=os.path.dirname(__file__)+"\\..\\wildcards\\**\\*.txt"
# print(f"import wildcards succ", style="bold GREEN" )
#except:
# print(f"import wildcards fail", style="bold RED")
# wildcardsOn=False
# err_msg = traceback.format_exc()
# print(err_msg)
def encode(clip, text):
+1 -1
View File
@@ -30,4 +30,4 @@ class TextWildcards:
print(f"[green]text : [/green]",text)
r=wildcards.run(text)
print(f"[green]result : [/green]",r)
return ([r, r], )
return (r, r)
+38
View File
@@ -0,0 +1,38 @@
import folder_paths
import comfy.sd
import os
from folder_paths import *
if __name__ == os.path.splitext(os.path.basename(__file__))[0] :
from ConsoleColor import print, console, ccolor
from mypath import *
else:
from .ConsoleColor import print, console, ccolor
from .mypath import *
class VAELoaderText:
@classmethod
def INPUT_TYPES(s):
return {"required": {
"vae_name": ("STRING", {
"multiline": False, #True if you want the field to look like the one on the ClipTextEncode node
"default": random.choice(folder_paths.get_filename_list("vae"))
}),
}}
RETURN_TYPES = ("VAE",)
FUNCTION = "load_vae"
CATEGORY = "loaders"
#TODO: scale factor?
def load_vae(self, vae_name):
print(f"[{ccolor}]vae_name : [/{ccolor}]", vae_name)
vae_path=getFullPath(vae_name,"vae")
try:
sd = comfy.utils.load_torch_file(vae_path)
vae = comfy.sd.VAE(sd=sd)
return (vae,)
except Exception as e:
console.print_exception()
return
+43 -17
View File
@@ -1,9 +1,24 @@
import sys
import os
if __name__ == os.path.splitext(os.path.basename(__file__))[0] :
print(f"__name__ : {__name__}")
print(f"__file__ : {__file__}")
print(f"os.path.basename(__file__) : {os.path.basename(__file__)}")
print(f"os.path.splitext(os.path.basename(__file__))[0] : {os.path.splitext(os.path.basename(__file__))[0]}")
#print(f"os.path.basename(__file__) : {os.path.basename('/ComfyUI_windows_portable/ComfyUI/custom_nodes/ComfyUI_node_Lilly/__init__.py')}")
#print(f"os.path.splitext(os.path.basename(__file__))[0] : {os.path.splitext(os.path.basename('/ComfyUI_windows_portable/ComfyUI/custom_nodes/ComfyUI_node_Lilly/__init__.py'))[0]}")
wd = os.getcwd()
print("working directory : ", wd)
if __name__ == os.path.splitext(os.path.basename(__file__))[0] or __name__ =='__main__':
from ConsoleColor import print, console
#md="custom_nodes.ComfyUI_node_Lilly."
else:
from .ConsoleColor import print, console
#md="custom_nodes.ComfyUI_node_Lilly."
md="custom_nodes.ComfyUI_node_Lilly."
#print(__file__)
#print(os.path.basename(__file__))
@@ -21,13 +36,14 @@ else:
#path, filename = os.path.split(absFilePath)
#print("Script file path is {}, filename is {}".format(path, filename))
wd = os.getcwd()
#print("working directory : ", wd)
nm=os.path.abspath(__name__)
#
#nm=os.path.abspath(__name__)
#nm=os.path.abspath(__name__)
#print("abspath __name__ : ", nm)
md=nm.replace(wd+"\\","")
#print("abspath __name__ : ", nm)
#
#md=nm.replace(wd+"\\","")
#print("import name", md)
"""
"""
@@ -35,32 +51,41 @@ md=nm.replace(wd+"\\","")
# print(f"{md!r} already in sys.modules")
#else:
# print(f"{md!r} not in sys.modules")
if not md.startswith("custom_nodes."):
import importlib
#from custom_nodes.ComfyUI_node_Lilly import eval(f"{name}")
#import importlib
#import ComfyUI_node_Lilly
#from custom_nodes.ComfyUI_node_Lilly import eval(f"{name}")
#print(dir(ComfyUI_node_Lilly))
#print(dir(ComfyUI_node_Lilly.ComfyUI_node_Lilly))
#print(__name__ == md)
#print(__name__ != md)
#print(__name__ == "ComfyUI_node_Lilly")
#print(__name__ != "ComfyUI_node_Lilly")
if __name__ == "ComfyUI_node_Lilly" :
NODE_CLASS_MAPPINGS = {
}
def add(name,clist=None):
#print(f"Load : {name}")
try:
pkg = importlib.import_module(f"{md}.{name}")
#pkg = importlib.import_module(f"{md}{name}")
#eval(f"{md}{name}")
exec(f"import {md}{name}")
if clist is None:
NODE_CLASS_MAPPINGS[name]=eval(f"pkg.{name}")
NODE_CLASS_MAPPINGS[name]=eval(f"{md}{name}.{name}")
elif type(clist) is str:
NODE_CLASS_MAPPINGS[clist]=eval(f"pkg.{clist}")
NODE_CLASS_MAPPINGS[clist]=eval(f"{md}{name}.{clist}")
elif type(clist) is list:
for c in clist:
NODE_CLASS_MAPPINGS[c]=eval(f"pkg.{c}")
NODE_CLASS_MAPPINGS[c]=eval(f"{md}{name}.{c}")
print(f"Load ok : {name}", style="bold green")
except Exception:
console.print_exception()
console.rule(f" init start ", style="bold green")
add("CheckpointLoaderRandom")
add("CheckpointLoaderSimpleText")
add("CLIPTextEncodeWildcards",["CLIPTextEncodeWildcards","CLIPTextEncodeWildcards2","CLIPTextEncodeWildcards3"])
@@ -68,9 +93,10 @@ if not md.startswith("custom_nodes."):
add("LoraLoaderTextRandom")
add("Random_Sampler")
add("VAELoaderDecode")
add("VAELoaderText")
add("SimpleSampler",["SimpleSampler","SimpleSamplerVAE"])
add("SaveImageSimple")
add("TextWildcards")
#add("test")
console.rule(" init end ", style="bold green")
+39 -8
View File
@@ -3,6 +3,7 @@ import json
import ast
import os, glob
import random
from folder_paths import *
if __name__ == os.path.splitext(os.path.basename(__file__))[0] :
from ConsoleColor import print, console
else:
@@ -25,27 +26,27 @@ print()
"""
py_name=os.path.basename(__file__)
print("os.path.basename(__file__) : ",py_name, style="bold CYAN")
#print("os.path.basename(__file__) : ",py_name, style="bold CYAN")
absFilePath = os.path.abspath(__file__)
print("os.path.abspath(__file__) : " , absFilePath , style="bold CYAN")
#print("os.path.abspath(__file__) : " , absFilePath , style="bold CYAN")
realFilePath = os.path.realpath(__file__)
print("os.path.abspath(__file__) : " + realFilePath , style="bold CYAN")
#print("os.path.abspath(__file__) : " + realFilePath , style="bold CYAN")
normpath=os.path.normpath(__file__)
print("os.path.normpath(__file__) : " + normpath , style="bold CYAN")
#print("os.path.normpath(__file__) : " + normpath , style="bold CYAN")
subfolder = os.path.dirname(normpath)
print("os.path.dirname(normpath) : " + subfolder , style="bold CYAN")
#print("os.path.dirname(normpath) : " + subfolder , style="bold CYAN")
filename = os.path.basename(normpath)
print("os.path.basename(normpath) : " + filename , style="bold CYAN")
#print("os.path.basename(normpath) : " + filename , style="bold CYAN")
mainFile = os.path.abspath(sys.modules['__main__'].__file__)
print("os.path.abspath(sys.modules\['__main__'].__file__) : " + mainFile ,style="bold CYAN")
#print("os.path.abspath(sys.modules\['__main__'].__file__) : " + mainFile ,style="bold CYAN")
mainfolder = os.path.dirname(mainFile)
print("os.path.dirname(mainFile) : " + mainfolder , style="bold CYAN")
#print("os.path.dirname(mainFile) : " + mainfolder , style="bold CYAN")
def check_name(kind,name,supported_extensions):
for ext in supported_extensions:
@@ -79,3 +80,33 @@ def filenameget(v_path):
name=os.path.basename(fullpath)
#r_path=[os.path.basename(fullpath) for fullpath in fullpaths]
return (name,fullpath)
# "test","vae",["pt","safetensors"]
def getFullPath(p,k,el=["safetensors","ckpt","pt"]):
if os.path.isabs(p):
path=p
else:
path=os.path.join(models_dir,k,"**",p)
#print(f"path : ", path)
t=False
for e in el:
if p.endswith('.'+e):
t=True
break
if t:
files=glob.glob(path, recursive=True)
else:
for e in el:
t=path+"."+e
#print(f"t : ", t)
files=glob.glob(t, recursive=True)
if len(files):
break
result=None
#print(f"files : ", files)
if len(files):
result=random.choice(files)
print(f"result : ", result)
else:
print("[red]No file in path[/red] : ", path)
return result
+68 -25
View File
@@ -1,7 +1,10 @@
import glob, sys
import os
import glob
import sys
import random
import re
import os
import fnmatch
if __name__ == os.path.splitext(os.path.basename(__file__))[0] or __name__ =='__main__':
from ConsoleColor import print, console, ccolor
else:
@@ -10,11 +13,25 @@ else:
#print(os.path.basename(__file__))
#print(os.getcwd())
import subprocess
import pkg_resources
required = {'chardet'}
installed = {pkg.key for pkg in pkg_resources.working_set}
missing = required - installed
if missing:
python = sys.executable
subprocess.check_call([python, '-m', 'pip', 'install', *missing], stdout=subprocess.DEVNULL)
import chardet
# ============================================================
class wildcards:
# 가져올 파일 목록
card_path=os.path.dirname(__file__)+"\\..\\..\\wildcards\\**\\*.txt"
card_path = os.path.join(os.path.dirname(__file__), "..", "..", "wildcards", "**", "*.txt")
#card_path=f"{os.getcwd()}\\wildcards\\**\\*.txt"
print(f"wildcards card_path : ", card_path , style="bold CYAN")
@@ -25,6 +42,7 @@ class wildcards:
recard = re.compile(r"(__)(.*?)(__)")
# 카드 목록
is_card_Load = False
cards = {}
seperator=", "
loop_max=50
@@ -100,12 +118,16 @@ class wildcards:
# 카드 중에서 가져오기
def card(match):
#print(f"card i : {match.group(2)}")
if match.group(2) in wildcards.cards :
r=random.choice(wildcards.cards[match.group(2)])
#print(f"card in : {match.group(2)}")
lst=fnmatch.filter(wildcards.cards, match.group(2))
if len(lst)>0:
#print(f"card lst : {lst}")
cd=random.choice(lst)
#print(f"card get : {cd}")
r=random.choice(wildcards.cards[cd])
else :
r= match.group(2)
#print(f"card r : {r}")
#print(f"card out : {r}")
return r
@@ -135,30 +157,44 @@ class wildcards:
#print(f"files : {files}")
for file in files:
basename = os.path.basename(file)
file_name = os.path.splitext(basename)[0]
basenameAll = os.path.basename(file)
basename = os.path.relpath(file, os.path.dirname(__file__)).replace("\\", "/").replace("../../wildcards/", "")
#print(f"basenameAll : {basenameAll}")
#print(f"basename : {basename}")
file_nameAll = os.path.splitext(basenameAll)[0]
file_name = "/"+os.path.splitext(basename)[0]
#print(f"file_nameAll : {file_nameAll}")
#print(f"file_name : {file_name}")
if not file_nameAll in cards:
cards[file_nameAll]=[]
if not file_name in cards:
cards[file_name]=[]
#print(f"file_name : {file_name}")
f = open(file, 'r', encoding='UTF8')
lines = f.readlines()
for line in lines:
line=line.strip()
# 주석 빈줄 제외
if line.startswith("#") or len(line)==0:
continue
cards[file_name]+=[line]
#print(f"line : {line}")
with open(file, "rb") as f:
raw_data = f.read()
encoding = chardet.detect(raw_data)["encoding"]
with open(file, "r", encoding=encoding) as f:
lines = f.readlines()
for line in lines:
line=line.strip()
# 주석 빈줄 제외
if line.startswith("#") or len(line)==0:
continue
cards[file_nameAll]+=[line]
cards[file_name]+=[line]
#print(f"line : {line}")
wildcards.cards=cards
print(f"[cyan]cards file count : [/cyan]", len(wildcards.cards))
#print(f"cards : {cards.keys()}")
wildcards.is_card_Load=True
# 실행기
def run(text):
if text is None or type(text) is not str:
def run(text,load=False):
if text is None or not isinstance(text, str):
print("[red]text is not str : [/red]",text)
return None
wildcards.card_load()
if not wildcards.is_card_Load or load:
wildcards.card_load()
#print(f"text : {text}")
result=wildcards.card_loop(text)
@@ -172,9 +208,16 @@ class wildcards:
#print(__name__)
#if __name__ == '__main__' :
# 테스트용
test="{3$$a1|{b2|c3|}|d4|{-$$|f|g}|{-2$$h||i}|{1-$$j|k|}}/{$$l|m|}/{0$$n|}/{9$$-$$a|b|c}/{9$$ {and|or} $$a|b|c}"
print("[green]wildcards test : [/green]",wildcards.run(test),style="reset")
#test="{3$$a1|{b2|c3|}|d4|{-$$|f|g}|{-2$$h||i}|{1-$$j|k|}}/{$$l|m|}/{0$$n|}/{9$$-$$a|b|c}/{9$$ {and|or} $$a|b|c}"
#print("[green]wildcards test : [/green]",wildcards.run(test),style="reset")
#print("wildcards test : "+wildcards.run("{9$$a|b}"))
#print("[green]wildcards test : [/green]",wildcards.run("__my__"))
print("wildcards test : "+wildcards.run("{9$$-$$a|b|c}"))
print("wildcards test : "+wildcards.run("{9$$ {and|or} $$a|b|c}"))
#print("wildcards test : "+wildcards.run("{9$$-$$a|b|c}"))
#print("wildcards test : "+wildcards.run("{9$$ {and|or} $$a|b|c}"))
#print("wildcards test : "+wildcards.run("{{slender,|} {nature,|} {curvy,|} {thin,|} {narrow,|} {slim,|} {mini,|} {little,|}| {|very }{-$$ $$thin|slender|narrow|slim|little|skinny|mini} body, }"))
print("wildcards test : "+wildcards.run("__aest__"))
print("wildcards test : "+wildcards.run("__*test__"))
print("wildcards test : "+wildcards.run("__?est__"))
print("wildcards test : "+wildcards.run("__test__"))
print("wildcards test : "+wildcards.run("__/test__"))
print("wildcards test : "+wildcards.run("__/0/test__"))