File size: 13,472 Bytes
f646433
40457bb
 
 
55575a2
b00fb13
25bf878
55575a2
239ed62
 
f16fef6
 
 
 
 
239ed62
f16fef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239ed62
f16fef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239ed62
 
f16fef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239ed62
 
f16fef6
239ed62
 
 
 
f16fef6
239ed62
 
 
f16fef6
239ed62
 
f16fef6
 
 
239ed62
 
f16fef6
 
239ed62
f16fef6
239ed62
 
f16fef6
239ed62
 
f16fef6
 
 
239ed62
f16fef6
239ed62
 
 
 
 
 
 
 
f16fef6
239ed62
f16fef6
239ed62
 
f16fef6
 
 
239ed62
f16fef6
 
 
 
ecfb95b
40457bb
3a7ee34
f646433
 
e2138e2
40457bb
 
b8060d1
b00fb13
fcc4c01
bfbec44
b16a39a
b00fb13
77414f0
40457bb
aa5d3e8
d383ce3
 
 
 
40457bb
 
 
f646433
 
40457bb
 
ea8e426
 
40457bb
d80f274
 
 
f5cf5e0
d10d76a
40457bb
 
d80f274
40457bb
 
 
 
b584574
239ed62
5d2d710
239ed62
 
 
f16fef6
 
239ed62
ecfb95b
f16fef6
 
 
 
0fb8fcf
ecfb95b
 
edda1c8
f16fef6
 
 
 
625830f
 
 
 
 
77414f0
fc967fc
 
f646433
 
6a5424e
 
f646433
 
40457bb
77414f0
 
 
 
 
40457bb
239ed62
f646433
675f93f
5998d1e
40457bb
f646433
 
675f93f
f646433
aa5d3e8
675f93f
f646433
 
8df6565
34d8968
675f93f
40457bb
675f93f
f646433
675f93f
40457bb
 
675f93f
7218a79
40457bb
f646433
40457bb
675f93f
40457bb
 
 
 
 
675f93f
40457bb
 
675f93f
40457bb
 
 
f5cf5e0
40457bb
 
675f93f
40457bb
 
 
d10d76a
40457bb
 
 
 
 
8b2605f
40457bb
20fb550
40457bb
 
675f93f
40457bb
22f8263
f646433
22f8263
f646433
 
6a5424e
 
 
 
b92ccd8
6a5424e
239ed62
40457bb
 
 
 
 
 
f646433
239ed62
ea8e426
f646433
 
 
40457bb
f646433
 
 
 
 
40457bb
f646433
 
55575a2
 
f646433
be0aa53
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
import random
import gradio as gr
import numpy as np
import spaces
import torch
from diffusers import AutoPipelineForText2Image, AutoencoderKL, EulerDiscreteScheduler
from compel import Compel, ReturnedEmbeddingsType

import re

# =====================================
# Prompt weights
# =====================================
import torch
import re
def parse_prompt_attention(text):
    re_attention = re.compile(r"""
      \\\(|
      \\\)|
      \\\[|
      \\]|
      \\\\|
      \\|
      \(|
      \[|
      :([+-]?[.\d]+)\)|
      \)|
      ]|
      [^\\()\[\]:]+|
      :
      """, re.X)

    res = []
    round_brackets = []
    square_brackets = []

    round_bracket_multiplier = 1.1
    square_bracket_multiplier = 1 / 1.1

    def multiply_range(start_position, multiplier):
        for p in range(start_position, len(res)):
            res[p][1] *= multiplier

    for m in re_attention.finditer(text):
        text = m.group(0)
        weight = m.group(1)

        if text.startswith('\\'):
            res.append([text[1:], 1.0])
        elif text == '(':
            round_brackets.append(len(res))
        elif text == '[':
            square_brackets.append(len(res))
        elif weight is not None and len(round_brackets) > 0:
            multiply_range(round_brackets.pop(), float(weight))
        elif text == ')' and len(round_brackets) > 0:
            multiply_range(round_brackets.pop(), round_bracket_multiplier)
        elif text == ']' and len(square_brackets) > 0:
            multiply_range(square_brackets.pop(), square_bracket_multiplier)
        else:
            parts = re.split(re.compile(r"\s*\bBREAK\b\s*", re.S), text)
            for i, part in enumerate(parts):
                if i > 0:
                    res.append(["BREAK", -1])
                res.append([part, 1.0])

    for pos in round_brackets:
        multiply_range(pos, round_bracket_multiplier)

    for pos in square_brackets:
        multiply_range(pos, square_bracket_multiplier)

    if len(res) == 0:
        res = [["", 1.0]]

    # merge runs of identical weights
    i = 0
    while i + 1 < len(res):
        if res[i][1] == res[i + 1][1]:
            res[i][0] += res[i + 1][0]
            res.pop(i + 1)
        else:
            i += 1

    return res

