Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/modules/infotext_utils.py
3055 views
1
from __future__ import annotations
2
import base64
3
import io
4
import json
5
import os
6
import re
7
import sys
8
9
import gradio as gr
10
from modules.paths import data_path
11
from modules import shared, ui_tempdir, script_callbacks, processing, infotext_versions, images, prompt_parser, errors
12
from PIL import Image
13
14
sys.modules['modules.generation_parameters_copypaste'] = sys.modules[__name__] # alias for old name
15
16
re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
17
re_param = re.compile(re_param_code)
18
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
19
re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
20
type_of_gr_update = type(gr.update())
21
22
23
class ParamBinding:
24
def __init__(self, paste_button, tabname, source_text_component=None, source_image_component=None, source_tabname=None, override_settings_component=None, paste_field_names=None):
25
self.paste_button = paste_button
26
self.tabname = tabname
27
self.source_text_component = source_text_component
28
self.source_image_component = source_image_component
29
self.source_tabname = source_tabname
30
self.override_settings_component = override_settings_component
31
self.paste_field_names = paste_field_names or []
32
33
34
class PasteField(tuple):
35
def __new__(cls, component, target, *, api=None):
36
return super().__new__(cls, (component, target))
37
38
def __init__(self, component, target, *, api=None):
39
super().__init__()
40
41
self.api = api
42
self.component = component
43
self.label = target if isinstance(target, str) else None
44
self.function = target if callable(target) else None
45
46
47
paste_fields: dict[str, dict] = {}
48
registered_param_bindings: list[ParamBinding] = []
49
50
51
def reset():
52
paste_fields.clear()
53
registered_param_bindings.clear()
54
55
56
def quote(text):
57
if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
58
return text
59
60
return json.dumps(text, ensure_ascii=False)
61
62
63
def unquote(text):
64
if len(text) == 0 or text[0] != '"' or text[-1] != '"':
65
return text
66
67
try:
68
return json.loads(text)
69
except Exception:
70
return text
71
72
73
def image_from_url_text(filedata):
74
if filedata is None:
75
return None
76
77
if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
78
filedata = filedata[0]
79
80
if type(filedata) == dict and filedata.get("is_file", False):
81
filename = filedata["name"]
82
is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
83
assert is_in_right_dir, 'trying to open image file outside of allowed directories'
84
85
filename = filename.rsplit('?', 1)[0]
86
return images.read(filename)
87
88
if type(filedata) == list:
89
if len(filedata) == 0:
90
return None
91
92
filedata = filedata[0]
93
94
if filedata.startswith("data:image/png;base64,"):
95
filedata = filedata[len("data:image/png;base64,"):]
96
97
filedata = base64.decodebytes(filedata.encode('utf-8'))
98
image = images.read(io.BytesIO(filedata))
99
return image
100
101
102
def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
103
104
if fields:
105
for i in range(len(fields)):
106
if not isinstance(fields[i], PasteField):
107
fields[i] = PasteField(*fields[i])
108
109
paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
110
111
# backwards compatibility for existing extensions
112
import modules.ui
113
if tabname == 'txt2img':
114
modules.ui.txt2img_paste_fields = fields
115
elif tabname == 'img2img':
116
modules.ui.img2img_paste_fields = fields
117
118
119
def create_buttons(tabs_list):
120
buttons = {}
121
for tab in tabs_list:
122
buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
123
return buttons
124
125
126
def bind_buttons(buttons, send_image, send_generate_info):
127
"""old function for backwards compatibility; do not use this, use register_paste_params_button"""
128
for tabname, button in buttons.items():
129
source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
130
source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
131
132
register_paste_params_button(ParamBinding(paste_button=button, tabname=tabname, source_text_component=source_text_component, source_image_component=send_image, source_tabname=source_tabname))
133
134
135
def register_paste_params_button(binding: ParamBinding):
136
registered_param_bindings.append(binding)
137
138
139
def connect_paste_params_buttons():
140
for binding in registered_param_bindings:
141
destination_image_component = paste_fields[binding.tabname]["init_img"]
142
fields = paste_fields[binding.tabname]["fields"]
143
override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
144
145
destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
146
destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
147
148
if binding.source_image_component and destination_image_component:
149
need_send_dementions = destination_width_component and binding.tabname != 'inpaint'
150
if isinstance(binding.source_image_component, gr.Gallery):
151
func = send_image_and_dimensions if need_send_dementions else image_from_url_text
152
jsfunc = "extract_image_from_gallery"
153
else:
154
func = send_image_and_dimensions if need_send_dementions else lambda x: x
155
jsfunc = None
156
157
binding.paste_button.click(
158
fn=func,
159
_js=jsfunc,
160
inputs=[binding.source_image_component],
161
outputs=[destination_image_component, destination_width_component, destination_height_component] if need_send_dementions else [destination_image_component],
162
show_progress=False,
163
)
164
165
if binding.source_text_component is not None and fields is not None:
166
connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
167
168
if binding.source_tabname is not None and fields is not None:
169
paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
170
binding.paste_button.click(
171
fn=lambda *x: x,
172
inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
173
outputs=[field for field, name in fields if name in paste_field_names],
174
show_progress=False,
175
)
176
177
binding.paste_button.click(
178
fn=None,
179
_js=f"switch_to_{binding.tabname}",
180
inputs=None,
181
outputs=None,
182
show_progress=False,
183
)
184
185
186
def send_image_and_dimensions(x):
187
if isinstance(x, Image.Image):
188
img = x
189
else:
190
img = image_from_url_text(x)
191
192
if shared.opts.send_size and isinstance(img, Image.Image):
193
w = img.width
194
h = img.height
195
else:
196
w = gr.update()
197
h = gr.update()
198
199
return img, w, h
200
201
202
def restore_old_hires_fix_params(res):
203
"""for infotexts that specify old First pass size parameter, convert it into
204
width, height, and hr scale"""
205
206
firstpass_width = res.get('First pass size-1', None)
207
firstpass_height = res.get('First pass size-2', None)
208
209
if shared.opts.use_old_hires_fix_width_height:
210
hires_width = int(res.get("Hires resize-1", 0))
211
hires_height = int(res.get("Hires resize-2", 0))
212
213
if hires_width and hires_height:
214
res['Size-1'] = hires_width
215
res['Size-2'] = hires_height
216
return
217
218
if firstpass_width is None or firstpass_height is None:
219
return
220
221
firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
222
width = int(res.get("Size-1", 512))
223
height = int(res.get("Size-2", 512))
224
225
if firstpass_width == 0 or firstpass_height == 0:
226
firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
227
228
res['Size-1'] = firstpass_width
229
res['Size-2'] = firstpass_height
230
res['Hires resize-1'] = width
231
res['Hires resize-2'] = height
232
233
234
def parse_generation_parameters(x: str, skip_fields: list[str] | None = None):
235
"""parses generation parameters string, the one you see in text field under the picture in UI:
236
```
237
girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
238
Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
239
Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
240
```
241
242
returns a dict with field values
243
"""
244
if skip_fields is None:
245
skip_fields = shared.opts.infotext_skip_pasting
246
247
res = {}
248
249
prompt = ""
250
negative_prompt = ""
251
252
done_with_prompt = False
253
254
*lines, lastline = x.strip().split("\n")
255
if len(re_param.findall(lastline)) < 3:
256
lines.append(lastline)
257
lastline = ''
258
259
for line in lines:
260
line = line.strip()
261
if line.startswith("Negative prompt:"):
262
done_with_prompt = True
263
line = line[16:].strip()
264
if done_with_prompt:
265
negative_prompt += ("" if negative_prompt == "" else "\n") + line
266
else:
267
prompt += ("" if prompt == "" else "\n") + line
268
269
for k, v in re_param.findall(lastline):
270
try:
271
if v[0] == '"' and v[-1] == '"':
272
v = unquote(v)
273
274
m = re_imagesize.match(v)
275
if m is not None:
276
res[f"{k}-1"] = m.group(1)
277
res[f"{k}-2"] = m.group(2)
278
else:
279
res[k] = v
280
except Exception:
281
print(f"Error parsing \"{k}: {v}\"")
282
283
# Extract styles from prompt
284
if shared.opts.infotext_styles != "Ignore":
285
found_styles, prompt_no_styles, negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
286
287
same_hr_styles = True
288
if ("Hires prompt" in res or "Hires negative prompt" in res) and (infotext_ver > infotext_versions.v180_hr_styles if (infotext_ver := infotext_versions.parse_version(res.get("Version"))) else True):
289
hr_prompt, hr_negative_prompt = res.get("Hires prompt", prompt), res.get("Hires negative prompt", negative_prompt)
290
hr_found_styles, hr_prompt_no_styles, hr_negative_prompt_no_styles = shared.prompt_styles.extract_styles_from_prompt(hr_prompt, hr_negative_prompt)
291
if same_hr_styles := found_styles == hr_found_styles:
292
res["Hires prompt"] = '' if hr_prompt_no_styles == prompt_no_styles else hr_prompt_no_styles
293
res['Hires negative prompt'] = '' if hr_negative_prompt_no_styles == negative_prompt_no_styles else hr_negative_prompt_no_styles
294
295
if same_hr_styles:
296
prompt, negative_prompt = prompt_no_styles, negative_prompt_no_styles
297
if (shared.opts.infotext_styles == "Apply if any" and found_styles) or shared.opts.infotext_styles == "Apply":
298
res['Styles array'] = found_styles
299
300
res["Prompt"] = prompt
301
res["Negative prompt"] = negative_prompt
302
303
# Missing CLIP skip means it was set to 1 (the default)
304
if "Clip skip" not in res:
305
res["Clip skip"] = "1"
306
307
hypernet = res.get("Hypernet", None)
308
if hypernet is not None:
309
res["Prompt"] += f"""<hypernet:{hypernet}:{res.get("Hypernet strength", "1.0")}>"""
310
311
if "Hires resize-1" not in res:
312
res["Hires resize-1"] = 0
313
res["Hires resize-2"] = 0
314
315
if "Hires sampler" not in res:
316
res["Hires sampler"] = "Use same sampler"
317
318
if "Hires schedule type" not in res:
319
res["Hires schedule type"] = "Use same scheduler"
320
321
if "Hires checkpoint" not in res:
322
res["Hires checkpoint"] = "Use same checkpoint"
323
324
if "Hires prompt" not in res:
325
res["Hires prompt"] = ""
326
327
if "Hires negative prompt" not in res:
328
res["Hires negative prompt"] = ""
329
330
if "Mask mode" not in res:
331
res["Mask mode"] = "Inpaint masked"
332
333
if "Masked content" not in res:
334
res["Masked content"] = 'original'
335
336
if "Inpaint area" not in res:
337
res["Inpaint area"] = "Whole picture"
338
339
if "Masked area padding" not in res:
340
res["Masked area padding"] = 32
341
342
restore_old_hires_fix_params(res)
343
344
# Missing RNG means the default was set, which is GPU RNG
345
if "RNG" not in res:
346
res["RNG"] = "GPU"
347
348
if "Schedule type" not in res:
349
res["Schedule type"] = "Automatic"
350
351
if "Schedule max sigma" not in res:
352
res["Schedule max sigma"] = 0
353
354
if "Schedule min sigma" not in res:
355
res["Schedule min sigma"] = 0
356
357
if "Schedule rho" not in res:
358
res["Schedule rho"] = 0
359
360
if "VAE Encoder" not in res:
361
res["VAE Encoder"] = "Full"
362
363
if "VAE Decoder" not in res:
364
res["VAE Decoder"] = "Full"
365
366
if "FP8 weight" not in res:
367
res["FP8 weight"] = "Disable"
368
369
if "Cache FP16 weight for LoRA" not in res and res["FP8 weight"] != "Disable":
370
res["Cache FP16 weight for LoRA"] = False
371
372
prompt_attention = prompt_parser.parse_prompt_attention(prompt)
373
prompt_attention += prompt_parser.parse_prompt_attention(negative_prompt)
374
prompt_uses_emphasis = len(prompt_attention) != len([p for p in prompt_attention if p[1] == 1.0 or p[0] == 'BREAK'])
375
if "Emphasis" not in res and prompt_uses_emphasis:
376
res["Emphasis"] = "Original"
377
378
if "Refiner switch by sampling steps" not in res:
379
res["Refiner switch by sampling steps"] = False
380
381
infotext_versions.backcompat(res)
382
383
for key in skip_fields:
384
res.pop(key, None)
385
386
return res
387
388
389
infotext_to_setting_name_mapping = [
390
391
]
392
"""Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
393
Example content:
394
395
infotext_to_setting_name_mapping = [
396
('Conditional mask weight', 'inpainting_mask_weight'),
397
('Model hash', 'sd_model_checkpoint'),
398
('ENSD', 'eta_noise_seed_delta'),
399
('Schedule type', 'k_sched_type'),
400
]
401
"""
402
403
404
def create_override_settings_dict(text_pairs):
405
"""creates processing's override_settings parameters from gradio's multiselect
406
407
Example input:
408
['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
409
410
Example output:
411
{'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
412
"""
413
414
res = {}
415
416
params = {}
417
for pair in text_pairs:
418
k, v = pair.split(":", maxsplit=1)
419
420
params[k] = v.strip()
421
422
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
423
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
424
value = params.get(param_name, None)
425
426
if value is None:
427
continue
428
429
res[setting_name] = shared.opts.cast_value(setting_name, value)
430
431
return res
432
433
434
def get_override_settings(params, *, skip_fields=None):
435
"""Returns a list of settings overrides from the infotext parameters dictionary.
436
437
This function checks the `params` dictionary for any keys that correspond to settings in `shared.opts` and returns
438
a list of tuples containing the parameter name, setting name, and new value cast to correct type.
439
440
It checks for conditions before adding an override:
441
- ignores settings that match the current value
442
- ignores parameter keys present in skip_fields argument.
443
444
Example input:
445
{"Clip skip": "2"}
446
447
Example output:
448
[("Clip skip", "CLIP_stop_at_last_layers", 2)]
449
"""
450
451
res = []
452
453
mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
454
for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
455
if param_name in (skip_fields or {}):
456
continue
457
458
v = params.get(param_name, None)
459
if v is None:
460
continue
461
462
if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
463
continue
464
465
v = shared.opts.cast_value(setting_name, v)
466
current_value = getattr(shared.opts, setting_name, None)
467
468
if v == current_value:
469
continue
470
471
res.append((param_name, setting_name, v))
472
473
return res
474
475
476
def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
477
def paste_func(prompt):
478
if not prompt and not shared.cmd_opts.hide_ui_dir_config and not shared.cmd_opts.no_prompt_history:
479
filename = os.path.join(data_path, "params.txt")
480
try:
481
with open(filename, "r", encoding="utf8") as file:
482
prompt = file.read()
483
except OSError:
484
pass
485
486
params = parse_generation_parameters(prompt)
487
script_callbacks.infotext_pasted_callback(prompt, params)
488
res = []
489
490
for output, key in paste_fields:
491
if callable(key):
492
try:
493
v = key(params)
494
except Exception:
495
errors.report(f"Error executing {key}", exc_info=True)
496
v = None
497
else:
498
v = params.get(key, None)
499
500
if v is None:
501
res.append(gr.update())
502
elif isinstance(v, type_of_gr_update):
503
res.append(v)
504
else:
505
try:
506
valtype = type(output.value)
507
508
if valtype == bool and v == "False":
509
val = False
510
elif valtype == int:
511
val = float(v)
512
else:
513
val = valtype(v)
514
515
res.append(gr.update(value=val))
516
except Exception:
517
res.append(gr.update())
518
519
return res
520
521
if override_settings_component is not None:
522
already_handled_fields = {key: 1 for _, key in paste_fields}
523
524
def paste_settings(params):
525
vals = get_override_settings(params, skip_fields=already_handled_fields)
526
527
vals_pairs = [f"{infotext_text}: {value}" for infotext_text, setting_name, value in vals]
528
529
return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
530
531
paste_fields = paste_fields + [(override_settings_component, paste_settings)]
532
533
button.click(
534
fn=paste_func,
535
inputs=[input_comp],
536
outputs=[x[0] for x in paste_fields],
537
show_progress=False,
538
)
539
button.click(
540
fn=None,
541
_js=f"recalculate_prompts_{tabname}",
542
inputs=[],
543
outputs=[],
544
show_progress=False,
545
)
546
547
548