stable-diffusion-webui

Форк
0
/
ui_prompt_styles.py 
123 строки · 5.8 Кб
1
import gradio as gr
2

3
from modules import shared, ui_common, ui_components, styles
4

5
styles_edit_symbol = '\U0001f58c\uFE0F'  # 🖌️
6
styles_materialize_symbol = '\U0001f4cb'  # 📋
7
styles_copy_symbol = '\U0001f4dd'  # 📝
8

9

10
def select_style(name):
11
    style = shared.prompt_styles.styles.get(name)
12
    existing = style is not None
13
    empty = not name
14

15
    prompt = style.prompt if style else gr.update()
16
    negative_prompt = style.negative_prompt if style else gr.update()
17

18
    return prompt, negative_prompt, gr.update(visible=existing), gr.update(visible=not empty)
19

20

21
def save_style(name, prompt, negative_prompt):
22
    if not name:
23
        return gr.update(visible=False)
24

25
    existing_style = shared.prompt_styles.styles.get(name)
26
    path = existing_style.path if existing_style is not None else None
27

28
    style = styles.PromptStyle(name, prompt, negative_prompt, path)
29
    shared.prompt_styles.styles[style.name] = style
30
    shared.prompt_styles.save_styles()
31

32
    return gr.update(visible=True)
33

34

35
def delete_style(name):
36
    if name == "":
37
        return
38

39
    shared.prompt_styles.styles.pop(name, None)
40
    shared.prompt_styles.save_styles()
41

42
    return '', '', ''
43

44

45
def materialize_styles(prompt, negative_prompt, styles):
46
    prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, styles)
47
    negative_prompt = shared.prompt_styles.apply_negative_styles_to_prompt(negative_prompt, styles)
48

49
    return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=negative_prompt), gr.Dropdown.update(value=[])]
50

51

52
def refresh_styles():
53
    return gr.update(choices=list(shared.prompt_styles.styles)), gr.update(choices=list(shared.prompt_styles.styles))
54

55

56
class UiPromptStyles:
57
    def __init__(self, tabname, main_ui_prompt, main_ui_negative_prompt):
58
        self.tabname = tabname
59
        self.main_ui_prompt = main_ui_prompt
60
        self.main_ui_negative_prompt = main_ui_negative_prompt
61

62
        with gr.Row(elem_id=f"{tabname}_styles_row"):
63
            self.dropdown = gr.Dropdown(label="Styles", show_label=False, elem_id=f"{tabname}_styles", choices=list(shared.prompt_styles.styles), value=[], multiselect=True, tooltip="Styles")
64
            edit_button = ui_components.ToolButton(value=styles_edit_symbol, elem_id=f"{tabname}_styles_edit_button", tooltip="Edit styles")
65

66
        with gr.Box(elem_id=f"{tabname}_styles_dialog", elem_classes="popup-dialog") as styles_dialog:
67
            with gr.Row():
68
                self.selection = gr.Dropdown(label="Styles", elem_id=f"{tabname}_styles_edit_select", choices=list(shared.prompt_styles.styles), value=[], allow_custom_value=True, info="Styles allow you to add custom text to prompt. Use the {prompt} token in style text, and it will be replaced with user's prompt when applying style. Otherwise, style's text will be added to the end of the prompt.")
69
                ui_common.create_refresh_button([self.dropdown, self.selection], shared.prompt_styles.reload, lambda: {"choices": list(shared.prompt_styles.styles)}, f"refresh_{tabname}_styles")
70
                self.materialize = ui_components.ToolButton(value=styles_materialize_symbol, elem_id=f"{tabname}_style_apply_dialog", tooltip="Apply all selected styles from the style selction dropdown in main UI to the prompt.")
71
                self.copy = ui_components.ToolButton(value=styles_copy_symbol, elem_id=f"{tabname}_style_copy", tooltip="Copy main UI prompt to style.")
72

73
            with gr.Row():
74
                self.prompt = gr.Textbox(label="Prompt", show_label=True, elem_id=f"{tabname}_edit_style_prompt", lines=3, elem_classes=["prompt"])
75

76
            with gr.Row():
77
                self.neg_prompt = gr.Textbox(label="Negative prompt", show_label=True, elem_id=f"{tabname}_edit_style_neg_prompt", lines=3, elem_classes=["prompt"])
78

79
            with gr.Row():
80
                self.save = gr.Button('Save', variant='primary', elem_id=f'{tabname}_edit_style_save', visible=False)
81
                self.delete = gr.Button('Delete', variant='primary', elem_id=f'{tabname}_edit_style_delete', visible=False)
82
                self.close = gr.Button('Close', variant='secondary', elem_id=f'{tabname}_edit_style_close')
83

84
        self.selection.change(
85
            fn=select_style,
86
            inputs=[self.selection],
87
            outputs=[self.prompt, self.neg_prompt, self.delete, self.save],
88
            show_progress=False,
89
        )
90

91
        self.save.click(
92
            fn=save_style,
93
            inputs=[self.selection, self.prompt, self.neg_prompt],
94
            outputs=[self.delete],
95
            show_progress=False,
96
        ).then(refresh_styles, outputs=[self.dropdown, self.selection], show_progress=False)
97

98
        self.delete.click(
99
            fn=delete_style,
100
            _js='function(name){ if(name == "") return ""; return confirm("Delete style " + name + "?") ? name : ""; }',
101
            inputs=[self.selection],
102
            outputs=[self.selection, self.prompt, self.neg_prompt],
103
            show_progress=False,
104
        ).then(refresh_styles, outputs=[self.dropdown, self.selection], show_progress=False)
105

106
        self.setup_apply_button(self.materialize)
107

108
        self.copy.click(
109
            fn=lambda p, n: (p, n),
110
            inputs=[main_ui_prompt, main_ui_negative_prompt],
111
            outputs=[self.prompt, self.neg_prompt],
112
            show_progress=False,
113
        )
114

115
        ui_common.setup_dialog(button_show=edit_button, dialog=styles_dialog, button_close=self.close)
116

117
    def setup_apply_button(self, button):
118
        button.click(
119
            fn=materialize_styles,
120
            inputs=[self.main_ui_prompt, self.main_ui_negative_prompt, self.dropdown],
121
            outputs=[self.main_ui_prompt, self.main_ui_negative_prompt, self.dropdown],
122
            show_progress=False,
123
        ).then(fn=None, _js="function(){update_"+self.tabname+"_tokens(); closePopup();}", show_progress=False)
124

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.