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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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
from pathlib import Path
import time

import torch
from transformers import AutoTokenizer, AutoModelForCausalLM

import gradio as gr

MODEL_NAME = "p1atdev/dart-test-1"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, trust_remote_code=True)


BOS = "<|bos|>"
EOS = "<|eos|>"
RATING_BOS = "<rating>"
RATING_EOS = "</rating>"
COPYRIGHT_BOS = "<copyright>"
COPYRIGHT_EOS = "</copyright>"
CHARACTER_BOS = "<character>"
CHARACTER_EOS = "</character>"
GENERAL_BOS = "<general>"
GENERAL_EOS = "</general>"

RATING_BOS_ID = tokenizer.convert_tokens_to_ids(RATING_BOS)
RATING_EOS_ID = tokenizer.convert_tokens_to_ids(RATING_EOS)
COPYRIGHT_BOS_ID = tokenizer.convert_tokens_to_ids(COPYRIGHT_BOS)
COPYRIGHT_EOS_ID = tokenizer.convert_tokens_to_ids(COPYRIGHT_EOS)
CHARACTER_BOS_ID = tokenizer.convert_tokens_to_ids(CHARACTER_BOS)
CHARACTER_EOS_ID = tokenizer.convert_tokens_to_ids(CHARACTER_EOS)
GENERAL_BOS_ID = tokenizer.convert_tokens_to_ids(GENERAL_BOS)
GENERAL_EOS_ID = tokenizer.convert_tokens_to_ids(GENERAL_EOS)

assert isinstance(RATING_BOS_ID, int)
assert isinstance(RATING_EOS_ID, int)
assert isinstance(COPYRIGHT_BOS_ID, int)
assert isinstance(COPYRIGHT_EOS_ID, int)
assert isinstance(CHARACTER_BOS_ID, int)
assert isinstance(CHARACTER_EOS_ID, int)
assert isinstance(GENERAL_BOS_ID, int)
assert isinstance(GENERAL_EOS_ID, int)

SPECIAL_TAGS = [
    BOS,
    EOS,
    RATING_BOS,
    RATING_EOS,
    COPYRIGHT_BOS,
    COPYRIGHT_EOS,
    CHARACTER_BOS,
    CHARACTER_EOS,
    GENERAL_BOS,
    GENERAL_EOS,
]

SPECIAL_TAG_IDS = tokenizer.convert_tokens_to_ids(SPECIAL_TAGS)
assert isinstance(SPECIAL_TAG_IDS, list)


RATING_TAGS = {
    "sfw": "rating:sfw",
    "nsfw": "rating:nsfw",
    "general": "rating:general",
    "sensitive": "rating:sensitive",
    "questionable": "rating:questionable",
    "explicit": "rating:explicit",
}
RATING_TAG_IDS = {k: tokenizer.convert_tokens_to_ids(v) for k, v in RATING_TAGS.items()}


def load_tags(path: str | Path):
    if isinstance(path, str):
        path = Path(path)

    with open(path, "r", encoding="utf-8") as file:
        lines = [line.strip() for line in file.readlines() if line.strip() != ""]

    return lines


COPYRIGHT_TAGS_LIST: list[str] = load_tags("./tags/copyright.txt")
CHARACTER_TAGS_LIST: list[str] = load_tags("./tags/character.txt")
PEOPLE_TAGS_LIST: list[str] = load_tags("./tags/people.txt")

PEOPLE_TAG_IDS_LIST = tokenizer.convert_tokens_to_ids(PEOPLE_TAGS_LIST)

assert isinstance(PEOPLE_TAG_IDS_LIST, list)


def compose_prompt(
    rating: str = "rating:sfw, rating:general",
    copyright: str = "",
    character: str = "",
    general: str = "",
):
    return "".join(
        [
            BOS,
            RATING_BOS,
            rating,
            RATING_EOS,
            COPYRIGHT_BOS,
            copyright,
            COPYRIGHT_EOS,
            CHARACTER_BOS,
            character,
            CHARACTER_EOS,
            GENERAL_BOS,
            general,
        ]
    )


@torch.no_grad()
def generate(
    input_text,
    max_new_tokens=128,
    do_sample: bool = True,
    temperature: float = 1.0,
    top_p: float = 1,
    top_k: int = 20,
    num_beams: int = 1,
    bad_words_ids: list[int] | None = None,
) -> list[int]:
    inputs = tokenizer(
        input_text,
        return_tensors="pt",
    ).input_ids

    generated = model.generate(
        inputs,
        max_new_tokens=max_new_tokens,
        do_sample=do_sample,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        num_beams=num_beams,
        bad_words_ids=(
            [[token] for token in bad_words_ids] if bad_words_ids is not None else None
        ),
        no_repeat_ngram_size=1,
    )[0]

    return generated.tolist()


