ui.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458
  1. import base64
  2. import html
  3. import io
  4. import json
  5. import math
  6. import mimetypes
  7. import os
  8. import random
  9. import sys
  10. import time
  11. import traceback
  12. import platform
  13. import subprocess as sp
  14. from functools import reduce
  15. import numpy as np
  16. import torch
  17. from PIL import Image, PngImagePlugin
  18. import piexif
  19. import gradio as gr
  20. import gradio.utils
  21. import gradio.routes
  22. from modules import sd_hijack
  23. from modules.paths import script_path
  24. from modules.shared import opts, cmd_opts
  25. import modules.shared as shared
  26. from modules.sd_samplers import samplers, samplers_for_img2img
  27. from modules.sd_hijack import model_hijack
  28. import modules.ldsr_model
  29. import modules.scripts
  30. import modules.gfpgan_model
  31. import modules.codeformer_model
  32. import modules.styles
  33. import modules.generation_parameters_copypaste
  34. from modules import prompt_parser
  35. from modules.images import save_image
  36. import modules.textual_inversion.ui
  37. import modules.hypernetwork.ui
  38. # this is a fix for Windows users. Without it, javascript files will be served with text/html content-type and the bowser 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. def gr_show(visible=True):
  46. return {"visible": visible, "__type__": "update"}
  47. sample_img2img = "assets/stable-samples/img2img/sketch-mountains-input.jpg"
  48. sample_img2img = sample_img2img if os.path.exists(sample_img2img) else None
  49. css_hide_progressbar = """
  50. .wrap .m-12 svg { display:none!important; }
  51. .wrap .m-12::before { content:"Loading..." }
  52. .progress-bar { display:none!important; }
  53. .meta-text { display:none!important; }
  54. """
  55. # Using constants for these since the variation selector isn't visible.
  56. # Important that they exactly match script.js for tooltip to work.
  57. random_symbol = '\U0001f3b2\ufe0f' # 🎲️
  58. reuse_symbol = '\u267b\ufe0f' # ♻️
  59. art_symbol = '\U0001f3a8' # 🎨
  60. paste_symbol = '\u2199\ufe0f' # ↙
  61. folder_symbol = '\U0001f4c2' # 📂
  62. def plaintext_to_html(text):
  63. text = "<p>" + "<br>\n".join([f"{html.escape(x)}" for x in text.split('\n')]) + "</p>"
  64. return text
  65. def image_from_url_text(filedata):
  66. if type(filedata) == list:
  67. if len(filedata) == 0:
  68. return None
  69. filedata = filedata[0]
  70. if filedata.startswith("data:image/png;base64,"):
  71. filedata = filedata[len("data:image/png;base64,"):]
  72. filedata = base64.decodebytes(filedata.encode('utf-8'))
  73. image = Image.open(io.BytesIO(filedata))
  74. return image
  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, index):
  80. import csv
  81. filenames = []
  82. #quick dictionary to class object conversion. Its neccesary due apply_filename_pattern requiring it
  83. class MyObject:
  84. def __init__(self, d=None):
  85. if d is not None:
  86. for key, value in d.items():
  87. setattr(self, key, value)
  88. data = json.loads(js_data)
  89. p = MyObject(data)
  90. path = opts.outdir_save
  91. save_to_dirs = opts.use_save_to_dirs_for_ui
  92. extension: str = opts.samples_format
  93. start_index = 0
  94. 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
  95. images = [images[index]]
  96. start_index = index
  97. with open(os.path.join(opts.outdir_save, "log.csv"), "a", encoding="utf8", newline='') as file:
  98. at_start = file.tell() == 0
  99. writer = csv.writer(file)
  100. if at_start:
  101. writer.writerow(["prompt", "seed", "width", "height", "sampler", "cfgs", "steps", "filename", "negative_prompt"])
  102. for image_index, filedata in enumerate(images, start_index):
  103. if filedata.startswith("data:image/png;base64,"):
  104. filedata = filedata[len("data:image/png;base64,"):]
  105. image = Image.open(io.BytesIO(base64.decodebytes(filedata.encode('utf-8'))))
  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 = 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. writer.writerow([data["prompt"], data["seed"], data["width"], data["height"], data["sampler"], data["cfg_scale"], data["steps"], filenames[0], data["negative_prompt"]])
  112. return '', '', plaintext_to_html(f"Saved: {filenames[0]}")
  113. def wrap_gradio_call(func, extra_outputs=None):
  114. def f(*args, extra_outputs_array=extra_outputs, **kwargs):
  115. run_memmon = opts.memmon_poll_rate > 0 and not shared.mem_mon.disabled
  116. if run_memmon:
  117. shared.mem_mon.monitor()
  118. t = time.perf_counter()
  119. try:
  120. res = list(func(*args, **kwargs))
  121. except Exception as e:
  122. print("Error completing request", file=sys.stderr)
  123. print("Arguments:", args, kwargs, file=sys.stderr)
  124. print(traceback.format_exc(), file=sys.stderr)
  125. shared.state.job = ""
  126. shared.state.job_count = 0
  127. if extra_outputs_array is None:
  128. extra_outputs_array = [None, '']
  129. res = extra_outputs_array + [f"<div class='error'>{plaintext_to_html(type(e).__name__+': '+str(e))}</div>"]
  130. elapsed = time.perf_counter() - t
  131. elapsed_m = int(elapsed // 60)
  132. elapsed_s = elapsed % 60
  133. elapsed_text = f"{elapsed_s:.2f}s"
  134. if (elapsed_m > 0):
  135. elapsed_text = f"{elapsed_m}m "+elapsed_text
  136. if run_memmon:
  137. mem_stats = {k: -(v//-(1024*1024)) for k, v in shared.mem_mon.stop().items()}
  138. active_peak = mem_stats['active_peak']
  139. reserved_peak = mem_stats['reserved_peak']
  140. sys_peak = mem_stats['system_peak']
  141. sys_total = mem_stats['total']
  142. sys_pct = round(sys_peak/max(sys_total, 1) * 100, 2)
  143. 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>"
  144. else:
  145. vram_html = ''
  146. # last item is always HTML
  147. res[-1] += f"<div class='performance'><p class='time'>Time taken: <wbr>{elapsed_text}</p>{vram_html}</div>"
  148. shared.state.interrupted = False
  149. shared.state.job_count = 0
  150. return tuple(res)
  151. return f
  152. def check_progress_call(id_part):
  153. if shared.state.job_count == 0:
  154. return "", gr_show(False), gr_show(False), gr_show(False)
  155. progress = 0
  156. if shared.state.job_count > 0:
  157. progress += shared.state.job_no / shared.state.job_count
  158. if shared.state.sampling_steps > 0:
  159. progress += 1 / shared.state.job_count * shared.state.sampling_step / shared.state.sampling_steps
  160. progress = min(progress, 1)
  161. progressbar = ""
  162. if opts.show_progressbar:
  163. progressbar = f"""<div class='progressDiv'><div class='progress' style="width:{progress * 100}%">{str(int(progress*100))+"%" if progress > 0.01 else ""}</div></div>"""
  164. image = gr_show(False)
  165. preview_visibility = gr_show(False)
  166. if opts.show_progress_every_n_steps > 0:
  167. if shared.parallel_processing_allowed:
  168. if shared.state.sampling_step - shared.state.current_image_sampling_step >= opts.show_progress_every_n_steps and shared.state.current_latent is not None:
  169. shared.state.current_image = modules.sd_samplers.sample_to_image(shared.state.current_latent)
  170. shared.state.current_image_sampling_step = shared.state.sampling_step
  171. image = shared.state.current_image
  172. if image is None:
  173. image = gr.update(value=None)
  174. else:
  175. preview_visibility = gr_show(True)
  176. if shared.state.textinfo is not None:
  177. textinfo_result = gr.HTML.update(value=shared.state.textinfo, visible=True)
  178. else:
  179. textinfo_result = gr_show(False)
  180. return f"<span id='{id_part}_progress_span' style='display: none'>{time.time()}</span><p>{progressbar}</p>", preview_visibility, image, textinfo_result
  181. def check_progress_call_initial(id_part):
  182. shared.state.job_count = -1
  183. shared.state.current_latent = None
  184. shared.state.current_image = None
  185. shared.state.textinfo = None
  186. return check_progress_call(id_part)
  187. def roll_artist(prompt):
  188. 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])
  189. artist = random.choice([x for x in shared.artist_db.artists if x.category in allowed_cats])
  190. return prompt + ", " + artist.name if prompt != '' else artist.name
  191. def visit(x, func, path=""):
  192. if hasattr(x, 'children'):
  193. for c in x.children:
  194. visit(c, func, path)
  195. elif x.label is not None:
  196. func(path + "/" + str(x.label), x)
  197. def add_style(name: str, prompt: str, negative_prompt: str):
  198. if name is None:
  199. return [gr_show(), gr_show()]
  200. style = modules.styles.PromptStyle(name, prompt, negative_prompt)
  201. shared.prompt_styles.styles[style.name] = style
  202. # Save all loaded prompt styles: this allows us to update the storage format in the future more easily, because we
  203. # reserialize all styles every time we save them
  204. shared.prompt_styles.save_styles(shared.styles_filename)
  205. return [gr.Dropdown.update(visible=True, choices=list(shared.prompt_styles.styles)) for _ in range(4)]
  206. def apply_styles(prompt, prompt_neg, style1_name, style2_name):
  207. prompt = shared.prompt_styles.apply_styles_to_prompt(prompt, [style1_name, style2_name])
  208. prompt_neg = shared.prompt_styles.apply_negative_styles_to_prompt(prompt_neg, [style1_name, style2_name])
  209. return [gr.Textbox.update(value=prompt), gr.Textbox.update(value=prompt_neg), gr.Dropdown.update(value="None"), gr.Dropdown.update(value="None")]
  210. def interrogate(image):
  211. prompt = shared.interrogator.interrogate(image)
  212. return gr_show(True) if prompt is None else prompt
  213. def create_seed_inputs():
  214. with gr.Row():
  215. with gr.Box():
  216. with gr.Row(elem_id='seed_row'):
  217. seed = (gr.Textbox if cmd_opts.use_textbox_seed else gr.Number)(label='Seed', value=-1)
  218. seed.style(container=False)
  219. random_seed = gr.Button(random_symbol, elem_id='random_seed')
  220. reuse_seed = gr.Button(reuse_symbol, elem_id='reuse_seed')
  221. with gr.Box(elem_id='subseed_show_box'):
  222. seed_checkbox = gr.Checkbox(label='Extra', elem_id='subseed_show', value=False)
  223. # Components to show/hide based on the 'Extra' checkbox
  224. seed_extras = []
  225. with gr.Row(visible=False) as seed_extra_row_1:
  226. seed_extras.append(seed_extra_row_1)
  227. with gr.Box():
  228. with gr.Row(elem_id='subseed_row'):
  229. subseed = gr.Number(label='Variation seed', value=-1)
  230. subseed.style(container=False)
  231. random_subseed = gr.Button(random_symbol, elem_id='random_subseed')
  232. reuse_subseed = gr.Button(reuse_symbol, elem_id='reuse_subseed')
  233. subseed_strength = gr.Slider(label='Variation strength', value=0.0, minimum=0, maximum=1, step=0.01)
  234. with gr.Row(visible=False) as seed_extra_row_2:
  235. seed_extras.append(seed_extra_row_2)
  236. seed_resize_from_w = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize seed from width", value=0)
  237. seed_resize_from_h = gr.Slider(minimum=0, maximum=2048, step=64, label="Resize seed from height", value=0)
  238. random_seed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[seed])
  239. random_subseed.click(fn=lambda: -1, show_progress=False, inputs=[], outputs=[subseed])
  240. def change_visibility(show):
  241. return {comp: gr_show(show) for comp in seed_extras}
  242. seed_checkbox.change(change_visibility, show_progress=False, inputs=[seed_checkbox], outputs=seed_extras)
  243. return seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox
  244. def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info: gr.Textbox, dummy_component, is_subseed):
  245. """ Connects a 'reuse (sub)seed' button's click event so that it copies last used
  246. (sub)seed value from generation info the to the seed field. If copying subseed and subseed strength
  247. was 0, i.e. no variation seed was used, it copies the normal seed value instead."""
  248. def copy_seed(gen_info_string: str, index):
  249. res = -1
  250. try:
  251. gen_info = json.loads(gen_info_string)
  252. index -= gen_info.get('index_of_first_image', 0)
  253. if is_subseed and gen_info.get('subseed_strength', 0) > 0:
  254. all_subseeds = gen_info.get('all_subseeds', [-1])
  255. res = all_subseeds[index if 0 <= index < len(all_subseeds) else 0]
  256. else:
  257. all_seeds = gen_info.get('all_seeds', [-1])
  258. res = all_seeds[index if 0 <= index < len(all_seeds) else 0]
  259. except json.decoder.JSONDecodeError as e:
  260. if gen_info_string != '':
  261. print("Error parsing JSON generation info:", file=sys.stderr)
  262. print(gen_info_string, file=sys.stderr)
  263. return [res, gr_show(False)]
  264. reuse_seed.click(
  265. fn=copy_seed,
  266. _js="(x, y) => [x, selected_gallery_index()]",
  267. show_progress=False,
  268. inputs=[generation_info, dummy_component],
  269. outputs=[seed, dummy_component]
  270. )
  271. def update_token_counter(text, steps):
  272. try:
  273. _, prompt_flat_list, _ = prompt_parser.get_multicond_prompt_list([text])
  274. prompt_schedules = prompt_parser.get_learned_conditioning_prompt_schedules(prompt_flat_list, steps)
  275. except Exception:
  276. # a parsing error can happen here during typing, and we don't want to bother the user with
  277. # messages related to it in console
  278. prompt_schedules = [[[steps, text]]]
  279. flat_prompts = reduce(lambda list1, list2: list1+list2, prompt_schedules)
  280. prompts = [prompt_text for step, prompt_text in flat_prompts]
  281. tokens, token_count, max_length = max([model_hijack.tokenize(prompt) for prompt in prompts], key=lambda args: args[1])
  282. style_class = ' class="red"' if (token_count > max_length) else ""
  283. return f"<span {style_class}>{token_count}/{max_length}</span>"
  284. def create_toprow(is_img2img):
  285. id_part = "img2img" if is_img2img else "txt2img"
  286. with gr.Row(elem_id="toprow"):
  287. with gr.Column(scale=4):
  288. with gr.Row():
  289. with gr.Column(scale=80):
  290. with gr.Row():
  291. prompt = gr.Textbox(label="Prompt", elem_id=f"{id_part}_prompt", show_label=False, placeholder="Prompt", lines=2)
  292. with gr.Column(scale=1, elem_id="roll_col"):
  293. roll = gr.Button(value=art_symbol, elem_id="roll", visible=len(shared.artist_db.artists) > 0)
  294. paste = gr.Button(value=paste_symbol, elem_id="paste")
  295. token_counter = gr.HTML(value="<span></span>", elem_id=f"{id_part}_token_counter")
  296. token_button = gr.Button(visible=False, elem_id=f"{id_part}_token_button")
  297. with gr.Column(scale=10, elem_id="style_pos_col"):
  298. 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())), visible=len(shared.prompt_styles.styles) > 1)
  299. with gr.Row():
  300. with gr.Column(scale=8):
  301. negative_prompt = gr.Textbox(label="Negative prompt", elem_id="negative_prompt", show_label=False, placeholder="Negative prompt", lines=2)
  302. with gr.Column(scale=1, elem_id="style_neg_col"):
  303. 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())), visible=len(shared.prompt_styles.styles) > 1)
  304. with gr.Column(scale=1):
  305. with gr.Row():
  306. interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt")
  307. submit = gr.Button('Generate', elem_id=f"{id_part}_generate", variant='primary')
  308. interrupt.click(
  309. fn=lambda: shared.state.interrupt(),
  310. inputs=[],
  311. outputs=[],
  312. )
  313. with gr.Row():
  314. if is_img2img:
  315. interrogate = gr.Button('Interrogate', elem_id="interrogate")
  316. else:
  317. interrogate = None
  318. prompt_style_apply = gr.Button('Apply style', elem_id="style_apply")
  319. save_style = gr.Button('Create style', elem_id="style_create")
  320. return prompt, roll, prompt_style, negative_prompt, prompt_style2, submit, interrogate, prompt_style_apply, save_style, paste, token_counter, token_button
  321. def setup_progressbar(progressbar, preview, id_part, textinfo=None):
  322. if textinfo is None:
  323. textinfo = gr.HTML(visible=False)
  324. check_progress = gr.Button('Check progress', elem_id=f"{id_part}_check_progress", visible=False)
  325. check_progress.click(
  326. fn=lambda: check_progress_call(id_part),
  327. show_progress=False,
  328. inputs=[],
  329. outputs=[progressbar, preview, preview, textinfo],
  330. )
  331. check_progress_initial = gr.Button('Check progress (first)', elem_id=f"{id_part}_check_progress_initial", visible=False)
  332. check_progress_initial.click(
  333. fn=lambda: check_progress_call_initial(id_part),
  334. show_progress=False,
  335. inputs=[],
  336. outputs=[progressbar, preview, preview, textinfo],
  337. )
  338. def create_ui(wrap_gradio_gpu_call):
  339. import modules.img2img
  340. import modules.txt2img
  341. with gr.Blocks(analytics_enabled=False) as txt2img_interface:
  342. txt2img_prompt, roll, txt2img_prompt_style, txt2img_negative_prompt, txt2img_prompt_style2, submit, _, txt2img_prompt_style_apply, txt2img_save_style, paste, token_counter, token_button = create_toprow(is_img2img=False)
  343. dummy_component = gr.Label(visible=False)
  344. with gr.Row(elem_id='txt2img_progress_row'):
  345. with gr.Column(scale=1):
  346. pass
  347. with gr.Column(scale=1):
  348. progressbar = gr.HTML(elem_id="txt2img_progressbar")
  349. txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False)
  350. setup_progressbar(progressbar, txt2img_preview, 'txt2img')
  351. with gr.Row().style(equal_height=False):
  352. with gr.Column(variant='panel'):
  353. steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20)
  354. sampler_index = gr.Radio(label='Sampling method', elem_id="txt2img_sampling", choices=[x.name for x in samplers], value=samplers[0].name, type="index")
  355. with gr.Group():
  356. width = gr.Slider(minimum=64, maximum=2048, step=64, label="Width", value=512)
  357. height = gr.Slider(minimum=64, maximum=2048, step=64, label="Height", value=512)
  358. with gr.Row():
  359. restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1)
  360. tiling = gr.Checkbox(label='Tiling', value=False)
  361. enable_hr = gr.Checkbox(label='Highres. fix', value=False)
  362. with gr.Row(visible=False) as hr_options:
  363. scale_latent = gr.Checkbox(label='Scale latent', value=False)
  364. denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.7)
  365. with gr.Row():
  366. batch_count = gr.Slider(minimum=1, maximum=cmd_opts.max_batch_count, step=1, label='Batch count', value=1)
  367. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1)
  368. cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0)
  369. seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs()
  370. with gr.Group():
  371. custom_inputs = modules.scripts.scripts_txt2img.setup_ui(is_img2img=False)
  372. with gr.Column(variant='panel'):
  373. with gr.Group():
  374. txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False)
  375. txt2img_gallery = gr.Gallery(label='Output', show_label=False, elem_id='txt2img_gallery').style(grid=4)
  376. with gr.Group():
  377. with gr.Row():
  378. save = gr.Button('Save')
  379. send_to_img2img = gr.Button('Send to img2img')
  380. send_to_inpaint = gr.Button('Send to inpaint')
  381. send_to_extras = gr.Button('Send to extras')
  382. button_id = "hidden_element" if shared.cmd_opts.hide_ui_dir_config else 'open_folder'
  383. open_txt2img_folder = gr.Button(folder_symbol, elem_id=button_id)
  384. with gr.Group():
  385. html_info = gr.HTML()
  386. generation_info = gr.Textbox(visible=False)
  387. connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
  388. connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
  389. txt2img_args = dict(
  390. fn=wrap_gradio_gpu_call(modules.txt2img.txt2img),
  391. _js="submit",
  392. inputs=[
  393. txt2img_prompt,
  394. txt2img_negative_prompt,
  395. txt2img_prompt_style,
  396. txt2img_prompt_style2,
  397. steps,
  398. sampler_index,
  399. restore_faces,
  400. tiling,
  401. batch_count,
  402. batch_size,
  403. cfg_scale,
  404. seed,
  405. subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
  406. height,
  407. width,
  408. enable_hr,
  409. scale_latent,
  410. denoising_strength,
  411. ] + custom_inputs,
  412. outputs=[
  413. txt2img_gallery,
  414. generation_info,
  415. html_info
  416. ],
  417. show_progress=False,
  418. )
  419. txt2img_prompt.submit(**txt2img_args)
  420. submit.click(**txt2img_args)
  421. enable_hr.change(
  422. fn=lambda x: gr_show(x),
  423. inputs=[enable_hr],
  424. outputs=[hr_options],
  425. )
  426. save.click(
  427. fn=wrap_gradio_call(save_files),
  428. _js="(x, y, z) => [x, y, selected_gallery_index()]",
  429. inputs=[
  430. generation_info,
  431. txt2img_gallery,
  432. html_info,
  433. ],
  434. outputs=[
  435. html_info,
  436. html_info,
  437. html_info,
  438. ]
  439. )
  440. roll.click(
  441. fn=roll_artist,
  442. _js="update_txt2img_tokens",
  443. inputs=[
  444. txt2img_prompt,
  445. ],
  446. outputs=[
  447. txt2img_prompt,
  448. ]
  449. )
  450. txt2img_paste_fields = [
  451. (txt2img_prompt, "Prompt"),
  452. (txt2img_negative_prompt, "Negative prompt"),
  453. (steps, "Steps"),
  454. (sampler_index, "Sampler"),
  455. (restore_faces, "Face restoration"),
  456. (cfg_scale, "CFG scale"),
  457. (seed, "Seed"),
  458. (width, "Size-1"),
  459. (height, "Size-2"),
  460. (batch_size, "Batch size"),
  461. (subseed, "Variation seed"),
  462. (subseed_strength, "Variation seed strength"),
  463. (seed_resize_from_w, "Seed resize from-1"),
  464. (seed_resize_from_h, "Seed resize from-2"),
  465. (denoising_strength, "Denoising strength"),
  466. (enable_hr, lambda d: "Denoising strength" in d),
  467. (hr_options, lambda d: gr.Row.update(visible="Denoising strength" in d)),
  468. ]
  469. modules.generation_parameters_copypaste.connect_paste(paste, txt2img_paste_fields, txt2img_prompt)
  470. token_button.click(fn=update_token_counter, inputs=[txt2img_prompt, steps], outputs=[token_counter])
  471. with gr.Blocks(analytics_enabled=False) as img2img_interface:
  472. img2img_prompt, roll, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_prompt_style_apply, img2img_save_style, paste, token_counter, token_button = create_toprow(is_img2img=True)
  473. with gr.Row(elem_id='img2img_progress_row'):
  474. with gr.Column(scale=1):
  475. pass
  476. with gr.Column(scale=1):
  477. progressbar = gr.HTML(elem_id="img2img_progressbar")
  478. img2img_preview = gr.Image(elem_id='img2img_preview', visible=False)
  479. setup_progressbar(progressbar, img2img_preview, 'img2img')
  480. with gr.Row().style(equal_height=False):
  481. with gr.Column(variant='panel'):
  482. with gr.Tabs(elem_id="mode_img2img") as tabs_img2img_mode:
  483. with gr.TabItem('img2img', id='img2img'):
  484. 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)
  485. with gr.TabItem('Inpaint', id='inpaint'):
  486. 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")
  487. 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")
  488. init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", visible=False, elem_id="img_inpaint_mask")
  489. mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4)
  490. with gr.Row():
  491. mask_mode = gr.Radio(label="Mask mode", show_label=False, choices=["Draw mask", "Upload mask"], type="index", value="Draw mask", elem_id="mask_mode")
  492. inpainting_mask_invert = gr.Radio(label='Masking mode', show_label=False, choices=['Inpaint masked', 'Inpaint not masked'], value='Inpaint masked', type="index")
  493. inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='original', type="index")
  494. with gr.Row():
  495. inpaint_full_res = gr.Checkbox(label='Inpaint at full resolution', value=False)
  496. inpaint_full_res_padding = gr.Slider(label='Inpaint at full resolution padding, pixels', minimum=0, maximum=256, step=4, value=32)
  497. with gr.TabItem('Batch img2img', id='batch'):
  498. hidden = '<br>Disabled when launched with --hide-ui-dir-config.' if shared.cmd_opts.hide_ui_dir_config else ''
  499. 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>")
  500. img2img_batch_input_dir = gr.Textbox(label="Input directory", **shared.hide_dirs)
  501. img2img_batch_output_dir = gr.Textbox(label="Output directory", **shared.hide_dirs)
  502. with gr.Row():
  503. 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")
  504. steps = gr.Slider(minimum=1, maximum=150, step=1, label="Sampling Steps", value=20)
  505. sampler_index = gr.Radio(label='Sampling method', choices=[x.name for x in samplers_for_img2img], value=samplers_for_img2img[0].name, type="index")
  506. with gr.Group():
  507. width = gr.Slider(minimum=64, maximum=2048, step=64, label="Width", value=512)
  508. height = gr.Slider(minimum=64, maximum=2048, step=64, label="Height", value=512)
  509. with gr.Row():
  510. restore_faces = gr.Checkbox(label='Restore faces', value=False, visible=len(shared.face_restorers) > 1)
  511. tiling = gr.Checkbox(label='Tiling', value=False)
  512. with gr.Row():
  513. batch_count = gr.Slider(minimum=1, maximum=cmd_opts.max_batch_count, step=1, label='Batch count', value=1)
  514. batch_size = gr.Slider(minimum=1, maximum=8, step=1, label='Batch size', value=1)
  515. with gr.Group():
  516. cfg_scale = gr.Slider(minimum=1.0, maximum=30.0, step=0.5, label='CFG Scale', value=7.0)
  517. denoising_strength = gr.Slider(minimum=0.0, maximum=1.0, step=0.01, label='Denoising strength', value=0.75)
  518. seed, reuse_seed, subseed, reuse_subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox = create_seed_inputs()
  519. with gr.Group():
  520. custom_inputs = modules.scripts.scripts_img2img.setup_ui(is_img2img=True)
  521. with gr.Column(variant='panel'):
  522. with gr.Group():
  523. img2img_preview = gr.Image(elem_id='img2img_preview', visible=False)
  524. img2img_gallery = gr.Gallery(label='Output', show_label=False, elem_id='img2img_gallery').style(grid=4)
  525. with gr.Group():
  526. with gr.Row():
  527. save = gr.Button('Save')
  528. img2img_send_to_img2img = gr.Button('Send to img2img')
  529. img2img_send_to_inpaint = gr.Button('Send to inpaint')
  530. img2img_send_to_extras = gr.Button('Send to extras')
  531. button_id = "hidden_element" if shared.cmd_opts.hide_ui_dir_config else 'open_folder'
  532. open_img2img_folder = gr.Button(folder_symbol, elem_id=button_id)
  533. with gr.Group():
  534. html_info = gr.HTML()
  535. generation_info = gr.Textbox(visible=False)
  536. connect_reuse_seed(seed, reuse_seed, generation_info, dummy_component, is_subseed=False)
  537. connect_reuse_seed(subseed, reuse_subseed, generation_info, dummy_component, is_subseed=True)
  538. mask_mode.change(
  539. lambda mode, img: {
  540. init_img_with_mask: gr_show(mode == 0),
  541. init_img_inpaint: gr_show(mode == 1),
  542. init_mask_inpaint: gr_show(mode == 1),
  543. },
  544. inputs=[mask_mode, init_img_with_mask],
  545. outputs=[
  546. init_img_with_mask,
  547. init_img_inpaint,
  548. init_mask_inpaint,
  549. ],
  550. )
  551. img2img_args = dict(
  552. fn=wrap_gradio_gpu_call(modules.img2img.img2img),
  553. _js="submit_img2img",
  554. inputs=[
  555. dummy_component,
  556. img2img_prompt,
  557. img2img_negative_prompt,
  558. img2img_prompt_style,
  559. img2img_prompt_style2,
  560. init_img,
  561. init_img_with_mask,
  562. init_img_inpaint,
  563. init_mask_inpaint,
  564. mask_mode,
  565. steps,
  566. sampler_index,
  567. mask_blur,
  568. inpainting_fill,
  569. restore_faces,
  570. tiling,
  571. batch_count,
  572. batch_size,
  573. cfg_scale,
  574. denoising_strength,
  575. seed,
  576. subseed, subseed_strength, seed_resize_from_h, seed_resize_from_w, seed_checkbox,
  577. height,
  578. width,
  579. resize_mode,
  580. inpaint_full_res,
  581. inpaint_full_res_padding,
  582. inpainting_mask_invert,
  583. img2img_batch_input_dir,
  584. img2img_batch_output_dir,
  585. ] + custom_inputs,
  586. outputs=[
  587. img2img_gallery,
  588. generation_info,
  589. html_info
  590. ],
  591. show_progress=False,
  592. )
  593. img2img_prompt.submit(**img2img_args)
  594. submit.click(**img2img_args)
  595. img2img_interrogate.click(
  596. fn=interrogate,
  597. inputs=[init_img],
  598. outputs=[img2img_prompt],
  599. )
  600. save.click(
  601. fn=wrap_gradio_call(save_files),
  602. _js="(x, y, z) => [x, y, selected_gallery_index()]",
  603. inputs=[
  604. generation_info,
  605. img2img_gallery,
  606. html_info
  607. ],
  608. outputs=[
  609. html_info,
  610. html_info,
  611. html_info,
  612. ]
  613. )
  614. roll.click(
  615. fn=roll_artist,
  616. _js="update_img2img_tokens",
  617. inputs=[
  618. img2img_prompt,
  619. ],
  620. outputs=[
  621. img2img_prompt,
  622. ]
  623. )
  624. prompts = [(txt2img_prompt, txt2img_negative_prompt), (img2img_prompt, img2img_negative_prompt)]
  625. style_dropdowns = [(txt2img_prompt_style, txt2img_prompt_style2), (img2img_prompt_style, img2img_prompt_style2)]
  626. style_js_funcs = ["update_txt2img_tokens", "update_img2img_tokens"]
  627. for button, (prompt, negative_prompt) in zip([txt2img_save_style, img2img_save_style], prompts):
  628. button.click(
  629. fn=add_style,
  630. _js="ask_for_style_name",
  631. # Have to pass empty dummy component here, because the JavaScript and Python function have to accept
  632. # the same number of parameters, but we only know the style-name after the JavaScript prompt
  633. inputs=[dummy_component, prompt, negative_prompt],
  634. outputs=[txt2img_prompt_style, img2img_prompt_style, txt2img_prompt_style2, img2img_prompt_style2],
  635. )
  636. 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):
  637. button.click(
  638. fn=apply_styles,
  639. _js=js_func,
  640. inputs=[prompt, negative_prompt, style1, style2],
  641. outputs=[prompt, negative_prompt, style1, style2],
  642. )
  643. img2img_paste_fields = [
  644. (img2img_prompt, "Prompt"),
  645. (img2img_negative_prompt, "Negative prompt"),
  646. (steps, "Steps"),
  647. (sampler_index, "Sampler"),
  648. (restore_faces, "Face restoration"),
  649. (cfg_scale, "CFG scale"),
  650. (seed, "Seed"),
  651. (width, "Size-1"),
  652. (height, "Size-2"),
  653. (batch_size, "Batch size"),
  654. (subseed, "Variation seed"),
  655. (subseed_strength, "Variation seed strength"),
  656. (seed_resize_from_w, "Seed resize from-1"),
  657. (seed_resize_from_h, "Seed resize from-2"),
  658. (denoising_strength, "Denoising strength"),
  659. ]
  660. modules.generation_parameters_copypaste.connect_paste(paste, img2img_paste_fields, img2img_prompt)
  661. token_button.click(fn=update_token_counter, inputs=[img2img_prompt, steps], outputs=[token_counter])
  662. with gr.Blocks(analytics_enabled=False) as extras_interface:
  663. with gr.Row().style(equal_height=False):
  664. with gr.Column(variant='panel'):
  665. with gr.Tabs(elem_id="mode_extras"):
  666. with gr.TabItem('Single Image'):
  667. extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil")
  668. with gr.TabItem('Batch Process'):
  669. image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file")
  670. upscaling_resize = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label="Resize", value=2)
  671. with gr.Group():
  672. extras_upscaler_1 = gr.Radio(label='Upscaler 1', choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index")
  673. with gr.Group():
  674. extras_upscaler_2 = gr.Radio(label='Upscaler 2', choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index")
  675. extras_upscaler_2_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="Upscaler 2 visibility", value=1)
  676. with gr.Group():
  677. gfpgan_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="GFPGAN visibility", value=0, interactive=modules.gfpgan_model.have_gfpgan)
  678. with gr.Group():
  679. codeformer_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="CodeFormer visibility", value=0, interactive=modules.codeformer_model.have_codeformer)
  680. 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)
  681. submit = gr.Button('Generate', elem_id="extras_generate", variant='primary')
  682. with gr.Column(variant='panel'):
  683. result_images = gr.Gallery(label="Result", show_label=False)
  684. html_info_x = gr.HTML()
  685. html_info = gr.HTML()
  686. extras_send_to_img2img = gr.Button('Send to img2img')
  687. extras_send_to_inpaint = gr.Button('Send to inpaint')
  688. button_id = "hidden_element" if shared.cmd_opts.hide_ui_dir_config else ''
  689. open_extras_folder = gr.Button('Open output directory', elem_id=button_id)
  690. submit.click(
  691. fn=wrap_gradio_gpu_call(modules.extras.run_extras),
  692. _js="get_extras_tab_index",
  693. inputs=[
  694. dummy_component,
  695. extras_image,
  696. image_batch,
  697. gfpgan_visibility,
  698. codeformer_visibility,
  699. codeformer_weight,
  700. upscaling_resize,
  701. extras_upscaler_1,
  702. extras_upscaler_2,
  703. extras_upscaler_2_visibility,
  704. ],
  705. outputs=[
  706. result_images,
  707. html_info_x,
  708. html_info,
  709. ]
  710. )
  711. extras_send_to_img2img.click(
  712. fn=lambda x: image_from_url_text(x),
  713. _js="extract_image_from_gallery_img2img",
  714. inputs=[result_images],
  715. outputs=[init_img],
  716. )
  717. extras_send_to_inpaint.click(
  718. fn=lambda x: image_from_url_text(x),
  719. _js="extract_image_from_gallery_img2img",
  720. inputs=[result_images],
  721. outputs=[init_img_with_mask],
  722. )
  723. with gr.Blocks(analytics_enabled=False) as pnginfo_interface:
  724. with gr.Row().style(equal_height=False):
  725. with gr.Column(variant='panel'):
  726. image = gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil")
  727. with gr.Column(variant='panel'):
  728. html = gr.HTML()
  729. generation_info = gr.Textbox(visible=False)
  730. html2 = gr.HTML()
  731. with gr.Row():
  732. pnginfo_send_to_txt2img = gr.Button('Send to txt2img')
  733. pnginfo_send_to_img2img = gr.Button('Send to img2img')
  734. image.change(
  735. fn=wrap_gradio_call(modules.extras.run_pnginfo),
  736. inputs=[image],
  737. outputs=[html, generation_info, html2],
  738. )
  739. with gr.Blocks() as modelmerger_interface:
  740. with gr.Row().style(equal_height=False):
  741. with gr.Column(variant='panel'):
  742. gr.HTML(value="<p>A merger of the two checkpoints will be generated in your <b>checkpoint</b> directory.</p>")
  743. with gr.Row():
  744. primary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_primary_model_name", label="Primary Model Name")
  745. secondary_model_name = gr.Dropdown(modules.sd_models.checkpoint_tiles(), elem_id="modelmerger_secondary_model_name", label="Secondary Model Name")
  746. custom_name = gr.Textbox(label="Custom Name (Optional)")
  747. interp_amount = gr.Slider(minimum=0.0, maximum=1.0, step=0.05, label='Interpolation Amount', value=0.3)
  748. interp_method = gr.Radio(choices=["Weighted Sum", "Sigmoid", "Inverse Sigmoid"], value="Weighted Sum", label="Interpolation Method")
  749. save_as_half = gr.Checkbox(value=False, label="Safe as float16")
  750. modelmerger_merge = gr.Button(elem_id="modelmerger_merge", label="Merge", variant='primary')
  751. with gr.Column(variant='panel'):
  752. submit_result = gr.Textbox(elem_id="modelmerger_result", show_label=False)
  753. sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings()
  754. with gr.Blocks() as textual_inversion_interface:
  755. with gr.Row().style(equal_height=False):
  756. with gr.Column():
  757. with gr.Group():
  758. 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>")
  759. gr.HTML(value="<p style='margin-bottom: 0.7em'>Create a new embedding</p>")
  760. new_embedding_name = gr.Textbox(label="Name")
  761. initialization_text = gr.Textbox(label="Initialization text", value="*")
  762. nvpt = gr.Slider(label="Number of vectors per token", minimum=1, maximum=75, step=1, value=1)
  763. with gr.Row():
  764. with gr.Column(scale=3):
  765. gr.HTML(value="")
  766. with gr.Column():
  767. create_embedding = gr.Button(value="Create", variant='primary')
  768. with gr.Group():
  769. gr.HTML(value="<p style='margin-bottom: 0.7em'>Create a new hypernetwork</p>")
  770. new_hypernetwork_name = gr.Textbox(label="Name")
  771. with gr.Row():
  772. with gr.Column(scale=3):
  773. gr.HTML(value="")
  774. with gr.Column():
  775. create_hypernetwork = gr.Button(value="Create", variant='primary')
  776. with gr.Group():
  777. gr.HTML(value="<p style='margin-bottom: 0.7em'>Preprocess images</p>")
  778. process_src = gr.Textbox(label='Source directory')
  779. process_dst = gr.Textbox(label='Destination directory')
  780. with gr.Row():
  781. process_flip = gr.Checkbox(label='Flip')
  782. process_split = gr.Checkbox(label='Split into two')
  783. process_caption = gr.Checkbox(label='Add caption')
  784. with gr.Row():
  785. with gr.Column(scale=3):
  786. gr.HTML(value="")
  787. with gr.Column():
  788. run_preprocess = gr.Button(value="Preprocess", variant='primary')
  789. with gr.Group():
  790. gr.HTML(value="<p style='margin-bottom: 0.7em'>Train an embedding; must specify a directory with a set of 512x512 images</p>")
  791. train_embedding_name = gr.Dropdown(label='Embedding', choices=sorted(sd_hijack.model_hijack.embedding_db.word_embeddings.keys()))
  792. train_hypernetwork_name = gr.Dropdown(label='Hypernetwork', choices=[x for x in shared.hypernetworks.keys()])
  793. learn_rate = gr.Number(label='Learning rate', value=5.0e-03)
  794. dataset_directory = gr.Textbox(label='Dataset directory', placeholder="Path to directory with input images")
  795. log_directory = gr.Textbox(label='Log directory', placeholder="Path to directory where to write outputs", value="textual_inversion")
  796. template_file = gr.Textbox(label='Prompt template file', value=os.path.join(script_path, "textual_inversion_templates", "style_filewords.txt"))
  797. steps = gr.Number(label='Max steps', value=100000, precision=0)
  798. create_image_every = gr.Number(label='Save an image to log directory every N steps, 0 to disable', value=500, precision=0)
  799. save_embedding_every = gr.Number(label='Save a copy of embedding to log directory every N steps, 0 to disable', value=500, precision=0)
  800. preview_image_prompt = gr.Textbox(label='Preview prompt', value="")
  801. with gr.Row():
  802. interrupt_training = gr.Button(value="Interrupt")
  803. train_hypernetwork = gr.Button(value="Train Hypernetwork", variant='primary')
  804. train_embedding = gr.Button(value="Train Embedding", variant='primary')
  805. with gr.Column():
  806. progressbar = gr.HTML(elem_id="ti_progressbar")
  807. ti_output = gr.Text(elem_id="ti_output", value="", show_label=False)
  808. ti_gallery = gr.Gallery(label='Output', show_label=False, elem_id='ti_gallery').style(grid=4)
  809. ti_preview = gr.Image(elem_id='ti_preview', visible=False)
  810. ti_progress = gr.HTML(elem_id="ti_progress", value="")
  811. ti_outcome = gr.HTML(elem_id="ti_error", value="")
  812. setup_progressbar(progressbar, ti_preview, 'ti', textinfo=ti_progress)
  813. create_embedding.click(
  814. fn=modules.textual_inversion.ui.create_embedding,
  815. inputs=[
  816. new_embedding_name,
  817. initialization_text,
  818. nvpt,
  819. ],
  820. outputs=[
  821. train_embedding_name,
  822. ti_output,
  823. ti_outcome,
  824. ]
  825. )
  826. create_hypernetwork.click(
  827. fn=modules.hypernetwork.ui.create_hypernetwork,
  828. inputs=[
  829. new_hypernetwork_name,
  830. ],
  831. outputs=[
  832. train_hypernetwork_name,
  833. ti_output,
  834. ti_outcome,
  835. ]
  836. )
  837. run_preprocess.click(
  838. fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.preprocess, extra_outputs=[gr.update()]),
  839. _js="start_training_textual_inversion",
  840. inputs=[
  841. process_src,
  842. process_dst,
  843. process_flip,
  844. process_split,
  845. process_caption,
  846. ],
  847. outputs=[
  848. ti_output,
  849. ti_outcome,
  850. ],
  851. )
  852. train_embedding.click(
  853. fn=wrap_gradio_gpu_call(modules.textual_inversion.ui.train_embedding, extra_outputs=[gr.update()]),
  854. _js="start_training_textual_inversion",
  855. inputs=[
  856. train_embedding_name,
  857. learn_rate,
  858. dataset_directory,
  859. log_directory,
  860. steps,
  861. create_image_every,
  862. save_embedding_every,
  863. template_file,
  864. ],
  865. outputs=[
  866. ti_output,
  867. ti_outcome,
  868. ]
  869. )
  870. train_hypernetwork.click(
  871. fn=wrap_gradio_gpu_call(modules.hypernetwork.ui.train_hypernetwork, extra_outputs=[gr.update()]),
  872. _js="start_training_textual_inversion",
  873. inputs=[
  874. train_hypernetwork_name,
  875. learn_rate,
  876. dataset_directory,
  877. log_directory,
  878. steps,
  879. create_image_every,
  880. save_embedding_every,
  881. template_file,
  882. preview_image_prompt,
  883. ],
  884. outputs=[
  885. ti_output,
  886. ti_outcome,
  887. ]
  888. )
  889. interrupt_training.click(
  890. fn=lambda: shared.state.interrupt(),
  891. inputs=[],
  892. outputs=[],
  893. )
  894. def create_setting_component(key):
  895. def fun():
  896. return opts.data[key] if key in opts.data else opts.data_labels[key].default
  897. info = opts.data_labels[key]
  898. t = type(info.default)
  899. args = info.component_args() if callable(info.component_args) else info.component_args
  900. if info.component is not None:
  901. comp = info.component
  902. elif t == str:
  903. comp = gr.Textbox
  904. elif t == int:
  905. comp = gr.Number
  906. elif t == bool:
  907. comp = gr.Checkbox
  908. else:
  909. raise Exception(f'bad options item type: {str(t)} for key {key}')
  910. return comp(label=info.label, value=fun, **(args or {}))
  911. components = []
  912. component_dict = {}
  913. def open_folder(f):
  914. if not shared.cmd_opts.hide_ui_dir_config:
  915. path = os.path.normpath(f)
  916. if platform.system() == "Windows":
  917. os.startfile(path)
  918. elif platform.system() == "Darwin":
  919. sp.Popen(["open", path])
  920. else:
  921. sp.Popen(["xdg-open", path])
  922. def run_settings(*args):
  923. changed = 0
  924. for key, value, comp in zip(opts.data_labels.keys(), args, components):
  925. if not opts.same_type(value, opts.data_labels[key].default):
  926. return f"Bad value for setting {key}: {value}; expecting {type(opts.data_labels[key].default).__name__}"
  927. for key, value, comp in zip(opts.data_labels.keys(), args, components):
  928. comp_args = opts.data_labels[key].component_args
  929. if comp_args and isinstance(comp_args, dict) and comp_args.get('visible') is False:
  930. continue
  931. oldval = opts.data.get(key, None)
  932. opts.data[key] = value
  933. if oldval != value:
  934. if opts.data_labels[key].onchange is not None:
  935. opts.data_labels[key].onchange()
  936. changed += 1
  937. opts.save(shared.config_filename)
  938. return f'{changed} settings changed.', opts.dumpjson()
  939. with gr.Blocks(analytics_enabled=False) as settings_interface:
  940. settings_submit = gr.Button(value="Apply settings", variant='primary')
  941. result = gr.HTML()
  942. settings_cols = 3
  943. items_per_col = int(len(opts.data_labels) * 0.9 / settings_cols)
  944. cols_displayed = 0
  945. items_displayed = 0
  946. previous_section = None
  947. column = None
  948. with gr.Row(elem_id="settings").style(equal_height=False):
  949. for i, (k, item) in enumerate(opts.data_labels.items()):
  950. if previous_section != item.section:
  951. if cols_displayed < settings_cols and (items_displayed >= items_per_col or previous_section is None):
  952. if column is not None:
  953. column.__exit__()
  954. column = gr.Column(variant='panel')
  955. column.__enter__()
  956. items_displayed = 0
  957. cols_displayed += 1
  958. previous_section = item.section
  959. gr.HTML(elem_id="settings_header_text_{}".format(item.section[0]), value='<h1 class="gr-button-lg">{}</h1>'.format(item.section[1]))
  960. component = create_setting_component(k)
  961. component_dict[k] = component
  962. components.append(component)
  963. items_displayed += 1
  964. request_notifications = gr.Button(value='Request browser notifications', elem_id="request_notifications")
  965. request_notifications.click(
  966. fn=lambda: None,
  967. inputs=[],
  968. outputs=[],
  969. _js='function(){}'
  970. )
  971. with gr.Row():
  972. reload_script_bodies = gr.Button(value='Reload custom script bodies (No ui updates, No restart)', variant='secondary')
  973. restart_gradio = gr.Button(value='Restart Gradio and Refresh components (Custom Scripts, ui.py, js and css only)', variant='primary')
  974. def reload_scripts():
  975. modules.scripts.reload_script_body_only()
  976. reload_script_bodies.click(
  977. fn=reload_scripts,
  978. inputs=[],
  979. outputs=[],
  980. _js='function(){}'
  981. )
  982. def request_restart():
  983. shared.state.interrupt()
  984. settings_interface.gradio_ref.do_restart = True
  985. restart_gradio.click(
  986. fn=request_restart,
  987. inputs=[],
  988. outputs=[],
  989. _js='function(){restart_reload()}'
  990. )
  991. if column is not None:
  992. column.__exit__()
  993. interfaces = [
  994. (txt2img_interface, "txt2img", "txt2img"),
  995. (img2img_interface, "img2img", "img2img"),
  996. (extras_interface, "Extras", "extras"),
  997. (pnginfo_interface, "PNG Info", "pnginfo"),
  998. (modelmerger_interface, "Checkpoint Merger", "modelmerger"),
  999. (textual_inversion_interface, "Textual inversion", "ti"),
  1000. (settings_interface, "Settings", "settings"),
  1001. ]
  1002. with open(os.path.join(script_path, "style.css"), "r", encoding="utf8") as file:
  1003. css = file.read()
  1004. if os.path.exists(os.path.join(script_path, "user.css")):
  1005. with open(os.path.join(script_path, "user.css"), "r", encoding="utf8") as file:
  1006. usercss = file.read()
  1007. css += usercss
  1008. if not cmd_opts.no_progressbar_hiding:
  1009. css += css_hide_progressbar
  1010. with gr.Blocks(css=css, analytics_enabled=False, title="Stable Diffusion") as demo:
  1011. settings_interface.gradio_ref = demo
  1012. with gr.Tabs() as tabs:
  1013. for interface, label, ifid in interfaces:
  1014. with gr.TabItem(label, id=ifid):
  1015. interface.render()
  1016. if os.path.exists(os.path.join(script_path, "notification.mp3")):
  1017. audio_notification = gr.Audio(interactive=False, value=os.path.join(script_path, "notification.mp3"), elem_id="audio_notification", visible=False)
  1018. text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
  1019. settings_submit.click(
  1020. fn=run_settings,
  1021. inputs=components,
  1022. outputs=[result, text_settings],
  1023. )
  1024. def modelmerger(*args):
  1025. try:
  1026. results = modules.extras.run_modelmerger(*args)
  1027. except Exception as e:
  1028. print("Error loading/saving model file:", file=sys.stderr)
  1029. print(traceback.format_exc(), file=sys.stderr)
  1030. modules.sd_models.list_models() # to remove the potentially missing models from the list
  1031. 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)]
  1032. return results
  1033. modelmerger_merge.click(
  1034. fn=modelmerger,
  1035. inputs=[
  1036. primary_model_name,
  1037. secondary_model_name,
  1038. interp_method,
  1039. interp_amount,
  1040. save_as_half,
  1041. custom_name,
  1042. ],
  1043. outputs=[
  1044. submit_result,
  1045. primary_model_name,
  1046. secondary_model_name,
  1047. component_dict['sd_model_checkpoint'],
  1048. ]
  1049. )
  1050. paste_field_names = ['Prompt', 'Negative prompt', 'Steps', 'Face restoration', 'Seed', 'Size-1', 'Size-2']
  1051. txt2img_fields = [field for field,name in txt2img_paste_fields if name in paste_field_names]
  1052. img2img_fields = [field for field,name in img2img_paste_fields if name in paste_field_names]
  1053. send_to_img2img.click(
  1054. fn=lambda img, *args: (image_from_url_text(img),*args),
  1055. _js="(gallery, ...args) => [extract_image_from_gallery_img2img(gallery), ...args]",
  1056. inputs=[txt2img_gallery] + txt2img_fields,
  1057. outputs=[init_img] + img2img_fields,
  1058. )
  1059. send_to_inpaint.click(
  1060. fn=lambda x, *args: (image_from_url_text(x), *args),
  1061. _js="(gallery, ...args) => [extract_image_from_gallery_inpaint(gallery), ...args]",
  1062. inputs=[txt2img_gallery] + txt2img_fields,
  1063. outputs=[init_img_with_mask] + img2img_fields,
  1064. )
  1065. img2img_send_to_img2img.click(
  1066. fn=lambda x: image_from_url_text(x),
  1067. _js="extract_image_from_gallery_img2img",
  1068. inputs=[img2img_gallery],
  1069. outputs=[init_img],
  1070. )
  1071. img2img_send_to_inpaint.click(
  1072. fn=lambda x: image_from_url_text(x),
  1073. _js="extract_image_from_gallery_inpaint",
  1074. inputs=[img2img_gallery],
  1075. outputs=[init_img_with_mask],
  1076. )
  1077. send_to_extras.click(
  1078. fn=lambda x: image_from_url_text(x),
  1079. _js="extract_image_from_gallery_extras",
  1080. inputs=[txt2img_gallery],
  1081. outputs=[extras_image],
  1082. )
  1083. open_txt2img_folder.click(
  1084. fn=lambda: open_folder(opts.outdir_samples or opts.outdir_txt2img_samples),
  1085. inputs=[],
  1086. outputs=[],
  1087. )
  1088. open_img2img_folder.click(
  1089. fn=lambda: open_folder(opts.outdir_samples or opts.outdir_img2img_samples),
  1090. inputs=[],
  1091. outputs=[],
  1092. )
  1093. open_extras_folder.click(
  1094. fn=lambda: open_folder(opts.outdir_samples or opts.outdir_extras_samples),
  1095. inputs=[],
  1096. outputs=[],
  1097. )
  1098. img2img_send_to_extras.click(
  1099. fn=lambda x: image_from_url_text(x),
  1100. _js="extract_image_from_gallery_extras",
  1101. inputs=[img2img_gallery],
  1102. outputs=[extras_image],
  1103. )
  1104. modules.generation_parameters_copypaste.connect_paste(pnginfo_send_to_txt2img, txt2img_paste_fields, generation_info, 'switch_to_txt2img')
  1105. modules.generation_parameters_copypaste.connect_paste(pnginfo_send_to_img2img, img2img_paste_fields, generation_info, 'switch_to_img2img_img2img')
  1106. ui_config_file = cmd_opts.ui_config_file
  1107. ui_settings = {}
  1108. settings_count = len(ui_settings)
  1109. error_loading = False
  1110. try:
  1111. if os.path.exists(ui_config_file):
  1112. with open(ui_config_file, "r", encoding="utf8") as file:
  1113. ui_settings = json.load(file)
  1114. except Exception:
  1115. error_loading = True
  1116. print("Error loading settings:", file=sys.stderr)
  1117. print(traceback.format_exc(), file=sys.stderr)
  1118. def loadsave(path, x):
  1119. def apply_field(obj, field, condition=None):
  1120. key = path + "/" + field
  1121. if getattr(obj,'custom_script_source',None) is not None:
  1122. key = 'customscript/' + obj.custom_script_source + '/' + key
  1123. if getattr(obj, 'do_not_save_to_config', False):
  1124. return
  1125. saved_value = ui_settings.get(key, None)
  1126. if saved_value is None:
  1127. ui_settings[key] = getattr(obj, field)
  1128. elif condition is None or condition(saved_value):
  1129. setattr(obj, field, saved_value)
  1130. if type(x) in [gr.Slider, gr.Radio, gr.Checkbox, gr.Textbox, gr.Number] and x.visible:
  1131. apply_field(x, 'visible')
  1132. if type(x) == gr.Slider:
  1133. apply_field(x, 'value')
  1134. apply_field(x, 'minimum')
  1135. apply_field(x, 'maximum')
  1136. apply_field(x, 'step')
  1137. if type(x) == gr.Radio:
  1138. apply_field(x, 'value', lambda val: val in x.choices)
  1139. if type(x) == gr.Checkbox:
  1140. apply_field(x, 'value')
  1141. if type(x) == gr.Textbox:
  1142. apply_field(x, 'value')
  1143. if type(x) == gr.Number:
  1144. apply_field(x, 'value')
  1145. visit(txt2img_interface, loadsave, "txt2img")
  1146. visit(img2img_interface, loadsave, "img2img")
  1147. visit(extras_interface, loadsave, "extras")
  1148. if not error_loading and (not os.path.exists(ui_config_file) or settings_count != len(ui_settings)):
  1149. with open(ui_config_file, "w", encoding="utf8") as file:
  1150. json.dump(ui_settings, file, indent=4)
  1151. return demo
  1152. with open(os.path.join(script_path, "script.js"), "r", encoding="utf8") as jsfile:
  1153. javascript = f'<script>{jsfile.read()}</script>'
  1154. jsdir = os.path.join(script_path, "javascript")
  1155. for filename in sorted(os.listdir(jsdir)):
  1156. with open(os.path.join(jsdir, filename), "r", encoding="utf8") as jsfile:
  1157. javascript += f"\n<script>{jsfile.read()}</script>"
  1158. if 'gradio_routes_templates_response' not in globals():
  1159. def template_response(*args, **kwargs):
  1160. res = gradio_routes_templates_response(*args, **kwargs)
  1161. res.body = res.body.replace(b'</head>', f'{javascript}</head>'.encode("utf8"))
  1162. res.init_headers()
  1163. return res
  1164. gradio_routes_templates_response = gradio.routes.templates.TemplateResponse
  1165. gradio.routes.templates.TemplateResponse = template_response