generation_parameters_copypaste.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import base64
  2. import io
  3. import json
  4. import os
  5. import re
  6. import gradio as gr
  7. from modules.paths import data_path
  8. from modules import shared, ui_tempdir, script_callbacks, processing
  9. from PIL import Image
  10. re_param_code = r'\s*(\w[\w \-/]+):\s*("(?:\\.|[^\\"])+"|[^,]*)(?:,|$)'
  11. re_param = re.compile(re_param_code)
  12. re_imagesize = re.compile(r"^(\d+)x(\d+)$")
  13. re_hypernet_hash = re.compile("\(([0-9a-f]+)\)$")
  14. type_of_gr_update = type(gr.update())
  15. paste_fields = {}
  16. registered_param_bindings = []
  17. class ParamBinding:
  18. 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):
  19. self.paste_button = paste_button
  20. self.tabname = tabname
  21. self.source_text_component = source_text_component
  22. self.source_image_component = source_image_component
  23. self.source_tabname = source_tabname
  24. self.override_settings_component = override_settings_component
  25. self.paste_field_names = paste_field_names or []
  26. def reset():
  27. paste_fields.clear()
  28. registered_param_bindings.clear()
  29. def quote(text):
  30. if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
  31. return text
  32. return json.dumps(text, ensure_ascii=False)
  33. def unquote(text):
  34. if len(text) == 0 or text[0] != '"' or text[-1] != '"':
  35. return text
  36. try:
  37. return json.loads(text)
  38. except Exception:
  39. return text
  40. def image_from_url_text(filedata):
  41. if filedata is None:
  42. return None
  43. if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
  44. filedata = filedata[0]
  45. if type(filedata) == dict and filedata.get("is_file", False):
  46. filename = filedata["name"]
  47. is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
  48. assert is_in_right_dir, 'trying to open image file outside of allowed directories'
  49. filename = filename.rsplit('?', 1)[0]
  50. return Image.open(filename)
  51. if type(filedata) == list:
  52. if len(filedata) == 0:
  53. return None
  54. filedata = filedata[0]
  55. if filedata.startswith("data:image/png;base64,"):
  56. filedata = filedata[len("data:image/png;base64,"):]
  57. filedata = base64.decodebytes(filedata.encode('utf-8'))
  58. image = Image.open(io.BytesIO(filedata))
  59. return image
  60. def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
  61. paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
  62. # backwards compatibility for existing extensions
  63. import modules.ui
  64. if tabname == 'txt2img':
  65. modules.ui.txt2img_paste_fields = fields
  66. elif tabname == 'img2img':
  67. modules.ui.img2img_paste_fields = fields
  68. def create_buttons(tabs_list):
  69. buttons = {}
  70. for tab in tabs_list:
  71. buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
  72. return buttons
  73. def bind_buttons(buttons, send_image, send_generate_info):
  74. """old function for backwards compatibility; do not use this, use register_paste_params_button"""
  75. for tabname, button in buttons.items():
  76. source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
  77. source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
  78. 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))
  79. def register_paste_params_button(binding: ParamBinding):
  80. registered_param_bindings.append(binding)
  81. def connect_paste_params_buttons():
  82. binding: ParamBinding
  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. return res
  235. infotext_to_setting_name_mapping = [
  236. ]
  237. """Mapping of infotext labels to setting names. Only left for backwards compatibility - use OptionInfo(..., infotext='...') instead.
  238. Example content:
  239. infotext_to_setting_name_mapping = [
  240. ('Conditional mask weight', 'inpainting_mask_weight'),
  241. ('Model hash', 'sd_model_checkpoint'),
  242. ('ENSD', 'eta_noise_seed_delta'),
  243. ('Schedule type', 'k_sched_type'),
  244. ]
  245. """
  246. def create_override_settings_dict(text_pairs):
  247. """creates processing's override_settings parameters from gradio's multiselect
  248. Example input:
  249. ['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
  250. Example output:
  251. {'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
  252. """
  253. res = {}
  254. params = {}
  255. for pair in text_pairs:
  256. k, v = pair.split(":", maxsplit=1)
  257. params[k] = v.strip()
  258. mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
  259. for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
  260. value = params.get(param_name, None)
  261. if value is None:
  262. continue
  263. res[setting_name] = shared.opts.cast_value(setting_name, value)
  264. return res
  265. def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
  266. def paste_func(prompt):
  267. if not prompt and not shared.cmd_opts.hide_ui_dir_config:
  268. filename = os.path.join(data_path, "params.txt")
  269. if os.path.exists(filename):
  270. with open(filename, "r", encoding="utf8") as file:
  271. prompt = file.read()
  272. params = parse_generation_parameters(prompt)
  273. script_callbacks.infotext_pasted_callback(prompt, params)
  274. res = []
  275. for output, key in paste_fields:
  276. if callable(key):
  277. v = key(params)
  278. else:
  279. v = params.get(key, None)
  280. if v is None:
  281. res.append(gr.update())
  282. elif isinstance(v, type_of_gr_update):
  283. res.append(v)
  284. else:
  285. try:
  286. valtype = type(output.value)
  287. if valtype == bool and v == "False":
  288. val = False
  289. else:
  290. val = valtype(v)
  291. res.append(gr.update(value=val))
  292. except Exception:
  293. res.append(gr.update())
  294. return res
  295. if override_settings_component is not None:
  296. already_handled_fields = {key: 1 for _, key in paste_fields}
  297. def paste_settings(params):
  298. vals = {}
  299. mapping = [(info.infotext, k) for k, info in shared.opts.data_labels.items() if info.infotext]
  300. for param_name, setting_name in mapping + infotext_to_setting_name_mapping:
  301. if param_name in already_handled_fields:
  302. continue
  303. v = params.get(param_name, None)
  304. if v is None:
  305. continue
  306. if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
  307. continue
  308. v = shared.opts.cast_value(setting_name, v)
  309. current_value = getattr(shared.opts, setting_name, None)
  310. if v == current_value:
  311. continue
  312. vals[param_name] = v
  313. vals_pairs = [f"{k}: {v}" for k, v in vals.items()]
  314. return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
  315. paste_fields = paste_fields + [(override_settings_component, paste_settings)]
  316. button.click(
  317. fn=paste_func,
  318. inputs=[input_comp],
  319. outputs=[x[0] for x in paste_fields],
  320. show_progress=False,
  321. )
  322. button.click(
  323. fn=None,
  324. _js=f"recalculate_prompts_{tabname}",
  325. inputs=[],
  326. outputs=[],
  327. show_progress=False,
  328. )