def decode_normal(token_ids: list[int], skip_special_tokens: bool = True):
    return tokenizer.decode(token_ids, skip_special_tokens=skip_special_tokens)


def decode_general_only(token_ids: list[int]):
    token_ids = token_ids[token_ids.index(GENERAL_BOS_ID) :]
    return tokenizer.decode(token_ids, skip_special_tokens=True)


def split_people_tokens_part(token_ids: list[int]):
    people_tokens = []
    other_tokens = []

    for token in token_ids:
        if token in PEOPLE_TAG_IDS_LIST:
            people_tokens.append(token)
        else:
            other_tokens.append(token)

    return people_tokens, other_tokens


def decode_animagine(token_ids: list[int]):
    def get_part(eos_token_id: int, remains_part: list[int]):
        part = []
        for i, token_id in enumerate(remains_part):
            if token_id == eos_token_id:
                return part, remains_part[i:]

            part.append(token_id)

        raise Exception("The provided EOS token was not found in the token_ids.")

    # get each part
    rating_part, remains = get_part(RATING_EOS_ID, token_ids)
    copyright_part, remains = get_part(COPYRIGHT_EOS_ID, remains)
    character_part, remains = get_part(CHARACTER_EOS_ID, remains)
    general_part, _ = get_part(GENERAL_EOS_ID, remains)

    # separete people tags (1girl, 1boy, no humans...)
    people_part, other_general_part = split_people_tokens_part(general_part)

    # remove "rating:sfw"
    rating_part = [token for token in rating_part if token != RATING_TAG_IDS["sfw"]]

    # AnimagineXL v3 style order
    rearranged_tokens = (
        people_part + character_part + copyright_part + other_general_part + rating_part
    )
    rearranged_tokens = [
        token for token in rearranged_tokens if token not in SPECIAL_TAG_IDS
    ]

    decoded = tokenizer.decode(rearranged_tokens, skip_special_tokens=True)

    # fix "nsfw" tag
    decoded = decoded.replace("rating:nsfw", "nsfw")

    return decoded


def prepare_rating_tags(rating: str):
    tag = RATING_TAGS[rating]
    if tag in [RATING_TAGS["general"], RATING_TAGS["sensitive"]]:
        parent = RATING_TAGS["sfw"]
    else:
        parent = RATING_TAGS["nsfw"]

    return f"{parent}, {tag}"


def handle_inputs(
    rating_tags: str,
    copyright_tags_list: list[str],
    character_tags_list: list[str],
    general_tags: str,
    ban_tags: str,
    max_new_tokens: int = 128,
    temperature: float = 1.0,
    top_p: float = 1.0,
    top_k: int = 20,
    num_beams: int = 1,
):
    """
    Returns:
        [
            output_tags_natural,
            output_tags_general_only,
            output_tags_animagine,
            input_prompt_raw,
            output_tags_raw,
            elapsed_time,
        ]
    """

    start_time = time.time()

    copyright_tags = ", ".join(copyright_tags_list)
    character_tags = ", ".join(character_tags_list)

    prompt = compose_prompt(
        rating=prepare_rating_tags(rating_tags),
        copyright=copyright_tags,
        character=character_tags,
        general=general_tags,
    )

    bad_words_ids = tokenizer.encode_plus(ban_tags).input_ids

    generated_ids = generate(
        prompt,
        max_new_tokens=max_new_tokens,
        do_sample=True,
        temperature=temperature,
        top_p=top_p,
        top_k=top_k,
        num_beams=num_beams,
        bad_words_ids=bad_words_ids if len(bad_words_ids) > 0 else None,
    )

    decoded_normal = decode_normal(generated_ids, skip_special_tokens=True)
    decoded_general_only = decode_general_only(generated_ids)
    decoded_animagine = decode_animagine(generated_ids)
    decoded_raw = decode_normal(generated_ids, skip_special_tokens=False)

    end_time = time.time()
    elapsed_time = f"Elapsed: {(end_time - start_time) * 1000:.2f} ms"

    return [
        decoded_normal,
        decoded_general_only,
        decoded_animagine,
        prompt,
        decoded_raw,
        elapsed_time,
    ]


