daasd commited on
Commit
babf604
Β·
1 Parent(s): db7a228

Upload ui.py

Browse files
Files changed (1) hide show
  1. ui.py +1798 -0
ui.py ADDED
@@ -0,0 +1,1798 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
2
+ import json
3
+ import math
4
+ import mimetypes
5
+ import os
6
+ import platform
7
+ import random
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ import traceback
12
+ from functools import partial, reduce
13
+ import warnings
14
+
15
+ import gradio as gr
16
+ import gradio.routes
17
+ import gradio.utils
18
+ import numpy as np
19
+ from PIL import Image, PngImagePlugin
20
+ from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call, wrap_gradio_call
21
+
22
+ from modules import sd_hijack, sd_models, localization, script_callbacks, ui_extensions, deepbooru, sd_vae, extra_networks, postprocessing, ui_components, ui_common, ui_postprocessing
23
+ from modules.ui_components import FormRow, FormGroup, ToolButton, FormHTML
24
+ from modules.paths import script_path, data_path
25
+
26
+ from modules.shared import opts, cmd_opts, restricted_opts
27
+
28
+ import modules.codeformer_model
29
+ import modules.generation_parameters_copypaste as parameters_copypaste
30
+ import modules.gfpgan_model
31
+ import modules.hypernetworks.ui
32
+ import modules.scripts
33
+ import modules.shared as shared
34
+ import modules.styles
35
+ import modules.textual_inversion.ui
36
+ from modules import prompt_parser
37
+ from modules.images import save_image
38
+ from modules.sd_hijack import model_hijack
39
+ from modules.sd_samplers import samplers, samplers_for_img2img
40
+ from modules.textual_inversion import textual_inversion
41
+ import modules.hypernetworks.ui
42
+ from modules.generation_parameters_copypaste import image_from_url_text
43
+ import modules.extras
44
+
45
+ warnings.filterwarnings("default" if opts.show_warnings else "ignore", category=UserWarning)
46
+
47
+ # this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the browser will not show any UI
48
+ mimetypes.init()
49
+ mimetypes.add_type('application/javascript', '.js')
50
+
51
+ if not cmd_opts.share and not cmd_opts.listen:
52
+ # fix gradio phoning home
53
+ gradio.utils.version_check = lambda: None
54
+ gradio.utils.get_local_ip_address = lambda: '127.0.0.1'
55
+
56
+ if cmd_opts.ngrok is not None:
57
+ import modules.ngrok as ngrok
58
+ print('ngrok authtoken detected, trying to connect...')
59
+ ngrok.connect(
60
+ cmd_opts.ngrok,
61
+ cmd_opts.port if cmd_opts.port is not None else 7860,
62
+ cmd_opts.ngrok_region
63
+ )
64
+
65
+
66
+ def gr_show(visible=True):
67
+ return {"visible": visible, "__type__": "update"}
68
+
69
+
70
+ sample_img2img = "assets/stable-samples/img2img/sketch-mountains-input.jpg"
71
+ sample_img2img = sample_img2img if os.path.exists(sample_img2img) else None
72
+
73
+ css_hide_progressbar = """
74
+ .wrap .m-12 svg { display:none!important; }
75
+ .wrap .m-12::before { content:"Loading..." }
76
+ .wrap .z-20 svg { display:none!important; }
77
+ .wrap .z-20::before { content:"Loading..." }
78
+ .wrap.cover-bg .z-20::before { content:"" }
79
+ .progress-bar { display:none!important; }
80
+ .meta-text { display:none!important; }
81
+ .meta-text-center { display:none!important; }
82
+ """
83
+
84
+ # Using constants for these since the variation selector isn't visible.
85
+ # Important that they exactly match script.js for tooltip to work.
86
+ random_symbol = '\U0001f3b2\ufe0f' # 🎲️
87
+ reuse_symbol = '\u267b\ufe0f' # ♻️
88
+ paste_symbol = '\u2199\ufe0f' # ↙
89
+ refresh_symbol = '\U0001f504' # πŸ”„
90
+ save_style_symbol = '\U0001f4be' # πŸ’Ύ
91
+ apply_style_symbol = '\U0001f4cb' # πŸ“‹
92
+ clear_prompt_symbol = '\U0001F5D1' # πŸ—‘οΈ
93
+ extra_networks_symbol = '\U0001F3B4' # 🎴
94
+ switch_values_symbol = '\U000021C5' # β‡…
95
+
96
+
97
+ def plaintext_to_html(text):
98
+ return ui_common.plaintext_to_html(text)
99
+
100
+
101
+ def send_gradio_gallery_to_image(x):
102
+ if len(x) == 0:
103
+ return None
104
+ return image_from_url_text(x[0])
105
+
106
+ def visit(x, func, path=""):
107
+ if hasattr(x, 'children'):
108
+ for c in x.children:
109
+ visit(c, func, path)
110
+ elif x.label is not None:
111
+ func(path + "/" + str(x.label), x)
112
+
113
+
114
+ def add_style(name: str, prompt: str, negative_prompt: str):
115
+ if name is None:
116
+ return [gr_show() for x in range(4)]
117
+
118
+ style = modules.styles.PromptStyle(name, prompt, negative_prompt)
119
+ shared.prompt_styles.styles[style.name] = style
120
+ # Save all loaded prompt styles: this allows us to update the storage format in the future more easily, because we
121
+ # reserialize all styles every time we save them
122
+ shared.prompt_styles.save_styles(shared.styles_filename)
123
+
124
+ return [gr.Dropdown.update(visible=True, choices=list(shared.prompt_styles.styles)) for _ in range(2)]
125
+
126
+
127
+ def calc_resolution_hires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y):
128
+ from modules import processing, devices
129
+
130
+ if not enable:
131
+ return ""
132
+
133
+ p = processing.StableDiffusionProcessingTxt2Img(width=width, height=height, enable_hr=True, hr_scale=hr_scale, hr_resize_x=hr_resize_x, hr_resize_y=hr_resize_y)
134
+
135
+ with devices.autocast():
136
+ p.init([""], [0], [0])
137
+
138
+ return f"resize: from <span class='resolution'>{p.width}x{p.height}</span> to <span class='resolution'>{p.hr_resize_x or p.hr_upscale_to_x}x{p.hr_resize_y or p.hr_upscale_to_y}</span>"
139
+
140
+
141
+ def apply_styles(prompt, prompt_neg, styles):
142
+ prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, styles)
143
+ prompt_neg = shared.prompt_styles.apply_negative_styles_to_prompt(prompt_neg, styles)
144
+
145
+ return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=prompt_neg), gr.Dropdown.update(value=[])]
146
+
147
+
148
+ def process_interrogate(interrogation_function, mode, ii_input_dir, ii_output_dir, *ii_singles):
149
+ if mode in {0, 1, 3, 4}:
150
+ return [interrogation_function(ii_singles[mode]), None]
151
+ elif mode == 2:
152
+ return [interrogation_function(ii_singles[mode]["image"]), None]
153
+ elif mode == 5:
154
+ assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
155
+ images = shared.listfiles(ii_input_dir)
156
+ print(f"Will process {len(images)} images.")
157
+ if ii_output_dir != "":
158
+ os.makedirs(ii_output_dir, exist_ok=True)
159
+ else:
160
+ ii_output_dir = ii_input_dir
161
+
162
+ for image in images:
163
+ img = Image.open(image)
164
+ filename = os.path.basename(image)
165
+ left, _ = os.path.splitext(filename)
166
+ print(interrogation_function(img), file=open(os.path.join(ii_output_dir, left + ".txt"), 'a'))
167
+
168
+ return [gr.update(), None]
169
+
170
+
171
+ def interrogate(image):
172
+ prompt = shared.interrogator.interrogate(image.convert("RGB"))
173
+ return gr.update() if prompt is None else prompt
174
+
175
+
176
+ def interrogate_deepbooru(image):
177
+ prompt = deepbooru.model.tag(image)
178
+ return gr.update() if prompt is None else prompt
179
+
180
+
181
+ def create_seed_inputs(target_interface):
182
+ with FormRow(elem_id=target_interface + '_seed_row'):
183
+ seed = (gr.Textbox if cmd_opts.use_textbox_seed else gr.Number)(label='Seed', value=-1, elem_id=target_interface + '_seed')
184
+ seed.style(container=False)
185
+ random_seed = gr.Button(random_symbol, elem_id=target_interface + '_random_seed')
186
+ reuse_seed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_seed')
187
+
188
+ with gr.Group(elem_id=target_interface + '_subseed_show_box'):
189
+ seed_checkbox = gr.Checkbox(label='Extra', elem_id=target_interface + '_subseed_show', value=False)
190
+
191
+ # Components to show/hide based on the 'Extra' checkbox
192
+ seed_extras = []
193
+
194
+ with FormRow(visible=False, elem_id=target_interface + '_subseed_row') as seed_extra_row_1:
195
+ seed_extras.append(seed_extra_row_1)
196
+ subseed = gr.Number(label='Variation seed', value=-1, elem_id=target_interface + '_subseed')
197
+ subseed.style(container=False)
198
+ random_subseed = gr.Button(random_symbol, elem_id=target_interface + '_random_subseed')
199
+ reuse_subseed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_subseed')
200
+ subseed_strength = gr.Slider(label='Variation strength', value=0.0, minimum=0, maximum=1, step=0.01, elem_id=target_interface + '_subseed_strength')
201
+
202
+ with FormRow(visible=False) as seed_extra_row_2:
203
+ seed_extras.append(seed_extra_row_2)
204
+ seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from width", value=0, elem_id=target_interface + '_seed_resize_from_w')
205
+ seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize seed from height", value=0, elem_id=target_interface + '_seed_resize_from_h')
206
+
207
+ random_seed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[seed])
208
+ random_subseed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[subseed])
209
+
210
+ def change_visibility(show):
211
+ return {comp: gr_show(show) for comp in seed_extras}
212
+
213
+ seed_checkbox.change(change_visibility, show_progress=False, inputs=[seed_checkbox], outputs=seed_extras)
214
+
215
+ return seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox
216
+
217
+
218
+
219
+ def connect_clear_prompt(button):
220
+ """Given clear button, prompt, and token_counter objects, setup clear prompt button click event"""
221
+ button.click(
222
+ _js="clear_prompt",
223
+ fn=None,
224
+ inputs=[],
225
+ outputs=[],
226
+ )
227
+
228
+
229
+ def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info: gr.Textbox, dummy_component, is_subseed):
230
+ """ Connects a 'reuse (sub)seed' button's click event so that it copies last used
231
+ (sub)seed value from generation info the to the seed field. If copying subseed and subseed strength
232
+ was 0, i.e. no variation seed was used, it copies the normal seed value instead."""
233
+ def copy_seed(gen_info_string: str, index):
234
+ res = -1
235
+
236
+ try:
237
+ gen_info = json.loads(gen_info_string)
238
+ index -= gen_info.get('index_of_first_image', 0)
239
+
240
+ if is_subseed and gen_info.get('subseed_strength', 0) > 0:
241
+ all_subseeds = gen_info.get('all_subseeds', [-1])
242
+ res = all_subseeds[index if 0 <= index < len(all_subseeds) else 0]
243
+ else:
244
+ all_seeds = gen_info.get('all_seeds', [-1])
245
+ res = all_seeds[index if 0 <= index < len(all_seeds) else 0]
246
+
247
+ except json.decoder.JSONDecodeError as e:
248
+ if gen_info_string != '':
249
+ print("Error parsing JSON generation info:", file=sys.stderr)
250
+ print(gen_info_string, file=sys.stderr)
251
+
252
+ return [res, gr_show(False)]
253
+
254
+ reuse_seed.click(
255
+ fn=copy_seed,
256
+ _js="(x, y) => [x, selected_gallery_index()]",
257
+ show_progress=False,
258
+ inputs=[generation_info, dummy_component],
259
+ outputs=[seed, dummy_component]
260
+ )
261
+
262
+
263
+ def update_token_counter(text, steps):
264
+ try:
265
+ text, _ = extra_networks.parse_prompt(text)
266
+
267
+ _, prompt_flat_list, _ = prompt_parser.get_multicond_prompt_list([text])
268
+ prompt_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(prompt_flat_list, steps)
269
+
270
+ except Exception:
271
+ # a parsing error can happen here during typing, and we don't want to bother the user with
272
+ # messages related to it in console
273
+ prompt_schedules = [[[steps, text]]]
274
+
275
+ flat_prompts = reduce(lambda list1, list2: list1+list2, prompt_schedules)
276
+ prompts = [prompt_text for step, prompt_text in flat_prompts]
277
+ token_count, max_length = max([model_hijack.get_prompt_lengths(prompt) for prompt in prompts], key=lambda args: args[0])
278
+ return f"<span class='gr-box gr-text-input'>{token_count}/{max_length}</span>"
279
+
280
+
281
+ def create_toprow(is_img2img):
282
+ id_part = "img2img" if is_img2img else "txt2img"
283
+
284
+ with gr.Row(elem_id=f"{id_part}_toprow", variant="compact"):
285
+ with gr.Column(elem_id=f"{id_part}_prompt_container", scale=6):
286
+ with gr.Row():
287
+ with gr.Column(scale=80):
288
+ with gr.Row():
289
+ prompt = gr.Textbox(label="Prompt", elem_id=f"{id_part}_prompt", show_label=False, lines=3, placeholder="Prompt (press Ctrl+Enter or Alt+Enter to generate)")
290
+
291
+ with gr.Row():
292
+ with gr.Column(scale=80):
293
+ with gr.Row():
294
+ negative_prompt = gr.Textbox(label="Negative prompt", elem_id=f"{id_part}_neg_prompt", show_label=False, lines=2, placeholder="Negative prompt (press Ctrl+Enter or Alt+Enter to generate)")
295
+
296
+ button_interrogate = None
297
+ button_deepbooru = None
298
+ if is_img2img:
299
+ with gr.Column(scale=1, elem_id="interrogate_col"):
300
+ button_interrogate = gr.Button('Interrogate\nCLIP', elem_id="interrogate")
301
+ button_deepbooru = gr.Button('Interrogate\nDeepBooru', elem_id="deepbooru")
302
+
303
+ with gr.Column(scale=1, elem_id=f"{id_part}_actions_column"):
304
+ with gr.Row(elem_id=f"{id_part}_generate_box"):
305
+ interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt")
306
+ skip = gr.Button('Skip', elem_id=f"{id_part}_skip")
307
+ submit = gr.Button('Generate', elem_id=f"{id_part}_generate", variant='primary')
308
+
309
+ skip.click(
310
+ fn=lambda: shared.state.skip(),
311
+ inputs=[],
312
+ outputs=[],
313
+ )
314
+
315
+ interrupt.click(
316
+ fn=lambda: shared.state.interrupt(),
317
+ inputs=[],
318
+ outputs=[],
319
+ )
320
+
321
+ with gr.Row(elem_id=f"{id_part}_tools"):
322
+ paste = ToolButton(value=paste_symbol, elem_id="paste")
323
+ clear_prompt_button = ToolButton(value=clear_prompt_symbol, elem_id=f"{id_part}_clear_prompt")
324
+ extra_networks_button = ToolButton(value=extra_networks_symbol, elem_id=f"{id_part}_extra_networks")
325
+ prompt_style_apply = ToolButton(value=apply_style_symbol, elem_id=f"{id_part}_style_apply")
326
+ save_style = ToolButton(value=save_style_symbol, elem_id=f"{id_part}_style_create")
327
+
328
+ token_counter = gr.HTML(value="<span></span>", elem_id=f"{id_part}_token_counter")
329
+ token_button = gr.Button(visible=False, elem_id=f"{id_part}_token_button")
330
+ negative_token_counter = gr.HTML(value="<span></span>", elem_id=f"{id_part}_negative_token_counter")
331
+ negative_token_button = gr.Button(visible=False, elem_id=f"{id_part}_negative_token_button")
332
+
333
+ clear_prompt_button.click(
334
+ fn=lambda *x: x,
335
+ _js="confirm_clear_prompt",
336
+ inputs=[prompt, negative_prompt],
337
+ outputs=[prompt, negative_prompt],
338
+ )
339
+
340
+ with gr.Row(elem_id=f"{id_part}_styles_row"):
341
+ prompt_styles = gr.Dropdown(label="Styles", elem_id=f"{id_part}_styles", choices=[k for k, v in shared.prompt_styles.styles.items()], value=[], multiselect=True)
342
+ create_refresh_button(prompt_styles, shared.prompt_styles.reload, lambda: {"choices": [k for k, v in shared.prompt_styles.styles.items()]}, f"refresh_{id_part}_styles")
343
+
344
+ return prompt, prompt_styles, negative_prompt, submit, button_interrogate, button_deepbooru, prompt_style_apply, save_style, paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button
345
+
346
+
347
+ def setup_progressbar(*args, **kwargs):
348
+ pass
349
+
350
+
351
+ def apply_setting(key, value):
352
+ if value is None:
353
+ return gr.update()
354
+
355
+ if shared.cmd_opts.freeze_settings:
356
+ return gr.update()
357
+
358
+ # dont allow model to be swapped when model hash exists in prompt
359
+ if key == "sd_model_checkpoint" and opts.disable_weights_auto_swap:
360
+ return gr.update()
361
+
362
+ if key == "sd_model_checkpoint":
363
+ ckpt_info = sd_models.get_closet_checkpoint_match(value)
364
+
365
+ if ckpt_info is not None:
366
+ value = ckpt_info.title
367
+ else:
368
+ return gr.update()
369
+
370
+ comp_args = opts.data_labels[key].component_args
371
+ if comp_args and isinstance(comp_args, dict) and comp_args.get('visible') is False:
372
+ return
373
+
374
+ valtype = type(opts.data_labels[key].default)
375
+ oldval = opts.data.get(key, None)
376
+ opts.data[key] = valtype(value) if valtype != type(None) else value
377
+ if oldval != value and opts.data_labels[key].onchange is not None:
378
+ opts.data_labels[key].onchange()
379
+
380
+ opts.save(shared.config_filename)
381
+ return getattr(opts, key)
382
+
383
+
384
+ def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id):
385
+ def refresh():
386
+ refresh_method()
387
+ args = refreshed_args() if callable(refreshed_args) else refreshed_args
388
+
389
+ for k, v in args.items():
390
+ setattr(refresh_component, k, v)
391
+
392
+ return gr.update(**(args or {}))
393
+
394
+ refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id)
395
+ refresh_button.click(
396
+ fn=refresh,
397
+ inputs=[],
398
+ outputs=[refresh_component]
399
+ )
400
+ return refresh_button
401
+
402
+
403
+ def create_output_panel(tabname, outdir):
404
+ return ui_common.create_output_panel(tabname, outdir)
405
+
406
+
407
+ def create_sampler_and_steps_selection(choices, tabname):
408
+ if opts.samplers_in_dropdown:
409
+ with FormRow(elem_id=f"sampler_selection_{tabname}"):
410
+ sampler_index = gr.Dropdown(label='Sampling method', elem_id=f"{tabname}_sampling", choices=[x.name for x in choices], value=choices[0].name, type="index")
411
+ steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20)
412
+ else:
413
+ with FormGroup(elem_id=f"sampler_selection_{tabname}"):
414
+ steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20)
415
+ sampler_index = gr.Radio(label='Sampling method', elem_id=f"{tabname}_sampling", choices=[x.name for x in choices], value=choices[0].name, type="index")
416
+
417
+ return steps, sampler_index
418
+
419
+
420
+ def ordered_ui_categories():
421
+ user_order = {x.strip(): i * 2 + 1 for i, x in enumerate(shared.opts.ui_reorder.split(","))}
422
+
423
+ for i, category in sorted(enumerate(shared.ui_reorder_categories), key=lambda x: user_order.get(x[1], x[0] * 2 + 0)):
424
+ yield category
425
+
426
+
427
+ def get_value_for_setting(key):
428
+ value = getattr(opts, key)
429
+
430
+ info = opts.data_labels[key]
431
+ args = info.component_args() if callable(info.component_args) else info.component_args or {}
432
+ args = {k: v for k, v in args.items() if k not in {'precision'}}
433
+
434
+ return gr.update(value=value, **args)
435
+
436
+
437
+ def create_override_settings_dropdown(tabname, row):
438
+ dropdown = gr.Dropdown([], label="Override settings", visible=False, elem_id=f"{tabname}_override_settings", multiselect=True)
439
+
440
+ dropdown.change(
441
+ fn=lambda x: gr.Dropdown.update(visible=len(x) > 0),
442
+ inputs=[dropdown],
443
+ outputs=[dropdown],
444
+ )
445
+
446
+ return dropdown
447
+
448
+
449
+ def create_ui():
450
+ import modules.img2img
451
+ import modules.txt2img
452
+
453
+ reload_javascript()
454
+
455
+ parameters_copypaste.reset()
456
+
457
+ modules.scripts.scripts_current = modules.scripts.scripts_txt2img
458
+ modules.scripts.scripts_txt2img.initialize_scripts(is_img2img=False)
459
+
460
+ with gr.Blocks(analytics_enabled=False) as txt2img_interface:
461
+ txt2img_prompt, txt2img_prompt_styles, txt2img_negative_prompt, submit, _, _, txt2img_prompt_style_apply, txt2img_save_style, txt2img_paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button = create_toprow(is_img2img=False)
462
+
463
+ dummy_component = gr.Label(visible=False)
464
+ txt_prompt_img = gr.File(label="", elem_id="txt2img_prompt_image", file_count="single", type="binary", visible=False)
465
+
466
+ with FormRow(variant='compact', elem_id="txt2img_extra_networks", visible=False) as extra_networks:
467
+ from modules import ui_extra_networks
468
+ extra_networks_ui = ui_extra_networks.create_ui(extra_networks, extra_networks_button, 'txt2img')
469
+
470
+ with gr.Row().style(equal_height=False):
471
+ with gr.Column(variant='compact', elem_id="txt2img_settings"):
472
+ for category in ordered_ui_categories():
473
+ if category == "sampler":
474
+ steps, sampler_index = create_sampler_and_steps_selection(samplers, "txt2img")
475
+
476
+ elif category == "dimensions":
477
+ with FormRow():
478
+ with gr.Column(elem_id="txt2img_column_size", scale=4):
479
+ width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="txt2img_width")
480
+ height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="txt2img_height")
481
+
482
+ res_switch_btn = ToolButton(value=switch_values_symbol, elem_id="txt2img_res_switch_btn")
483
+ if opts.dimensions_and_batch_together:
484
+ with gr.Column(elem_id="txt2img_column_batch"):
485
+ batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count")
486
+ batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size")
487
+
488
+ elif category == "cfg":
489
+ cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="txt2img_cfg_scale")
490
+
491
+ elif category == "seed":
492
+ seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('txt2img')
493
+
494
+ elif category == "checkboxes":
495
+ with FormRow(elem_id="txt2img_checkboxes", variant="compact"):
496
+ restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="txt2img_restore_faces")
497
+ tiling = gr.Checkbox(label='Tiling', value=False, elem_id="txt2img_tiling")
498
+ enable_hr = gr.Checkbox(label='Hires. fix', value=False, elem_id="txt2img_enable_hr")
499
+ hr_final_resolution = FormHTML(value="", elem_id="txtimg_hr_finalres", label="Upscaled resolution", interactive=False)
500
+
501
+ elif category == "hires_fix":
502
+ with FormGroup(visible=False, elem_id="txt2img_hires_fix") as hr_options:
503
+ with FormRow(elem_id="txt2img_hires_fix_row1", variant="compact"):
504
+ hr_upscaler = gr.Dropdown(label="Upscaler", elem_id="txt2img_hr_upscaler", choices=[*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]], value=shared.latent_upscale_default_mode)
505
+ hr_second_pass_steps = gr.Slider(minimum=0, maximum=150, step=1, label='Hires steps', value=0, elem_id="txt2img_hires_steps")
506
+ denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.7, elem_id="txt2img_denoising_strength")
507
+
508
+ with FormRow(elem_id="txt2img_hires_fix_row2", variant="compact"):
509
+ hr_scale = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label="Upscale by", value=2.0, elem_id="txt2img_hr_scale")
510
+ hr_resize_x = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize width to", value=0, elem_id="txt2img_hr_resize_x")
511
+ hr_resize_y = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize height to", value=0, elem_id="txt2img_hr_resize_y")
512
+
513
+ elif category == "batch":
514
+ if not opts.dimensions_and_batch_together:
515
+ with FormRow(elem_id="txt2img_column_batch"):
516
+ batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count")
517
+ batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size")
518
+
519
+ elif category == "override_settings":
520
+ with FormRow(elem_id="txt2img_override_settings_row") as row:
521
+ override_settings = create_override_settings_dropdown('txt2img', row)
522
+
523
+ elif category == "scripts":
524
+ with FormGroup(elem_id="txt2img_script_container"):
525
+ custom_inputs = modules.scripts.scripts_txt2img.setup_ui()
526
+
527
+ hr_resolution_preview_inputs = [enable_hr, width, height, hr_scale, hr_resize_x, hr_resize_y]
528
+ for input in hr_resolution_preview_inputs:
529
+ input.change(
530
+ fn=calc_resolution_hires,
531
+ inputs=hr_resolution_preview_inputs,
532
+ outputs=[hr_final_resolution],
533
+ show_progress=False,
534
+ )
535
+ input.change(
536
+ None,
537
+ _js="onCalcResolutionHires",
538
+ inputs=hr_resolution_preview_inputs,
539
+ outputs=[],
540
+ show_progress=False,
541
+ )
542
+
543
+ txt2img_gallery, generation_info, html_info, html_log = create_output_panel("txt2img", opts.outdir_txt2img_samples)
544
+
545
+ connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
546
+ connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
547
+
548
+ txt2img_args = dict(
549
+ fn=wrap_gradio_gpu_call(modules.txt2img.txt2img, extra_outputs=[None, '', '']),
550
+ _js="submit",
551
+ inputs=[
552
+ dummy_component,
553
+ txt2img_prompt,
554
+ txt2img_negative_prompt,
555
+ txt2img_prompt_styles,
556
+ steps,
557
+ sampler_index,
558
+ restore_faces,
559
+ tiling,
560
+ batch_count,
561
+ batch_size,
562
+ cfg_scale,
563
+ seed,
564
+ subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
565
+ height,
566
+ width,
567
+ enable_hr,
568
+ denoising_strength,
569
+ hr_scale,
570
+ hr_upscaler,
571
+ hr_second_pass_steps,
572
+ hr_resize_x,
573
+ hr_resize_y,
574
+ override_settings,
575
+ ] + custom_inputs,
576
+
577
+ outputs=[
578
+ txt2img_gallery,
579
+ generation_info,
580
+ html_info,
581
+ html_log,
582
+ ],
583
+ show_progress=False,
584
+ )
585
+
586
+ txt2img_prompt.submit(**txt2img_args)
587
+ submit.click(**txt2img_args)
588
+
589
+ res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height])
590
+
591
+ txt_prompt_img.change(
592
+ fn=modules.images.image_data,
593
+ inputs=[
594
+ txt_prompt_img
595
+ ],
596
+ outputs=[
597
+ txt2img_prompt,
598
+ txt_prompt_img
599
+ ]
600
+ )
601
+
602
+ enable_hr.change(
603
+ fn=lambda x: gr_show(x),
604
+ inputs=[enable_hr],
605
+ outputs=[hr_options],
606
+ show_progress = False,
607
+ )
608
+
609
+ txt2img_paste_fields = [
610
+ (txt2img_prompt, "Prompt"),
611
+ (txt2img_negative_prompt, "Negative prompt"),
612
+ (steps, "Steps"),
613
+ (sampler_index, "Sampler"),
614
+ (restore_faces, "Face restoration"),
615
+ (cfg_scale, "CFG scale"),
616
+ (seed, "Seed"),
617
+ (width, "Size-1"),
618
+ (height, "Size-2"),
619
+ (batch_size, "Batch size"),
620
+ (subseed, "Variation seed"),
621
+ (subseed_strength, "Variation seed strength"),
622
+ (seed_resize_from_w, "Seed resize from-1"),
623
+ (seed_resize_from_h, "Seed resize from-2"),
624
+ (denoising_strength, "Denoising strength"),
625
+ (enable_hr, lambda d: "Denoising strength" in d),
626
+ (hr_options, lambda d: gr.Row.update(visible="Denoising strength" in d)),
627
+ (hr_scale, "Hires upscale"),
628
+ (hr_upscaler, "Hires upscaler"),
629
+ (hr_second_pass_steps, "Hires steps"),
630
+ (hr_resize_x, "Hires resize-1"),
631
+ (hr_resize_y, "Hires resize-2"),
632
+ *modules.scripts.scripts_txt2img.infotext_fields
633
+ ]
634
+ parameters_copypaste.add_paste_fields("txt2img", None, txt2img_paste_fields, override_settings)
635
+ parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding(
636
+ paste_button=txt2img_paste, tabname="txt2img", source_text_component=txt2img_prompt, source_image_component=None,
637
+ ))
638
+
639
+ txt2img_preview_params = [
640
+ txt2img_prompt,
641
+ txt2img_negative_prompt,
642
+ steps,
643
+ sampler_index,
644
+ cfg_scale,
645
+ seed,
646
+ width,
647
+ height,
648
+ ]
649
+
650
+ token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_prompt, steps], outputs=[token_counter])
651
+ negative_token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_negative_prompt, steps], outputs=[negative_token_counter])
652
+
653
+ ui_extra_networks.setup_ui(extra_networks_ui, txt2img_gallery)
654
+
655
+ modules.scripts.scripts_current = modules.scripts.scripts_img2img
656
+ modules.scripts.scripts_img2img.initialize_scripts(is_img2img=True)
657
+
658
+ with gr.Blocks(analytics_enabled=False) as img2img_interface:
659
+ img2img_prompt, img2img_prompt_styles, img2img_negative_prompt, submit, img2img_interrogate, img2img_deepbooru, img2img_prompt_style_apply, img2img_save_style, img2img_paste, extra_networks_button, token_counter, token_button, negative_token_counter, negative_token_button = create_toprow(is_img2img=True)
660
+
661
+ img2img_prompt_img = gr.File(label="", elem_id="img2img_prompt_image", file_count="single", type="binary", visible=False)
662
+
663
+ with FormRow(variant='compact', elem_id="img2img_extra_networks", visible=False) as extra_networks:
664
+ from modules import ui_extra_networks
665
+ extra_networks_ui_img2img = ui_extra_networks.create_ui(extra_networks, extra_networks_button, 'img2img')
666
+
667
+ with FormRow().style(equal_height=False):
668
+ with gr.Column(variant='compact', elem_id="img2img_settings"):
669
+ copy_image_buttons = []
670
+ copy_image_destinations = {}
671
+
672
+ def add_copy_image_controls(tab_name, elem):
673
+ with gr.Row(variant="compact", elem_id=f"img2img_copy_to_{tab_name}"):
674
+ gr.HTML("Copy image to: ", elem_id=f"img2img_label_copy_to_{tab_name}")
675
+
676
+ for title, name in zip(['img2img', 'sketch', 'inpaint', 'inpaint sketch'], ['img2img', 'sketch', 'inpaint', 'inpaint_sketch']):
677
+ if name == tab_name:
678
+ gr.Button(title, interactive=False)
679
+ copy_image_destinations[name] = elem
680
+ continue
681
+
682
+ button = gr.Button(title)
683
+ copy_image_buttons.append((button, name, elem))
684
+
685
+ with gr.Tabs(elem_id="mode_img2img"):
686
+ with gr.TabItem('img2img', id='img2img', elem_id="img2img_img2img_tab") as tab_img2img:
687
+ init_img = gr.Image(label="Image for img2img", elem_id="img2img_image", show_label=False, source="upload", interactive=True, type="pil", tool="editor", image_mode="RGBA").style(height=480)
688
+ add_copy_image_controls('img2img', init_img)
689
+
690
+ with gr.TabItem('Sketch', id='img2img_sketch', elem_id="img2img_img2img_sketch_tab") as tab_sketch:
691
+ sketch = gr.Image(label="Image for img2img", elem_id="img2img_sketch", show_label=False, source="upload", interactive=True, type="pil", tool="color-sketch", image_mode="RGBA").style(height=480)
692
+ add_copy_image_controls('sketch', sketch)
693
+
694
+ with gr.TabItem('Inpaint', id='inpaint', elem_id="img2img_inpaint_tab") as tab_inpaint:
695
+ init_img_with_mask = gr.Image(label="Image for inpainting with mask", show_label=False, elem_id="img2maskimg", source="upload", interactive=True, type="pil", tool="sketch", image_mode="RGBA").style(height=480)
696
+ add_copy_image_controls('inpaint', init_img_with_mask)
697
+
698
+ with gr.TabItem('Inpaint sketch', id='inpaint_sketch', elem_id="img2img_inpaint_sketch_tab") as tab_inpaint_color:
699
+ inpaint_color_sketch = gr.Image(label="Color sketch inpainting", show_label=False, elem_id="inpaint_sketch", source="upload", interactive=True, type="pil", tool="color-sketch", image_mode="RGBA").style(height=480)
700
+ inpaint_color_sketch_orig = gr.State(None)
701
+ add_copy_image_controls('inpaint_sketch', inpaint_color_sketch)
702
+
703
+ def update_orig(image, state):
704
+ if image is not None:
705
+ same_size = state is not None and state.size == image.size
706
+ has_exact_match = np.any(np.all(np.array(image) == np.array(state), axis=-1))
707
+ edited = same_size and has_exact_match
708
+ return image if not edited or state is None else state
709
+
710
+ inpaint_color_sketch.change(update_orig, [inpaint_color_sketch, inpaint_color_sketch_orig], inpaint_color_sketch_orig)
711
+
712
+ with gr.TabItem('Inpaint upload', id='inpaint_upload', elem_id="img2img_inpaint_upload_tab") as tab_inpaint_upload:
713
+ init_img_inpaint = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil", elem_id="img_inpaint_base")
714
+ init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", elem_id="img_inpaint_mask")
715
+
716
+ with gr.TabItem('Batch', id='batch', elem_id="img2img_batch_tab") as tab_batch:
717
+ hidden = '<br>Disabled when launched with --hide-ui-dir-config.' if shared.cmd_opts.hide_ui_dir_config else ''
718
+ gr.HTML(
719
+ f"<p style='padding-bottom: 1em;' class=\"text-gray-500\">Process images in a directory on the same machine where the server is running." +
720
+ f"<br>Use an empty output directory to save pictures normally instead of writing to the output directory." +
721
+ f"<br>Add inpaint batch mask directory to enable inpaint batch processing."
722
+ f"{hidden}</p>"
723
+ )
724
+ img2img_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, elem_id="img2img_batch_input_dir")
725
+ img2img_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, elem_id="img2img_batch_output_dir")
726
+ img2img_batch_inpaint_mask_dir = gr.Textbox(label="Inpaint batch mask directory (required for inpaint batch processing only)", **shared.hide_dirs, elem_id="img2img_batch_inpaint_mask_dir")
727
+
728
+ def copy_image(img):
729
+ if isinstance(img, dict) and 'image' in img:
730
+ return img['image']
731
+
732
+ return img
733
+
734
+ for button, name, elem in copy_image_buttons:
735
+ button.click(
736
+ fn=copy_image,
737
+ inputs=[elem],
738
+ outputs=[copy_image_destinations[name]],
739
+ )
740
+ button.click(
741
+ fn=lambda: None,
742
+ _js="switch_to_"+name.replace(" ", "_"),
743
+ inputs=[],
744
+ outputs=[],
745
+ )
746
+
747
+ with FormRow():
748
+ resize_mode = gr.Radio(label="Resize mode", elem_id="resize_mode", choices=["Just resize", "Crop and resize", "Resize and fill", "Just resize (latent upscale)"], type="index", value="Just resize")
749
+
750
+ for category in ordered_ui_categories():
751
+ if category == "sampler":
752
+ steps, sampler_index = create_sampler_and_steps_selection(samplers_for_img2img, "img2img")
753
+
754
+ elif category == "dimensions":
755
+ with FormRow():
756
+ with gr.Column(elem_id="img2img_column_size", scale=4):
757
+ width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="img2img_width")
758
+ height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="img2img_height")
759
+
760
+ res_switch_btn = ToolButton(value=switch_values_symbol, elem_id="img2img_res_switch_btn")
761
+ if opts.dimensions_and_batch_together:
762
+ with gr.Column(elem_id="img2img_column_batch"):
763
+ batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count")
764
+ batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size")
765
+
766
+ elif category == "cfg":
767
+ with FormGroup():
768
+ with FormRow():
769
+ cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="img2img_cfg_scale")
770
+ image_cfg_scale = gr.Slider(minimum=0, maximum=3.0, step=0.05, label='Image CFG Scale', value=1.5, elem_id="img2img_image_cfg_scale", visible=shared.sd_model and shared.sd_model.cond_stage_key == "edit")
771
+ denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.75, elem_id="img2img_denoising_strength")
772
+
773
+ elif category == "seed":
774
+ seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('img2img')
775
+
776
+ elif category == "checkboxes":
777
+ with FormRow(elem_id="img2img_checkboxes", variant="compact"):
778
+ restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="img2img_restore_faces")
779
+ tiling = gr.Checkbox(label='Tiling', value=False, elem_id="img2img_tiling")
780
+
781
+ elif category == "batch":
782
+ if not opts.dimensions_and_batch_together:
783
+ with FormRow(elem_id="img2img_column_batch"):
784
+ batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count")
785
+ batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size")
786
+
787
+ elif category == "override_settings":
788
+ with FormRow(elem_id="img2img_override_settings_row") as row:
789
+ override_settings = create_override_settings_dropdown('img2img', row)
790
+
791
+ elif category == "scripts":
792
+ with FormGroup(elem_id="img2img_script_container"):
793
+ custom_inputs = modules.scripts.scripts_img2img.setup_ui()
794
+
795
+ elif category == "inpaint":
796
+ with FormGroup(elem_id="inpaint_controls", visible=False) as inpaint_controls:
797
+ with FormRow():
798
+ mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, elem_id="img2img_mask_blur")
799
+ mask_alpha = gr.Slider(label="Mask transparency", visible=False, elem_id="img2img_mask_alpha")
800
+
801
+ with FormRow():
802
+ inpainting_mask_invert = gr.Radio(label='Mask mode', choices=['Inpaint masked', 'Inpaint not masked'], value='Inpaint masked', type="index", elem_id="img2img_mask_mode")
803
+
804
+ with FormRow():
805
+ inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='original', type="index", elem_id="img2img_inpainting_fill")
806
+
807
+ with FormRow():
808
+ with gr.Column():
809
+ inpaint_full_res = gr.Radio(label="Inpaint area", choices=["Whole picture", "Only masked"], type="index", value="Whole picture", elem_id="img2img_inpaint_full_res")
810
+
811
+ with gr.Column(scale=4):
812
+ inpaint_full_res_padding = gr.Slider(label='Only masked padding, pixels', minimum=0, maximum=256, step=4, value=32, elem_id="img2img_inpaint_full_res_padding")
813
+
814
+ def select_img2img_tab(tab):
815
+ return gr.update(visible=tab in [2, 3, 4]), gr.update(visible=tab == 3),
816
+
817
+ for i, elem in enumerate([tab_img2img, tab_sketch, tab_inpaint, tab_inpaint_color, tab_inpaint_upload, tab_batch]):
818
+ elem.select(
819
+ fn=lambda tab=i: select_img2img_tab(tab),
820
+ inputs=[],
821
+ outputs=[inpaint_controls, mask_alpha],
822
+ )
823
+
824
+ img2img_gallery, generation_info, html_info, html_log = create_output_panel("img2img", opts.outdir_img2img_samples)
825
+
826
+ connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
827
+ connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
828
+
829
+ img2img_prompt_img.change(
830
+ fn=modules.images.image_data,
831
+ inputs=[
832
+ img2img_prompt_img
833
+ ],
834
+ outputs=[
835
+ img2img_prompt,
836
+ img2img_prompt_img
837
+ ]
838
+ )
839
+
840
+ img2img_args = dict(
841
+ fn=wrap_gradio_gpu_call(modules.img2img.img2img, extra_outputs=[None, '', '']),
842
+ _js="submit_img2img",
843
+ inputs=[
844
+ dummy_component,
845
+ dummy_component,
846
+ img2img_prompt,
847
+ img2img_negative_prompt,
848
+ img2img_prompt_styles,
849
+ init_img,
850
+ sketch,
851
+ init_img_with_mask,
852
+ inpaint_color_sketch,
853
+ inpaint_color_sketch_orig,
854
+ init_img_inpaint,
855
+ init_mask_inpaint,
856
+ steps,
857
+ sampler_index,
858
+ mask_blur,
859
+ mask_alpha,
860
+ inpainting_fill,
861
+ restore_faces,
862
+ tiling,
863
+ batch_count,
864
+ batch_size,
865
+ cfg_scale,
866
+ image_cfg_scale,
867
+ denoising_strength,
868
+ seed,
869
+ subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
870
+ height,
871
+ width,
872
+ resize_mode,
873
+ inpaint_full_res,
874
+ inpaint_full_res_padding,
875
+ inpainting_mask_invert,
876
+ img2img_batch_input_dir,
877
+ img2img_batch_output_dir,
878
+ img2img_batch_inpaint_mask_dir,
879
+ override_settings,
880
+ ] + custom_inputs,
881
+ outputs=[
882
+ img2img_gallery,
883
+ generation_info,
884
+ html_info,
885
+ html_log,
886
+ ],
887
+ show_progress=False,
888
+ )
889
+
890
+ interrogate_args = dict(
891
+ _js="get_img2img_tab_index",
892
+ inputs=[
893
+ dummy_component,
894
+ img2img_batch_input_dir,
895
+ img2img_batch_output_dir,
896
+ init_img,
897
+ sketch,
898
+ init_img_with_mask,
899
+ inpaint_color_sketch,
900
+ init_img_inpaint,
901
+ ],
902
+ outputs=[img2img_prompt, dummy_component],
903
+ )
904
+
905
+ img2img_prompt.submit(**img2img_args)
906
+ submit.click(**img2img_args)
907
+ res_switch_btn.click(lambda w, h: (h, w), inputs=[width, height], outputs=[width, height])
908
+
909
+ img2img_interrogate.click(
910
+ fn=lambda *args: process_interrogate(interrogate, *args),
911
+ **interrogate_args,
912
+ )
913
+
914
+ img2img_deepbooru.click(
915
+ fn=lambda *args: process_interrogate(interrogate_deepbooru, *args),
916
+ **interrogate_args,
917
+ )
918
+
919
+ prompts = [(txt2img_prompt, txt2img_negative_prompt), (img2img_prompt, img2img_negative_prompt)]
920
+ style_dropdowns = [txt2img_prompt_styles, img2img_prompt_styles]
921
+ style_js_funcs = ["update_txt2img_tokens", "update_img2img_tokens"]
922
+
923
+ for button, (prompt, negative_prompt) in zip([txt2img_save_style, img2img_save_style], prompts):
924
+ button.click(
925
+ fn=add_style,
926
+ _js="ask_for_style_name",
927
+ # Have to pass empty dummy component here, because the JavaScript and Python function have to accept
928
+ # the same number of parameters, but we only know the style-name after the JavaScript prompt
929
+ inputs=[dummy_component, prompt, negative_prompt],
930
+ outputs=[txt2img_prompt_styles, img2img_prompt_styles],
931
+ )
932
+
933
+ for button, (prompt, negative_prompt), styles, js_func in zip([txt2img_prompt_style_apply, img2img_prompt_style_apply], prompts, style_dropdowns, style_js_funcs):
934
+ button.click(
935
+ fn=apply_styles,
936
+ _js=js_func,
937
+ inputs=[prompt, negative_prompt, styles],
938
+ outputs=[prompt, negative_prompt, styles],
939
+ )
940
+
941
+ token_button.click(fn=update_token_counter, inputs=[img2img_prompt, steps], outputs=[token_counter])
942
+ negative_token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_negative_prompt, steps], outputs=[negative_token_counter])
943
+
944
+ ui_extra_networks.setup_ui(extra_networks_ui_img2img, img2img_gallery)
945
+
946
+ img2img_paste_fields = [
947
+ (img2img_prompt, "Prompt"),
948
+ (img2img_negative_prompt, "Negative prompt"),
949
+ (steps, "Steps"),
950
+ (sampler_index, "Sampler"),
951
+ (restore_faces, "Face restoration"),
952
+ (cfg_scale, "CFG scale"),
953
+ (image_cfg_scale, "Image CFG scale"),
954
+ (seed, "Seed"),
955
+ (width, "Size-1"),
956
+ (height, "Size-2"),
957
+ (batch_size, "Batch size"),
958
+ (subseed, "Variation seed"),
959
+ (subseed_strength, "Variation seed strength"),
960
+ (seed_resize_from_w, "Seed resize from-1"),
961
+ (seed_resize_from_h, "Seed resize from-2"),
962
+ (denoising_strength, "Denoising strength"),
963
+ (mask_blur, "Mask blur"),
964
+ *modules.scripts.scripts_img2img.infotext_fields
965
+ ]
966
+ parameters_copypaste.add_paste_fields("img2img", init_img, img2img_paste_fields, override_settings)
967
+ parameters_copypaste.add_paste_fields("inpaint", init_img_with_mask, img2img_paste_fields, override_settings)
968
+ parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding(
969
+ paste_button=img2img_paste, tabname="img2img", source_text_component=img2img_prompt, source_image_component=None,
970
+ ))
971
+
972
+ modules.scripts.scripts_current = None
973
+
974
+ with gr.Blocks(analytics_enabled=False) as extras_interface:
975
+ ui_postprocessing.create_ui()
976
+
977
+ with gr.Blocks(analytics_enabled=False) as pnginfo_interface:
978
+ with gr.Row().style(equal_height=False):
979
+ with gr.Column(variant='panel'):
980
+ image = gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil")
981
+
982
+ with gr.Column(variant='panel'):
983
+ html = gr.HTML()
984
+ generation_info = gr.Textbox(visible=False, elem_id="pnginfo_generation_info")
985
+ html2 = gr.HTML()
986
+ with gr.Row():
987
+ buttons = parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"])
988
+
989
+ # for tabname, button in buttons.items():
990
+ # parameters_copypaste.register_paste_params_button(parameters_copypaste.ParamBinding(
991
+ # paste_button=button, tabname=tabname, source_text_component=generation_info, source_image_component=image,
992
+ # ))
993
+ #
994
+ # image.change(
995
+ # fn=wrap_gradio_call(modules.extras.run_pnginfo),
996
+ # inputs=[image],
997
+ # outputs=[html, generation_info, html2],
998
+ # )
999
+
1000
+ def update_interp_description(value):
1001
+ interp_description_css = "<p style='margin-bottom: 2.5em'>{}</p>"
1002
+ interp_descriptions = {
1003
+ "No interpolation": interp_description_css.format("No interpolation will be used. Requires one model; A. Allows for format conversion and VAE baking."),
1004
+ "Weighted sum": interp_description_css.format("A weighted sum will be used for interpolation. Requires two models; A and B. The result is calculated as A * (1 - M) + B * M"),
1005
+ "Add difference": interp_description_css.format("The difference between the last two models will be added to the first. Requires three models; A, B and C. The result is calculated as A + (B - C) * M")
1006
+ }
1007
+ return interp_descriptions[value]
1008
+
1009
+ with gr.Blocks(analytics_enabled=False) as modelmerger_interface:
1010
+ with gr.Row().style(equal_height=False):
1011
+ with gr.Column(variant='compact'):
1012
+ interp_description = gr.HTML(value=update_interp_description("Weighted sum"), elem_id="modelmerger_interp_description")
1013
+
1014
+ with FormRow(elem_id="modelmerger_models"):
1015
+ primary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_primary_model_name", label="Primary model (A)")
1016
+ create_refresh_button(primary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_A")
1017
+
1018
+ secondary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_secondary_model_name", label="Secondary model (B)")
1019
+ create_refresh_button(secondary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_B")
1020
+
1021
+ tertiary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_tertiary_model_name", label="Tertiary model (C)")
1022
+ create_refresh_button(tertiary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_C")
1023
+
1024
+ custom_name = gr.Textbox(label="Custom Name (Optional)", elem_id="modelmerger_custom_name")
1025
+ interp_amount = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label='Multiplier (M) - set to 0 to get model A', value=0.3, elem_id="modelmerger_interp_amount")
1026
+ interp_method = gr.Radio(choices=["No interpolation", "Weighted sum", "Add difference"], value="Weighted sum", label="Interpolation Method", elem_id="modelmerger_interp_method")
1027
+ interp_method.change(fn=update_interp_description, inputs=[interp_method], outputs=[interp_description])
1028
+
1029
+ with FormRow():
1030
+ checkpoint_format = gr.Radio(choices=["ckpt", "safetensors"], value="ckpt", label="Checkpoint format", elem_id="modelmerger_checkpoint_format")
1031
+ save_as_half = gr.Checkbox(value=False, label="Save as float16", elem_id="modelmerger_save_as_half")
1032
+
1033
+ with FormRow():
1034
+ with gr.Column():
1035
+ config_source = gr.Radio(choices=["A, B or C", "B", "C", "Don't"], value="A, B or C", label="Copy config from", type="index", elem_id="modelmerger_config_method")
1036
+
1037
+ with gr.Column():
1038
+ with FormRow():
1039
+ bake_in_vae = gr.Dropdown(choices=["None"] + list(sd_vae.vae_dict), value="None", label="Bake in VAE", elem_id="modelmerger_bake_in_vae")
1040
+ create_refresh_button(bake_in_vae, sd_vae.refresh_vae_list, lambda: {"choices": ["None"] + list(sd_vae.vae_dict)}, "modelmerger_refresh_bake_in_vae")
1041
+
1042
+ with FormRow():
1043
+ discard_weights = gr.Textbox(value="", label="Discard weights with matching name", elem_id="modelmerger_discard_weights")
1044
+
1045
+ with gr.Row():
1046
+ modelmerger_merge = gr.Button(elem_id="modelmerger_merge", value="Merge", variant='primary')
1047
+
1048
+ with gr.Column(variant='compact', elem_id="modelmerger_results_container"):
1049
+ with gr.Group(elem_id="modelmerger_results_panel"):
1050
+ modelmerger_result = gr.HTML(elem_id="modelmerger_result", show_label=False)
1051
+
1052
+ with gr.Blocks(analytics_enabled=False) as train_interface:
1053
+ with gr.Row().style(equal_height=False):
1054
+ gr.HTML(value="<p style='margin-bottom: 0.7em'>See <b><a href=\"https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Textual-Inversion\">wiki</a></b> for detailed explanation.</p>")
1055
+
1056
+ with gr.Row(variant="compact").style(equal_height=False):
1057
+ with gr.Tabs(elem_id="train_tabs"):
1058
+
1059
+ with gr.Tab(label="Create embedding"):
1060
+ new_embedding_name = gr.Textbox(label="Name", elem_id="train_new_embedding_name")
1061
+ initialization_text = gr.Textbox(label="Initialization text", value="*", elem_id="train_initialization_text")
1062
+ nvpt = gr.Slider(label="Number of vectors per token", minimum=1, maximum=75, step=1, value=1, elem_id="train_nvpt")
1063
+ overwrite_old_embedding = gr.Checkbox(value=False, label="Overwrite Old Embedding", elem_id="train_overwrite_old_embedding")
1064
+
1065
+ with gr.Row():
1066
+ with gr.Column(scale=3):
1067
+ gr.HTML(value="")
1068
+
1069
+ with gr.Column():
1070
+ create_embedding = gr.Button(value="Create embedding", variant='primary', elem_id="train_create_embedding")
1071
+
1072
+ with gr.Tab(label="Create hypernetwork"):
1073
+ new_hypernetwork_name = gr.Textbox(label="Name", elem_id="train_new_hypernetwork_name")
1074
+ new_hypernetwork_sizes = gr.CheckboxGroup(label="Modules", value=["768", "320", "640", "1280"], choices=["768", "1024", "320", "640", "1280"], elem_id="train_new_hypernetwork_sizes")
1075
+ new_hypernetwork_layer_structure = gr.Textbox("1, 2, 1", label="Enter hypernetwork layer structure", placeholder="1st and last digit must be 1. ex:'1, 2, 1'", elem_id="train_new_hypernetwork_layer_structure")
1076
+ new_hypernetwork_activation_func = gr.Dropdown(value="linear", label="Select activation function of hypernetwork. Recommended : Swish / Linear(none)", choices=modules.hypernetworks.ui.keys, elem_id="train_new_hypernetwork_activation_func")
1077
+ new_hypernetwork_initialization_option = gr.Dropdown(value = "Normal", label="Select Layer weights initialization. Recommended: Kaiming for relu-like, Xavier for sigmoid-like, Normal otherwise", choices=["Normal", "KaimingUniform", "KaimingNormal", "XavierUniform", "XavierNormal"], elem_id="train_new_hypernetwork_initialization_option")
1078
+ new_hypernetwork_add_layer_norm = gr.Checkbox(label="Add layer normalization", elem_id="train_new_hypernetwork_add_layer_norm")
1079
+ new_hypernetwork_use_dropout = gr.Checkbox(label="Use dropout", elem_id="train_new_hypernetwork_use_dropout")
1080
+ new_hypernetwork_dropout_structure = gr.Textbox("0, 0, 0", label="Enter hypernetwork Dropout structure (or empty). Recommended : 0~0.35 incrementing sequence: 0, 0.05, 0.15", placeholder="1st and last digit must be 0 and values should be between 0 and 1. ex:'0, 0.01, 0'")
1081
+ overwrite_old_hypernetwork = gr.Checkbox(value=False, label="Overwrite Old Hypernetwork", elem_id="train_overwrite_old_hypernetwork")
1082
+
1083
+ with gr.Row():
1084
+ with gr.Column(scale=3):
1085
+ gr.HTML(value="")
1086
+
1087
+ with gr.Column():
1088
+ create_hypernetwork = gr.Button(value="Create hypernetwork", variant='primary', elem_id="train_create_hypernetwork")
1089
+
1090
+ with gr.Tab(label="Preprocess images"):
1091
+ process_src = gr.Textbox(label='Source directory', elem_id="train_process_src")
1092
+ process_dst = gr.Textbox(label='Destination directory', elem_id="train_process_dst")
1093
+ process_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_process_width")
1094
+ process_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_process_height")
1095
+ preprocess_txt_action = gr.Dropdown(label='Existing Caption txt Action', value="ignore", choices=["ignore", "copy", "prepend", "append"], elem_id="train_preprocess_txt_action")
1096
+
1097
+ with gr.Row():
1098
+ process_flip = gr.Checkbox(label='Create flipped copies', elem_id="train_process_flip")
1099
+ process_split = gr.Checkbox(label='Split oversized images', elem_id="train_process_split")
1100
+ process_focal_crop = gr.Checkbox(label='Auto focal point crop', elem_id="train_process_focal_crop")
1101
+ process_multicrop = gr.Checkbox(label='Auto-sized crop', elem_id="train_process_multicrop")
1102
+ process_caption = gr.Checkbox(label='Use BLIP for caption', elem_id="train_process_caption")
1103
+ process_caption_deepbooru = gr.Checkbox(label='Use deepbooru for caption', visible=True, elem_id="train_process_caption_deepbooru")
1104
+
1105
+ with gr.Row(visible=False) as process_split_extra_row:
1106
+ process_split_threshold = gr.Slider(label='Split image threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_split_threshold")
1107
+ process_overlap_ratio = gr.Slider(label='Split image overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="train_process_overlap_ratio")
1108
+
1109
+ with gr.Row(visible=False) as process_focal_crop_row:
1110
+ process_focal_crop_face_weight = gr.Slider(label='Focal point face weight', value=0.9, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_face_weight")
1111
+ process_focal_crop_entropy_weight = gr.Slider(label='Focal point entropy weight', value=0.15, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_entropy_weight")
1112
+ process_focal_crop_edges_weight = gr.Slider(label='Focal point edges weight', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="train_process_focal_crop_edges_weight")
1113
+ process_focal_crop_debug = gr.Checkbox(label='Create debug image', elem_id="train_process_focal_crop_debug")
1114
+
1115
+ with gr.Column(visible=False) as process_multicrop_col:
1116
+ gr.Markdown('Each image is center-cropped with an automatically chosen width and height.')
1117
+ with gr.Row():
1118
+ process_multicrop_mindim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension lower bound", value=384, elem_id="train_process_multicrop_mindim")
1119
+ process_multicrop_maxdim = gr.Slider(minimum=64, maximum=2048, step=8, label="Dimension upper bound", value=768, elem_id="train_process_multicrop_maxdim")
1120
+ with gr.Row():
1121
+ process_multicrop_minarea = gr.Slider(minimum=64*64, maximum=2048*2048, step=1, label="Area lower bound", value=64*64, elem_id="train_process_multicrop_minarea")
1122
+ process_multicrop_maxarea = gr.Slider(minimum=64*64, maximum=2048*2048, step=1, label="Area upper bound", value=640*640, elem_id="train_process_multicrop_maxarea")
1123
+ with gr.Row():
1124
+ process_multicrop_objective = gr.Radio(["Maximize area", "Minimize error"], value="Maximize area", label="Resizing objective", elem_id="train_process_multicrop_objective")
1125
+ process_multicrop_threshold = gr.Slider(minimum=0, maximum=1, step=0.01, label="Error threshold", value=0.1, elem_id="train_process_multicrop_threshold")
1126
+
1127
+ with gr.Row():
1128
+ with gr.Column(scale=3):
1129
+ gr.HTML(value="")
1130
+
1131
+ with gr.Column():
1132
+ with gr.Row():
1133
+ interrupt_preprocessing = gr.Button("Interrupt", elem_id="train_interrupt_preprocessing")
1134
+ run_preprocess = gr.Button(value="Preprocess", variant='primary', elem_id="train_run_preprocess")
1135
+
1136
+ process_split.change(
1137
+ fn=lambda show: gr_show(show),
1138
+ inputs=[process_split],
1139
+ outputs=[process_split_extra_row],
1140
+ )
1141
+
1142
+ process_focal_crop.change(
1143
+ fn=lambda show: gr_show(show),
1144
+ inputs=[process_focal_crop],
1145
+ outputs=[process_focal_crop_row],
1146
+ )
1147
+
1148
+ process_multicrop.change(
1149
+ fn=lambda show: gr_show(show),
1150
+ inputs=[process_multicrop],
1151
+ outputs=[process_multicrop_col],
1152
+ )
1153
+
1154
+ def get_textual_inversion_template_names():
1155
+ return sorted([x for x in textual_inversion.textual_inversion_templates])
1156
+
1157
+ with gr.Tab(label="Train"):
1158
+ gr.HTML(value="<p style='margin-bottom: 0.7em'>Train an embedding or Hypernetwork; you must specify a directory with a set of 1:1 ratio images <a href=\"https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Textual-Inversion\" style=\"font-weight:bold;\">[wiki]</a></p>")
1159
+ with FormRow():
1160
+ train_embedding_name = gr.Dropdown(label='Embedding', elem_id="train_embedding", choices=sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys()))
1161
+ create_refresh_button(train_embedding_name, sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings, lambda: {"choices": sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys())}, "refresh_train_embedding_name")
1162
+
1163
+ train_hypernetwork_name = gr.Dropdown(label='Hypernetwork', elem_id="train_hypernetwork", choices=[x for x in shared.hypernetworks.keys()])
1164
+ create_refresh_button(train_hypernetwork_name, shared.reload_hypernetworks, lambda: {"choices": sorted([x for x in shared.hypernetworks.keys()])}, "refresh_train_hypernetwork_name")
1165
+
1166
+ with FormRow():
1167
+ embedding_learn_rate = gr.Textbox(label='Embedding Learning rate', placeholder="Embedding Learning rate", value="0.005", elem_id="train_embedding_learn_rate")
1168
+ hypernetwork_learn_rate = gr.Textbox(label='Hypernetwork Learning rate', placeholder="Hypernetwork Learning rate", value="0.00001", elem_id="train_hypernetwork_learn_rate")
1169
+
1170
+ with FormRow():
1171
+ clip_grad_mode = gr.Dropdown(value="disabled", label="Gradient Clipping", choices=["disabled", "value", "norm"])
1172
+ clip_grad_value = gr.Textbox(placeholder="Gradient clip value", value="0.1", show_label=False)
1173
+
1174
+ with FormRow():
1175
+ batch_size = gr.Number(label='Batch size', value=1, precision=0, elem_id="train_batch_size")
1176
+ gradient_step = gr.Number(label='Gradient accumulation steps', value=1, precision=0, elem_id="train_gradient_step")
1177
+
1178
+ dataset_directory = gr.Textbox(label='Dataset directory', placeholder="Path to directory with input images", elem_id="train_dataset_directory")
1179
+ log_directory = gr.Textbox(label='Log directory', placeholder="Path to directory where to write outputs", value="textual_inversion", elem_id="train_log_directory")
1180
+
1181
+ with FormRow():
1182
+ template_file = gr.Dropdown(label='Prompt template', value="style_filewords.txt", elem_id="train_template_file", choices=get_textual_inversion_template_names())
1183
+ create_refresh_button(template_file, textual_inversion.list_textual_inversion_templates, lambda: {"choices": get_textual_inversion_template_names()}, "refrsh_train_template_file")
1184
+
1185
+ training_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_training_width")
1186
+ training_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_training_height")
1187
+ varsize = gr.Checkbox(label="Do not resize images", value=False, elem_id="train_varsize")
1188
+ steps = gr.Number(label='Max steps', value=100000, precision=0, elem_id="train_steps")
1189
+
1190
+ with FormRow():
1191
+ create_image_every = gr.Number(label='Save an image to log directory every N steps, 0 to disable', value=500, precision=0, elem_id="train_create_image_every")
1192
+ save_embedding_every = gr.Number(label='Save a copy of embedding to log directory every N steps, 0 to disable', value=500, precision=0, elem_id="train_save_embedding_every")
1193
+
1194
+ use_weight = gr.Checkbox(label="Use PNG alpha channel as loss weight", value=False, elem_id="use_weight")
1195
+
1196
+ save_image_with_stored_embedding = gr.Checkbox(label='Save images with embedding in PNG chunks', value=True, elem_id="train_save_image_with_stored_embedding")
1197
+ preview_from_txt2img = gr.Checkbox(label='Read parameters (prompt, etc...) from txt2img tab when making previews', value=False, elem_id="train_preview_from_txt2img")
1198
+
1199
+ shuffle_tags = gr.Checkbox(label="Shuffle tags by ',' when creating prompts.", value=False, elem_id="train_shuffle_tags")
1200
+ tag_drop_out = gr.Slider(minimum=0, maximum=1, step=0.1, label="Drop out tags when creating prompts.", value=0, elem_id="train_tag_drop_out")
1201
+
1202
+ latent_sampling_method = gr.Radio(label='Choose latent sampling method', value="once", choices=['once', 'deterministic', 'random'], elem_id="train_latent_sampling_method")
1203
+
1204
+ with gr.Row():
1205
+ train_embedding = gr.Button(value="Train Embedding", variant='primary', elem_id="train_train_embedding")
1206
+ interrupt_training = gr.Button(value="Interrupt", elem_id="train_interrupt_training")
1207
+ train_hypernetwork = gr.Button(value="Train Hypernetwork", variant='primary', elem_id="train_train_hypernetwork")
1208
+
1209
+ params = script_callbacks.UiTrainTabParams(txt2img_preview_params)
1210
+
1211
+ script_callbacks.ui_train_tabs_callback(params)
1212
+
1213
+ with gr.Column(elem_id='ti_gallery_container'):
1214
+ ti_output = gr.Text(elem_id="ti_output", value="", show_label=False)
1215
+ ti_gallery = gr.Gallery(label='Output', show_label=False, elem_id='ti_gallery').style(grid=4)
1216
+ ti_progress = gr.HTML(elem_id="ti_progress", value="")
1217
+ ti_outcome = gr.HTML(elem_id="ti_error", value="")
1218
+
1219
+ create_embedding.click(
1220
+ fn=modules.textual_inversion.ui.create_embedding,
1221
+ inputs=[
1222
+ new_embedding_name,
1223
+ initialization_text,
1224
+ nvpt,
1225
+ overwrite_old_embedding,
1226
+ ],
1227
+ outputs=[
1228
+ train_embedding_name,
1229
+ ti_output,
1230
+ ti_outcome,
1231
+ ]
1232
+ )
1233
+
1234
+ create_hypernetwork.click(
1235
+ fn=modules.hypernetworks.ui.create_hypernetwork,
1236
+ inputs=[
1237
+ new_hypernetwork_name,
1238
+ new_hypernetwork_sizes,
1239
+ overwrite_old_hypernetwork,
1240
+ new_hypernetwork_layer_structure,
1241
+ new_hypernetwork_activation_func,
1242
+ new_hypernetwork_initialization_option,
1243
+ new_hypernetwork_add_layer_norm,
1244
+ new_hypernetwork_use_dropout,
1245
+ new_hypernetwork_dropout_structure
1246
+ ],
1247
+ outputs=[
1248
+ train_hypernetwork_name,
1249
+ ti_output,
1250
+ ti_outcome,
1251
+ ]
1252
+ )
1253
+
1254
+ run_preprocess.click(
1255
+ fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.preprocess, extra_outputs=[gr.update()]),
1256
+ _js="start_training_textual_inversion",
1257
+ inputs=[
1258
+ dummy_component,
1259
+ process_src,
1260
+ process_dst,
1261
+ process_width,
1262
+ process_height,
1263
+ preprocess_txt_action,
1264
+ process_flip,
1265
+ process_split,
1266
+ process_caption,
1267
+ process_caption_deepbooru,
1268
+ process_split_threshold,
1269
+ process_overlap_ratio,
1270
+ process_focal_crop,
1271
+ process_focal_crop_face_weight,
1272
+ process_focal_crop_entropy_weight,
1273
+ process_focal_crop_edges_weight,
1274
+ process_focal_crop_debug,
1275
+ process_multicrop,
1276
+ process_multicrop_mindim,
1277
+ process_multicrop_maxdim,
1278
+ process_multicrop_minarea,
1279
+ process_multicrop_maxarea,
1280
+ process_multicrop_objective,
1281
+ process_multicrop_threshold,
1282
+ ],
1283
+ outputs=[
1284
+ ti_output,
1285
+ ti_outcome,
1286
+ ],
1287
+ )
1288
+
1289
+ train_embedding.click(
1290
+ fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.train_embedding, extra_outputs=[gr.update()]),
1291
+ _js="start_training_textual_inversion",
1292
+ inputs=[
1293
+ dummy_component,
1294
+ train_embedding_name,
1295
+ embedding_learn_rate,
1296
+ batch_size,
1297
+ gradient_step,
1298
+ dataset_directory,
1299
+ log_directory,
1300
+ training_width,
1301
+ training_height,
1302
+ varsize,
1303
+ steps,
1304
+ clip_grad_mode,
1305
+ clip_grad_value,
1306
+ shuffle_tags,
1307
+ tag_drop_out,
1308
+ latent_sampling_method,
1309
+ use_weight,
1310
+ create_image_every,
1311
+ save_embedding_every,
1312
+ template_file,
1313
+ save_image_with_stored_embedding,
1314
+ preview_from_txt2img,
1315
+ *txt2img_preview_params,
1316
+ ],
1317
+ outputs=[
1318
+ ti_output,
1319
+ ti_outcome,
1320
+ ]
1321
+ )
1322
+
1323
+ train_hypernetwork.click(
1324
+ fn=wrap_gradio_gpu_call(modules.hypernetworks.ui.train_hypernetwork, extra_outputs=[gr.update()]),
1325
+ _js="start_training_textual_inversion",
1326
+ inputs=[
1327
+ dummy_component,
1328
+ train_hypernetwork_name,
1329
+ hypernetwork_learn_rate,
1330
+ batch_size,
1331
+ gradient_step,
1332
+ dataset_directory,
1333
+ log_directory,
1334
+ training_width,
1335
+ training_height,
1336
+ varsize,
1337
+ steps,
1338
+ clip_grad_mode,
1339
+ clip_grad_value,
1340
+ shuffle_tags,
1341
+ tag_drop_out,
1342
+ latent_sampling_method,
1343
+ use_weight,
1344
+ create_image_every,
1345
+ save_embedding_every,
1346
+ template_file,
1347
+ preview_from_txt2img,
1348
+ *txt2img_preview_params,
1349
+ ],
1350
+ outputs=[
1351
+ ti_output,
1352
+ ti_outcome,
1353
+ ]
1354
+ )
1355
+
1356
+ interrupt_training.click(
1357
+ fn=lambda: shared.state.interrupt(),
1358
+ inputs=[],
1359
+ outputs=[],
1360
+ )
1361
+
1362
+ interrupt_preprocessing.click(
1363
+ fn=lambda: shared.state.interrupt(),
1364
+ inputs=[],
1365
+ outputs=[],
1366
+ )
1367
+
1368
+ def create_setting_component(key, is_quicksettings=False):
1369
+ def fun():
1370
+ return opts.data[key] if key in opts.data else opts.data_labels[key].default
1371
+
1372
+ info = opts.data_labels[key]
1373
+ t = type(info.default)
1374
+
1375
+ args = info.component_args() if callable(info.component_args) else info.component_args
1376
+
1377
+ if info.component is not None:
1378
+ comp = info.component
1379
+ elif t == str:
1380
+ comp = gr.Textbox
1381
+ elif t == int:
1382
+ comp = gr.Number
1383
+ elif t == bool:
1384
+ comp = gr.Checkbox
1385
+ else:
1386
+ raise Exception(f'bad options item type: {str(t)} for key {key}')
1387
+
1388
+ elem_id = "setting_"+key
1389
+
1390
+ if info.refresh is not None:
1391
+ if is_quicksettings:
1392
+ res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
1393
+ create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key)
1394
+ else:
1395
+ with FormRow():
1396
+ res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
1397
+ create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key)
1398
+ else:
1399
+ res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
1400
+
1401
+ return res
1402
+
1403
+ components = []
1404
+ component_dict = {}
1405
+ shared.settings_components = component_dict
1406
+
1407
+ script_callbacks.ui_settings_callback()
1408
+ opts.reorder()
1409
+
1410
+ def run_settings(*args):
1411
+ changed = []
1412
+
1413
+ for key, value, comp in zip(opts.data_labels.keys(), args, components):
1414
+ assert comp == dummy_component or opts.same_type(value, opts.data_labels[key].default), f"Bad value for setting {key}: {value}; expecting {type(opts.data_labels[key].default).__name__}"
1415
+
1416
+ for key, value, comp in zip(opts.data_labels.keys(), args, components):
1417
+ if comp == dummy_component:
1418
+ continue
1419
+
1420
+ if opts.set(key, value):
1421
+ changed.append(key)
1422
+
1423
+ try:
1424
+ opts.save(shared.config_filename)
1425
+ except RuntimeError:
1426
+ return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.'
1427
+ return opts.dumpjson(), f'{len(changed)} settings changed{": " if len(changed) > 0 else ""}{", ".join(changed)}.'
1428
+
1429
+ def run_settings_single(value, key):
1430
+ if not opts.same_type(value, opts.data_labels[key].default):
1431
+ return gr.update(visible=True), opts.dumpjson()
1432
+
1433
+ if not opts.set(key, value):
1434
+ return gr.update(value=getattr(opts, key)), opts.dumpjson()
1435
+
1436
+ opts.save(shared.config_filename)
1437
+
1438
+ return get_value_for_setting(key), opts.dumpjson()
1439
+
1440
+ with gr.Blocks(analytics_enabled=False) as settings_interface:
1441
+ with gr.Row():
1442
+ with gr.Column(scale=6):
1443
+ settings_submit = gr.Button(value="Apply settings", variant='primary', elem_id="settings_submit")
1444
+ with gr.Column():
1445
+ restart_gradio = gr.Button(value='Reload UI', variant='primary', elem_id="settings_restart_gradio")
1446
+
1447
+ result = gr.HTML(elem_id="settings_result")
1448
+
1449
+ quicksettings_names = [x.strip() for x in opts.quicksettings.split(",")]
1450
+ quicksettings_names = {x: i for i, x in enumerate(quicksettings_names) if x != 'quicksettings'}
1451
+
1452
+ quicksettings_list = []
1453
+
1454
+ previous_section = None
1455
+ current_tab = None
1456
+ current_row = None
1457
+ with gr.Tabs(elem_id="settings"):
1458
+ for i, (k, item) in enumerate(opts.data_labels.items()):
1459
+ section_must_be_skipped = item.section[0] is None
1460
+
1461
+ if previous_section != item.section and not section_must_be_skipped:
1462
+ elem_id, text = item.section
1463
+
1464
+ if current_tab is not None:
1465
+ current_row.__exit__()
1466
+ current_tab.__exit__()
1467
+
1468
+ gr.Group()
1469
+ current_tab = gr.TabItem(elem_id="settings_{}".format(elem_id), label=text)
1470
+ current_tab.__enter__()
1471
+ current_row = gr.Column(variant='compact')
1472
+ current_row.__enter__()
1473
+
1474
+ previous_section = item.section
1475
+
1476
+ if k in quicksettings_names and not shared.cmd_opts.freeze_settings:
1477
+ quicksettings_list.append((i, k, item))
1478
+ components.append(dummy_component)
1479
+ elif section_must_be_skipped:
1480
+ components.append(dummy_component)
1481
+ else:
1482
+ component = create_setting_component(k)
1483
+ component_dict[k] = component
1484
+ components.append(component)
1485
+
1486
+ if current_tab is not None:
1487
+ current_row.__exit__()
1488
+ current_tab.__exit__()
1489
+
1490
+ with gr.TabItem("Actions"):
1491
+ request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications")
1492
+ download_localization = gr.Button(value='Download localization template', elem_id="download_localization")
1493
+ reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary', elem_id="settings_reload_script_bodies")
1494
+
1495
+ with gr.TabItem("Licenses"):
1496
+ gr.HTML(shared.html("licenses.html"), elem_id="licenses")
1497
+
1498
+ gr.Button(value="Show all pages", elem_id="settings_show_all_pages")
1499
+
1500
+ request_notifications.click(
1501
+ fn=lambda: None,
1502
+ inputs=[],
1503
+ outputs=[],
1504
+ _js='function(){}'
1505
+ )
1506
+
1507
+ download_localization.click(
1508
+ fn=lambda: None,
1509
+ inputs=[],
1510
+ outputs=[],
1511
+ _js='download_localization'
1512
+ )
1513
+
1514
+ def reload_scripts():
1515
+ modules.scripts.reload_script_body_only()
1516
+ reload_javascript() # need to refresh the html page
1517
+
1518
+ reload_script_bodies.click(
1519
+ fn=reload_scripts,
1520
+ inputs=[],
1521
+ outputs=[]
1522
+ )
1523
+
1524
+ def request_restart():
1525
+ shared.state.interrupt()
1526
+ shared.state.need_restart = True
1527
+
1528
+ restart_gradio.click(
1529
+ fn=request_restart,
1530
+ _js='restart_reload',
1531
+ inputs=[],
1532
+ outputs=[],
1533
+ )
1534
+
1535
+ interfaces = [
1536
+ (txt2img_interface, "txt2img", "txt2img"),
1537
+ (img2img_interface, "img2img", "img2img"),
1538
+ (extras_interface, "Extras", "extras"),
1539
+ (pnginfo_interface, "PNG Info", "pnginfo"),
1540
+ (modelmerger_interface, "Checkpoint Merger", "modelmerger"),
1541
+ (train_interface, "Train", "ti"),
1542
+ ]
1543
+
1544
+ css = ""
1545
+
1546
+ for cssfile in modules.scripts.list_files_with_name("style.css"):
1547
+ if not os.path.isfile(cssfile):
1548
+ continue
1549
+
1550
+ with open(cssfile, "r", encoding="utf8") as file:
1551
+ css += file.read() + "\n"
1552
+
1553
+ if os.path.exists(os.path.join(data_path, "user.css")):
1554
+ with open(os.path.join(data_path, "user.css"), "r", encoding="utf8") as file:
1555
+ css += file.read() + "\n"
1556
+
1557
+ if not cmd_opts.no_progressbar_hiding:
1558
+ css += css_hide_progressbar
1559
+
1560
+ interfaces += script_callbacks.ui_tabs_callback()
1561
+ interfaces += [(settings_interface, "Settings", "settings")]
1562
+
1563
+ extensions_interface = ui_extensions.create_ui()
1564
+ interfaces += [(extensions_interface, "Extensions", "extensions")]
1565
+
1566
+ with gr.Blocks(css=css, analytics_enabled=False, title="Stable Diffusion") as demo:
1567
+ with gr.Row(elem_id="quicksettings", variant="compact"):
1568
+ for i, k, item in sorted(quicksettings_list, key=lambda x: quicksettings_names.get(x[1], x[0])):
1569
+ component = create_setting_component(k, is_quicksettings=True)
1570
+ component_dict[k] = component
1571
+
1572
+ parameters_copypaste.connect_paste_params_buttons()
1573
+
1574
+ with gr.Tabs(elem_id="tabs") as tabs:
1575
+ for interface, label, ifid in interfaces:
1576
+ with gr.TabItem(label, id=ifid, elem_id='tab_' + ifid):
1577
+ interface.render()
1578
+
1579
+ if os.path.exists(os.path.join(script_path, "notification.mp3")):
1580
+ audio_notification = gr.Audio(interactive=False, value=os.path.join(script_path, "notification.mp3"), elem_id="audio_notification", visible=False)
1581
+
1582
+ footer = shared.html("footer.html")
1583
+ footer = footer.format(versions=versions_html())
1584
+ gr.HTML(footer, elem_id="footer")
1585
+
1586
+ text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
1587
+ settings_submit.click(
1588
+ fn=wrap_gradio_call(run_settings, extra_outputs=[gr.update()]),
1589
+ inputs=components,
1590
+ outputs=[text_settings, result],
1591
+ )
1592
+
1593
+ for i, k, item in quicksettings_list:
1594
+ component = component_dict[k]
1595
+
1596
+ component.change(
1597
+ fn=lambda value, k=k: run_settings_single(value, key=k),
1598
+ inputs=[component],
1599
+ outputs=[component, text_settings],
1600
+ )
1601
+
1602
+ text_settings.change(
1603
+ fn=lambda: gr.update(visible=shared.sd_model and shared.sd_model.cond_stage_key == "edit"),
1604
+ inputs=[],
1605
+ outputs=[image_cfg_scale],
1606
+ )
1607
+
1608
+ button_set_checkpoint = gr.Button('Change checkpoint', elem_id='change_checkpoint', visible=False)
1609
+ button_set_checkpoint.click(
1610
+ fn=lambda value, _: run_settings_single(value, key='sd_model_checkpoint'),
1611
+ _js="function(v){ var res = desiredCheckpointName; desiredCheckpointName = ''; return [res || v, null]; }",
1612
+ inputs=[component_dict['sd_model_checkpoint'], dummy_component],
1613
+ outputs=[component_dict['sd_model_checkpoint'], text_settings],
1614
+ )
1615
+
1616
+ component_keys = [k for k in opts.data_labels.keys() if k in component_dict]
1617
+
1618
+ def get_settings_values():
1619
+ return [get_value_for_setting(key) for key in component_keys]
1620
+
1621
+ demo.load(
1622
+ fn=get_settings_values,
1623
+ inputs=[],
1624
+ outputs=[component_dict[k] for k in component_keys],
1625
+ )
1626
+
1627
+ def modelmerger(*args):
1628
+ try:
1629
+ results = modules.extras.run_modelmerger(*args)
1630
+ except Exception as e:
1631
+ print("Error loading/saving model file:", file=sys.stderr)
1632
+ print(traceback.format_exc(), file=sys.stderr)
1633
+ modules.sd_models.list_models() # to remove the potentially missing models from the list
1634
+ return [*[gr.Dropdown.update(choices=modules.sd_models.checkpoint_tiles()) for _ in range(4)], f"Error merging checkpoints: {e}"]
1635
+ return results
1636
+
1637
+ modelmerger_merge.click(fn=lambda: '', inputs=[], outputs=[modelmerger_result])
1638
+ modelmerger_merge.click(
1639
+ fn=wrap_gradio_gpu_call(modelmerger, extra_outputs=lambda: [gr.update() for _ in range(4)]),
1640
+ _js='modelmerger',
1641
+ inputs=[
1642
+ dummy_component,
1643
+ primary_model_name,
1644
+ secondary_model_name,
1645
+ tertiary_model_name,
1646
+ interp_method,
1647
+ interp_amount,
1648
+ save_as_half,
1649
+ custom_name,
1650
+ checkpoint_format,
1651
+ config_source,
1652
+ bake_in_vae,
1653
+ discard_weights,
1654
+ ],
1655
+ outputs=[
1656
+ primary_model_name,
1657
+ secondary_model_name,
1658
+ tertiary_model_name,
1659
+ component_dict['sd_model_checkpoint'],
1660
+ modelmerger_result,
1661
+ ]
1662
+ )
1663
+
1664
+ ui_config_file = cmd_opts.ui_config_file
1665
+ ui_settings = {}
1666
+ settings_count = len(ui_settings)
1667
+ error_loading = False
1668
+
1669
+ try:
1670
+ if os.path.exists(ui_config_file):
1671
+ with open(ui_config_file, "r", encoding="utf8") as file:
1672
+ ui_settings = json.load(file)
1673
+ except Exception:
1674
+ error_loading = True
1675
+ print("Error loading settings:", file=sys.stderr)
1676
+ print(traceback.format_exc(), file=sys.stderr)
1677
+
1678
+ def loadsave(path, x):
1679
+ def apply_field(obj, field, condition=None, init_field=None):
1680
+ key = path + "/" + field
1681
+
1682
+ if getattr(obj, 'custom_script_source', None) is not None:
1683
+ key = 'customscript/' + obj.custom_script_source + '/' + key
1684
+
1685
+ if getattr(obj, 'do_not_save_to_config', False):
1686
+ return
1687
+
1688
+ saved_value = ui_settings.get(key, None)
1689
+ if saved_value is None:
1690
+ ui_settings[key] = getattr(obj, field)
1691
+ elif condition and not condition(saved_value):
1692
+ pass
1693
+
1694
+ # this warning is generally not useful;
1695
+ # print(f'Warning: Bad ui setting value: {key}: {saved_value}; Default value "{getattr(obj, field)}" will be used instead.')
1696
+ else:
1697
+ setattr(obj, field, saved_value)
1698
+ if init_field is not None:
1699
+ init_field(saved_value)
1700
+
1701
+ if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown] and x.visible:
1702
+ apply_field(x, 'visible')
1703
+
1704
+ if type(x) == gr.Slider:
1705
+ apply_field(x, 'value')
1706
+ apply_field(x, 'minimum')
1707
+ apply_field(x, 'maximum')
1708
+ apply_field(x, 'step')
1709
+
1710
+ if type(x) == gr.Radio:
1711
+ apply_field(x, 'value', lambda val: val in x.choices)
1712
+
1713
+ if type(x) == gr.Checkbox:
1714
+ apply_field(x, 'value')
1715
+
1716
+ if type(x) == gr.Textbox:
1717
+ apply_field(x, 'value')
1718
+
1719
+ if type(x) == gr.Number:
1720
+ apply_field(x, 'value')
1721
+
1722
+ if type(x) == gr.Dropdown:
1723
+ def check_dropdown(val):
1724
+ if getattr(x, 'multiselect', False):
1725
+ return all([value in x.choices for value in val])
1726
+ else:
1727
+ return val in x.choices
1728
+
1729
+ apply_field(x, 'value', check_dropdown, getattr(x, 'init_field', None))
1730
+
1731
+ visit(txt2img_interface, loadsave, "txt2img")
1732
+ visit(img2img_interface, loadsave, "img2img")
1733
+ visit(extras_interface, loadsave, "extras")
1734
+ visit(modelmerger_interface, loadsave, "modelmerger")
1735
+ visit(train_interface, loadsave, "train")
1736
+
1737
+ if not error_loading and (not os.path.exists(ui_config_file) or settings_count != len(ui_settings)):
1738
+ with open(ui_config_file, "w", encoding="utf8") as file:
1739
+ json.dump(ui_settings, file, indent=4)
1740
+
1741
+ # Required as a workaround for change() event not triggering when loading values from ui-config.json
1742
+ interp_description.value = update_interp_description(interp_method.value)
1743
+
1744
+ return demo
1745
+
1746
+
1747
+ def reload_javascript():
1748
+ head = f'<script type="text/javascript" src="file={os.path.abspath("script.js")}?{os.path.getmtime("script.js")}"></script>\n'
1749
+
1750
+ inline = f"{localization.localization_js(shared.opts.localization)};"
1751
+ if cmd_opts.theme is not None:
1752
+ inline += f"set_theme('{cmd_opts.theme}');"
1753
+
1754
+ for script in modules.scripts.list_scripts("javascript", ".js"):
1755
+ head += f'<script type="text/javascript" src="file={script.path}?{os.path.getmtime(script.path)}"></script>\n'
1756
+
1757
+ head += f'<script type="text/javascript">{inline}</script>\n'
1758
+
1759
+ def template_response(*args, **kwargs):
1760
+ res = shared.GradioTemplateResponseOriginal(*args, **kwargs)
1761
+ res.body = res.body.replace(b'</head>', f'{head}</head>'.encode("utf8"))
1762
+ res.init_headers()
1763
+ return res
1764
+
1765
+ gradio.routes.templates.TemplateResponse = template_response
1766
+
1767
+
1768
+ if not hasattr(shared, 'GradioTemplateResponseOriginal'):
1769
+ shared.GradioTemplateResponseOriginal = gradio.routes.templates.TemplateResponse
1770
+
1771
+
1772
+ def versions_html():
1773
+ import torch
1774
+ import launch
1775
+
1776
+ python_version = ".".join([str(x) for x in sys.version_info[0:3]])
1777
+ commit = launch.commit_hash()
1778
+ short_commit = commit[0:8]
1779
+
1780
+ if shared.xformers_available:
1781
+ import xformers
1782
+ xformers_version = xformers.__version__
1783
+ else:
1784
+ xformers_version = "N/A"
1785
+
1786
+ return f"""
1787
+ python: <span title="{sys.version}">{python_version}</span>
1788
+ β€€β€’β€€
1789
+ torch: {getattr(torch, '__long_version__',torch.__version__)}
1790
+ β€€β€’β€€
1791
+ xformers: {xformers_version}
1792
+ β€€β€’β€€
1793
+ gradio: {gr.__version__}
1794
+ β€€β€’β€€
1795
+ commit: <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/{commit}">{short_commit}</a>
1796
+ β€€β€’β€€
1797
+ checkpoint: <a id="sd_checkpoint_hash">N/A</a>
1798
+ """