def prompt_attention_to_invoke_prompt(attention):
    tokens = []
    for text, weight in attention:
        # Round weight to 2 decimal places
        weight = round(weight, 2)
        if weight == 1.0:
            tokens.append(text)
        elif weight < 1.0:
            if weight < 0.8:
                tokens.append(f"({text}){weight}")
            else:
                tokens.append(f"({text})-" + "-" * int((1.0 - weight) * 10))
        else:
            if weight < 1.3:
                tokens.append(f"({text})" + "+" * int((weight - 1.0) * 10))
            else:
                tokens.append(f"({text}){weight}")
    return "".join(tokens)

def concat_tensor(t):
    t_list = torch.split(t, 1, dim=0)
    t = torch.cat(t_list, dim=1)
    return t

def merge_embeds(prompt_chanks, compel):
    num_chanks = len(prompt_chanks)
    if num_chanks != 0:
        power_prompt = 1/(num_chanks*(num_chanks+1)//2)
        prompt_embs = compel(prompt_chanks)
        t_list = list(torch.split(prompt_embs, 1, dim=0))
        for i in range(num_chanks):
            t_list[-(i+1)] = t_list[-(i+1)] * ((i+1)*power_prompt)
        prompt_emb = torch.stack(t_list, dim=0).sum(dim=0)
    else:
        prompt_emb = compel('')
    return prompt_emb

def detokenize(chunk, actual_prompt):
    chunk[-1] = chunk[-1].replace('</w>', '')
    chanked_prompt = ''.join(chunk).strip()
    while '</w>' in chanked_prompt:
        if actual_prompt[chanked_prompt.find('</w>')] == ' ':
            chanked_prompt = chanked_prompt.replace('</w>', ' ', 1)
        else:
            chanked_prompt = chanked_prompt.replace('</w>', '', 1)
    actual_prompt = actual_prompt.replace(chanked_prompt,'')
    return chanked_prompt.strip(), actual_prompt.strip()

def tokenize_line(line, tokenizer): # split into chunks
    actual_prompt = line.lower().strip()
    actual_tokens = tokenizer.tokenize(actual_prompt)
    max_tokens = tokenizer.model_max_length - 2
    comma_token = tokenizer.tokenize(',')[0]

    chunks = []
    chunk = []
    for item in actual_tokens:
        chunk.append(item)
        if len(chunk) == max_tokens:
            if chunk[-1] != comma_token:
                for i in range(max_tokens-1, -1, -1):
                    if chunk[i] == comma_token:
                        actual_chunk, actual_prompt = detokenize(chunk[:i+1], actual_prompt)
                        chunks.append(actual_chunk)
                        chunk = chunk[i+1:]
                        break
                else:
                    actual_chunk, actual_prompt = detokenize(chunk, actual_prompt)
                    chunks.append(actual_chunk)
                    chunk = []
            else:
                actual_chunk, actual_prompt = detokenize(chunk, actual_prompt)
                chunks.append(actual_chunk)
                chunk = []
    if chunk:
        actual_chunk, _ = detokenize(chunk, actual_prompt)
        chunks.append(actual_chunk)

    return chunks

def get_embed_new(prompt, pipeline, compel, only_convert_string=False, compel_process_sd=False):

    if compel_process_sd:
        return merge_embeds(tokenize_line(prompt, pipeline.tokenizer), compel)
    else:
        # fix bug weights conversion excessive emphasis
        prompt = prompt.replace("((", "(").replace("))", ")").replace("\\", "\\\\\\")

    # Convert to Compel
    attention = parse_prompt_attention(prompt)
    global_attention_chanks = []

    for att in attention:
        for chank in att[0].split(','):
            temp_prompt_chanks = tokenize_line(chank, pipeline.tokenizer)
            for small_chank in temp_prompt_chanks:
                temp_dict = {
                    "weight": round(att[1], 2),
                    "lenght": len(pipeline.tokenizer.tokenize(f'{small_chank},')),
                    "prompt": f'{small_chank},'
                }
                global_attention_chanks.append(temp_dict)

    max_tokens = pipeline.tokenizer.model_max_length - 2
    global_prompt_chanks = []
    current_list = []
    current_length = 0
    for item in global_attention_chanks:
        if current_length + item['lenght'] > max_tokens:
            global_prompt_chanks.append(current_list)
            current_list = [[item['prompt'], item['weight']]]
            current_length = item['lenght']
        else:
            if not current_list:
                current_list.append([item['prompt'], item['weight']])
            else:
                if item['weight'] != current_list[-1][1]:
                    current_list.append([item['prompt'], item['weight']])
                else:
                    current_list[-1][0] += f" {item['prompt']}"
            current_length += item['lenght']
    if current_list:
        global_prompt_chanks.append(current_list)

    if only_convert_string:
        return ' '.join([prompt_attention_to_invoke_prompt(i) for i in global_prompt_chanks])

    return merge_embeds([prompt_attention_to_invoke_prompt(i) for i in global_prompt_chanks], compel)

def add_comma_after_pattern_ti(text):
    pattern = re.compile(r'\b\w+_\d+\b')
    modified_text = pattern.sub(lambda x: x.group() + ',', text)
    return modified_text
    
if not torch.cuda.is_available():
    DESCRIPTION += "\n<p>你现在运行在CPU上 但是此项目只支持GPU.</p>"

MAX_SEED = np.iinfo(np.int32).max
MAX_IMAGE_SIZE = 4096

if torch.cuda.is_available():
    vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
    pipe = AutoPipelineForText2Image.from_pretrained(
        "Menyu/noobaiXLNAIXL_vPred065SVersion",
        vae=vae,
        torch_dtype=torch.float16,
        use_safetensors=True,
        add_watermarker=False
    )
    pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
    pipe.scheduler.register_to_config(
        prediction_type="v_prediction",
        rescale_betas_zero_snr=True,
    )
    pipe.to("cuda")

def randomize_seed_fn(seed: int, randomize_seed: bool) -> int:
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    return seed

@spaces.GPU
def infer(
    prompt: str,
    negative_prompt: str = "lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, watermark, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]",
    use_negative_prompt: bool = True,
    seed: int = 7,
    width: int = 832,
    height: int = 1216,
    guidance_scale: float = 3,
    num_inference_steps: int = 30,
    randomize_seed: bool = True,
    use_resolution_binning: bool = True,
    progress=gr.Progress(track_tqdm=True),
):
    seed = int(randomize_seed_fn(seed, randomize_seed))
    generator = torch.Generator().manual_seed(seed)
    # 初始化 Compel 实例
    compel = Compel(
        tokenizer=[pipe.tokenizer, pipe.tokenizer_2],
        text_encoder=[pipe.text_encoder, pipe.text_encoder_2],
        returned_embeddings_type=ReturnedEmbeddingsType.PENULTIMATE_HIDDEN_STATES_NON_NORMALIZED,
        requires_pooled=[False, True],
        truncate_long_prompts=False
    )
    # 在 infer 函数中调用 get_embed_new
    if not use_negative_prompt:
        negative_prompt = ""
    prompt = get_embed_new(prompt, pipe, compel, only_convert_string=True)
    negative_prompt = get_embed_new(negative_prompt, pipe, compel, only_convert_string=True)
    conditioning, pooled = compel([prompt, negative_prompt]) # 必须同时处理来保证长度相等
    
    # 在调用 pipe 时,使用新的参数名称(确保参数名称正确)
    image = pipe(
        prompt_embeds=conditioning[0:1],
        pooled_prompt_embeds=pooled[0:1],
        negative_prompt_embeds=conditioning[1:2],
        negative_pooled_prompt_embeds=pooled[1:2],
        width=width,
        height=height,
        guidance_scale=guidance_scale,
        num_inference_steps=num_inference_steps,
        generator=generator,
        use_resolution_binning=use_resolution_binning,
    ).images[0]
    return image, seed

examples = [
    "nahida (genshin impact)",
    "klee (genshin impact)",
]

css = '''
.gradio-container{max-width: 560px !important}
h1{text-align:center}
footer {
    visibility: hidden
}
'''

with gr.Blocks(css=css) as demo:
    gr.Markdown("""# 梦羽的模型生成器
        ### 快速生成NoobAIXL V预测0.65s版本的模型图片""")
    with gr.Group():
        with gr.Row():
            prompt = gr.Text(
                label="关键词",
                show_label=False,
                max_lines=5,
                placeholder="输入你要的图片关键词",
                container=False,
            )
            run_button = gr.Button("生成", scale=0, variant="primary")
        result = gr.Image(label="Result", show_label=False, format="png")
    with gr.Accordion("高级选项", open=False):
        with gr.Row():
            use_negative_prompt = gr.Checkbox(label="使用反向词条", value=True)
            negative_prompt = gr.Text(
                label="反向词条",
                max_lines=5,
                lines=4,
                placeholder="输入你要排除的图片关键词",
                value="lowres, {bad}, error, fewer, extra, missing, worst quality, jpeg artifacts, bad quality, watermark, unfinished, displeasing, chromatic aberration, signature, extra digits, artistic error, username, scan, [abstract]",
                visible=True,
            )
        seed = gr.Slider(
            label="种子",
            minimum=0,
            maximum=MAX_SEED,
            step=1,
            value=0,
        )
        randomize_seed = gr.Checkbox(label="随机种子", value=True)
        with gr.Row(visible=True):
            width = gr.Slider(
                label="宽度",
                minimum=512,
                maximum=MAX_IMAGE_SIZE,
                step=64,
                value=832,
            )
            height = gr.Slider(
                label="高度",
                minimum=512,
                maximum=MAX_IMAGE_SIZE,
                step=64,
                value=1216,
            )
        with gr.Row():
            guidance_scale = gr.Slider(
                label="Guidance Scale",
                minimum=0.1,
                maximum=10,
                step=0.1,
                value=5.0,
            )
            num_inference_steps = gr.Slider(
                label="生成步数",
                minimum=1,
                maximum=50,
                step=1,
                value=28,
            )

    gr.Examples(
        examples=examples,
        inputs=prompt,
        outputs=[result, seed],
        fn=infer
    )

    use_negative_prompt.change(
        fn=lambda x: gr.update(visible=x),
        inputs=use_negative_prompt,
        outputs=negative_prompt,
    )

    gr.on(
        triggers=[prompt.submit, run_button.click],
        fn=infer,
        inputs=[
            prompt,
            negative_prompt,
            use_negative_prompt,
            seed,
            width,
            height,
            guidance_scale,
            num_inference_steps,
            randomize_seed,
        ],
        outputs=[result, seed],
    )

if __name__ == "__main__":
    demo.launch()