def demo():
    with gr.Blocks() as ui:
        with gr.Row():
            with gr.Column():
                with gr.Group():
                    rating_dropdown = gr.Dropdown(
                        label="Rating",
                        choices=[
                            "general",
                            "sensitive",
                            "questionable",
                            "explicit",
                        ],
                        value="general",
                    )

                    with gr.Group():
                        copyright_tags_mode_dropdown = gr.Dropdown(
                            label="Copyright tags mode",
                            choices=[
                                "None",
                                "Original",
                                # "Auto", # TODO: implement these modes
                                # "Random",
                                "Custom",
                            ],
                            value="None",
                            interactive=True,
                        )
                        copyright_tags_dropdown = gr.Dropdown(
                            label="Copyright tags",
                            choices=COPYRIGHT_TAGS_LIST,
                            value=[],
                            multiselect=True,
                            visible=False,
                        )

                        def on_change_copyright_tags_dropdouwn(mode: str):
                            kwargs: dict = {"visible": mode == "Custom"}
                            if mode == "Original":
                                kwargs["value"] = ["original"]
                            elif mode == "None":
                                kwargs["value"] = []

                            return gr.update(**kwargs)

                    with gr.Group():
                        character_tags_mode_dropdown = gr.Dropdown(
                            label="Character tags mode",
                            choices=[
                                "None",
                                # "Auto", # TODO: implement these modes
                                # "Random",
                                "Custom",
                            ],
                            value="None",
                            interactive=True,
                        )
                        character_tags_dropdown = gr.Dropdown(
                            label="Character tags",
                            choices=CHARACTER_TAGS_LIST,
                            value=[],
                            multiselect=True,
                            visible=False,
                        )

                        def on_change_character_tags_dropdouwn(mode: str):
                            kwargs: dict = {"visible": mode == "Custom"}

                            return gr.update(**kwargs)

                with gr.Group():
                    general_tags_textbox = gr.Textbox(
                        label="General tags",
                        placeholder="1girl, ...",
                        lines=4,
                    )

                    ban_tags_textbox = gr.Textbox(
                        label="Ban tags",
                        placeholder="",
                        value="",
                        lines=2,
                    )

                with gr.Accordion(label="Generation config", open=False):
                    with gr.Group():
                        max_new_tokens_slider = gr.Slider(
                            label="Max new tokens",
                            maximum=256,
                            minimum=1,
                            step=1,
                            value=128,
                        )
                        temperature_slider = gr.Slider(
                            label="Temperature (larger is more random)",
                            maximum=1.0,
                            minimum=0.0,
                            step=0.1,
                            value=1.0,
                        )
                        top_p_slider = gr.Slider(
                            label="Top p (larger is more random)",
                            maximum=1.0,
                            minimum=0.0,
                            step=0.1,
                            value=1.0,
                        )
                        top_k_slider = gr.Slider(
                            label="Top k (larger is more random)",
                            maximum=500,
                            minimum=1,
                            step=1,
                            value=100,
                        )
                        num_beams_slider = gr.Slider(
                            label="Number of beams (smaller is more random)",
                            maximum=10,
                            minimum=1,
                            step=1,
                            value=1,
                        )

                generate_btn = gr.Button("Generate", variant="primary")

            with gr.Column():
                output_tags_natural = gr.Textbox(
                    label="Generation result",
                    # placeholder="tags will be here",
                    interactive=False,
                )

                output_tags_general_only = gr.Textbox(
                    label="General tags only",
                    interactive=False,
                )

                output_tags_animagine = gr.Textbox(
                    label="Output tags (AnimagineXL v3 style order)",
                    # placeholder="tags will be here in Animagine v3 style order",
                    interactive=False,
                )

                elapsed_time_md = gr.Markdown(value="Waiting to generate...")

                with gr.Accordion(label="Metadata", open=False):
                    input_prompt_raw = gr.Textbox(
                        label="Input prompt (raw)",
                        interactive=False,
                        lines=4,
                    )

                    output_tags_raw = gr.Textbox(
                        label="Output tags (raw)",
                        interactive=False,
                        lines=4,
                    )

            copyright_tags_mode_dropdown.change(
                on_change_copyright_tags_dropdouwn,
                inputs=[copyright_tags_mode_dropdown],
                outputs=[copyright_tags_dropdown],
            )
            character_tags_mode_dropdown.change(
                on_change_character_tags_dropdouwn,
                inputs=[character_tags_mode_dropdown],
                outputs=[character_tags_dropdown],
            )

            generate_btn.click(
                handle_inputs,
                inputs=[
                    rating_dropdown,
                    copyright_tags_dropdown,
                    character_tags_dropdown,
                    general_tags_textbox,
                    ban_tags_textbox,
                    max_new_tokens_slider,
                    temperature_slider,
                    top_p_slider,
                    top_k_slider,
                    num_beams_slider,
                ],
                outputs=[
                    output_tags_natural,
                    output_tags_general_only,
                    output_tags_animagine,
                    input_prompt_raw,
                    output_tags_raw,
                    elapsed_time_md,
                ],
            )

    ui.launch()


if __name__ == "__main__":
    demo()