generation_parameters_copypaste.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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
  9. from PIL import Image
  10. re_param_code = r'\s*([\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. def quote(text):
  29. if ',' not in str(text) and '\n' not in str(text) and ':' not in str(text):
  30. return text
  31. return json.dumps(text, ensure_ascii=False)
  32. def unquote(text):
  33. if len(text) == 0 or text[0] != '"' or text[-1] != '"':
  34. return text
  35. try:
  36. return json.loads(text)
  37. except Exception:
  38. return text
  39. def image_from_url_text(filedata):
  40. if filedata is None:
  41. return None
  42. if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
  43. filedata = filedata[0]
  44. if type(filedata) == dict and filedata.get("is_file", False):
  45. filename = filedata["name"]
  46. is_in_right_dir = ui_tempdir.check_tmp_file(shared.demo, filename)
  47. assert is_in_right_dir, 'trying to open image file outside of allowed directories'
  48. filename = filename.rsplit('?', 1)[0]
  49. return Image.open(filename)
  50. if type(filedata) == list:
  51. if len(filedata) == 0:
  52. return None
  53. filedata = filedata[0]
  54. if filedata.startswith("data:image/png;base64,"):
  55. filedata = filedata[len("data:image/png;base64,"):]
  56. filedata = base64.decodebytes(filedata.encode('utf-8'))
  57. image = Image.open(io.BytesIO(filedata))
  58. return image
  59. def add_paste_fields(tabname, init_img, fields, override_settings_component=None):
  60. paste_fields[tabname] = {"init_img": init_img, "fields": fields, "override_settings_component": override_settings_component}
  61. # backwards compatibility for existing extensions
  62. import modules.ui
  63. if tabname == 'txt2img':
  64. modules.ui.txt2img_paste_fields = fields
  65. elif tabname == 'img2img':
  66. modules.ui.img2img_paste_fields = fields
  67. def create_buttons(tabs_list):
  68. buttons = {}
  69. for tab in tabs_list:
  70. buttons[tab] = gr.Button(f"Send to {tab}", elem_id=f"{tab}_tab")
  71. return buttons
  72. def bind_buttons(buttons, send_image, send_generate_info):
  73. """old function for backwards compatibility; do not use this, use register_paste_params_button"""
  74. for tabname, button in buttons.items():
  75. source_text_component = send_generate_info if isinstance(send_generate_info, gr.components.Component) else None
  76. source_tabname = send_generate_info if isinstance(send_generate_info, str) else None
  77. 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))
  78. def register_paste_params_button(binding: ParamBinding):
  79. registered_param_bindings.append(binding)
  80. def connect_paste_params_buttons():
  81. binding: ParamBinding
  82. for binding in registered_param_bindings:
  83. destination_image_component = paste_fields[binding.tabname]["init_img"]
  84. fields = paste_fields[binding.tabname]["fields"]
  85. override_settings_component = binding.override_settings_component or paste_fields[binding.tabname]["override_settings_component"]
  86. destination_width_component = next(iter([field for field, name in fields if name == "Size-1"] if fields else []), None)
  87. destination_height_component = next(iter([field for field, name in fields if name == "Size-2"] if fields else []), None)
  88. if binding.source_image_component and destination_image_component:
  89. if isinstance(binding.source_image_component, gr.Gallery):
  90. func = send_image_and_dimensions if destination_width_component else image_from_url_text
  91. jsfunc = "extract_image_from_gallery"
  92. else:
  93. func = send_image_and_dimensions if destination_width_component else lambda x: x
  94. jsfunc = None
  95. binding.paste_button.click(
  96. fn=func,
  97. _js=jsfunc,
  98. inputs=[binding.source_image_component],
  99. outputs=[destination_image_component, destination_width_component, destination_height_component] if destination_width_component else [destination_image_component],
  100. show_progress=False,
  101. )
  102. if binding.source_text_component is not None and fields is not None:
  103. connect_paste(binding.paste_button, fields, binding.source_text_component, override_settings_component, binding.tabname)
  104. if binding.source_tabname is not None and fields is not None:
  105. paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration'] + (["Seed"] if shared.opts.send_seed else []) + binding.paste_field_names
  106. binding.paste_button.click(
  107. fn=lambda *x: x,
  108. inputs=[field for field, name in paste_fields[binding.source_tabname]["fields"] if name in paste_field_names],
  109. outputs=[field for field, name in fields if name in paste_field_names],
  110. show_progress=False,
  111. )
  112. binding.paste_button.click(
  113. fn=None,
  114. _js=f"switch_to_{binding.tabname}",
  115. inputs=None,
  116. outputs=None,
  117. show_progress=False,
  118. )
  119. def send_image_and_dimensions(x):
  120. if isinstance(x, Image.Image):
  121. img = x
  122. else:
  123. img = image_from_url_text(x)
  124. if shared.opts.send_size and isinstance(img, Image.Image):
  125. w = img.width
  126. h = img.height
  127. else:
  128. w = gr.update()
  129. h = gr.update()
  130. return img, w, h
  131. def restore_old_hires_fix_params(res):
  132. """for infotexts that specify old First pass size parameter, convert it into
  133. width, height, and hr scale"""
  134. firstpass_width = res.get('First pass size-1', None)
  135. firstpass_height = res.get('First pass size-2', None)
  136. if shared.opts.use_old_hires_fix_width_height:
  137. hires_width = int(res.get("Hires resize-1", 0))
  138. hires_height = int(res.get("Hires resize-2", 0))
  139. if hires_width and hires_height:
  140. res['Size-1'] = hires_width
  141. res['Size-2'] = hires_height
  142. return
  143. if firstpass_width is None or firstpass_height is None:
  144. return
  145. firstpass_width, firstpass_height = int(firstpass_width), int(firstpass_height)
  146. width = int(res.get("Size-1", 512))
  147. height = int(res.get("Size-2", 512))
  148. if firstpass_width == 0 or firstpass_height == 0:
  149. from modules import processing
  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 prompt" not in res:
  213. res["Hires prompt"] = ""
  214. if "Hires negative prompt" not in res:
  215. res["Hires negative prompt"] = ""
  216. restore_old_hires_fix_params(res)
  217. # Missing RNG means the default was set, which is GPU RNG
  218. if "RNG" not in res:
  219. res["RNG"] = "GPU"
  220. if "Schedule type" not in res:
  221. res["Schedule type"] = "Automatic"
  222. if "Schedule max sigma" not in res:
  223. res["Schedule max sigma"] = 0
  224. if "Schedule min sigma" not in res:
  225. res["Schedule min sigma"] = 0
  226. if "Schedule rho" not in res:
  227. res["Schedule rho"] = 0
  228. return res
  229. infotext_to_setting_name_mapping = [
  230. ('Clip skip', 'CLIP_stop_at_last_layers', ),
  231. ('Conditional mask weight', 'inpainting_mask_weight'),
  232. ('Model hash', 'sd_model_checkpoint'),
  233. ('ENSD', 'eta_noise_seed_delta'),
  234. ('Schedule type', 'k_sched_type'),
  235. ('Schedule max sigma', 'sigma_max'),
  236. ('Schedule min sigma', 'sigma_min'),
  237. ('Schedule rho', 'rho'),
  238. ('Noise multiplier', 'initial_noise_multiplier'),
  239. ('Eta', 'eta_ancestral'),
  240. ('Eta DDIM', 'eta_ddim'),
  241. ('Discard penultimate sigma', 'always_discard_next_to_last_sigma'),
  242. ('UniPC variant', 'uni_pc_variant'),
  243. ('UniPC skip type', 'uni_pc_skip_type'),
  244. ('UniPC order', 'uni_pc_order'),
  245. ('UniPC lower order final', 'uni_pc_lower_order_final'),
  246. ('Token merging ratio', 'token_merging_ratio'),
  247. ('Token merging ratio hr', 'token_merging_ratio_hr'),
  248. ('RNG', 'randn_source'),
  249. ('NGMS', 's_min_uncond'),
  250. ('Pad conds', 'pad_cond_uncond'),
  251. ]
  252. def create_override_settings_dict(text_pairs):
  253. """creates processing's override_settings parameters from gradio's multiselect
  254. Example input:
  255. ['Clip skip: 2', 'Model hash: e6e99610c4', 'ENSD: 31337']
  256. Example output:
  257. {'CLIP_stop_at_last_layers': 2, 'sd_model_checkpoint': 'e6e99610c4', 'eta_noise_seed_delta': 31337}
  258. """
  259. res = {}
  260. params = {}
  261. for pair in text_pairs:
  262. k, v = pair.split(":", maxsplit=1)
  263. params[k] = v.strip()
  264. for param_name, setting_name in infotext_to_setting_name_mapping:
  265. value = params.get(param_name, None)
  266. if value is None:
  267. continue
  268. res[setting_name] = shared.opts.cast_value(setting_name, value)
  269. return res
  270. def connect_paste(button, paste_fields, input_comp, override_settings_component, tabname):
  271. def paste_func(prompt):
  272. if not prompt and not shared.cmd_opts.hide_ui_dir_config:
  273. filename = os.path.join(data_path, "params.txt")
  274. if os.path.exists(filename):
  275. with open(filename, "r", encoding="utf8") as file:
  276. prompt = file.read()
  277. params = parse_generation_parameters(prompt)
  278. script_callbacks.infotext_pasted_callback(prompt, params)
  279. res = []
  280. for output, key in paste_fields:
  281. if callable(key):
  282. v = key(params)
  283. else:
  284. v = params.get(key, None)
  285. if v is None:
  286. res.append(gr.update())
  287. elif isinstance(v, type_of_gr_update):
  288. res.append(v)
  289. else:
  290. try:
  291. valtype = type(output.value)
  292. if valtype == bool and v == "False":
  293. val = False
  294. else:
  295. val = valtype(v)
  296. res.append(gr.update(value=val))
  297. except Exception:
  298. res.append(gr.update())
  299. return res
  300. if override_settings_component is not None:
  301. def paste_settings(params):
  302. vals = {}
  303. for param_name, setting_name in infotext_to_setting_name_mapping:
  304. v = params.get(param_name, None)
  305. if v is None:
  306. continue
  307. if setting_name == "sd_model_checkpoint" and shared.opts.disable_weights_auto_swap:
  308. continue
  309. v = shared.opts.cast_value(setting_name, v)
  310. current_value = getattr(shared.opts, setting_name, None)
  311. if v == current_value:
  312. continue
  313. vals[param_name] = v
  314. vals_pairs = [f"{k}: {v}" for k, v in vals.items()]
  315. return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
  316. paste_fields = paste_fields + [(override_settings_component, paste_settings)]
  317. button.click(
  318. fn=paste_func,
  319. inputs=[input_comp],
  320. outputs=[x[0] for x in paste_fields],
  321. show_progress=False,
  322. )
  323. button.click(
  324. fn=None,
  325. _js=f"recalculate_prompts_{tabname}",
  326. inputs=[],
  327. outputs=[],
  328. show_progress=False,
  329. )