File size: 5,921 Bytes
85226b0
 
 
 
 
 
264c7c2
85226b0
 
264c7c2
85226b0
 
 
8650fd3
 
 
85226b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8650fd3
264c7c2
85226b0
 
9618844
 
264c7c2
85226b0
 
 
 
 
 
 
 
 
 
 
9618844
 
 
 
 
 
 
85226b0
 
 
 
 
8650fd3
264c7c2
85226b0
 
 
 
 
 
9618844
 
 
85226b0
264c7c2
 
 
 
 
 
 
 
 
 
 
85226b0
9618844
85226b0
 
8650fd3
 
85226b0
8650fd3
85226b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8650fd3
85226b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8650fd3
85226b0
 
 
8650fd3
85226b0
 
8650fd3
85226b0
 
 
8650fd3
85226b0
 
 
264c7c2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import gzip
import hashlib
import os
import requests
import json
import base64

from io import BytesIO
from PIL import Image
from tag_autocomplete import PromptSuggester

# Language
LANG_EN = {
    "character1": "Character list EN",
    "character2": "Character list EN",
    "character3": "Character list CN",
    "action": "Action list",
    "original_character": "Original Character",    
}

LANG = LANG_EN

# JavaScript
JAVA_SCRIPT = """
function refresh() {
    const url = new URL(window.location);

    if (url.searchParams.get('__theme') !== 'dark') {
        url.searchParams.set('__theme', 'dark');
        window.location.href = url.href;
    }
}
"""

# CSS
CSS_SCRIPT = """
#custom_prompt_text textarea {color: darkorange}
#positive_prompt_text textarea {color: greenyellow}
#negative_prompt_text textarea {color: red}
#ai_prompt_text textarea {color: hotpink}
#prompt_ban_text textarea {color: Khaki}
"""

TITLE = "WAI Character Select Preview"
CAT = "WAI_Character_Select"
ENGLISH_CHARACTER_NAME = True

current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
json_folder = os.path.join(parent_dir, 'json')

character_list = ''
character_dict = {}
wai_image_dict = {}
character_list_cn = ''
TAG_AUTOCOMPLETE = None

wai_illustrious_character_select_files = [
    {'name': 'wai_character', 'file_path': os.path.join(json_folder, 'wai_characters.csv'), 'url':'https://raw.githubusercontent.com/mirabarukaso/character_select_stand_alone_app/refs/heads/main/json/wai_characters.csv'},
    {'name': 'wai_image', 'file_path': os.path.join(json_folder, 'wai_character_thumbs.json'), 'url': 'https://huggingface.co/datasets/flagrantia/character_select_stand_alone_app/resolve/main/wai_character_thumbs.json'},
    {'name': 'e621_sfw', 'file_path': os.path.join(json_folder, 'e621_sfw.csv'), 'url': 'https://raw.githubusercontent.com/DominikDoom/a1111-sd-webui-tagcomplete/refs/heads/main/tags/e621_sfw.csv'},
]
def get_md5_hash(input_str):
    md5_hash = hashlib.md5()
    md5_hash.update(input_str.encode('utf-8'))
    return md5_hash.hexdigest()

def base64_to_image(base64_data):
    compressed_data = base64.b64decode(base64_data)
    webp_data = gzip.decompress(compressed_data)
    image = Image.open(BytesIO(webp_data))  
    return image

def download_file(url, file_path):   
    response = requests.get(url)
    response.raise_for_status() 
    print(f'[{CAT}]:Downloading... {url}')
    with open(file_path, 'wb') as file:
        file.write(response.content)        
            
def load_jsons():
    global character_list
    global character_dict
    global wai_image_dict
    global character_list_cn
    global TAG_AUTOCOMPLETE
    
    # download file
    for item in wai_illustrious_character_select_files:
        name = item['name']
        file_path = item['file_path']
        url = item['url']        
        
        if not os.path.exists(file_path):
            download_file(url, file_path)
            
        if 'e621_sfw' == name:
            TAG_AUTOCOMPLETE = PromptSuggester(file_path)
        else:
            with open(file_path, 'r', encoding='utf-8') as file:        
                if 'wai_character' == name:
                    lines = file.readlines()
                    for line in lines:
                        key, value = line.split(',')
                        character_dict[key.strip()]=value.strip()
                elif 'wai_image' == name:
                    wai_image_dict = json.load(file)                
                                        
    # Create list        
    character_list = list(character_dict.values())   
    character_list.insert(0, "none")
    character_list_cn = list(character_dict.keys())   
    character_list_cn.insert(0, "none")

def illustrious_character_select_ex(character = 'random', optimise_tags = True, random_action_seed = 1, use_cn=False):
    chara = ''
    rnd_character = ''
    
    if 'none' == character:
        return '', '', None
    
    if 'random' == character:
        index = random_action_seed % len(character_list)
        rnd_character = character_list[index]
        if 'random' == rnd_character:
            rnd_character = character_list[index+2]
        elif 'none' == rnd_character:
            rnd_character = character_list[index+1]
    else:
        rnd_character = character
    if not use_cn:
        chara = rnd_character
    else:
        chara = character_dict[rnd_character]
        
    md5_chara = get_md5_hash(chara.replace('(','\\(').replace(')','\\)'))                
    thumb_image = Image.new('RGB', (128, 128), (128, 128, 128))
    if wai_image_dict.keys().__contains__(md5_chara):
        thumb_image = base64_to_image(wai_image_dict.get(md5_chara))
    
    opt_chara = chara
    if optimise_tags:
        opt_chara = opt_chara.replace('(', '\\(').replace(')', '\\)')  
        #print(f'{CAT}:Optimise Tags:[{chara}]->[{opt_chara}]')
    
    if not opt_chara.endswith(','):
        opt_chara = f'{opt_chara},'   
            
    return rnd_character, opt_chara, thumb_image

def refresh_character_thumb_image(character1, character2, character3):
    thumb_image = []
    if 'none' != character1 and 'random' != character1:
        _, _, thumb_image1 = illustrious_character_select_ex(character = character1)        
        thumb_image.append(thumb_image1)
    
    if 'none' != character2 and 'random' != character2:
        _, _, thumb_image2 = illustrious_character_select_ex(character = character2)        
        thumb_image.append(thumb_image2)
    if 'none' != character3 and 'random' != character3:
        _, _, thumb_image3 = illustrious_character_select_ex(character = character3, use_cn=True)        
        thumb_image.append(thumb_image3)
    return thumb_image

def init():        
    load_jsons()    
    print(f'[{CAT}]:Starting...')
    
    return character_list, character_list_cn, LANG, TAG_AUTOCOMPLETE