ui.py 63 KB

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