ui.py 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. import html
  2. import json
  3. import math
  4. import mimetypes
  5. import os
  6. import platform
  7. import random
  8. import subprocess as sp
  9. import sys
  10. import tempfile
  11. import time
  12. import traceback
  13. from functools import partial, reduce
  14. import gradio as gr
  15. import gradio.routes
  16. import gradio.utils
  17. import numpy as np
  18. from PIL import Image, PngImagePlugin
  19. from modules.call_queue import wrap_gradio_gpu_call, wrap_queued_call, wrap_gradio_call
  20. from modules import sd_hijack, sd_models, localization, script_callbacks, ui_extensions, deepbooru
  21. from modules.ui_components import FormRow, FormGroup, ToolButton, FormHTML
  22. from modules.paths import script_path
  23. from modules.shared import opts, cmd_opts, restricted_opts
  24. import modules.codeformer_model
  25. import modules.generation_parameters_copypaste as parameters_copypaste
  26. import modules.gfpgan_model
  27. import modules.hypernetworks.ui
  28. import modules.scripts
  29. import modules.shared as shared
  30. import modules.styles
  31. import modules.textual_inversion.ui
  32. from modules import prompt_parser
  33. from modules.images import save_image
  34. from modules.sd_hijack import model_hijack
  35. from modules.sd_samplers import samplers, samplers_for_img2img
  36. from modules.textual_inversion import textual_inversion
  37. import modules.hypernetworks.ui
  38. from modules.generation_parameters_copypaste import image_from_url_text
  39. # 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
  40. mimetypes.init()
  41. mimetypes.add_type('application/javascript', '.js')
  42. if not cmd_opts.share and not cmd_opts.listen:
  43. # fix gradio phoning home
  44. gradio.utils.version_check = lambda: None
  45. gradio.utils.get_local_ip_address = lambda: '127.0.0.1'
  46. if cmd_opts.ngrok is not None:
  47. import modules.ngrok as ngrok
  48. print('ngrok authtoken detected, trying to connect...')
  49. ngrok.connect(
  50. cmd_opts.ngrok,
  51. cmd_opts.port if cmd_opts.port is not None else 7860,
  52. cmd_opts.ngrok_region
  53. )
  54. def gr_show(visible=True):
  55. return {"visible": visible, "__type__": "update"}
  56. sample_img2img = "assets/stable-samples/img2img/sketch-mountains-input.jpg"
  57. sample_img2img = sample_img2img if os.path.exists(sample_img2img) else None
  58. css_hide_progressbar = """
  59. .wrap .m-12 svg { display:none!important; }
  60. .wrap .m-12::before { content:"Loading..." }
  61. .wrap .z-20 svg { display:none!important; }
  62. .wrap .z-20::before { content:"Loading..." }
  63. .progress-bar { display:none!important; }
  64. .meta-text { display:none!important; }
  65. .meta-text-center { display:none!important; }
  66. """
  67. # Using constants for these since the variation selector isn't visible.
  68. # Important that they exactly match script.js for tooltip to work.
  69. random_symbol = '\U0001f3b2\ufe0f' # 🎲️
  70. reuse_symbol = '\u267b\ufe0f' # ♻️
  71. paste_symbol = '\u2199\ufe0f' # ↙
  72. folder_symbol = '\U0001f4c2' # 📂
  73. refresh_symbol = '\U0001f504' # 🔄
  74. save_style_symbol = '\U0001f4be' # 💾
  75. apply_style_symbol = '\U0001f4cb' # 📋
  76. clear_prompt_symbol = '\U0001F5D1' # 🗑️
  77. def plaintext_to_html(text):
  78. text = "<p>" + "<br>\n".join([f"{html.escape(x)}" for x in text.split('\n')]) + "</p>"
  79. return text
  80. def send_gradio_gallery_to_image(x):
  81. if len(x) == 0:
  82. return None
  83. return image_from_url_text(x[0])
  84. def save_files(js_data, images, do_make_zip, index):
  85. import csv
  86. filenames = []
  87. fullfns = []
  88. #quick dictionary to class object conversion. Its necessary due apply_filename_pattern requiring it
  89. class MyObject:
  90. def __init__(self, d=None):
  91. if d is not None:
  92. for key, value in d.items():
  93. setattr(self, key, value)
  94. data = json.loads(js_data)
  95. p = MyObject(data)
  96. path = opts.outdir_save
  97. save_to_dirs = opts.use_save_to_dirs_for_ui
  98. extension: str = opts.samples_format
  99. start_index = 0
  100. if index > -1 and opts.save_selected_only and (index >= data["index_of_first_image"]): # ensures we are looking at a specific non-grid picture, and we have save_selected_only
  101. images = [images[index]]
  102. start_index = index
  103. os.makedirs(opts.outdir_save, exist_ok=True)
  104. with open(os.path.join(opts.outdir_save, "log.csv"), "a", encoding="utf8", newline='') as file:
  105. at_start = file.tell() == 0
  106. writer = csv.writer(file)
  107. if at_start:
  108. writer.writerow(["prompt", "seed", "width", "height", "sampler", "cfgs", "steps", "filename", "negative_prompt"])
  109. for image_index, filedata in enumerate(images, start_index):
  110. image = image_from_url_text(filedata)
  111. is_grid = image_index < p.index_of_first_image
  112. i = 0 if is_grid else (image_index - p.index_of_first_image)
  113. fullfn, txt_fullfn = save_image(image, path, "", seed=p.all_seeds[i], prompt=p.all_prompts[i], extension=extension, info=p.infotexts[image_index], grid=is_grid, p=p, save_to_dirs=save_to_dirs)
  114. filename = os.path.relpath(fullfn, path)
  115. filenames.append(filename)
  116. fullfns.append(fullfn)
  117. if txt_fullfn:
  118. filenames.append(os.path.basename(txt_fullfn))
  119. fullfns.append(txt_fullfn)
  120. writer.writerow([data["prompt"], data["seed"], data["width"], data["height"], data["sampler_name"], data["cfg_scale"], data["steps"], filenames[0], data["negative_prompt"]])
  121. # Make Zip
  122. if do_make_zip:
  123. zip_filepath = os.path.join(path, "images.zip")
  124. from zipfile import ZipFile
  125. with ZipFile(zip_filepath, "w") as zip_file:
  126. for i in range(len(fullfns)):
  127. with open(fullfns[i], mode="rb") as f:
  128. zip_file.writestr(filenames[i], f.read())
  129. fullfns.insert(0, zip_filepath)
  130. return gr.File.update(value=fullfns, visible=True), plaintext_to_html(f"Saved: {filenames[0]}")
  131. def visit(x, func, path=""):
  132. if hasattr(x, 'children'):
  133. for c in x.children:
  134. visit(c, func, path)
  135. elif x.label is not None:
  136. func(path + "/" + str(x.label), x)
  137. def add_style(name: str, prompt: str, negative_prompt: str):
  138. if name is None:
  139. return [gr_show() for x in range(4)]
  140. style = modules.styles.PromptStyle(name, prompt, negative_prompt)
  141. shared.prompt_styles.styles[style.name] = style
  142. # Save all loaded prompt styles: this allows us to update the storage format in the future more easily, because we
  143. # reserialize all styles every time we save them
  144. shared.prompt_styles.save_styles(shared.styles_filename)
  145. return [gr.Dropdown.update(visible=True, choices=list(shared.prompt_styles.styles)) for _ in range(4)]
  146. def calc_resolution_hires(enable, width, height, hr_scale, hr_resize_x, hr_resize_y):
  147. from modules import processing, devices
  148. if not enable:
  149. return ""
  150. 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)
  151. with devices.autocast():
  152. p.init([""], [0], [0])
  153. 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>"
  154. def apply_styles(prompt, prompt_neg, style1_name, style2_name):
  155. prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, [style1_name, style2_name])
  156. prompt_neg = shared.prompt_styles.apply_negative_styles_to_prompt(prompt_neg, [style1_name, style2_name])
  157. return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=prompt_neg), gr.Dropdown.update(value="None"), gr.Dropdown.update(value="None")]
  158. def interrogate(image):
  159. prompt = shared.interrogator.interrogate(image.convert("RGB"))
  160. return gr_show(True) if prompt is None else prompt
  161. def interrogate_deepbooru(image):
  162. prompt = deepbooru.model.tag(image)
  163. return gr_show(True) if prompt is None else prompt
  164. def create_seed_inputs(target_interface):
  165. with FormRow(elem_id=target_interface + '_seed_row'):
  166. seed = (gr.Textbox if cmd_opts.use_textbox_seed else gr.Number)(label='Seed', value=-1, elem_id=target_interface + '_seed')
  167. seed.style(container=False)
  168. random_seed = gr.Button(random_symbol, elem_id=target_interface + '_random_seed')
  169. reuse_seed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_seed')
  170. with gr.Group(elem_id=target_interface + '_subseed_show_box'):
  171. seed_checkbox = gr.Checkbox(label='Extra', elem_id=target_interface + '_subseed_show', value=False)
  172. # Components to show/hide based on the 'Extra' checkbox
  173. seed_extras = []
  174. with FormRow(visible=False, elem_id=target_interface + '_subseed_row') as seed_extra_row_1:
  175. seed_extras.append(seed_extra_row_1)
  176. subseed = gr.Number(label='Variation seed', value=-1, elem_id=target_interface + '_subseed')
  177. subseed.style(container=False)
  178. random_subseed = gr.Button(random_symbol, elem_id=target_interface + '_random_subseed')
  179. reuse_subseed = gr.Button(reuse_symbol, elem_id=target_interface + '_reuse_subseed')
  180. subseed_strength = gr.Slider(label='Variation strength', value=0.0, minimum=0, maximum=1, step=0.01, elem_id=target_interface + '_subseed_strength')
  181. with FormRow(visible=False) as seed_extra_row_2:
  182. seed_extras.append(seed_extra_row_2)
  183. 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')
  184. 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')
  185. random_seed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[seed])
  186. random_subseed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[subseed])
  187. def change_visibility(show):
  188. return {comp: gr_show(show) for comp in seed_extras}
  189. seed_checkbox.change(change_visibility, show_progress=False, inputs=[seed_checkbox], outputs=seed_extras)
  190. return seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox
  191. def connect_clear_prompt(button):
  192. """Given clear button, prompt, and token_counter objects, setup clear prompt button click event"""
  193. button.click(
  194. _js="clear_prompt",
  195. fn=None,
  196. inputs=[],
  197. outputs=[],
  198. )
  199. def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info: gr.Textbox, dummy_component, is_subseed):
  200. """ Connects a 'reuse (sub)seed' button's click event so that it copies last used
  201. (sub)seed value from generation info the to the seed field. If copying subseed and subseed strength
  202. was 0, i.e. no variation seed was used, it copies the normal seed value instead."""
  203. def copy_seed(gen_info_string: str, index):
  204. res = -1
  205. try:
  206. gen_info = json.loads(gen_info_string)
  207. index -= gen_info.get('index_of_first_image', 0)
  208. if is_subseed and gen_info.get('subseed_strength', 0) > 0:
  209. all_subseeds = gen_info.get('all_subseeds', [-1])
  210. res = all_subseeds[index if 0 <= index < len(all_subseeds) else 0]
  211. else:
  212. all_seeds = gen_info.get('all_seeds', [-1])
  213. res = all_seeds[index if 0 <= index < len(all_seeds) else 0]
  214. except json.decoder.JSONDecodeError as e:
  215. if gen_info_string != '':
  216. print("Error parsing JSON generation info:", file=sys.stderr)
  217. print(gen_info_string, file=sys.stderr)
  218. return [res, gr_show(False)]
  219. reuse_seed.click(
  220. fn=copy_seed,
  221. _js="(x, y) => [x, selected_gallery_index()]",
  222. show_progress=False,
  223. inputs=[generation_info, dummy_component],
  224. outputs=[seed, dummy_component]
  225. )
  226. def update_token_counter(text, steps):
  227. try:
  228. _, prompt_flat_list, _ = prompt_parser.get_multicond_prompt_list([text])
  229. prompt_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(prompt_flat_list, steps)
  230. except Exception:
  231. # a parsing error can happen here during typing, and we don't want to bother the user with
  232. # messages related to it in console
  233. prompt_schedules = [[[steps, text]]]
  234. flat_prompts = reduce(lambda list1, list2: list1+list2, prompt_schedules)
  235. prompts = [prompt_text for step, prompt_text in flat_prompts]
  236. token_count, max_length = max([model_hijack.get_prompt_lengths(prompt) for prompt in prompts], key=lambda args: args[0])
  237. style_class = ' class="red"' if (token_count > max_length) else ""
  238. return f"<span {style_class}>{token_count}/{max_length}</span>"
  239. def create_toprow(is_img2img):
  240. id_part = "img2img" if is_img2img else "txt2img"
  241. with gr.Row(elem_id="toprow"):
  242. with gr.Column(scale=6):
  243. with gr.Row():
  244. with gr.Column(scale=80):
  245. with gr.Row():
  246. prompt = gr.Textbox(label="Prompt", elem_id=f"{id_part}_prompt", show_label=False, lines=2,
  247. placeholder="Prompt (press Ctrl+Enter or Alt+Enter to generate)"
  248. )
  249. with gr.Row():
  250. with gr.Column(scale=80):
  251. with gr.Row():
  252. negative_prompt = gr.Textbox(label="Negative prompt", elem_id=f"{id_part}_neg_prompt", show_label=False, lines=2,
  253. placeholder="Negative prompt (press Ctrl+Enter or Alt+Enter to generate)"
  254. )
  255. with gr.Column(scale=1, elem_id="roll_col"):
  256. paste = gr.Button(value=paste_symbol, elem_id="paste")
  257. save_style = gr.Button(value=save_style_symbol, elem_id="style_create")
  258. prompt_style_apply = gr.Button(value=apply_style_symbol, elem_id="style_apply")
  259. clear_prompt_button = gr.Button(value=clear_prompt_symbol, elem_id=f"{id_part}_clear_prompt")
  260. token_counter = gr.HTML(value="<span></span>", elem_id=f"{id_part}_token_counter")
  261. token_button = gr.Button(visible=False, elem_id=f"{id_part}_token_button")
  262. clear_prompt_button.click(
  263. fn=lambda *x: x,
  264. _js="confirm_clear_prompt",
  265. inputs=[prompt, negative_prompt],
  266. outputs=[prompt, negative_prompt],
  267. )
  268. button_interrogate = None
  269. button_deepbooru = None
  270. if is_img2img:
  271. with gr.Column(scale=1, elem_id="interrogate_col"):
  272. button_interrogate = gr.Button('Interrogate\nCLIP', elem_id="interrogate")
  273. button_deepbooru = gr.Button('Interrogate\nDeepBooru', elem_id="deepbooru")
  274. with gr.Column(scale=1):
  275. with gr.Row(elem_id=f"{id_part}_generate_box"):
  276. skip = gr.Button('Skip', elem_id=f"{id_part}_skip")
  277. interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt")
  278. submit = gr.Button('Generate', elem_id=f"{id_part}_generate", variant='primary')
  279. skip.click(
  280. fn=lambda: shared.state.skip(),
  281. inputs=[],
  282. outputs=[],
  283. )
  284. interrupt.click(
  285. fn=lambda: shared.state.interrupt(),
  286. inputs=[],
  287. outputs=[],
  288. )
  289. with gr.Row():
  290. with gr.Column(scale=1, elem_id="style_pos_col"):
  291. prompt_style = gr.Dropdown(label="Style 1", elem_id=f"{id_part}_style_index", choices=[k for k, v in shared.prompt_styles.styles.items()], value=next(iter(shared.prompt_styles.styles.keys())))
  292. with gr.Column(scale=1, elem_id="style_neg_col"):
  293. prompt_style2 = gr.Dropdown(label="Style 2", elem_id=f"{id_part}_style2_index", choices=[k for k, v in shared.prompt_styles.styles.items()], value=next(iter(shared.prompt_styles.styles.keys())))
  294. return prompt, prompt_style, negative_prompt, prompt_style2, submit, button_interrogate, button_deepbooru, prompt_style_apply, save_style, paste, token_counter, token_button
  295. def setup_progressbar(*args, **kwargs):
  296. pass
  297. def apply_setting(key, value):
  298. if value is None:
  299. return gr.update()
  300. if shared.cmd_opts.freeze_settings:
  301. return gr.update()
  302. # dont allow model to be swapped when model hash exists in prompt
  303. if key == "sd_model_checkpoint" and opts.disable_weights_auto_swap:
  304. return gr.update()
  305. if key == "sd_model_checkpoint":
  306. ckpt_info = sd_models.get_closet_checkpoint_match(value)
  307. if ckpt_info is not None:
  308. value = ckpt_info.title
  309. else:
  310. return gr.update()
  311. comp_args = opts.data_labels[key].component_args
  312. if comp_args and isinstance(comp_args, dict) and comp_args.get('visible') is False:
  313. return
  314. valtype = type(opts.data_labels[key].default)
  315. oldval = opts.data.get(key, None)
  316. opts.data[key] = valtype(value) if valtype != type(None) else value
  317. if oldval != value and opts.data_labels[key].onchange is not None:
  318. opts.data_labels[key].onchange()
  319. opts.save(shared.config_filename)
  320. return value
  321. def update_generation_info(args):
  322. generation_info, html_info, img_index = args
  323. try:
  324. generation_info = json.loads(generation_info)
  325. if img_index < 0 or img_index >= len(generation_info["infotexts"]):
  326. return html_info
  327. return plaintext_to_html(generation_info["infotexts"][img_index])
  328. except Exception:
  329. pass
  330. # if the json parse or anything else fails, just return the old html_info
  331. return html_info
  332. def create_refresh_button(refresh_component, refresh_method, refreshed_args, elem_id):
  333. def refresh():
  334. refresh_method()
  335. args = refreshed_args() if callable(refreshed_args) else refreshed_args
  336. for k, v in args.items():
  337. setattr(refresh_component, k, v)
  338. return gr.update(**(args or {}))
  339. refresh_button = ToolButton(value=refresh_symbol, elem_id=elem_id)
  340. refresh_button.click(
  341. fn=refresh,
  342. inputs=[],
  343. outputs=[refresh_component]
  344. )
  345. return refresh_button
  346. def create_output_panel(tabname, outdir):
  347. def open_folder(f):
  348. if not os.path.exists(f):
  349. print(f'Folder "{f}" does not exist. After you create an image, the folder will be created.')
  350. return
  351. elif not os.path.isdir(f):
  352. print(f"""
  353. WARNING
  354. An open_folder request was made with an argument that is not a folder.
  355. This could be an error or a malicious attempt to run code on your computer.
  356. Requested path was: {f}
  357. """, file=sys.stderr)
  358. return
  359. if not shared.cmd_opts.hide_ui_dir_config:
  360. path = os.path.normpath(f)
  361. if platform.system() == "Windows":
  362. os.startfile(path)
  363. elif platform.system() == "Darwin":
  364. sp.Popen(["open", path])
  365. elif "microsoft-standard-WSL2" in platform.uname().release:
  366. sp.Popen(["wsl-open", path])
  367. else:
  368. sp.Popen(["xdg-open", path])
  369. with gr.Column(variant='panel', elem_id=f"{tabname}_results"):
  370. with gr.Group(elem_id=f"{tabname}_gallery_container"):
  371. result_gallery = gr.Gallery(label='Output', show_label=False, elem_id=f"{tabname}_gallery").style(grid=4)
  372. generation_info = None
  373. with gr.Column():
  374. with gr.Row(elem_id=f"image_buttons_{tabname}"):
  375. open_folder_button = gr.Button(folder_symbol, elem_id="hidden_element" if shared.cmd_opts.hide_ui_dir_config else f'open_folder_{tabname}')
  376. if tabname != "extras":
  377. save = gr.Button('Save', elem_id=f'save_{tabname}')
  378. save_zip = gr.Button('Zip', elem_id=f'save_zip_{tabname}')
  379. buttons = parameters_copypaste.create_buttons(["img2img", "inpaint", "extras"])
  380. open_folder_button.click(
  381. fn=lambda: open_folder(opts.outdir_samples or outdir),
  382. inputs=[],
  383. outputs=[],
  384. )
  385. if tabname != "extras":
  386. with gr.Row():
  387. download_files = gr.File(None, file_count="multiple", interactive=False, show_label=False, visible=False, elem_id=f'download_files_{tabname}')
  388. with gr.Group():
  389. html_info = gr.HTML(elem_id=f'html_info_{tabname}')
  390. html_log = gr.HTML(elem_id=f'html_log_{tabname}')
  391. generation_info = gr.Textbox(visible=False, elem_id=f'generation_info_{tabname}')
  392. if tabname == 'txt2img' or tabname == 'img2img':
  393. generation_info_button = gr.Button(visible=False, elem_id=f"{tabname}_generation_info_button")
  394. generation_info_button.click(
  395. fn=update_generation_info,
  396. _js="(x, y) => [x, y, selected_gallery_index()]",
  397. inputs=[generation_info, html_info],
  398. outputs=[html_info],
  399. preprocess=False
  400. )
  401. save.click(
  402. fn=wrap_gradio_call(save_files),
  403. _js="(x, y, z, w) => [x, y, false, selected_gallery_index()]",
  404. inputs=[
  405. generation_info,
  406. result_gallery,
  407. html_info,
  408. html_info,
  409. ],
  410. outputs=[
  411. download_files,
  412. html_log,
  413. ]
  414. )
  415. save_zip.click(
  416. fn=wrap_gradio_call(save_files),
  417. _js="(x, y, z, w) => [x, y, true, selected_gallery_index()]",
  418. inputs=[
  419. generation_info,
  420. result_gallery,
  421. html_info,
  422. html_info,
  423. ],
  424. outputs=[
  425. download_files,
  426. html_log,
  427. ]
  428. )
  429. else:
  430. html_info_x = gr.HTML(elem_id=f'html_info_x_{tabname}')
  431. html_info = gr.HTML(elem_id=f'html_info_{tabname}')
  432. html_log = gr.HTML(elem_id=f'html_log_{tabname}')
  433. parameters_copypaste.bind_buttons(buttons, result_gallery, "txt2img" if tabname == "txt2img" else None)
  434. return result_gallery, generation_info if tabname != "extras" else html_info_x, html_info, html_log
  435. def create_sampler_and_steps_selection(choices, tabname):
  436. if opts.samplers_in_dropdown:
  437. with FormRow(elem_id=f"sampler_selection_{tabname}"):
  438. 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")
  439. steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20)
  440. else:
  441. with FormGroup(elem_id=f"sampler_selection_{tabname}"):
  442. steps = gr.Slider(minimum=1, maximum=150, step=1, elem_id=f"{tabname}_steps", label="Sampling steps", value=20)
  443. 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")
  444. return steps, sampler_index
  445. def ordered_ui_categories():
  446. user_order = {x.strip(): i for i, x in enumerate(shared.opts.ui_reorder.split(","))}
  447. for i, category in sorted(enumerate(shared.ui_reorder_categories), key=lambda x: user_order.get(x[1], x[0] + 1000)):
  448. yield category
  449. def create_ui():
  450. import modules.img2img
  451. import modules.txt2img
  452. reload_javascript()
  453. parameters_copypaste.reset()
  454. modules.scripts.scripts_current = modules.scripts.scripts_txt2img
  455. modules.scripts.scripts_txt2img.initialize_scripts(is_img2img=False)
  456. with gr.Blocks(analytics_enabled=False) as txt2img_interface:
  457. txt2img_prompt, txt2img_prompt_style, txt2img_negative_prompt, txt2img_prompt_style2, submit, _, _,txt2img_prompt_style_apply, txt2img_save_style, txt2img_paste, token_counter, token_button = create_toprow(is_img2img=False)
  458. dummy_component = gr.Label(visible=False)
  459. txt_prompt_img = gr.File(label="", elem_id="txt2img_prompt_image", file_count="single", type="bytes", visible=False)
  460. with gr.Row().style(equal_height=False):
  461. with gr.Column(variant='panel', elem_id="txt2img_settings"):
  462. for category in ordered_ui_categories():
  463. if category == "sampler":
  464. steps, sampler_index = create_sampler_and_steps_selection(samplers, "txt2img")
  465. elif category == "dimensions":
  466. with FormRow():
  467. with gr.Column(elem_id="txt2img_column_size", scale=4):
  468. width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="txt2img_width")
  469. height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="txt2img_height")
  470. if opts.dimensions_and_batch_together:
  471. with gr.Column(elem_id="txt2img_column_batch"):
  472. batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count")
  473. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size")
  474. elif category == "cfg":
  475. cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="txt2img_cfg_scale")
  476. elif category == "seed":
  477. seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('txt2img')
  478. elif category == "checkboxes":
  479. with FormRow(elem_id="txt2img_checkboxes"):
  480. restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="txt2img_restore_faces")
  481. tiling = gr.Checkbox(label='Tiling', value=False, elem_id="txt2img_tiling")
  482. enable_hr = gr.Checkbox(label='Hires. fix', value=False, elem_id="txt2img_enable_hr")
  483. hr_final_resolution = FormHTML(value="", elem_id="txtimg_hr_finalres", label="Upscaled resolution", interactive=False)
  484. elif category == "hires_fix":
  485. with FormGroup(visible=False, elem_id="txt2img_hires_fix") as hr_options:
  486. with FormRow(elem_id="txt2img_hires_fix_row1"):
  487. 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)
  488. hr_second_pass_steps = gr.Slider(minimum=0, maximum=150, step=1, label='Hires steps', value=0, elem_id="txt2img_hires_steps")
  489. denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.7, elem_id="txt2img_denoising_strength")
  490. with FormRow(elem_id="txt2img_hires_fix_row2"):
  491. hr_scale = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label="Upscale by", value=2.0, elem_id="txt2img_hr_scale")
  492. hr_resize_x = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize width to", value=0, elem_id="txt2img_hr_resize_x")
  493. hr_resize_y = gr.Slider(minimum=0, maximum=2048, step=8, label="Resize height to", value=0, elem_id="txt2img_hr_resize_y")
  494. elif category == "batch":
  495. if not opts.dimensions_and_batch_together:
  496. with FormRow(elem_id="txt2img_column_batch"):
  497. batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="txt2img_batch_count")
  498. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="txt2img_batch_size")
  499. elif category == "scripts":
  500. with FormGroup(elem_id="txt2img_script_container"):
  501. custom_inputs = modules.scripts.scripts_txt2img.setup_ui()
  502. hr_resolution_preview_inputs = [enable_hr, width, height, hr_scale, hr_resize_x, hr_resize_y]
  503. for input in hr_resolution_preview_inputs:
  504. input.change(
  505. fn=calc_resolution_hires,
  506. inputs=hr_resolution_preview_inputs,
  507. outputs=[hr_final_resolution],
  508. show_progress=False,
  509. )
  510. input.change(
  511. None,
  512. _js="onCalcResolutionHires",
  513. inputs=hr_resolution_preview_inputs,
  514. outputs=[],
  515. show_progress=False,
  516. )
  517. txt2img_gallery, generation_info, html_info, html_log = create_output_panel("txt2img", opts.outdir_txt2img_samples)
  518. parameters_copypaste.bind_buttons({"txt2img": txt2img_paste}, None, txt2img_prompt)
  519. connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
  520. connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
  521. txt2img_args = dict(
  522. fn=wrap_gradio_gpu_call(modules.txt2img.txt2img, extra_outputs=[None, '', '']),
  523. _js="submit",
  524. inputs=[
  525. dummy_component,
  526. txt2img_prompt,
  527. txt2img_negative_prompt,
  528. txt2img_prompt_style,
  529. txt2img_prompt_style2,
  530. steps,
  531. sampler_index,
  532. restore_faces,
  533. tiling,
  534. batch_count,
  535. batch_size,
  536. cfg_scale,
  537. seed,
  538. subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
  539. height,
  540. width,
  541. enable_hr,
  542. denoising_strength,
  543. hr_scale,
  544. hr_upscaler,
  545. hr_second_pass_steps,
  546. hr_resize_x,
  547. hr_resize_y,
  548. ] + custom_inputs,
  549. outputs=[
  550. txt2img_gallery,
  551. generation_info,
  552. html_info,
  553. html_log,
  554. ],
  555. show_progress=False,
  556. )
  557. txt2img_prompt.submit(**txt2img_args)
  558. submit.click(**txt2img_args)
  559. txt_prompt_img.change(
  560. fn=modules.images.image_data,
  561. inputs=[
  562. txt_prompt_img
  563. ],
  564. outputs=[
  565. txt2img_prompt,
  566. txt_prompt_img
  567. ]
  568. )
  569. enable_hr.change(
  570. fn=lambda x: gr_show(x),
  571. inputs=[enable_hr],
  572. outputs=[hr_options],
  573. show_progress = False,
  574. )
  575. txt2img_paste_fields = [
  576. (txt2img_prompt, "Prompt"),
  577. (txt2img_negative_prompt, "Negative prompt"),
  578. (steps, "Steps"),
  579. (sampler_index, "Sampler"),
  580. (restore_faces, "Face restoration"),
  581. (cfg_scale, "CFG scale"),
  582. (seed, "Seed"),
  583. (width, "Size-1"),
  584. (height, "Size-2"),
  585. (batch_size, "Batch size"),
  586. (subseed, "Variation seed"),
  587. (subseed_strength, "Variation seed strength"),
  588. (seed_resize_from_w, "Seed resize from-1"),
  589. (seed_resize_from_h, "Seed resize from-2"),
  590. (denoising_strength, "Denoising strength"),
  591. (enable_hr, lambda d: "Denoising strength" in d),
  592. (hr_options, lambda d: gr.Row.update(visible="Denoising strength" in d)),
  593. (hr_scale, "Hires upscale"),
  594. (hr_upscaler, "Hires upscaler"),
  595. (hr_second_pass_steps, "Hires steps"),
  596. (hr_resize_x, "Hires resize-1"),
  597. (hr_resize_y, "Hires resize-2"),
  598. *modules.scripts.scripts_txt2img.infotext_fields
  599. ]
  600. parameters_copypaste.add_paste_fields("txt2img", None, txt2img_paste_fields)
  601. txt2img_preview_params = [
  602. txt2img_prompt,
  603. txt2img_negative_prompt,
  604. steps,
  605. sampler_index,
  606. cfg_scale,
  607. seed,
  608. width,
  609. height,
  610. ]
  611. token_button.click(fn=wrap_queued_call(update_token_counter), inputs=[txt2img_prompt, steps], outputs=[token_counter])
  612. modules.scripts.scripts_current = modules.scripts.scripts_img2img
  613. modules.scripts.scripts_img2img.initialize_scripts(is_img2img=True)
  614. with gr.Blocks(analytics_enabled=False) as img2img_interface:
  615. img2img_prompt, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_deepbooru, img2img_prompt_style_apply, img2img_save_style, img2img_paste,token_counter, token_button = create_toprow(is_img2img=True)
  616. img2img_prompt_img = gr.File(label="", elem_id="img2img_prompt_image", file_count="single", type="bytes", visible=False)
  617. with FormRow().style(equal_height=False):
  618. with gr.Column(variant='panel', elem_id="img2img_settings"):
  619. copy_image_buttons = []
  620. copy_image_destinations = {}
  621. def add_copy_image_controls(tab_name, elem):
  622. with gr.Row(variant="compact", elem_id=f"img2img_copy_to_{tab_name}"):
  623. gr.HTML("Copy image to: ", elem_id=f"img2img_label_copy_to_{tab_name}")
  624. for title, name in zip(['img2img', 'sketch', 'inpaint', 'inpaint sketch'], ['img2img', 'sketch', 'inpaint', 'inpaint_sketch']):
  625. if name == tab_name:
  626. gr.Button(title, interactive=False)
  627. copy_image_destinations[name] = elem
  628. continue
  629. button = gr.Button(title)
  630. copy_image_buttons.append((button, name, elem))
  631. with gr.Tabs(elem_id="mode_img2img"):
  632. with gr.TabItem('img2img', id='img2img', elem_id="img2img_img2img_tab") as tab_img2img:
  633. 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)
  634. add_copy_image_controls('img2img', init_img)
  635. with gr.TabItem('Sketch', id='img2img_sketch', elem_id="img2img_img2img_sketch_tab") as tab_sketch:
  636. 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)
  637. add_copy_image_controls('sketch', sketch)
  638. with gr.TabItem('Inpaint', id='inpaint', elem_id="img2img_inpaint_tab") as tab_inpaint:
  639. 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)
  640. add_copy_image_controls('inpaint', init_img_with_mask)
  641. with gr.TabItem('Inpaint sketch', id='inpaint_sketch', elem_id="img2img_inpaint_sketch_tab") as tab_inpaint_color:
  642. 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)
  643. inpaint_color_sketch_orig = gr.State(None)
  644. add_copy_image_controls('inpaint_sketch', inpaint_color_sketch)
  645. def update_orig(image, state):
  646. if image is not None:
  647. same_size = state is not None and state.size == image.size
  648. has_exact_match = np.any(np.all(np.array(image) == np.array(state), axis=-1))
  649. edited = same_size and has_exact_match
  650. return image if not edited or state is None else state
  651. inpaint_color_sketch.change(update_orig, [inpaint_color_sketch, inpaint_color_sketch_orig], inpaint_color_sketch_orig)
  652. with gr.TabItem('Inpaint upload', id='inpaint_upload', elem_id="img2img_inpaint_upload_tab") as tab_inpaint_upload:
  653. init_img_inpaint = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil", elem_id="img_inpaint_base")
  654. init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", elem_id="img_inpaint_mask")
  655. with gr.TabItem('Batch', id='batch', elem_id="img2img_batch_tab") as tab_batch:
  656. hidden = '<br>Disabled when launched with --hide-ui-dir-config.' if shared.cmd_opts.hide_ui_dir_config else ''
  657. gr.HTML(f"<p style='padding-bottom: 1em;' class=\"text-gray-500\">Process images in a directory on the same machine where the server is running.<br>Use an empty output directory to save pictures normally instead of writing to the output directory.{hidden}</p>")
  658. img2img_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, elem_id="img2img_batch_input_dir")
  659. img2img_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, elem_id="img2img_batch_output_dir")
  660. def copy_image(img):
  661. if isinstance(img, dict) and 'image' in img:
  662. return img['image']
  663. return img
  664. for button, name, elem in copy_image_buttons:
  665. button.click(
  666. fn=copy_image,
  667. inputs=[elem],
  668. outputs=[copy_image_destinations[name]],
  669. )
  670. button.click(
  671. fn=lambda: None,
  672. _js="switch_to_"+name.replace(" ", "_"),
  673. inputs=[],
  674. outputs=[],
  675. )
  676. with FormGroup(elem_id="inpaint_controls", visible=False) as inpaint_controls:
  677. with FormRow():
  678. mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, elem_id="img2img_mask_blur")
  679. mask_alpha = gr.Slider(label="Mask transparency", visible=False, elem_id="img2img_mask_alpha")
  680. with FormRow():
  681. inpainting_mask_invert = gr.Radio(label='Mask mode', choices=['Inpaint masked', 'Inpaint not masked'], value='Inpaint masked', type="index", elem_id="img2img_mask_mode")
  682. with FormRow():
  683. inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='original', type="index", elem_id="img2img_inpainting_fill")
  684. with FormRow():
  685. with gr.Column():
  686. inpaint_full_res = gr.Radio(label="Inpaint area", choices=["Whole picture", "Only masked"], type="index", value="Whole picture", elem_id="img2img_inpaint_full_res")
  687. with gr.Column(scale=4):
  688. 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")
  689. def select_img2img_tab(tab):
  690. return gr.update(visible=tab in [2, 3, 4]), gr.update(visible=tab == 3),
  691. for i, elem in enumerate([tab_img2img, tab_sketch, tab_inpaint, tab_inpaint_color, tab_inpaint_upload, tab_batch]):
  692. elem.select(
  693. fn=lambda tab=i: select_img2img_tab(tab),
  694. inputs=[],
  695. outputs=[inpaint_controls, mask_alpha],
  696. )
  697. with FormRow():
  698. 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")
  699. for category in ordered_ui_categories():
  700. if category == "sampler":
  701. steps, sampler_index = create_sampler_and_steps_selection(samplers_for_img2img, "img2img")
  702. elif category == "dimensions":
  703. with FormRow():
  704. with gr.Column(elem_id="img2img_column_size", scale=4):
  705. width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="img2img_width")
  706. height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="img2img_height")
  707. if opts.dimensions_and_batch_together:
  708. with gr.Column(elem_id="img2img_column_batch"):
  709. batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count")
  710. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size")
  711. elif category == "cfg":
  712. with FormGroup():
  713. cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0, elem_id="img2img_cfg_scale")
  714. denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.75, elem_id="img2img_denoising_strength")
  715. elif category == "seed":
  716. seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs('img2img')
  717. elif category == "checkboxes":
  718. with FormRow(elem_id="img2img_checkboxes"):
  719. restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1, elem_id="img2img_restore_faces")
  720. tiling = gr.Checkbox(label='Tiling', value=False, elem_id="img2img_tiling")
  721. elif category == "batch":
  722. if not opts.dimensions_and_batch_together:
  723. with FormRow(elem_id="img2img_column_batch"):
  724. batch_count = gr.Slider(minimum=1, step=1, label='Batch count', value=1, elem_id="img2img_batch_count")
  725. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1, elem_id="img2img_batch_size")
  726. elif category == "scripts":
  727. with FormGroup(elem_id="img2img_script_container"):
  728. custom_inputs = modules.scripts.scripts_img2img.setup_ui()
  729. img2img_gallery, generation_info, html_info, html_log = create_output_panel("img2img", opts.outdir_img2img_samples)
  730. parameters_copypaste.bind_buttons({"img2img": img2img_paste}, None, img2img_prompt)
  731. connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
  732. connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
  733. img2img_prompt_img.change(
  734. fn=modules.images.image_data,
  735. inputs=[
  736. img2img_prompt_img
  737. ],
  738. outputs=[
  739. img2img_prompt,
  740. img2img_prompt_img
  741. ]
  742. )
  743. img2img_args = dict(
  744. fn=wrap_gradio_gpu_call(modules.img2img.img2img, extra_outputs=[None, '', '']),
  745. _js="submit_img2img",
  746. inputs=[
  747. dummy_component,
  748. dummy_component,
  749. img2img_prompt,
  750. img2img_negative_prompt,
  751. img2img_prompt_style,
  752. img2img_prompt_style2,
  753. init_img,
  754. sketch,
  755. init_img_with_mask,
  756. inpaint_color_sketch,
  757. inpaint_color_sketch_orig,
  758. init_img_inpaint,
  759. init_mask_inpaint,
  760. steps,
  761. sampler_index,
  762. mask_blur,
  763. mask_alpha,
  764. inpainting_fill,
  765. restore_faces,
  766. tiling,
  767. batch_count,
  768. batch_size,
  769. cfg_scale,
  770. denoising_strength,
  771. seed,
  772. subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
  773. height,
  774. width,
  775. resize_mode,
  776. inpaint_full_res,
  777. inpaint_full_res_padding,
  778. inpainting_mask_invert,
  779. img2img_batch_input_dir,
  780. img2img_batch_output_dir,
  781. ] + custom_inputs,
  782. outputs=[
  783. img2img_gallery,
  784. generation_info,
  785. html_info,
  786. html_log,
  787. ],
  788. show_progress=False,
  789. )
  790. img2img_prompt.submit(**img2img_args)
  791. submit.click(**img2img_args)
  792. img2img_interrogate.click(
  793. fn=interrogate,
  794. inputs=[init_img],
  795. outputs=[img2img_prompt],
  796. )
  797. img2img_deepbooru.click(
  798. fn=interrogate_deepbooru,
  799. inputs=[init_img],
  800. outputs=[img2img_prompt],
  801. )
  802. prompts = [(txt2img_prompt, txt2img_negative_prompt), (img2img_prompt, img2img_negative_prompt)]
  803. style_dropdowns = [(txt2img_prompt_style, txt2img_prompt_style2), (img2img_prompt_style, img2img_prompt_style2)]
  804. style_js_funcs = ["update_txt2img_tokens", "update_img2img_tokens"]
  805. for button, (prompt, negative_prompt) in zip([txt2img_save_style, img2img_save_style], prompts):
  806. button.click(
  807. fn=add_style,
  808. _js="ask_for_style_name",
  809. # Have to pass empty dummy component here, because the JavaScript and Python function have to accept
  810. # the same number of parameters, but we only know the style-name after the JavaScript prompt
  811. inputs=[dummy_component, prompt, negative_prompt],
  812. outputs=[txt2img_prompt_style, img2img_prompt_style, txt2img_prompt_style2, img2img_prompt_style2],
  813. )
  814. for button, (prompt, negative_prompt), (style1, style2), js_func in zip([txt2img_prompt_style_apply, img2img_prompt_style_apply], prompts, style_dropdowns, style_js_funcs):
  815. button.click(
  816. fn=apply_styles,
  817. _js=js_func,
  818. inputs=[prompt, negative_prompt, style1, style2],
  819. outputs=[prompt, negative_prompt, style1, style2],
  820. )
  821. token_button.click(fn=update_token_counter, inputs=[img2img_prompt, steps], outputs=[token_counter])
  822. img2img_paste_fields = [
  823. (img2img_prompt, "Prompt"),
  824. (img2img_negative_prompt, "Negative prompt"),
  825. (steps, "Steps"),
  826. (sampler_index, "Sampler"),
  827. (restore_faces, "Face restoration"),
  828. (cfg_scale, "CFG scale"),
  829. (seed, "Seed"),
  830. (width, "Size-1"),
  831. (height, "Size-2"),
  832. (batch_size, "Batch size"),
  833. (subseed, "Variation seed"),
  834. (subseed_strength, "Variation seed strength"),
  835. (seed_resize_from_w, "Seed resize from-1"),
  836. (seed_resize_from_h, "Seed resize from-2"),
  837. (denoising_strength, "Denoising strength"),
  838. (mask_blur, "Mask blur"),
  839. *modules.scripts.scripts_img2img.infotext_fields
  840. ]
  841. parameters_copypaste.add_paste_fields("img2img", init_img, img2img_paste_fields)
  842. parameters_copypaste.add_paste_fields("inpaint", init_img_with_mask, img2img_paste_fields)
  843. modules.scripts.scripts_current = None
  844. with gr.Blocks(analytics_enabled=False) as extras_interface:
  845. with gr.Row().style(equal_height=False):
  846. with gr.Column(variant='panel'):
  847. with gr.Tabs(elem_id="mode_extras"):
  848. with gr.TabItem('Single Image', elem_id="extras_single_tab"):
  849. extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil", elem_id="extras_image")
  850. with gr.TabItem('Batch Process', elem_id="extras_batch_process_tab"):
  851. image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file", elem_id="extras_image_batch")
  852. with gr.TabItem('Batch from Directory', elem_id="extras_batch_directory_tab"):
  853. extras_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs, placeholder="A directory on the same machine where the server is running.", elem_id="extras_batch_input_dir")
  854. extras_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs, placeholder="Leave blank to save images to the default path.", elem_id="extras_batch_output_dir")
  855. show_extras_results = gr.Checkbox(label='Show result images', value=True, elem_id="extras_show_extras_results")
  856. submit = gr.Button('Generate', elem_id="extras_generate", variant='primary')
  857. with gr.Tabs(elem_id="extras_resize_mode"):
  858. with gr.TabItem('Scale by', elem_id="extras_scale_by_tab"):
  859. upscaling_resize = gr.Slider(minimum=1.0, maximum=8.0, step=0.05, label="Resize", value=4, elem_id="extras_upscaling_resize")
  860. with gr.TabItem('Scale to', elem_id="extras_scale_to_tab"):
  861. with gr.Group():
  862. with gr.Row():
  863. upscaling_resize_w = gr.Number(label="Width", value=512, precision=0, elem_id="extras_upscaling_resize_w")
  864. upscaling_resize_h = gr.Number(label="Height", value=512, precision=0, elem_id="extras_upscaling_resize_h")
  865. upscaling_crop = gr.Checkbox(label='Crop to fit', value=True, elem_id="extras_upscaling_crop")
  866. with gr.Group():
  867. extras_upscaler_1 = gr.Radio(label='Upscaler 1', elem_id="extras_upscaler_1", choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index")
  868. with gr.Group():
  869. extras_upscaler_2 = gr.Radio(label='Upscaler 2', elem_id="extras_upscaler_2", choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index")
  870. extras_upscaler_2_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="Upscaler 2 visibility", value=1, elem_id="extras_upscaler_2_visibility")
  871. with gr.Group():
  872. gfpgan_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="GFPGAN visibility", value=0, interactive=modules.gfpgan_model.have_gfpgan, elem_id="extras_gfpgan_visibility")
  873. with gr.Group():
  874. codeformer_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="CodeFormer visibility", value=0, interactive=modules.codeformer_model.have_codeformer, elem_id="extras_codeformer_visibility")
  875. codeformer_weight = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="CodeFormer weight (0 = maximum effect, 1 = minimum effect)", value=0, interactive=modules.codeformer_model.have_codeformer, elem_id="extras_codeformer_weight")
  876. with gr.Group():
  877. upscale_before_face_fix = gr.Checkbox(label='Upscale Before Restoring Faces', value=False, elem_id="extras_upscale_before_face_fix")
  878. result_images, html_info_x, html_info, html_log = create_output_panel("extras", opts.outdir_extras_samples)
  879. submit.click(
  880. fn=wrap_gradio_gpu_call(modules.extras.run_extras, extra_outputs=[None, '']),
  881. _js="get_extras_tab_index",
  882. inputs=[
  883. dummy_component,
  884. dummy_component,
  885. extras_image,
  886. image_batch,
  887. extras_batch_input_dir,
  888. extras_batch_output_dir,
  889. show_extras_results,
  890. gfpgan_visibility,
  891. codeformer_visibility,
  892. codeformer_weight,
  893. upscaling_resize,
  894. upscaling_resize_w,
  895. upscaling_resize_h,
  896. upscaling_crop,
  897. extras_upscaler_1,
  898. extras_upscaler_2,
  899. extras_upscaler_2_visibility,
  900. upscale_before_face_fix,
  901. ],
  902. outputs=[
  903. result_images,
  904. html_info_x,
  905. html_info,
  906. ]
  907. )
  908. parameters_copypaste.add_paste_fields("extras", extras_image, None)
  909. extras_image.change(
  910. fn=modules.extras.clear_cache,
  911. inputs=[], outputs=[]
  912. )
  913. with gr.Blocks(analytics_enabled=False) as pnginfo_interface:
  914. with gr.Row().style(equal_height=False):
  915. with gr.Column(variant='panel'):
  916. image = gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil")
  917. with gr.Column(variant='panel'):
  918. html = gr.HTML()
  919. generation_info = gr.Textbox(visible=False, elem_id="pnginfo_generation_info")
  920. html2 = gr.HTML()
  921. with gr.Row():
  922. buttons = parameters_copypaste.create_buttons(["txt2img", "img2img", "inpaint", "extras"])
  923. parameters_copypaste.bind_buttons(buttons, image, generation_info)
  924. image.change(
  925. fn=wrap_gradio_call(modules.extras.run_pnginfo),
  926. inputs=[image],
  927. outputs=[html, generation_info, html2],
  928. )
  929. with gr.Blocks(analytics_enabled=False) as modelmerger_interface:
  930. with gr.Row().style(equal_height=False):
  931. with gr.Column(variant='panel'):
  932. gr.HTML(value="<p>A merger of the two checkpoints will be generated in your <b>checkpoint</b> directory.</p>")
  933. with FormRow():
  934. primary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_primary_model_name", label="Primary model (A)")
  935. create_refresh_button(primary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_A")
  936. secondary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_secondary_model_name", label="Secondary model (B)")
  937. create_refresh_button(secondary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_B")
  938. tertiary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_tertiary_model_name", label="Tertiary model (C)")
  939. create_refresh_button(tertiary_model_name, modules.sd_models.list_models, lambda: {"choices": modules.sd_models.checkpoint_tiles()}, "refresh_checkpoint_C")
  940. custom_name = gr.Textbox(label="Custom Name (Optional)", elem_id="modelmerger_custom_name")
  941. 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")
  942. interp_method = gr.Radio(choices=["Weighted sum", "Add difference"], value="Weighted sum", label="Interpolation Method", elem_id="modelmerger_interp_method")
  943. with FormRow():
  944. checkpoint_format = gr.Radio(choices=["ckpt", "safetensors"], value="ckpt", label="Checkpoint format", elem_id="modelmerger_checkpoint_format")
  945. save_as_half = gr.Checkbox(value=False, label="Save as float16", elem_id="modelmerger_save_as_half")
  946. 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")
  947. modelmerger_merge = gr.Button(elem_id="modelmerger_merge", value="Merge", variant='primary')
  948. with gr.Column(variant='panel'):
  949. submit_result = gr.Textbox(elem_id="modelmerger_result", show_label=False)
  950. with gr.Blocks(analytics_enabled=False) as train_interface:
  951. with gr.Row().style(equal_height=False):
  952. 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>")
  953. with gr.Row().style(equal_height=False):
  954. with gr.Tabs(elem_id="train_tabs"):
  955. with gr.Tab(label="Create embedding"):
  956. new_embedding_name = gr.Textbox(label="Name", elem_id="train_new_embedding_name")
  957. initialization_text = gr.Textbox(label="Initialization text", value="*", elem_id="train_initialization_text")
  958. nvpt = gr.Slider(label="Number of vectors per token", minimum=1, maximum=75, step=1, value=1, elem_id="train_nvpt")
  959. overwrite_old_embedding = gr.Checkbox(value=False, label="Overwrite Old Embedding", elem_id="train_overwrite_old_embedding")
  960. with gr.Row():
  961. with gr.Column(scale=3):
  962. gr.HTML(value="")
  963. with gr.Column():
  964. create_embedding = gr.Button(value="Create embedding", variant='primary', elem_id="train_create_embedding")
  965. with gr.Tab(label="Create hypernetwork"):
  966. new_hypernetwork_name = gr.Textbox(label="Name", elem_id="train_new_hypernetwork_name")
  967. new_hypernetwork_sizes = gr.CheckboxGroup(label="Modules", value=["768", "320", "640", "1280"], choices=["768", "1024", "320", "640", "1280"], elem_id="train_new_hypernetwork_sizes")
  968. 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")
  969. 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")
  970. 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")
  971. new_hypernetwork_add_layer_norm = gr.Checkbox(label="Add layer normalization", elem_id="train_new_hypernetwork_add_layer_norm")
  972. new_hypernetwork_use_dropout = gr.Checkbox(label="Use dropout", elem_id="train_new_hypernetwork_use_dropout")
  973. 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'")
  974. overwrite_old_hypernetwork = gr.Checkbox(value=False, label="Overwrite Old Hypernetwork", elem_id="train_overwrite_old_hypernetwork")
  975. with gr.Row():
  976. with gr.Column(scale=3):
  977. gr.HTML(value="")
  978. with gr.Column():
  979. create_hypernetwork = gr.Button(value="Create hypernetwork", variant='primary', elem_id="train_create_hypernetwork")
  980. with gr.Tab(label="Preprocess images"):
  981. process_src = gr.Textbox(label='Source directory', elem_id="train_process_src")
  982. process_dst = gr.Textbox(label='Destination directory', elem_id="train_process_dst")
  983. process_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_process_width")
  984. process_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_process_height")
  985. preprocess_txt_action = gr.Dropdown(label='Existing Caption txt Action', value="ignore", choices=["ignore", "copy", "prepend", "append"], elem_id="train_preprocess_txt_action")
  986. with gr.Row():
  987. process_flip = gr.Checkbox(label='Create flipped copies', elem_id="train_process_flip")
  988. process_split = gr.Checkbox(label='Split oversized images', elem_id="train_process_split")
  989. process_focal_crop = gr.Checkbox(label='Auto focal point crop', elem_id="train_process_focal_crop")
  990. process_caption = gr.Checkbox(label='Use BLIP for caption', elem_id="train_process_caption")
  991. process_caption_deepbooru = gr.Checkbox(label='Use deepbooru for caption', visible=True, elem_id="train_process_caption_deepbooru")
  992. with gr.Row(visible=False) as process_split_extra_row:
  993. 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")
  994. 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")
  995. with gr.Row(visible=False) as process_focal_crop_row:
  996. 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")
  997. 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")
  998. 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")
  999. process_focal_crop_debug = gr.Checkbox(label='Create debug image', elem_id="train_process_focal_crop_debug")
  1000. with gr.Row():
  1001. with gr.Column(scale=3):
  1002. gr.HTML(value="")
  1003. with gr.Column():
  1004. with gr.Row():
  1005. interrupt_preprocessing = gr.Button("Interrupt", elem_id="train_interrupt_preprocessing")
  1006. run_preprocess = gr.Button(value="Preprocess", variant='primary', elem_id="train_run_preprocess")
  1007. process_split.change(
  1008. fn=lambda show: gr_show(show),
  1009. inputs=[process_split],
  1010. outputs=[process_split_extra_row],
  1011. )
  1012. process_focal_crop.change(
  1013. fn=lambda show: gr_show(show),
  1014. inputs=[process_focal_crop],
  1015. outputs=[process_focal_crop_row],
  1016. )
  1017. def get_textual_inversion_template_names():
  1018. return sorted([x for x in textual_inversion.textual_inversion_templates])
  1019. with gr.Tab(label="Train"):
  1020. 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>")
  1021. with FormRow():
  1022. train_embedding_name = gr.Dropdown(label='Embedding', elem_id="train_embedding", choices=sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys()))
  1023. 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")
  1024. train_hypernetwork_name = gr.Dropdown(label='Hypernetwork', elem_id="train_hypernetwork", choices=[x for x in shared.hypernetworks.keys()])
  1025. create_refresh_button(train_hypernetwork_name, shared.reload_hypernetworks, lambda: {"choices": sorted([x for x in shared.hypernetworks.keys()])}, "refresh_train_hypernetwork_name")
  1026. with FormRow():
  1027. embedding_learn_rate = gr.Textbox(label='Embedding Learning rate', placeholder="Embedding Learning rate", value="0.005", elem_id="train_embedding_learn_rate")
  1028. hypernetwork_learn_rate = gr.Textbox(label='Hypernetwork Learning rate', placeholder="Hypernetwork Learning rate", value="0.00001", elem_id="train_hypernetwork_learn_rate")
  1029. with FormRow():
  1030. clip_grad_mode = gr.Dropdown(value="disabled", label="Gradient Clipping", choices=["disabled", "value", "norm"])
  1031. clip_grad_value = gr.Textbox(placeholder="Gradient clip value", value="0.1", show_label=False)
  1032. with FormRow():
  1033. batch_size = gr.Number(label='Batch size', value=1, precision=0, elem_id="train_batch_size")
  1034. gradient_step = gr.Number(label='Gradient accumulation steps', value=1, precision=0, elem_id="train_gradient_step")
  1035. dataset_directory = gr.Textbox(label='Dataset directory', placeholder="Path to directory with input images", elem_id="train_dataset_directory")
  1036. log_directory = gr.Textbox(label='Log directory', placeholder="Path to directory where to write outputs", value="textual_inversion", elem_id="train_log_directory")
  1037. with FormRow():
  1038. template_file = gr.Dropdown(label='Prompt template', value="style_filewords.txt", elem_id="train_template_file", choices=get_textual_inversion_template_names())
  1039. create_refresh_button(template_file, textual_inversion.list_textual_inversion_templates, lambda: {"choices": get_textual_inversion_template_names()}, "refrsh_train_template_file")
  1040. training_width = gr.Slider(minimum=64, maximum=2048, step=8, label="Width", value=512, elem_id="train_training_width")
  1041. training_height = gr.Slider(minimum=64, maximum=2048, step=8, label="Height", value=512, elem_id="train_training_height")
  1042. varsize = gr.Checkbox(label="Do not resize images", value=False, elem_id="train_varsize")
  1043. steps = gr.Number(label='Max steps', value=100000, precision=0, elem_id="train_steps")
  1044. with FormRow():
  1045. 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")
  1046. 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")
  1047. 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")
  1048. preview_from_txt2img = gr.Checkbox(label='Read parameters (prompt, etc...) from txt2img tab when making previews', value=False, elem_id="train_preview_from_txt2img")
  1049. shuffle_tags = gr.Checkbox(label="Shuffle tags by ',' when creating prompts.", value=False, elem_id="train_shuffle_tags")
  1050. 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")
  1051. latent_sampling_method = gr.Radio(label='Choose latent sampling method', value="once", choices=['once', 'deterministic', 'random'], elem_id="train_latent_sampling_method")
  1052. with gr.Row():
  1053. train_embedding = gr.Button(value="Train Embedding", variant='primary', elem_id="train_train_embedding")
  1054. interrupt_training = gr.Button(value="Interrupt", elem_id="train_interrupt_training")
  1055. train_hypernetwork = gr.Button(value="Train Hypernetwork", variant='primary', elem_id="train_train_hypernetwork")
  1056. params = script_callbacks.UiTrainTabParams(txt2img_preview_params)
  1057. script_callbacks.ui_train_tabs_callback(params)
  1058. with gr.Column(elem_id='ti_gallery_container'):
  1059. ti_output = gr.Text(elem_id="ti_output", value="", show_label=False)
  1060. ti_gallery = gr.Gallery(label='Output', show_label=False, elem_id='ti_gallery').style(grid=4)
  1061. ti_progress = gr.HTML(elem_id="ti_progress", value="")
  1062. ti_outcome = gr.HTML(elem_id="ti_error", value="")
  1063. create_embedding.click(
  1064. fn=modules.textual_inversion.ui.create_embedding,
  1065. inputs=[
  1066. new_embedding_name,
  1067. initialization_text,
  1068. nvpt,
  1069. overwrite_old_embedding,
  1070. ],
  1071. outputs=[
  1072. train_embedding_name,
  1073. ti_output,
  1074. ti_outcome,
  1075. ]
  1076. )
  1077. create_hypernetwork.click(
  1078. fn=modules.hypernetworks.ui.create_hypernetwork,
  1079. inputs=[
  1080. new_hypernetwork_name,
  1081. new_hypernetwork_sizes,
  1082. overwrite_old_hypernetwork,
  1083. new_hypernetwork_layer_structure,
  1084. new_hypernetwork_activation_func,
  1085. new_hypernetwork_initialization_option,
  1086. new_hypernetwork_add_layer_norm,
  1087. new_hypernetwork_use_dropout,
  1088. new_hypernetwork_dropout_structure
  1089. ],
  1090. outputs=[
  1091. train_hypernetwork_name,
  1092. ti_output,
  1093. ti_outcome,
  1094. ]
  1095. )
  1096. run_preprocess.click(
  1097. fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.preprocess, extra_outputs=[gr.update()]),
  1098. _js="start_training_textual_inversion",
  1099. inputs=[
  1100. dummy_component,
  1101. process_src,
  1102. process_dst,
  1103. process_width,
  1104. process_height,
  1105. preprocess_txt_action,
  1106. process_flip,
  1107. process_split,
  1108. process_caption,
  1109. process_caption_deepbooru,
  1110. process_split_threshold,
  1111. process_overlap_ratio,
  1112. process_focal_crop,
  1113. process_focal_crop_face_weight,
  1114. process_focal_crop_entropy_weight,
  1115. process_focal_crop_edges_weight,
  1116. process_focal_crop_debug,
  1117. ],
  1118. outputs=[
  1119. ti_output,
  1120. ti_outcome,
  1121. ],
  1122. )
  1123. train_embedding.click(
  1124. fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.train_embedding, extra_outputs=[gr.update()]),
  1125. _js="start_training_textual_inversion",
  1126. inputs=[
  1127. dummy_component,
  1128. train_embedding_name,
  1129. embedding_learn_rate,
  1130. batch_size,
  1131. gradient_step,
  1132. dataset_directory,
  1133. log_directory,
  1134. training_width,
  1135. training_height,
  1136. varsize,
  1137. steps,
  1138. clip_grad_mode,
  1139. clip_grad_value,
  1140. shuffle_tags,
  1141. tag_drop_out,
  1142. latent_sampling_method,
  1143. create_image_every,
  1144. save_embedding_every,
  1145. template_file,
  1146. save_image_with_stored_embedding,
  1147. preview_from_txt2img,
  1148. *txt2img_preview_params,
  1149. ],
  1150. outputs=[
  1151. ti_output,
  1152. ti_outcome,
  1153. ]
  1154. )
  1155. train_hypernetwork.click(
  1156. fn=wrap_gradio_gpu_call(modules.hypernetworks.ui.train_hypernetwork, extra_outputs=[gr.update()]),
  1157. _js="start_training_textual_inversion",
  1158. inputs=[
  1159. dummy_component,
  1160. train_hypernetwork_name,
  1161. hypernetwork_learn_rate,
  1162. batch_size,
  1163. gradient_step,
  1164. dataset_directory,
  1165. log_directory,
  1166. training_width,
  1167. training_height,
  1168. varsize,
  1169. steps,
  1170. clip_grad_mode,
  1171. clip_grad_value,
  1172. shuffle_tags,
  1173. tag_drop_out,
  1174. latent_sampling_method,
  1175. create_image_every,
  1176. save_embedding_every,
  1177. template_file,
  1178. preview_from_txt2img,
  1179. *txt2img_preview_params,
  1180. ],
  1181. outputs=[
  1182. ti_output,
  1183. ti_outcome,
  1184. ]
  1185. )
  1186. interrupt_training.click(
  1187. fn=lambda: shared.state.interrupt(),
  1188. inputs=[],
  1189. outputs=[],
  1190. )
  1191. interrupt_preprocessing.click(
  1192. fn=lambda: shared.state.interrupt(),
  1193. inputs=[],
  1194. outputs=[],
  1195. )
  1196. def create_setting_component(key, is_quicksettings=False):
  1197. def fun():
  1198. return opts.data[key] if key in opts.data else opts.data_labels[key].default
  1199. info = opts.data_labels[key]
  1200. t = type(info.default)
  1201. args = info.component_args() if callable(info.component_args) else info.component_args
  1202. if info.component is not None:
  1203. comp = info.component
  1204. elif t == str:
  1205. comp = gr.Textbox
  1206. elif t == int:
  1207. comp = gr.Number
  1208. elif t == bool:
  1209. comp = gr.Checkbox
  1210. else:
  1211. raise Exception(f'bad options item type: {str(t)} for key {key}')
  1212. elem_id = "setting_"+key
  1213. if info.refresh is not None:
  1214. if is_quicksettings:
  1215. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  1216. create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key)
  1217. else:
  1218. with FormRow():
  1219. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  1220. create_refresh_button(res, info.refresh, info.component_args, "refresh_" + key)
  1221. else:
  1222. res = comp(label=info.label, value=fun(), elem_id=elem_id, **(args or {}))
  1223. return res
  1224. components = []
  1225. component_dict = {}
  1226. script_callbacks.ui_settings_callback()
  1227. opts.reorder()
  1228. def run_settings(*args):
  1229. changed = []
  1230. for key, value, comp in zip(opts.data_labels.keys(), args, components):
  1231. 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__}"
  1232. for key, value, comp in zip(opts.data_labels.keys(), args, components):
  1233. if comp == dummy_component:
  1234. continue
  1235. if opts.set(key, value):
  1236. changed.append(key)
  1237. try:
  1238. opts.save(shared.config_filename)
  1239. except RuntimeError:
  1240. return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.'
  1241. return opts.dumpjson(), f'{len(changed)} settings changed{": " if len(changed) > 0 else ""}{", ".join(changed)}.'
  1242. def run_settings_single(value, key):
  1243. if not opts.same_type(value, opts.data_labels[key].default):
  1244. return gr.update(visible=True), opts.dumpjson()
  1245. if not opts.set(key, value):
  1246. return gr.update(value=getattr(opts, key)), opts.dumpjson()
  1247. opts.save(shared.config_filename)
  1248. return gr.update(value=value), opts.dumpjson()
  1249. with gr.Blocks(analytics_enabled=False) as settings_interface:
  1250. with gr.Row():
  1251. with gr.Column(scale=6):
  1252. settings_submit = gr.Button(value="Apply settings", variant='primary', elem_id="settings_submit")
  1253. with gr.Column():
  1254. restart_gradio = gr.Button(value='Reload UI', variant='primary', elem_id="settings_restart_gradio")
  1255. result = gr.HTML(elem_id="settings_result")
  1256. quicksettings_names = [x.strip() for x in opts.quicksettings.split(",")]
  1257. quicksettings_names = {x: i for i, x in enumerate(quicksettings_names) if x != 'quicksettings'}
  1258. quicksettings_list = []
  1259. previous_section = None
  1260. current_tab = None
  1261. with gr.Tabs(elem_id="settings"):
  1262. for i, (k, item) in enumerate(opts.data_labels.items()):
  1263. section_must_be_skipped = item.section[0] is None
  1264. if previous_section != item.section and not section_must_be_skipped:
  1265. elem_id, text = item.section
  1266. if current_tab is not None:
  1267. current_tab.__exit__()
  1268. current_tab = gr.TabItem(elem_id="settings_{}".format(elem_id), label=text)
  1269. current_tab.__enter__()
  1270. previous_section = item.section
  1271. if k in quicksettings_names and not shared.cmd_opts.freeze_settings:
  1272. quicksettings_list.append((i, k, item))
  1273. components.append(dummy_component)
  1274. elif section_must_be_skipped:
  1275. components.append(dummy_component)
  1276. else:
  1277. component = create_setting_component(k)
  1278. component_dict[k] = component
  1279. components.append(component)
  1280. if current_tab is not None:
  1281. current_tab.__exit__()
  1282. with gr.TabItem("Actions"):
  1283. request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications")
  1284. download_localization = gr.Button(value='Download localization template', elem_id="download_localization")
  1285. reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary', elem_id="settings_reload_script_bodies")
  1286. if os.path.exists("html/licenses.html"):
  1287. with open("html/licenses.html", encoding="utf8") as file:
  1288. with gr.TabItem("Licenses"):
  1289. gr.HTML(file.read(), elem_id="licenses")
  1290. gr.Button(value="Show all pages", elem_id="settings_show_all_pages")
  1291. request_notifications.click(
  1292. fn=lambda: None,
  1293. inputs=[],
  1294. outputs=[],
  1295. _js='function(){}'
  1296. )
  1297. download_localization.click(
  1298. fn=lambda: None,
  1299. inputs=[],
  1300. outputs=[],
  1301. _js='download_localization'
  1302. )
  1303. def reload_scripts():
  1304. modules.scripts.reload_script_body_only()
  1305. reload_javascript() # need to refresh the html page
  1306. reload_script_bodies.click(
  1307. fn=reload_scripts,
  1308. inputs=[],
  1309. outputs=[]
  1310. )
  1311. def request_restart():
  1312. shared.state.interrupt()
  1313. shared.state.need_restart = True
  1314. restart_gradio.click(
  1315. fn=request_restart,
  1316. _js='restart_reload',
  1317. inputs=[],
  1318. outputs=[],
  1319. )
  1320. interfaces = [
  1321. (txt2img_interface, "txt2img", "txt2img"),
  1322. (img2img_interface, "img2img", "img2img"),
  1323. (extras_interface, "Extras", "extras"),
  1324. (pnginfo_interface, "PNG Info", "pnginfo"),
  1325. (modelmerger_interface, "Checkpoint Merger", "modelmerger"),
  1326. (train_interface, "Train", "ti"),
  1327. ]
  1328. css = ""
  1329. for cssfile in modules.scripts.list_files_with_name("style.css"):
  1330. if not os.path.isfile(cssfile):
  1331. continue
  1332. with open(cssfile, "r", encoding="utf8") as file:
  1333. css += file.read() + "\n"
  1334. if os.path.exists(os.path.join(script_path, "user.css")):
  1335. with open(os.path.join(script_path, "user.css"), "r", encoding="utf8") as file:
  1336. css += file.read() + "\n"
  1337. if not cmd_opts.no_progressbar_hiding:
  1338. css += css_hide_progressbar
  1339. interfaces += script_callbacks.ui_tabs_callback()
  1340. interfaces += [(settings_interface, "Settings", "settings")]
  1341. extensions_interface = ui_extensions.create_ui()
  1342. interfaces += [(extensions_interface, "Extensions", "extensions")]
  1343. with gr.Blocks(css=css, analytics_enabled=False, title="Stable Diffusion") as demo:
  1344. with gr.Row(elem_id="quicksettings"):
  1345. for i, k, item in sorted(quicksettings_list, key=lambda x: quicksettings_names.get(x[1], x[0])):
  1346. component = create_setting_component(k, is_quicksettings=True)
  1347. component_dict[k] = component
  1348. parameters_copypaste.integrate_settings_paste_fields(component_dict)
  1349. parameters_copypaste.run_bind()
  1350. with gr.Tabs(elem_id="tabs") as tabs:
  1351. for interface, label, ifid in interfaces:
  1352. with gr.TabItem(label, id=ifid, elem_id='tab_' + ifid):
  1353. interface.render()
  1354. if os.path.exists(os.path.join(script_path, "notification.mp3")):
  1355. audio_notification = gr.Audio(interactive=False, value=os.path.join(script_path, "notification.mp3"), elem_id="audio_notification", visible=False)
  1356. if os.path.exists("html/footer.html"):
  1357. with open("html/footer.html", encoding="utf8") as file:
  1358. footer = file.read()
  1359. footer = footer.format(versions=versions_html())
  1360. gr.HTML(footer, elem_id="footer")
  1361. text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
  1362. settings_submit.click(
  1363. fn=wrap_gradio_call(run_settings, extra_outputs=[gr.update()]),
  1364. inputs=components,
  1365. outputs=[text_settings, result],
  1366. )
  1367. for i, k, item in quicksettings_list:
  1368. component = component_dict[k]
  1369. component.change(
  1370. fn=lambda value, k=k: run_settings_single(value, key=k),
  1371. inputs=[component],
  1372. outputs=[component, text_settings],
  1373. )
  1374. component_keys = [k for k in opts.data_labels.keys() if k in component_dict]
  1375. def get_settings_values():
  1376. return [getattr(opts, key) for key in component_keys]
  1377. demo.load(
  1378. fn=get_settings_values,
  1379. inputs=[],
  1380. outputs=[component_dict[k] for k in component_keys],
  1381. )
  1382. def modelmerger(*args):
  1383. try:
  1384. results = modules.extras.run_modelmerger(*args)
  1385. except Exception as e:
  1386. print("Error loading/saving model file:", file=sys.stderr)
  1387. print(traceback.format_exc(), file=sys.stderr)
  1388. modules.sd_models.list_models() # to remove the potentially missing models from the list
  1389. return [f"Error merging checkpoints: {e}"] + [gr.Dropdown.update(choices=modules.sd_models.checkpoint_tiles()) for _ in range(4)]
  1390. return results
  1391. modelmerger_merge.click(
  1392. fn=modelmerger,
  1393. inputs=[
  1394. primary_model_name,
  1395. secondary_model_name,
  1396. tertiary_model_name,
  1397. interp_method,
  1398. interp_amount,
  1399. save_as_half,
  1400. custom_name,
  1401. checkpoint_format,
  1402. config_source,
  1403. ],
  1404. outputs=[
  1405. submit_result,
  1406. primary_model_name,
  1407. secondary_model_name,
  1408. tertiary_model_name,
  1409. component_dict['sd_model_checkpoint'],
  1410. ]
  1411. )
  1412. ui_config_file = cmd_opts.ui_config_file
  1413. ui_settings = {}
  1414. settings_count = len(ui_settings)
  1415. error_loading = False
  1416. try:
  1417. if os.path.exists(ui_config_file):
  1418. with open(ui_config_file, "r", encoding="utf8") as file:
  1419. ui_settings = json.load(file)
  1420. except Exception:
  1421. error_loading = True
  1422. print("Error loading settings:", file=sys.stderr)
  1423. print(traceback.format_exc(), file=sys.stderr)
  1424. def loadsave(path, x):
  1425. def apply_field(obj, field, condition=None, init_field=None):
  1426. key = path + "/" + field
  1427. if getattr(obj, 'custom_script_source', None) is not None:
  1428. key = 'customscript/' + obj.custom_script_source + '/' + key
  1429. if getattr(obj, 'do_not_save_to_config', False):
  1430. return
  1431. saved_value = ui_settings.get(key, None)
  1432. if saved_value is None:
  1433. ui_settings[key] = getattr(obj, field)
  1434. elif condition and not condition(saved_value):
  1435. print(f'Warning: Bad ui setting value: {key}: {saved_value}; Default value "{getattr(obj, field)}" will be used instead.')
  1436. else:
  1437. setattr(obj, field, saved_value)
  1438. if init_field is not None:
  1439. init_field(saved_value)
  1440. if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number, gr.Dropdown] and x.visible:
  1441. apply_field(x, 'visible')
  1442. if type(x) == gr.Slider:
  1443. apply_field(x, 'value')
  1444. apply_field(x, 'minimum')
  1445. apply_field(x, 'maximum')
  1446. apply_field(x, 'step')
  1447. if type(x) == gr.Radio:
  1448. apply_field(x, 'value', lambda val: val in x.choices)
  1449. if type(x) == gr.Checkbox:
  1450. apply_field(x, 'value')
  1451. if type(x) == gr.Textbox:
  1452. apply_field(x, 'value')
  1453. if type(x) == gr.Number:
  1454. apply_field(x, 'value')
  1455. if type(x) == gr.Dropdown:
  1456. apply_field(x, 'value', lambda val: val in x.choices, getattr(x, 'init_field', None))
  1457. visit(txt2img_interface, loadsave, "txt2img")
  1458. visit(img2img_interface, loadsave, "img2img")
  1459. visit(extras_interface, loadsave, "extras")
  1460. visit(modelmerger_interface, loadsave, "modelmerger")
  1461. visit(train_interface, loadsave, "train")
  1462. if not error_loading and (not os.path.exists(ui_config_file) or settings_count != len(ui_settings)):
  1463. with open(ui_config_file, "w", encoding="utf8") as file:
  1464. json.dump(ui_settings, file, indent=4)
  1465. return demo
  1466. def reload_javascript():
  1467. with open(os.path.join(script_path, "script.js"), "r", encoding="utf8") as jsfile:
  1468. javascript = f'<script>{jsfile.read()}</script>'
  1469. scripts_list = modules.scripts.list_scripts("javascript", ".js")
  1470. for basedir, filename, path in scripts_list:
  1471. with open(path, "r", encoding="utf8") as jsfile:
  1472. javascript += f"\n<!-- {filename} --><script>{jsfile.read()}</script>"
  1473. if cmd_opts.theme is not None:
  1474. javascript += f"\n<script>set_theme('{cmd_opts.theme}');</script>\n"
  1475. javascript += f"\n<script>{localization.localization_js(shared.opts.localization)}</script>"
  1476. def template_response(*args, **kwargs):
  1477. res = shared.GradioTemplateResponseOriginal(*args, **kwargs)
  1478. res.body = res.body.replace(
  1479. b'</head>', f'{javascript}</head>'.encode("utf8"))
  1480. res.init_headers()
  1481. return res
  1482. gradio.routes.templates.TemplateResponse = template_response
  1483. if not hasattr(shared, 'GradioTemplateResponseOriginal'):
  1484. shared.GradioTemplateResponseOriginal = gradio.routes.templates.TemplateResponse
  1485. def versions_html():
  1486. import torch
  1487. import launch
  1488. python_version = ".".join([str(x) for x in sys.version_info[0:3]])
  1489. commit = launch.commit_hash()
  1490. short_commit = commit[0:8]
  1491. if shared.xformers_available:
  1492. import xformers
  1493. xformers_version = xformers.__version__
  1494. else:
  1495. xformers_version = "N/A"
  1496. return f"""
  1497. python: <span title="{sys.version}">{python_version}</span>
  1498.  • 
  1499. torch: {torch.__version__}
  1500.  • 
  1501. xformers: {xformers_version}
  1502.  • 
  1503. gradio: {gr.__version__}
  1504.  • 
  1505. commit: <a href="https://github.com/AUTOMATIC1111/stable-diffusion-webui/commit/{commit}">{short_commit}</a>
  1506.  • 
  1507. checkpoint: <a id="sd_checkpoint_hash">N/A</a>
  1508. """