ui.py 81 KB

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