generation_parameters_copypaste.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. from __future__ import annotations
  2. import base64
  3. import io
  4. import json
  5. import os
  6. import re
  7. import gradio as gr
  8. from modules.paths import data_path
  9. from modules import shared, ui_tempdir, script_callbacks, processing
  10. from PIL import Image
  11. re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
  12. re_param = re.compile(re_param_code)
  13. re_imagesize = re.compile(r"^(\d+)x(\d+)$")
  14. re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
  15. type_of_gr_update = type(gr.update())
  16. class ParamBinding:
  17. 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):
  18. self.paste_button = paste_button
  19. self.tabname = tabname
  20. self.source_text_component = source_text_component
  21. self.source_image_component = source_image_component
  22. self.source_tabname = source_tabname
  23. self.override_settings_component = override_settings_component
  24. self.paste_field_names = paste_field_names or []
  25. paste_fields: dict[str, dict] = {}
  26. registered_param_bindings: list[ParamBinding] = []
  27. def reset():
  28. paste_fields.clear()
  29. registered_param_bindings.clear()
  30. def quote(text):
  31. if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
  32. return text
  33. return json.dumps(text, ensure_ascii=False)
  34. def unquote(text):
  35. if len(text) == 0 or text[0] != '"' or text[-1] != '"':
  36. return text
  37. try:
  38. return json.loads(text)
  39. except Exception:
  40. return text
  41. def image_from_url_text(filedata):
  42. if filedata is None:
  43. return None
  44. if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
  45. filedata = filedata[0]
  46. if type(filedata) == dict and filedata.get("is_file", False):
  47. filename = filedata["name"]
  48. is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
  49. assert is_in_right_dir, 'trying to open image file outside of allowed directories'
  50. filename = filename.rsplit('?', 1)[0]
  51. return Image.open(filename)
  52. if type(filedata) == list:
  53. if len(filedata) == 0:
  54. return None
  55. filedata = filedata[0]
  56. if filedata.startswith("data:image/png;base64,"):
  57. filedata = filedata[len("data:image/png;base64,"):]
  58. filedata = base64.decodebytes(filedata.encode('utf-8'))
  59. image = Image.open(io.BytesIO(filedata))
  60. return image
  61. def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
  62. paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
  63. # backwards compatibility for existing extensions
  64. import modules.ui
  65. if tabname == 'txt2img':
  66. modules.ui.txt2img_paste_fields = fields
  67. elif tabname == 'img2img':
  68. modules.ui.img2img_paste_fields = fields
  69. def create_buttons(tabs_list):
  70. buttons = {}
  71. for tab in tabs_list:
  72. buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
  73. return buttons
  74. def bind_buttons(buttons, send_image, send_generate_info):
  75. """old function for backwards compatibility; do not use this, use register_paste_params_button"""
  76. for tabname, button in buttons.items():
  77. source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
  78. source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
  79. 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))
  80. def register_paste_params_button(binding: ParamBinding):
  81. registered_param_bindings.append(binding)
  82. def connect_paste_params_buttons():
  83. for binding in registered_param_bindings:
  84. destination_image_component = paste_fields[binding.tabname]["init_img"]
  85. fields = paste_fields[binding.tabname]["fields"]
  86. override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
  87. destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
  88. destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
  89. if binding.source_image_component and destination_image_component:
  90. if isinstance(binding.source_image_component, gr.Gallery):
  91. func = send_image_and_dimensions if destination_width_component else image_from_url_text
  92. jsfunc = "extract_image_from_gallery"
  93. else:
  94. func = send_image_and_dimensions if destination_width_component else lambda x: x
  95. jsfunc = None
  96. binding.paste_button.click(
  97. fn=func,
  98. _js=jsfunc,
  99. inputs=[binding.source_image_component],
  100. outputs=[destination_image_component, destination_width_component, destination_height_component] if destination_width_component else [destination_image_component],
  101. show_progress=False,
  102. )
  103. if binding.source_text_component is not None and fields is not None:
  104. connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
  105. if binding.source_tabname is not None and fields is not None:
  106. paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
  107. binding.paste_button.click(
  108. fn=lambda *x: x,
  109. inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
  110. outputs=[field for field, name in fields if name in paste_field_names],
  111. show_progress=False,
  112. )
  113. binding.paste_button.click(
  114. fn=None,
  115. _js=f"switch_to_{binding.tabname}",
  116. inputs=None,
  117. outputs=None,
  118. show_progress=False,
  119. )
  120. def send_image_and_dimensions(x):
  121. if isinstance(x, Image.Image):
  122. img = x
  123. else:
  124. img = image_from_url_text(x)
  125. if shared.opts.send_size and isinstance(img, Image.Image):
  126. w = img.width
  127. h = img.height
  128. else:
  129. w = gr.update()
  130. h = gr.update()
  131. return img, w, h
  132. def restore_old_hires_fix_params(res):
  133. """for infotexts that specify old First pass size parameter, convert it into
  134. width, height, and hr scale"""
  135. firstpass_width = res.get('First pass size-1', None)
  136. firstpass_height = res.get('First pass size-2', None)
  137. if shared.opts.use_old_hires_fix_width_height:
  138. hires_width = int(res.get("Hires resize-1", 0))
  139. hires_height = int(res.get("Hires resize-2", 0))
  140. if hires_width and hires_height:
  141. res['Size-1'] = hires_width
  142. res['Size-2'] = hires_height
  143. return
  144. if firstpass_width is None or firstpass_height is None:
  145. return
  146. firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
  147. width = int(res.get("Size-1", 512))
  148. height = int(res.get("Size-2", 512))
  149. if firstpass_width == 0 or firstpass_height == 0:
  150. firstpass_width, firstpass_height = processing.old_hires_fix_first_pass_dimensions(width, height)
  151. res['Size-1'] = firstpass_width
  152. res['Size-2'] = firstpass_height
  153. res['Hires resize-1'] = width
  154. res['Hires resize-2'] = height
  155. def parse_generation_parameters(x: str):
  156. """parses generation parameters string, the one you see in text field under the picture in UI:
  157. ```
  158. 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
  159. Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
  160. Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
  161. ```
  162. returns a dict with field values
  163. """
  164. res = {}
  165. prompt = ""
  166. negative_prompt = ""
  167. done_with_prompt = False
  168. *lines, lastline = x.strip().split("\n")
  169. if len(re_param.findall(lastline)) < 3:
  170. lines.append(lastline)
  171. lastline = ''
  172. for line in lines:
  173. line = line.strip()
  174. if line.startswith("Negative prompt:"):
  175. done_with_prompt = True
  176. line = line[16:].strip()
  177. if done_with_prompt:
  178. negative_prompt += ("" if negative_prompt == "" else "\n") + line
  179. else:
  180. prompt += ("" if prompt == "" else "\n") + line
  181. if shared.opts.infotext_styles != "Ignore":
  182. found_styles, prompt, negative_prompt = shared.prompt_styles.extract_styles_from_prompt(prompt, negative_prompt)
  183. if shared.opts.infotext_styles == "Apply":
  184. res["Styles array"] = found_styles
  185. elif shared.opts.infotext_styles == "Apply if any" and found_styles:
  186. res["Styles array"] = found_styles
  187. res["Prompt"] = prompt
  188. res["Negative prompt"] = negative_prompt
  189. for k, v in re_param.findall(lastline):
  190. try:
  191. if v[0] == '"' and v[-1] == '"':
  192. v = unquote(v)
  193. m = re_imagesize.match(v)
  194. if m is not None:
  195. res[f"{k}-1"] = m.group(1)
  196. res[f"{k}-2"] = m.group(2)
  197. else:
  198. res[k] = v
  199. except Exception:
  200. print(f"Error parsing \"{k}: {v}\"")
  201. # Missing CLIP skip means it was set to 1 (the default)
  202. if "Clip skip" not in res:
  203. res["Clip skip"] = "1"
  204. hypernet = res.get("Hypernet", None)
  205. if hypernet is not None:
  206. res["Prompt"] += f"""<hypernet:{hypernet}:{res.get("Hypernet strength", "1.0")}>"""
  207. if "Hires resize-1" not in res:
  208. res["Hires resize-1"] = 0
  209. res["Hires resize-2"] = 0
  210. if "Hires sampler" not in res:
  211. res["Hires sampler"] = "Use same sampler"
  212. if "Hires checkpoint" not in res:
  213. res["Hires checkpoint"] = "Use same checkpoint"
  214. if "Hires prompt" not in res:
  215. res["Hires prompt"] = ""
  216. if "Hires negative prompt" not in res:
  217. res["Hires negative prompt"] = ""
  218. restore_old_hires_fix_params(res)
  219. # Missing RNG means the default was set, which is GPU RNG
  220. if "RNG" not in res:
  221. res["RNG"] = "GPU"
  222. if "Schedule type" not in res:
  223. res["Schedule type"] = "Automatic"
  224. if "Schedule max sigma" not in res:
  225. res["Schedule max sigma"] = 0
  226. if "Schedule min sigma" not in res:
  227. res["Schedule min sigma"] = 0
  228. if "Schedule rho" not in res:
  229. res["Schedule rho"] = 0
  230. if "VAE Encoder" not in res:
  231. res["VAE Encoder"] = "Full"
  232. if "VAE Decoder" not in res:
  233. res["VAE Decoder"] = "Full"
  234. skip = set(shared.opts.infotext_skip_pasting)
  235. res = {k: v for k, v in res.items() if k not in skip}
  236. return res
  237. infotext_to_setting_name_mapping = [
  238. ]
  239. """Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
  240. Example content:
  241. infotext_to_setting_name_mapping = [
  242. ('Conditional mask weight', 'inpainting_mask_weight'),
  243. ('Model hash', 'sd_model_checkpoint'),
  244. ('ENSD', 'eta_noise_seed_delta'),
  245. ('Schedule type', 'k_sched_type'),
  246. ]
  247. """
  248. def create_override_settings_dict(text_pairs):
  249. """creates processing's override_settings parameters from gradio's multiselect
  250. Example input:
  251. ['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
  252. Example output:
  253. {'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
  254. """
  255. res = {}
  256. params = {}
  257. for pair in text_pairs:
  258. k, v = pair.split(":", maxsplit=1)
  259. params[k] = v.strip()
  260. mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
  261. for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
  262. value = params.get(param_name, None)
  263. if value is None:
  264. continue
  265. res[setting_name] = shared.opts.cast_value(setting_name, value)
  266. return res
  267. def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
  268. def paste_func(prompt):
  269. if not prompt and not shared.cmd_opts.hide_ui_dir_config:
  270. filename = os.path.join(data_path, "params.txt")
  271. if os.path.exists(filename):
  272. with open(filename, "r", encoding="utf8") as file:
  273. prompt = file.read()
  274. params = parse_generation_parameters(prompt)
  275. script_callbacks.infotext_pasted_callback(prompt, params)
  276. res = []
  277. for output, key in paste_fields:
  278. if callable(key):
  279. v = key(params)
  280. else:
  281. v = params.get(key, None)
  282. if v is None:
  283. res.append(gr.update())
  284. elif isinstance(v, type_of_gr_update):
  285. res.append(v)
  286. else:
  287. try:
  288. valtype = type(output.value)
  289. if valtype == bool and v == "False":
  290. val = False
  291. else:
  292. val = valtype(v)
  293. res.append(gr.update(value=val))
  294. except Exception:
  295. res.append(gr.update())
  296. return res
  297. if override_settings_component is not None:
  298. already_handled_fields = {key: 1 for _, key in paste_fields}
  299. def paste_settings(params):
  300. vals = {}
  301. mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
  302. for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
  303. if param_name in already_handled_fields:
  304. continue
  305. v = params.get(param_name, None)
  306. if v is None:
  307. continue
  308. if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
  309. continue
  310. v = shared.opts.cast_value(setting_name, v)
  311. current_value = getattr(shared.opts, setting_name, None)
  312. if v == current_value:
  313. continue
  314. vals[param_name] = v
  315. vals_pairs = [f"{k}: {v}" for k, v in vals.items()]
  316. return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
  317. paste_fields = paste_fields + [(override_settings_component, paste_settings)]
  318. button.click(
  319. fn=paste_func,
  320. inputs=[input_comp],
  321. outputs=[x[0] for x in paste_fields],
  322. show_progress=False,
  323. )
  324. button.click(
  325. fn=None,
  326. _js=f"recalculate_prompts_{tabname}",
  327. inputs=[],
  328. outputs=[],
  329. show_progress=False,
  330. )