ui.py 79 KB

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