shared.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. import argparse
  2. import datetime
  3. import json
  4. import os
  5. import sys
  6. import time
  7. from PIL import Image
  8. import gradio as gr
  9. import tqdm
  10. import modules.interrogate
  11. import modules.memmon
  12. import modules.styles
  13. import modules.devices as devices
  14. from modules import localization, script_loading, errors, ui_components, shared_items, cmd_args
  15. from modules.paths_internal import models_path, script_path, data_path, sd_configs_path, sd_default_config, sd_model_file, default_sd_model_file, extensions_dir, extensions_builtin_dir
  16. demo = None
  17. parser = cmd_args.parser
  18. script_loading.preload_extensions(extensions_dir, parser)
  19. script_loading.preload_extensions(extensions_builtin_dir, parser)
  20. if os.environ.get('IGNORE_CMD_ARGS_ERRORS', None) is None:
  21. cmd_opts = parser.parse_args()
  22. else:
  23. cmd_opts, _ = parser.parse_known_args()
  24. restricted_opts = {
  25. "samples_filename_pattern",
  26. "directories_filename_pattern",
  27. "outdir_samples",
  28. "outdir_txt2img_samples",
  29. "outdir_img2img_samples",
  30. "outdir_extras_samples",
  31. "outdir_grids",
  32. "outdir_txt2img_grids",
  33. "outdir_save",
  34. }
  35. ui_reorder_categories = [
  36. "inpaint",
  37. "sampler",
  38. "checkboxes",
  39. "hires_fix",
  40. "dimensions",
  41. "cfg",
  42. "seed",
  43. "batch",
  44. "override_settings",
  45. "scripts",
  46. ]
  47. cmd_opts.disable_extension_access = (cmd_opts.share or cmd_opts.listen or cmd_opts.server_name) and not cmd_opts.enable_insecure_extension_access
  48. devices.device, devices.device_interrogate, devices.device_gfpgan, devices.device_esrgan, devices.device_codeformer = \
  49. (devices.cpu if any(y in cmd_opts.use_cpu for y in [x, 'all']) else devices.get_optimal_device() for x in ['sd', 'interrogate', 'gfpgan', 'esrgan', 'codeformer'])
  50. device = devices.device
  51. weight_load_location = None if cmd_opts.lowram else "cpu"
  52. batch_cond_uncond = cmd_opts.always_batch_cond_uncond or not (cmd_opts.lowvram or cmd_opts.medvram)
  53. parallel_processing_allowed = not cmd_opts.lowvram and not cmd_opts.medvram
  54. xformers_available = False
  55. config_filename = cmd_opts.ui_settings_file
  56. os.makedirs(cmd_opts.hypernetwork_dir, exist_ok=True)
  57. hypernetworks = {}
  58. loaded_hypernetworks = []
  59. def reload_hypernetworks():
  60. from modules.hypernetworks import hypernetwork
  61. global hypernetworks
  62. hypernetworks = hypernetwork.list_hypernetworks(cmd_opts.hypernetwork_dir)
  63. class State:
  64. skipped = False
  65. interrupted = False
  66. job = ""
  67. job_no = 0
  68. job_count = 0
  69. processing_has_refined_job_count = False
  70. job_timestamp = '0'
  71. sampling_step = 0
  72. sampling_steps = 0
  73. current_latent = None
  74. current_image = None
  75. current_image_sampling_step = 0
  76. id_live_preview = 0
  77. textinfo = None
  78. time_start = None
  79. need_restart = False
  80. server_start = None
  81. def skip(self):
  82. self.skipped = True
  83. def interrupt(self):
  84. self.interrupted = True
  85. def nextjob(self):
  86. if opts.live_previews_enable and opts.show_progress_every_n_steps == -1:
  87. self.do_set_current_image()
  88. self.job_no += 1
  89. self.sampling_step = 0
  90. self.current_image_sampling_step = 0
  91. def dict(self):
  92. obj = {
  93. "skipped": self.skipped,
  94. "interrupted": self.interrupted,
  95. "job": self.job,
  96. "job_count": self.job_count,
  97. "job_timestamp": self.job_timestamp,
  98. "job_no": self.job_no,
  99. "sampling_step": self.sampling_step,
  100. "sampling_steps": self.sampling_steps,
  101. }
  102. return obj
  103. def begin(self):
  104. self.sampling_step = 0
  105. self.job_count = -1
  106. self.processing_has_refined_job_count = False
  107. self.job_no = 0
  108. self.job_timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
  109. self.current_latent = None
  110. self.current_image = None
  111. self.current_image_sampling_step = 0
  112. self.id_live_preview = 0
  113. self.skipped = False
  114. self.interrupted = False
  115. self.textinfo = None
  116. self.time_start = time.time()
  117. devices.torch_gc()
  118. def end(self):
  119. self.job = ""
  120. self.job_count = 0
  121. devices.torch_gc()
  122. def set_current_image(self):
  123. """sets self.current_image from self.current_latent if enough sampling steps have been made after the last call to this"""
  124. if not parallel_processing_allowed:
  125. return
  126. if self.sampling_step - self.current_image_sampling_step >= opts.show_progress_every_n_steps and opts.live_previews_enable and opts.show_progress_every_n_steps != -1:
  127. self.do_set_current_image()
  128. def do_set_current_image(self):
  129. if self.current_latent is None:
  130. return
  131. import modules.sd_samplers
  132. if opts.show_progress_grid:
  133. self.assign_current_image(modules.sd_samplers.samples_to_image_grid(self.current_latent))
  134. else:
  135. self.assign_current_image(modules.sd_samplers.sample_to_image(self.current_latent))
  136. self.current_image_sampling_step = self.sampling_step
  137. def assign_current_image(self, image):
  138. self.current_image = image
  139. self.id_live_preview += 1
  140. state = State()
  141. state.server_start = time.time()
  142. styles_filename = cmd_opts.styles_file
  143. prompt_styles = modules.styles.StyleDatabase(styles_filename)
  144. interrogator = modules.interrogate.InterrogateModels("interrogate")
  145. face_restorers = []
  146. class OptionInfo:
  147. def __init__(self, default=None, label="", component=None, component_args=None, onchange=None, section=None, refresh=None):
  148. self.default = default
  149. self.label = label
  150. self.component = component
  151. self.component_args = component_args
  152. self.onchange = onchange
  153. self.section = section
  154. self.refresh = refresh
  155. def options_section(section_identifier, options_dict):
  156. for k, v in options_dict.items():
  157. v.section = section_identifier
  158. return options_dict
  159. def list_checkpoint_tiles():
  160. import modules.sd_models
  161. return modules.sd_models.checkpoint_tiles()
  162. def refresh_checkpoints():
  163. import modules.sd_models
  164. return modules.sd_models.list_models()
  165. def list_samplers():
  166. import modules.sd_samplers
  167. return modules.sd_samplers.all_samplers
  168. hide_dirs = {"visible": not cmd_opts.hide_ui_dir_config}
  169. tab_names = []
  170. options_templates = {}
  171. options_templates.update(options_section(('saving-images', "Saving images/grids"), {
  172. "samples_save": OptionInfo(True, "Always save all generated images"),
  173. "samples_format": OptionInfo('png', 'File format for images'),
  174. "samples_filename_pattern": OptionInfo("", "Images filename pattern", component_args=hide_dirs),
  175. "save_images_add_number": OptionInfo(True, "Add number to filename when saving", component_args=hide_dirs),
  176. "grid_save": OptionInfo(True, "Always save all generated image grids"),
  177. "grid_format": OptionInfo('png', 'File format for grids'),
  178. "grid_extended_filename": OptionInfo(False, "Add extended info (seed, prompt) to filename when saving grid"),
  179. "grid_only_if_multiple": OptionInfo(True, "Do not save grids consisting of one picture"),
  180. "grid_prevent_empty_spots": OptionInfo(False, "Prevent empty spots in grid (when set to autodetect)"),
  181. "n_rows": OptionInfo(-1, "Grid row count; use -1 for autodetect and 0 for it to be same as batch size", gr.Slider, {"minimum": -1, "maximum": 16, "step": 1}),
  182. "enable_pnginfo": OptionInfo(True, "Save text information about generation parameters as chunks to png files"),
  183. "save_txt": OptionInfo(False, "Create a text file next to every image with generation parameters."),
  184. "save_images_before_face_restoration": OptionInfo(False, "Save a copy of image before doing face restoration."),
  185. "save_images_before_highres_fix": OptionInfo(False, "Save a copy of image before applying highres fix."),
  186. "save_images_before_color_correction": OptionInfo(False, "Save a copy of image before applying color correction to img2img results"),
  187. "save_mask": OptionInfo(False, "For inpainting, save a copy of the greyscale mask"),
  188. "save_mask_composite": OptionInfo(False, "For inpainting, save a masked composite"),
  189. "jpeg_quality": OptionInfo(80, "Quality for saved jpeg images", gr.Slider, {"minimum": 1, "maximum": 100, "step": 1}),
  190. "webp_lossless": OptionInfo(False, "Use lossless compression for webp images"),
  191. "export_for_4chan": OptionInfo(True, "If the saved image file size is above the limit, or its either width or height are above the limit, save a downscaled copy as JPG"),
  192. "img_downscale_threshold": OptionInfo(4.0, "File size limit for the above option, MB", gr.Number),
  193. "target_side_length": OptionInfo(4000, "Width/height limit for the above option, in pixels", gr.Number),
  194. "img_max_size_mp": OptionInfo(200, "Maximum image size, in megapixels", gr.Number),
  195. "use_original_name_batch": OptionInfo(True, "Use original name for output filename during batch process in extras tab"),
  196. "use_upscaler_name_as_suffix": OptionInfo(False, "Use upscaler name as filename suffix in the extras tab"),
  197. "save_selected_only": OptionInfo(True, "When using 'Save' button, only save a single selected image"),
  198. "do_not_add_watermark": OptionInfo(False, "Do not add watermark to images"),
  199. "temp_dir": OptionInfo("", "Directory for temporary images; leave empty for default"),
  200. "clean_temp_dir_at_start": OptionInfo(False, "Cleanup non-default temporary directory when starting webui"),
  201. }))
  202. options_templates.update(options_section(('saving-paths', "Paths for saving"), {
  203. "outdir_samples": OptionInfo("", "Output directory for images; if empty, defaults to three directories below", component_args=hide_dirs),
  204. "outdir_txt2img_samples": OptionInfo("outputs/txt2img-images", 'Output directory for txt2img images', component_args=hide_dirs),
  205. "outdir_img2img_samples": OptionInfo("outputs/img2img-images", 'Output directory for img2img images', component_args=hide_dirs),
  206. "outdir_extras_samples": OptionInfo("outputs/extras-images", 'Output directory for images from extras tab', component_args=hide_dirs),
  207. "outdir_grids": OptionInfo("", "Output directory for grids; if empty, defaults to two directories below", component_args=hide_dirs),
  208. "outdir_txt2img_grids": OptionInfo("outputs/txt2img-grids", 'Output directory for txt2img grids', component_args=hide_dirs),
  209. "outdir_img2img_grids": OptionInfo("outputs/img2img-grids", 'Output directory for img2img grids', component_args=hide_dirs),
  210. "outdir_save": OptionInfo("log/images", "Directory for saving images using the Save button", component_args=hide_dirs),
  211. }))
  212. options_templates.update(options_section(('saving-to-dirs', "Saving to a directory"), {
  213. "save_to_dirs": OptionInfo(True, "Save images to a subdirectory"),
  214. "grid_save_to_dirs": OptionInfo(True, "Save grids to a subdirectory"),
  215. "use_save_to_dirs_for_ui": OptionInfo(False, "When using \"Save\" button, save images to a subdirectory"),
  216. "directories_filename_pattern": OptionInfo("[date]", "Directory name pattern", component_args=hide_dirs),
  217. "directories_max_prompt_words": OptionInfo(8, "Max prompt words for [prompt_words] pattern", gr.Slider, {"minimum": 1, "maximum": 20, "step": 1, **hide_dirs}),
  218. }))
  219. options_templates.update(options_section(('upscaling', "Upscaling"), {
  220. "ESRGAN_tile": OptionInfo(192, "Tile size for ESRGAN upscalers. 0 = no tiling.", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}),
  221. "ESRGAN_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for ESRGAN upscalers. Low values = visible seam.", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}),
  222. "realesrgan_enabled_models": OptionInfo(["R-ESRGAN 4x+", "R-ESRGAN 4x+ Anime6B"], "Select which Real-ESRGAN models to show in the web UI. (Requires restart)", gr.CheckboxGroup, lambda: {"choices": shared_items.realesrgan_models_names()}),
  223. "upscaler_for_img2img": OptionInfo(None, "Upscaler for img2img", gr.Dropdown, lambda: {"choices": [x.name for x in sd_upscalers]}),
  224. }))
  225. options_templates.update(options_section(('face-restoration', "Face restoration"), {
  226. "face_restoration_model": OptionInfo("CodeFormer", "Face restoration model", gr.Radio, lambda: {"choices": [x.name() for x in face_restorers]}),
  227. "code_former_weight": OptionInfo(0.5, "CodeFormer weight parameter; 0 = maximum effect; 1 = minimum effect", gr.Slider, {"minimum": 0, "maximum": 1, "step": 0.01}),
  228. "face_restoration_unload": OptionInfo(False, "Move face restoration model from VRAM into RAM after processing"),
  229. }))
  230. options_templates.update(options_section(('system', "System"), {
  231. "show_warnings": OptionInfo(False, "Show warnings in console."),
  232. "memmon_poll_rate": OptionInfo(8, "VRAM usage polls per second during generation. Set to 0 to disable.", gr.Slider, {"minimum": 0, "maximum": 40, "step": 1}),
  233. "samples_log_stdout": OptionInfo(False, "Always print all generation info to standard output"),
  234. "multiple_tqdm": OptionInfo(True, "Add a second progress bar to the console that shows progress for an entire job."),
  235. "print_hypernet_extra": OptionInfo(False, "Print extra hypernetwork information to console."),
  236. }))
  237. options_templates.update(options_section(('training', "Training"), {
  238. "unload_models_when_training": OptionInfo(False, "Move VAE and CLIP to RAM when training if possible. Saves VRAM."),
  239. "pin_memory": OptionInfo(False, "Turn on pin_memory for DataLoader. Makes training slightly faster but can increase memory usage."),
  240. "save_optimizer_state": OptionInfo(False, "Saves Optimizer state as separate *.optim file. Training of embedding or HN can be resumed with the matching optim file."),
  241. "save_training_settings_to_txt": OptionInfo(True, "Save textual inversion and hypernet settings to a text file whenever training starts."),
  242. "dataset_filename_word_regex": OptionInfo("", "Filename word regex"),
  243. "dataset_filename_join_string": OptionInfo(" ", "Filename join string"),
  244. "training_image_repeats_per_epoch": OptionInfo(1, "Number of repeats for a single input image per epoch; used only for displaying epoch number", gr.Number, {"precision": 0}),
  245. "training_write_csv_every": OptionInfo(500, "Save an csv containing the loss to log directory every N steps, 0 to disable"),
  246. "training_xattention_optimizations": OptionInfo(False, "Use cross attention optimizations while training"),
  247. "training_enable_tensorboard": OptionInfo(False, "Enable tensorboard logging."),
  248. "training_tensorboard_save_images": OptionInfo(False, "Save generated images within tensorboard."),
  249. "training_tensorboard_flush_every": OptionInfo(120, "How often, in seconds, to flush the pending tensorboard events and summaries to disk."),
  250. }))
  251. options_templates.update(options_section(('sd', "Stable Diffusion"), {
  252. "sd_model_checkpoint": OptionInfo(None, "Stable Diffusion checkpoint", gr.Dropdown, lambda: {"choices": list_checkpoint_tiles()}, refresh=refresh_checkpoints),
  253. "sd_checkpoint_cache": OptionInfo(0, "Checkpoints to cache in RAM", gr.Slider, {"minimum": 0, "maximum": 10, "step": 1}),
  254. "sd_vae_checkpoint_cache": OptionInfo(0, "VAE Checkpoints to cache in RAM", gr.Slider, {"minimum": 0, "maximum": 10, "step": 1}),
  255. "sd_vae": OptionInfo("Automatic", "SD VAE", gr.Dropdown, lambda: {"choices": shared_items.sd_vae_items()}, refresh=shared_items.refresh_vae_list),
  256. "sd_vae_as_default": OptionInfo(True, "Ignore selected VAE for stable diffusion checkpoints that have their own .vae.pt next to them"),
  257. "inpainting_mask_weight": OptionInfo(1.0, "Inpainting conditioning mask strength", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  258. "initial_noise_multiplier": OptionInfo(1.0, "Noise multiplier for img2img", gr.Slider, {"minimum": 0.5, "maximum": 1.5, "step": 0.01}),
  259. "img2img_color_correction": OptionInfo(False, "Apply color correction to img2img results to match original colors."),
  260. "img2img_fix_steps": OptionInfo(False, "With img2img, do exactly the amount of steps the slider specifies (normally you'd do less with less denoising)."),
  261. "img2img_background_color": OptionInfo("#ffffff", "With img2img, fill image's transparent parts with this color.", ui_components.FormColorPicker, {}),
  262. "enable_quantization": OptionInfo(False, "Enable quantization in K samplers for sharper and cleaner results. This may change existing seeds. Requires restart to apply."),
  263. "enable_emphasis": OptionInfo(True, "Emphasis: use (text) to make model pay more attention to text and [text] to make it pay less attention"),
  264. "enable_batch_seeds": OptionInfo(True, "Make K-diffusion samplers produce same images in a batch as when making a single image"),
  265. "comma_padding_backtrack": OptionInfo(20, "Increase coherency by padding from the last comma within n tokens when using more than 75 tokens", gr.Slider, {"minimum": 0, "maximum": 74, "step": 1 }),
  266. "CLIP_stop_at_last_layers": OptionInfo(1, "Clip skip", gr.Slider, {"minimum": 1, "maximum": 12, "step": 1}),
  267. "upcast_attn": OptionInfo(False, "Upcast cross attention layer to float32"),
  268. }))
  269. options_templates.update(options_section(('compatibility', "Compatibility"), {
  270. "use_old_emphasis_implementation": OptionInfo(False, "Use old emphasis implementation. Can be useful to reproduce old seeds."),
  271. "use_old_karras_scheduler_sigmas": OptionInfo(False, "Use old karras scheduler sigmas (0.1 to 10)."),
  272. "no_dpmpp_sde_batch_determinism": OptionInfo(False, "Do not make DPM++ SDE deterministic across different batch sizes."),
  273. "use_old_hires_fix_width_height": OptionInfo(False, "For hires fix, use width/height sliders to set final resolution rather than first pass (disables Upscale by, Resize width/height to)."),
  274. }))
  275. options_templates.update(options_section(('interrogate', "Interrogate Options"), {
  276. "interrogate_keep_models_in_memory": OptionInfo(False, "Interrogate: keep models in VRAM"),
  277. "interrogate_return_ranks": OptionInfo(False, "Interrogate: include ranks of model tags matches in results (Has no effect on caption-based interrogators)."),
  278. "interrogate_clip_num_beams": OptionInfo(1, "Interrogate: num_beams for BLIP", gr.Slider, {"minimum": 1, "maximum": 16, "step": 1}),
  279. "interrogate_clip_min_length": OptionInfo(24, "Interrogate: minimum description length (excluding artists, etc..)", gr.Slider, {"minimum": 1, "maximum": 128, "step": 1}),
  280. "interrogate_clip_max_length": OptionInfo(48, "Interrogate: maximum description length", gr.Slider, {"minimum": 1, "maximum": 256, "step": 1}),
  281. "interrogate_clip_dict_limit": OptionInfo(1500, "CLIP: maximum number of lines in text file (0 = No limit)"),
  282. "interrogate_clip_skip_categories": OptionInfo([], "CLIP: skip inquire categories", gr.CheckboxGroup, lambda: {"choices": modules.interrogate.category_types()}, refresh=modules.interrogate.category_types),
  283. "interrogate_deepbooru_score_threshold": OptionInfo(0.5, "Interrogate: deepbooru score threshold", gr.Slider, {"minimum": 0, "maximum": 1, "step": 0.01}),
  284. "deepbooru_sort_alpha": OptionInfo(True, "Interrogate: deepbooru sort alphabetically"),
  285. "deepbooru_use_spaces": OptionInfo(False, "use spaces for tags in deepbooru"),
  286. "deepbooru_escape": OptionInfo(True, "escape (\\) brackets in deepbooru (so they are used as literal brackets and not for emphasis)"),
  287. "deepbooru_filter_tags": OptionInfo("", "filter out those tags from deepbooru output (separated by comma)"),
  288. }))
  289. options_templates.update(options_section(('extra_networks', "Extra Networks"), {
  290. "extra_networks_default_view": OptionInfo("cards", "Default view for Extra Networks", gr.Dropdown, {"choices": ["cards", "thumbs"]}),
  291. "extra_networks_default_multiplier": OptionInfo(1.0, "Multiplier for extra networks", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  292. "extra_networks_card_width": OptionInfo(0, "Card width for Extra Networks (px)"),
  293. "extra_networks_card_height": OptionInfo(0, "Card height for Extra Networks (px)"),
  294. "extra_networks_add_text_separator": OptionInfo(" ", "Extra text to add before <...> when adding extra network to prompt"),
  295. "sd_hypernetwork": OptionInfo("None", "Add hypernetwork to prompt", gr.Dropdown, lambda: {"choices": [""] + [x for x in hypernetworks.keys()]}, refresh=reload_hypernetworks),
  296. }))
  297. options_templates.update(options_section(('ui', "User interface"), {
  298. "return_grid": OptionInfo(True, "Show grid in results for web"),
  299. "return_mask": OptionInfo(False, "For inpainting, include the greyscale mask in results for web"),
  300. "return_mask_composite": OptionInfo(False, "For inpainting, include masked composite in results for web"),
  301. "do_not_show_images": OptionInfo(False, "Do not show any images in results for web"),
  302. "add_model_hash_to_info": OptionInfo(True, "Add model hash to generation information"),
  303. "add_model_name_to_info": OptionInfo(True, "Add model name to generation information"),
  304. "disable_weights_auto_swap": OptionInfo(True, "When reading generation parameters from text into UI (from PNG info or pasted text), do not change the selected model/checkpoint."),
  305. "send_seed": OptionInfo(True, "Send seed when sending prompt or image to other interface"),
  306. "send_size": OptionInfo(True, "Send size when sending prompt or image to another interface"),
  307. "font": OptionInfo("", "Font for image grids that have text"),
  308. "js_modal_lightbox": OptionInfo(True, "Enable full page image viewer"),
  309. "js_modal_lightbox_initially_zoomed": OptionInfo(True, "Show images zoomed in by default in full page image viewer"),
  310. "show_progress_in_title": OptionInfo(True, "Show generation progress in window title."),
  311. "samplers_in_dropdown": OptionInfo(True, "Use dropdown for sampler selection instead of radio group"),
  312. "dimensions_and_batch_together": OptionInfo(True, "Show Width/Height and Batch sliders in same row"),
  313. "keyedit_precision_attention": OptionInfo(0.1, "Ctrl+up/down precision when editing (attention:1.1)", gr.Slider, {"minimum": 0.01, "maximum": 0.2, "step": 0.001}),
  314. "keyedit_precision_extra": OptionInfo(0.05, "Ctrl+up/down precision when editing <extra networks:0.9>", gr.Slider, {"minimum": 0.01, "maximum": 0.2, "step": 0.001}),
  315. "quicksettings": OptionInfo("sd_model_checkpoint", "Quicksettings list"),
  316. "hidden_tabs": OptionInfo([], "Hidden UI tabs (requires restart)", ui_components.DropdownMulti, lambda: {"choices": [x for x in tab_names]}),
  317. "ui_reorder": OptionInfo(", ".join(ui_reorder_categories), "txt2img/img2img UI item order"),
  318. "ui_extra_networks_tab_reorder": OptionInfo("", "Extra networks tab order"),
  319. "localization": OptionInfo("None", "Localization (requires restart)", gr.Dropdown, lambda: {"choices": ["None"] + list(localization.localizations.keys())}, refresh=lambda: localization.list_localizations(cmd_opts.localizations_dir)),
  320. }))
  321. options_templates.update(options_section(('ui', "Live previews"), {
  322. "show_progressbar": OptionInfo(True, "Show progressbar"),
  323. "live_previews_enable": OptionInfo(True, "Show live previews of the created image"),
  324. "show_progress_grid": OptionInfo(True, "Show previews of all images generated in a batch as a grid"),
  325. "show_progress_every_n_steps": OptionInfo(10, "Show new live preview image every N sampling steps. Set to -1 to show after completion of batch.", gr.Slider, {"minimum": -1, "maximum": 32, "step": 1}),
  326. "show_progress_type": OptionInfo("Approx NN", "Image creation progress preview mode", gr.Radio, {"choices": ["Full", "Approx NN", "Approx cheap"]}),
  327. "live_preview_content": OptionInfo("Prompt", "Live preview subject", gr.Radio, {"choices": ["Combined", "Prompt", "Negative prompt"]}),
  328. "live_preview_refresh_period": OptionInfo(1000, "Progressbar/preview update period, in milliseconds")
  329. }))
  330. options_templates.update(options_section(('sampler-params', "Sampler parameters"), {
  331. "hide_samplers": OptionInfo([], "Hide samplers in user interface (requires restart)", gr.CheckboxGroup, lambda: {"choices": [x.name for x in list_samplers()]}),
  332. "eta_ddim": OptionInfo(0.0, "eta (noise multiplier) for DDIM", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  333. "eta_ancestral": OptionInfo(1.0, "eta (noise multiplier) for ancestral samplers", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  334. "ddim_discretize": OptionInfo('uniform', "img2img DDIM discretize", gr.Radio, {"choices": ['uniform', 'quad']}),
  335. 's_churn': OptionInfo(0.0, "sigma churn", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  336. 's_tmin': OptionInfo(0.0, "sigma tmin", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  337. 's_noise': OptionInfo(1.0, "sigma noise", gr.Slider, {"minimum": 0.0, "maximum": 1.0, "step": 0.01}),
  338. 'eta_noise_seed_delta': OptionInfo(0, "Eta noise seed delta", gr.Number, {"precision": 0}),
  339. 'always_discard_next_to_last_sigma': OptionInfo(False, "Always discard next-to-last sigma"),
  340. 'uni_pc_variant': OptionInfo("bh1", "UniPC variant", gr.Radio, {"choices": ["bh1", "bh2", "vary_coeff"]}),
  341. 'uni_pc_skip_type': OptionInfo("time_uniform", "UniPC skip type", gr.Radio, {"choices": ["time_uniform", "time_quadratic", "logSNR"]}),
  342. 'uni_pc_order': OptionInfo(3, "UniPC order (must be < sampling steps)", gr.Slider, {"minimum": 1, "maximum": 50, "step": 1}),
  343. 'uni_pc_lower_order_final': OptionInfo(True, "UniPC lower order final"),
  344. }))
  345. options_templates.update(options_section(('postprocessing', "Postprocessing"), {
  346. 'postprocessing_enable_in_main_ui': OptionInfo([], "Enable postprocessing operations in txt2img and img2img tabs", ui_components.DropdownMulti, lambda: {"choices": [x.name for x in shared_items.postprocessing_scripts()]}),
  347. 'postprocessing_operation_order': OptionInfo([], "Postprocessing operation order", ui_components.DropdownMulti, lambda: {"choices": [x.name for x in shared_items.postprocessing_scripts()]}),
  348. 'upscaling_max_images_in_cache': OptionInfo(5, "Maximum number of images in upscaling cache", gr.Slider, {"minimum": 0, "maximum": 10, "step": 1}),
  349. }))
  350. options_templates.update(options_section((None, "Hidden options"), {
  351. "disabled_extensions": OptionInfo([], "Disable these extensions"),
  352. "disable_all_extensions": OptionInfo("none", "Disable all extensions (preserves the list of disabled extensions)", gr.Radio, {"choices": ["none", "extra", "all"]}),
  353. "sd_checkpoint_hash": OptionInfo("", "SHA256 hash of the current checkpoint"),
  354. }))
  355. options_templates.update()
  356. class Options:
  357. data = None
  358. data_labels = options_templates
  359. typemap = {int: float}
  360. def __init__(self):
  361. self.data = {k: v.default for k, v in self.data_labels.items()}
  362. def __setattr__(self, key, value):
  363. if self.data is not None:
  364. if key in self.data or key in self.data_labels:
  365. assert not cmd_opts.freeze_settings, "changing settings is disabled"
  366. info = opts.data_labels.get(key, None)
  367. comp_args = info.component_args if info else None
  368. if isinstance(comp_args, dict) and comp_args.get('visible', True) is False:
  369. raise RuntimeError(f"not possible to set {key} because it is restricted")
  370. if cmd_opts.hide_ui_dir_config and key in restricted_opts:
  371. raise RuntimeError(f"not possible to set {key} because it is restricted")
  372. self.data[key] = value
  373. return
  374. return super(Options, self).__setattr__(key, value)
  375. def __getattr__(self, item):
  376. if self.data is not None:
  377. if item in self.data:
  378. return self.data[item]
  379. if item in self.data_labels:
  380. return self.data_labels[item].default
  381. return super(Options, self).__getattribute__(item)
  382. def set(self, key, value):
  383. """sets an option and calls its onchange callback, returning True if the option changed and False otherwise"""
  384. oldval = self.data.get(key, None)
  385. if oldval == value:
  386. return False
  387. try:
  388. setattr(self, key, value)
  389. except RuntimeError:
  390. return False
  391. if self.data_labels[key].onchange is not None:
  392. try:
  393. self.data_labels[key].onchange()
  394. except Exception as e:
  395. errors.display(e, f"changing setting {key} to {value}")
  396. setattr(self, key, oldval)
  397. return False
  398. return True
  399. def get_default(self, key):
  400. """returns the default value for the key"""
  401. data_label = self.data_labels.get(key)
  402. if data_label is None:
  403. return None
  404. return data_label.default
  405. def save(self, filename):
  406. assert not cmd_opts.freeze_settings, "saving settings is disabled"
  407. with open(filename, "w", encoding="utf8") as file:
  408. json.dump(self.data, file, indent=4)
  409. def same_type(self, x, y):
  410. if x is None or y is None:
  411. return True
  412. type_x = self.typemap.get(type(x), type(x))
  413. type_y = self.typemap.get(type(y), type(y))
  414. return type_x == type_y
  415. def load(self, filename):
  416. with open(filename, "r", encoding="utf8") as file:
  417. self.data = json.load(file)
  418. bad_settings = 0
  419. for k, v in self.data.items():
  420. info = self.data_labels.get(k, None)
  421. if info is not None and not self.same_type(info.default, v):
  422. print(f"Warning: bad setting value: {k}: {v} ({type(v).__name__}; expected {type(info.default).__name__})", file=sys.stderr)
  423. bad_settings += 1
  424. if bad_settings > 0:
  425. print(f"The program is likely to not work with bad settings.\nSettings file: {filename}\nEither fix the file, or delete it and restart.", file=sys.stderr)
  426. def onchange(self, key, func, call=True):
  427. item = self.data_labels.get(key)
  428. item.onchange = func
  429. if call:
  430. func()
  431. def dumpjson(self):
  432. d = {k: self.data.get(k, self.data_labels.get(k).default) for k in self.data_labels.keys()}
  433. return json.dumps(d)
  434. def add_option(self, key, info):
  435. self.data_labels[key] = info
  436. def reorder(self):
  437. """reorder settings so that all items related to section always go together"""
  438. section_ids = {}
  439. settings_items = self.data_labels.items()
  440. for k, item in settings_items:
  441. if item.section not in section_ids:
  442. section_ids[item.section] = len(section_ids)
  443. self.data_labels = {k: v for k, v in sorted(settings_items, key=lambda x: section_ids[x[1].section])}
  444. def cast_value(self, key, value):
  445. """casts an arbitrary to the same type as this setting's value with key
  446. Example: cast_value("eta_noise_seed_delta", "12") -> returns 12 (an int rather than str)
  447. """
  448. if value is None:
  449. return None
  450. default_value = self.data_labels[key].default
  451. if default_value is None:
  452. default_value = getattr(self, key, None)
  453. if default_value is None:
  454. return None
  455. expected_type = type(default_value)
  456. if expected_type == bool and value == "False":
  457. value = False
  458. else:
  459. value = expected_type(value)
  460. return value
  461. opts = Options()
  462. if os.path.exists(config_filename):
  463. opts.load(config_filename)
  464. settings_components = None
  465. """assinged from ui.py, a mapping on setting anmes to gradio components repsponsible for those settings"""
  466. latent_upscale_default_mode = "Latent"
  467. latent_upscale_modes = {
  468. "Latent": {"mode": "bilinear", "antialias": False},
  469. "Latent (antialiased)": {"mode": "bilinear", "antialias": True},
  470. "Latent (bicubic)": {"mode": "bicubic", "antialias": False},
  471. "Latent (bicubic antialiased)": {"mode": "bicubic", "antialias": True},
  472. "Latent (nearest)": {"mode": "nearest", "antialias": False},
  473. "Latent (nearest-exact)": {"mode": "nearest-exact", "antialias": False},
  474. }
  475. sd_upscalers = []
  476. sd_model = None
  477. clip_model = None
  478. progress_print_out = sys.stdout
  479. class TotalTQDM:
  480. def __init__(self):
  481. self._tqdm = None
  482. def reset(self):
  483. self._tqdm = tqdm.tqdm(
  484. desc="Total progress",
  485. total=state.job_count * state.sampling_steps,
  486. position=1,
  487. file=progress_print_out
  488. )
  489. def update(self):
  490. if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
  491. return
  492. if self._tqdm is None:
  493. self.reset()
  494. self._tqdm.update()
  495. def updateTotal(self, new_total):
  496. if not opts.multiple_tqdm or cmd_opts.disable_console_progressbars:
  497. return
  498. if self._tqdm is None:
  499. self.reset()
  500. self._tqdm.total = new_total
  501. def clear(self):
  502. if self._tqdm is not None:
  503. self._tqdm.refresh()
  504. self._tqdm.close()
  505. self._tqdm = None
  506. total_tqdm = TotalTQDM()
  507. mem_mon = modules.memmon.MemUsageMonitor("MemMon", device, opts)
  508. mem_mon.start()
  509. def listfiles(dirname):
  510. filenames = [os.path.join(dirname, x) for x in sorted(os.listdir(dirname), key=str.lower) if not x.startswith(".")]
  511. return [file for file in filenames if os.path.isfile(file)]
  512. def html_path(filename):
  513. return os.path.join(script_path, "html", filename)
  514. def html(filename):
  515. path = html_path(filename)
  516. if os.path.exists(path):
  517. with open(path, encoding="utf8") as file:
  518. return file.read()
  519. return ""