Compare commits

..
Author SHA1 Message Date
Connum d5ecf56f8e make callback queue handling reusable and implement onUiTabChange() 2022-09-24 01:12:13 +02:00
AUTOMATIC 74f940e818 Merge remote-tracking branch 'origin/master' 2022-09-24 00:13:47 +03:00
AUTOMATIC 71cfb9ebac fix for settings sometimes not applying on javascript side 2022-09-24 00:13:32 +03:00
innovaciones b04a36be37 Tweak margin 2022-09-23 23:41:10 +03:00
innovaciones e1d49c5262 Fix border 2022-09-23 23:41:10 +03:00
innovaciones 6cd613811b Fix preview images position 2022-09-23 23:41:10 +03:00
DepFA e560eb8b60 Only switch between visible gallery entries
Since the other tabs are kept in the dom now filtering is needed.
2022-09-23 23:38:45 +03:00
AUTOMATIC e12793e937 delete unwanted console.log 2022-09-23 23:34:33 +03:00
AUTOMATIC c8c662901b fix for inpaint at full resolution breaking if you have an NN upscaler. 2022-09-23 23:29:53 +03:00
AUTOMATIC 39ce23f42d add the bitton to paste parameters into UI for txt2img, img2img, and pnginfo tabs
fixed some [send to..] buttons to work properly with all tabs
2022-09-23 22:49:21 +03:00
AUTOMATIC 9c92a1a9aa removed some information that its owner decided he did not want to share 2022-09-23 20:55:54 +03:00
AUTOMATIC 8ffc07b7b1 one change didn't make it into the previous commit 2022-09-23 20:54:17 +03:00
AUTOMATIC 0065327726 upgrade to gradio==3.4b3 t fixthe inpain bugs
rework progressbar/preview to work with new gradio
remove unnecessary create style button
added link to alternative colab
2022-09-23 20:46:02 +03:00
12 changed files with 364 additions and 145 deletions

No files matched your search

+4 -1
View File
@@ -51,7 +51,10 @@ A browser interface based on Gradio library for Stable Diffusion.
## Installation and Running ## Installation and Running
Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for both [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended) and [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs. Make sure the required [dependencies](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Dependencies) are met and follow the instructions available for both [NVidia](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-NVidia-GPUs) (recommended) and [AMD](https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Install-and-Run-on-AMD-GPUs) GPUs.
Alternatively, use [Google Colab](https://colab.research.google.com/drive/1Iy-xW9t1-OQWhb0hNxueGij8phCyluOh). Alternatively, use Google Colab:
- [Colab, maintained by Akaibu](https://colab.research.google.com/drive/1kw3egmSn-KgWsikYvOMjJkVDsPLjEMzl)
- [Colab, original by me, outdated](https://colab.research.google.com/drive/1Iy-xW9t1-OQWhb0hNxueGij8phCyluOh).
### Automatic Installation on Windows ### Automatic Installation on Windows
1. Install [Python 3.10.6](https://www.python.org/downloads/windows/), checking "Add Python to PATH" 1. Install [Python 3.10.6](https://www.python.org/downloads/windows/), checking "Add Python to PATH"
+2 -2
View File
@@ -13,6 +13,8 @@ titles = {
"Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result", "Seed": "A value that determines the output of random number generator - if you create an image with same parameters and seed as another image, you'll get the same result",
"\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time", "\u{1f3b2}\ufe0f": "Set seed to -1, which will cause a new random number to be used every time",
"\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed", "\u267b\ufe0f": "Reuse seed from last generation, mostly useful if it was randomed",
"\u{1f3a8}": "Add a random artist to the prompt.",
"\u2199\ufe0f": "Read generation parameters from prompt into user interface.",
"Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt", "Inpaint a part of image": "Draw a mask over an image, and the script will regenerate the masked area with content according to prompt",
"SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back", "SD upscale": "Upscale image normally, split result into tiles, improve each tile using img2img, merge whole image back",
@@ -48,8 +50,6 @@ titles = {
"Tiling": "Produce an image that can be tiled.", "Tiling": "Produce an image that can be tiled.",
"Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.", "Tile overlap": "For SD upscale, how much overlap in pixels should there be between tiles. Tiles overlap so that when they are merged back into one picture, there is no clearly visible seam.",
"Roll": "Add a random artist to the prompt.",
"Variation seed": "Seed of a different picture to be mixed into the generation.", "Variation seed": "Seed of a different picture to be mixed into the generation.",
"Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).", "Variation strength": "How strong of a variation to produce. At 0, there will be no effect. At 1, you will get the complete picture with variation seed (except for ancestral samplers, where you will just get something).",
"Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution", "Resize seed from height": "Make an attempt to produce a picture similar to what would have been produced with same seed at specified resolution",
+14 -2
View File
@@ -22,10 +22,22 @@ function negmod(n, m) {
} }
function modalImageSwitch(offset){ function modalImageSwitch(offset){
var galleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all") var allgalleryButtons = gradioApp().querySelectorAll(".gallery-item.transition-all")
var galleryButtons = []
allgalleryButtons.forEach(function(elem){
if(elem.parentElement.offsetParent){
galleryButtons.push(elem);
}
})
if(galleryButtons.length>1){ if(galleryButtons.length>1){
var currentButton = gradioApp().querySelector(".gallery-item.transition-all.\\!ring-2") var allcurrentButtons = gradioApp().querySelectorAll(".gallery-item.transition-all.\\!ring-2")
var currentButton = null
allcurrentButtons.forEach(function(elem){
if(elem.parentElement.offsetParent){
currentButton = elem;
}
})
var result = -1 var result = -1
galleryButtons.forEach(function(v, i){ if(v==currentButton) { result = i } }) galleryButtons.forEach(function(v, i){ if(v==currentButton) { result = i } })
+27 -29
View File
@@ -1,53 +1,51 @@
// code related to showing and updating progressbar shown as the image is being made // code related to showing and updating progressbar shown as the image is being made
global_progressbar = null global_progressbars = {}
onUiUpdate(function(){ function check_progressbar(id_part, id_progressbar, id_progressbar_span, id_interrupt, id_preview, id_gallery){
progressbar = gradioApp().getElementById('progressbar') var progressbar = gradioApp().getElementById(id_progressbar)
progressDiv = gradioApp().querySelectorAll('#progressSpan').length > 0; var interrupt = gradioApp().getElementById(id_interrupt)
interrupt = gradioApp().getElementById('interrupt') if(progressbar!= null && progressbar != global_progressbars[id_progressbar]){
if(progressbar!= null && progressbar != global_progressbar){ global_progressbars[id_progressbar] = progressbar
global_progressbar = progressbar
var mutationObserver = new MutationObserver(function(m){ var mutationObserver = new MutationObserver(function(m){
txt2img_preview = gradioApp().getElementById('txt2img_preview') preview = gradioApp().getElementById(id_preview)
txt2img_gallery = gradioApp().getElementById('txt2img_gallery') gallery = gradioApp().getElementById(id_gallery)
img2img_preview = gradioApp().getElementById('img2img_preview')
img2img_gallery = gradioApp().getElementById('img2img_gallery')
if(txt2img_preview != null && txt2img_gallery != null){ if(preview != null && gallery != null){
txt2img_preview.style.width = txt2img_gallery.clientWidth + "px" preview.style.width = gallery.clientWidth + "px"
txt2img_preview.style.height = txt2img_gallery.clientHeight + "px" preview.style.height = gallery.clientHeight + "px"
var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
if(!progressDiv){ if(!progressDiv){
interrupt.style.display = "none" interrupt.style.display = "none"
} }
} }
if(img2img_preview != null && img2img_gallery != null){ window.setTimeout(function(){ requestMoreProgress(id_part, id_progressbar_span, id_interrupt) }, 500)
img2img_preview.style.width = img2img_gallery.clientWidth + "px"
img2img_preview.style.height = img2img_gallery.clientHeight + "px"
if(!progressDiv){
interrupt.style.display = "none"
}
}
window.setTimeout(requestMoreProgress, 500)
}); });
mutationObserver.observe( progressbar, { childList:true, subtree:true }) mutationObserver.observe( progressbar, { childList:true, subtree:true })
} }
}
onUiUpdate(function(){
check_progressbar('txt2img', 'txt2img_progressbar', 'txt2img_progress_span', 'txt2img_interrupt', 'txt2img_preview', 'txt2img_gallery')
check_progressbar('img2img', 'img2img_progressbar', 'img2img_progress_span', 'img2img_interrupt', 'img2img_preview', 'img2img_gallery')
}) })
function requestMoreProgress(){
btn = gradioApp().getElementById("check_progress"); function requestMoreProgress(id_part, id_progressbar_span, id_interrupt){
btn = gradioApp().getElementById(id_part+"_check_progress");
if(btn==null) return; if(btn==null) return;
btn.click(); btn.click();
progressDiv = gradioApp().querySelectorAll('#progressSpan').length > 0; var progressDiv = gradioApp().querySelectorAll('#' + id_progressbar_span).length > 0;
if(progressDiv){ var interrupt = gradioApp().getElementById(id_interrupt)
if(progressDiv && interrupt){
interrupt.style.display = "block" interrupt.style.display = "block"
} }
} }
function requestProgress(){ function requestProgress(id_part){
btn = gradioApp().getElementById("check_progress_initial"); btn = gradioApp().getElementById(id_part+"_check_progress_initial");
if(btn==null) return; if(btn==null) return;
btn.click(); btn.click();
+48 -4
View File
@@ -25,13 +25,57 @@ function extract_image_from_gallery(gallery){
return gallery[index]; return gallery[index];
} }
function extract_image_from_gallery_img2img(gallery){ function args_to_array(args){
res = []
for(var i=0;i<args.length;i++){
res.push(args[i])
}
return res
}
function switch_to_txt2img(){
gradioApp().querySelectorAll('button')[0].click();
return args_to_array(arguments);
}
function switch_to_img2img_img2img(){
gradioApp().querySelectorAll('button')[1].click(); gradioApp().querySelectorAll('button')[1].click();
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[0].click();
return args_to_array(arguments);
}
function switch_to_img2img_inpaint(){
gradioApp().querySelectorAll('button')[1].click();
gradioApp().getElementById('mode_img2img').querySelectorAll('button')[1].click();
return args_to_array(arguments);
}
function switch_to_extras(){
gradioApp().querySelectorAll('button')[2].click();
return args_to_array(arguments);
}
function extract_image_from_gallery_txt2img(gallery){
switch_to_txt2img()
return extract_image_from_gallery(gallery);
}
function extract_image_from_gallery_img2img(gallery){
switch_to_img2img_img2img()
return extract_image_from_gallery(gallery);
}
function extract_image_from_gallery_inpaint(gallery){
switch_to_img2img_inpaint()
return extract_image_from_gallery(gallery); return extract_image_from_gallery(gallery);
} }
function extract_image_from_gallery_extras(gallery){ function extract_image_from_gallery_extras(gallery){
gradioApp().querySelectorAll('button')[2].click(); switch_to_extras()
return extract_image_from_gallery(gallery); return extract_image_from_gallery(gallery);
} }
@@ -79,13 +123,13 @@ function create_submit_args(args){
} }
function submit(){ function submit(){
requestProgress() requestProgress('txt2img')
return create_submit_args(arguments) return create_submit_args(arguments)
} }
function submit_img2img(){ function submit_img2img(){
requestProgress() requestProgress('img2img')
res = create_submit_args(arguments) res = create_submit_args(arguments)
+4 -2
View File
@@ -102,6 +102,7 @@ def run_pnginfo(image):
return '', '', '' return '', '', ''
items = image.info items = image.info
geninfo = ''
if "exif" in image.info: if "exif" in image.info:
exif = piexif.load(image.info["exif"]) exif = piexif.load(image.info["exif"])
@@ -111,13 +112,14 @@ def run_pnginfo(image):
except ValueError: except ValueError:
exif_comment = exif_comment.decode('utf8', errors="ignore") exif_comment = exif_comment.decode('utf8', errors="ignore")
items['exif comment'] = exif_comment items['exif comment'] = exif_comment
geninfo = exif_comment
for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif', for field in ['jfif', 'jfif_version', 'jfif_unit', 'jfif_density', 'dpi', 'exif',
'loop', 'background', 'timestamp', 'duration']: 'loop', 'background', 'timestamp', 'duration']:
items.pop(field, None) items.pop(field, None)
geninfo = items.get('parameters', geninfo)
info = '' info = ''
for key, text in items.items(): for key, text in items.items():
@@ -132,4 +134,4 @@ def run_pnginfo(image):
message = "Nothing found in the image." message = "Nothing found in the image."
info = f"<div><p>{message}<p></div>" info = f"<div><p>{message}<p></div>"
return '', '', info return '', geninfo, info
@@ -0,0 +1,88 @@
from collections import namedtuple
import re
import gradio as gr
re_param = re.compile(r"\s*([\w ]+):\s*([^,]+)(?:,|$)")
re_imagesize = re.compile(r"^(\d+)x(\d+)$")
def parse_generation_parameters(x: str):
"""parses generation parameters string, the one you see in text field under the picture in UI:
```
girl with an artist's beret, determined, blue eyes, desert scene, computer monitors, heavy makeup, by Alphonse Mucha and Charlie Bowater, ((eyeshadow)), (coquettish), detailed, intricate
Negative prompt: ugly, fat, obese, chubby, (((deformed))), [blurry], bad anatomy, disfigured, poorly drawn face, mutation, mutated, (extra_limb), (ugly), (poorly drawn hands), messy drawing
Steps: 20, Sampler: Euler a, CFG scale: 7, Seed: 965400086, Size: 512x512, Model hash: 45dee52b
```
returns a dict with field values
"""
res = {}
prompt = ""
negative_prompt = ""
done_with_prompt = False
*lines, lastline = x.strip().split("\n")
for i, line in enumerate(lines):
line = line.strip()
if line.startswith("Negative prompt:"):
done_with_prompt = True
line = line[16:].strip()
if done_with_prompt:
negative_prompt += line
else:
prompt += line
if len(prompt) > 0:
res["Prompt"] = prompt
if len(negative_prompt) > 0:
res["Negative prompt"] = negative_prompt
for k, v in re_param.findall(lastline):
m = re_imagesize.match(v)
if m is not None:
res[k+"-1"] = m.group(1)
res[k+"-2"] = m.group(2)
else:
res[k] = v
return res
def connect_paste(button, d, input_comp, js=None):
items = []
outputs = []
def paste_func(prompt):
params = parse_generation_parameters(prompt)
res = []
for key, output in zip(items, outputs):
v = params.get(key, None)
if v is None:
res.append(gr.update())
else:
try:
valtype = type(output.value)
val = valtype(v)
res.append(gr.update(value=val))
except Exception:
res.append(gr.update())
return res
for k, v in d.items():
items.append(k)
outputs.append(v)
button.click(
fn=paste_func,
_js=js,
inputs=[input_comp],
outputs=outputs,
)
+1 -1
View File
@@ -210,7 +210,7 @@ def draw_prompt_matrix(im, width, height, all_prompts):
def resize_image(resize_mode, im, width, height): def resize_image(resize_mode, im, width, height):
def resize(im, w, h): def resize(im, w, h):
if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None": if opts.upscaler_for_img2img is None or opts.upscaler_for_img2img == "None" or im.mode == 'L':
return im.resize((w, h), resample=LANCZOS) return im.resize((w, h), resample=LANCZOS)
upscaler = [x for x in shared.sd_upscalers if x.name == opts.upscaler_for_img2img][0] upscaler = [x for x in shared.sd_upscalers if x.name == opts.upscaler_for_img2img][0]
+115 -86
View File
@@ -27,6 +27,7 @@ import modules.scripts
import modules.gfpgan_model import modules.gfpgan_model
import modules.codeformer_model import modules.codeformer_model
import modules.styles import modules.styles
import modules.generation_parameters_copypaste
# 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 # 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
mimetypes.init() mimetypes.init()
@@ -57,6 +58,8 @@ css_hide_progressbar = """
# Important that they exactly match script.js for tooltip to work. # Important that they exactly match script.js for tooltip to work.
random_symbol = '\U0001f3b2\ufe0f' # 🎲️ random_symbol = '\U0001f3b2\ufe0f' # 🎲️
reuse_symbol = '\u267b\ufe0f' # ♻️ reuse_symbol = '\u267b\ufe0f' # ♻️
art_symbol = '\U0001f3a8' # 🎨
paste_symbol = '\u2199\ufe0f' # ↙
def plaintext_to_html(text): def plaintext_to_html(text):
@@ -166,7 +169,7 @@ def wrap_gradio_call(func):
return f return f
def check_progress_call(): def check_progress_call(id_part):
if shared.state.job_count == 0: if shared.state.job_count == 0:
return "", gr_show(False), gr_show(False) return "", gr_show(False), gr_show(False)
@@ -200,15 +203,15 @@ def check_progress_call():
else: else:
preview_visibility = gr_show(True) preview_visibility = gr_show(True)
return f"<span id='progressSpan' style='display: none'>{time.time()}</span><p>{progressbar}</p>", preview_visibility, image return f"<span id='{id_part}_progress_span' style='display: none'>{time.time()}</span><p>{progressbar}</p>", preview_visibility, image
def check_progress_call_initial(): def check_progress_call_initial(id_part):
shared.state.job_count = -1 shared.state.job_count = -1
shared.state.current_latent = None shared.state.current_latent = None
shared.state.current_image = None shared.state.current_image = None
return check_progress_call() return check_progress_call(id_part)
def roll_artist(prompt): def roll_artist(prompt):
@@ -236,8 +239,7 @@ def add_style(name: str, prompt: str, negative_prompt: str):
# reserialize all styles every time we save them # reserialize all styles every time we save them
shared.prompt_styles.save_styles(shared.styles_filename) shared.prompt_styles.save_styles(shared.styles_filename)
update = {"visible": True, "choices": list(shared.prompt_styles.styles), "__type__": "update"} return [gr.Dropdown.update(visible=True, choices=list(shared.prompt_styles.styles)) for _ in range(4)]
return [update, update, update, update]
def apply_styles(prompt, prompt_neg, style1_name, style2_name): def apply_styles(prompt, prompt_neg, style1_name, style2_name):
@@ -329,27 +331,32 @@ def connect_reuse_seed(seed: gr.Number, reuse_seed: gr.Button, generation_info:
def create_toprow(is_img2img): def create_toprow(is_img2img):
id_part = "img2img" if is_img2img else "txt2img"
with gr.Row(elem_id="toprow"): with gr.Row(elem_id="toprow"):
with gr.Column(scale=4): with gr.Column(scale=4):
with gr.Row(): with gr.Row():
with gr.Column(scale=8): with gr.Column(scale=80):
with gr.Row(): with gr.Row():
prompt = gr.Textbox(label="Prompt", elem_id="prompt", show_label=False, placeholder="Prompt", lines=2) prompt = gr.Textbox(label="Prompt", elem_id="prompt", show_label=False, placeholder="Prompt", lines=2)
roll = gr.Button('Roll', elem_id="roll", visible=len(shared.artist_db.artists) > 0)
with gr.Column(scale=1, elem_id="style_pos_col"): with gr.Column(scale=1, elem_id="roll_col"):
prompt_style = gr.Dropdown(label="Style 1", elem_id="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) roll = gr.Button(value=art_symbol, elem_id="roll", visible=len(shared.artist_db.artists) > 0)
paste = gr.Button(value=paste_symbol, elem_id="paste")
with gr.Column(scale=10, elem_id="style_pos_col"):
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)
with gr.Row(): with gr.Row():
with gr.Column(scale=8): with gr.Column(scale=8):
negative_prompt = gr.Textbox(label="Negative prompt", elem_id="negative_prompt", show_label=False, placeholder="Negative prompt", lines=2) negative_prompt = gr.Textbox(label="Negative prompt", elem_id="negative_prompt", show_label=False, placeholder="Negative prompt", lines=2)
with gr.Column(scale=1, elem_id="style_neg_col"): with gr.Column(scale=1, elem_id="style_neg_col"):
prompt_style2 = gr.Dropdown(label="Style 2", elem_id="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) 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)
with gr.Column(scale=1): with gr.Column(scale=1):
with gr.Row(): with gr.Row():
interrupt = gr.Button('Interrupt', elem_id="interrupt") interrupt = gr.Button('Interrupt', elem_id=f"{id_part}_interrupt")
submit = gr.Button('Generate', elem_id="generate", variant='primary') submit = gr.Button('Generate', elem_id="generate", variant='primary')
interrupt.click( interrupt.click(
@@ -366,21 +373,21 @@ def create_toprow(is_img2img):
prompt_style_apply = gr.Button('Apply style', elem_id="style_apply") prompt_style_apply = gr.Button('Apply style', elem_id="style_apply")
save_style = gr.Button('Create style', elem_id="style_create") save_style = gr.Button('Create style', elem_id="style_create")
return prompt, roll, prompt_style, negative_prompt, prompt_style2, submit, interrogate, prompt_style_apply, save_style return prompt, roll, prompt_style, negative_prompt, prompt_style2, submit, interrogate, prompt_style_apply, save_style, paste
def setup_progressbar(progressbar, preview): def setup_progressbar(progressbar, preview, id_part):
check_progress = gr.Button('Check progress', elem_id="check_progress", visible=False) check_progress = gr.Button('Check progress', elem_id=f"{id_part}_check_progress", visible=False)
check_progress.click( check_progress.click(
fn=check_progress_call, fn=lambda: check_progress_call(id_part),
show_progress=False, show_progress=False,
inputs=[], inputs=[],
outputs=[progressbar, preview, preview], outputs=[progressbar, preview, preview],
) )
check_progress_initial = gr.Button('Check progress (first)', elem_id="check_progress_initial", visible=False) check_progress_initial = gr.Button('Check progress (first)', elem_id=f"{id_part}_check_progress_initial", visible=False)
check_progress_initial.click( check_progress_initial.click(
fn=check_progress_call_initial, fn=lambda: check_progress_call_initial(id_part),
show_progress=False, show_progress=False,
inputs=[], inputs=[],
outputs=[progressbar, preview, preview], outputs=[progressbar, preview, preview],
@@ -389,17 +396,17 @@ def setup_progressbar(progressbar, preview):
def create_ui(txt2img, img2img, run_extras, run_pnginfo): def create_ui(txt2img, img2img, run_extras, run_pnginfo):
with gr.Blocks(analytics_enabled=False) as txt2img_interface: with gr.Blocks(analytics_enabled=False) as txt2img_interface:
txt2img_prompt, roll, txt2img_prompt_style, txt2img_negative_prompt, txt2img_prompt_style2, submit, _, txt2img_prompt_style_apply, txt2img_save_style = create_toprow(is_img2img=False) txt2img_prompt, roll, txt2img_prompt_style, txt2img_negative_prompt, txt2img_prompt_style2, submit, _, txt2img_prompt_style_apply, txt2img_save_style, paste = create_toprow(is_img2img=False)
dummy_component = gr.Label(visible=False) dummy_component = gr.Label(visible=False)
with gr.Row(elem_id='progressRow'): with gr.Row(elem_id='txt2img_progress_row'):
with gr.Column(scale=1): with gr.Column(scale=1):
columnEmpty = "Empty" pass
with gr.Column(scale=1): with gr.Column(scale=1):
progressbar = gr.HTML(elem_id="progressbar") progressbar = gr.HTML(elem_id="txt2img_progressbar")
txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False) txt2img_preview = gr.Image(elem_id='txt2img_preview', visible=False)
setup_progressbar(progressbar, txt2img_preview) setup_progressbar(progressbar, txt2img_preview, 'txt2img')
with gr.Row().style(equal_height=False): with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'): with gr.Column(variant='panel'):
@@ -515,28 +522,46 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
] ]
) )
txt2img_paste_fields = {
"Prompt": txt2img_prompt,
"Negative prompt": txt2img_negative_prompt,
"Steps": steps,
"Sampler": sampler_index,
"Face restoration": restore_faces,
"CFG scale": cfg_scale,
"Seed": seed,
"Size-1": width,
"Size-2": height,
"Batch size": batch_size,
"Variation seed": subseed,
"Variation seed strength": subseed_strength,
"Seed resize from-1": seed_resize_from_w,
"Seed resize from-2": seed_resize_from_h,
"Denoising strength": denoising_strength,
}
modules.generation_parameters_copypaste.connect_paste(paste, txt2img_paste_fields, txt2img_prompt)
with gr.Blocks(analytics_enabled=False) as img2img_interface: with gr.Blocks(analytics_enabled=False) as img2img_interface:
img2img_prompt, roll, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_prompt_style_apply, img2img_save_style = create_toprow(is_img2img=True) img2img_prompt, roll, img2img_prompt_style, img2img_negative_prompt, img2img_prompt_style2, submit, img2img_interrogate, img2img_prompt_style_apply, img2img_save_style, paste = create_toprow(is_img2img=True)
with gr.Row(elem_id='progressRow'): with gr.Row(elem_id='img2img_progress_row'):
with gr.Column(scale=1): with gr.Column(scale=1):
columnEmpty = "Empty" pass
with gr.Column(scale=1): with gr.Column(scale=1):
progressbar = gr.HTML(elem_id="progressbar") progressbar = gr.HTML(elem_id="img2img_progressbar")
img2img_preview = gr.Image(elem_id='img2img_preview', visible=False) img2img_preview = gr.Image(elem_id='img2img_preview', visible=False)
setup_progressbar(progressbar, img2img_preview) setup_progressbar(progressbar, img2img_preview, 'img2img')
with gr.Row().style(equal_height=False): with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'): with gr.Column(variant='panel'):
with gr.Tabs(elem_id="mode_img2img") as tabs_img2img_mode: with gr.Tabs(elem_id="mode_img2img") as tabs_img2img_mode:
with gr.TabItem('img2img'): with gr.TabItem('img2img', id='img2img'):
init_img = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil") init_img = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil")
with gr.TabItem('Inpaint'): with gr.TabItem('Inpaint', id='inpaint'):
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") 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")
init_img_with_mask_comment = gr.HTML(elem_id="mask_bug_info", value="<small>if the editor shows ERROR, switch to another tab and back, then to \"Upload mask\" mode above and back</small>")
init_img_inpaint = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil", visible=False) init_img_inpaint = gr.Image(label="Image for img2img", show_label=False, source="upload", interactive=True, type="pil", visible=False)
init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", visible=False) init_mask_inpaint = gr.Image(label="Mask", source="upload", interactive=True, type="pil", visible=False)
@@ -553,7 +578,7 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
inpaint_full_res = gr.Checkbox(label='Inpaint at full resolution', value=False) inpaint_full_res = gr.Checkbox(label='Inpaint at full resolution', value=False)
inpaint_full_res_padding = gr.Slider(label='Inpaint at full resolution padding, pixels', minimum=0, maximum=256, step=4, value=32) inpaint_full_res_padding = gr.Slider(label='Inpaint at full resolution padding, pixels', minimum=0, maximum=256, step=4, value=32)
with gr.TabItem('Batch img2img'): with gr.TabItem('Batch img2img', id='batch'):
gr.HTML("<p class=\"text-gray-500\">Process images in a directory on the same machine where the server is running.</p>") gr.HTML("<p class=\"text-gray-500\">Process images in a directory on the same machine where the server is running.</p>")
img2img_batch_input_dir = gr.Textbox(label="Input directory") img2img_batch_input_dir = gr.Textbox(label="Input directory")
img2img_batch_output_dir = gr.Textbox(label="Output directory") img2img_batch_output_dir = gr.Textbox(label="Output directory")
@@ -597,7 +622,6 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
img2img_send_to_img2img = gr.Button('Send to img2img') img2img_send_to_img2img = gr.Button('Send to img2img')
img2img_send_to_inpaint = gr.Button('Send to inpaint') img2img_send_to_inpaint = gr.Button('Send to inpaint')
img2img_send_to_extras = gr.Button('Send to extras') img2img_send_to_extras = gr.Button('Send to extras')
img2img_save_style = gr.Button('Save prompt as style')
with gr.Group(): with gr.Group():
html_info = gr.HTML() html_info = gr.HTML()
@@ -608,16 +632,13 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
mask_mode.change( mask_mode.change(
lambda mode, img: { lambda mode, img: {
#init_img_with_mask: gr.Image.update(visible=mode == 0, value=img["image"]),
init_img_with_mask: gr_show(mode == 0), init_img_with_mask: gr_show(mode == 0),
init_img_with_mask_comment: gr_show(mode == 0),
init_img_inpaint: gr_show(mode == 1), init_img_inpaint: gr_show(mode == 1),
init_mask_inpaint: gr_show(mode == 1), init_mask_inpaint: gr_show(mode == 1),
}, },
inputs=[mask_mode, init_img_with_mask], inputs=[mask_mode, init_img_with_mask],
outputs=[ outputs=[
init_img_with_mask, init_img_with_mask,
init_img_with_mask_comment,
init_img_inpaint, init_img_inpaint,
init_mask_inpaint, init_mask_inpaint,
], ],
@@ -720,12 +741,31 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
outputs=[prompt, negative_prompt, style1, style2], outputs=[prompt, negative_prompt, style1, style2],
) )
img2img_paste_fields = {
"Prompt": img2img_prompt,
"Negative prompt": img2img_negative_prompt,
"Steps": steps,
"Sampler": sampler_index,
"Face restoration": restore_faces,
"CFG scale": cfg_scale,
"Seed": seed,
"Size-1": width,
"Size-2": height,
"Batch size": batch_size,
"Variation seed": subseed,
"Variation seed strength": subseed_strength,
"Seed resize from-1": seed_resize_from_w,
"Seed resize from-2": seed_resize_from_h,
"Denoising strength": denoising_strength,
}
modules.generation_parameters_copypaste.connect_paste(paste, img2img_paste_fields, img2img_prompt)
with gr.Blocks(analytics_enabled=False) as extras_interface: with gr.Blocks(analytics_enabled=False) as extras_interface:
with gr.Row().style(equal_height=False): with gr.Row().style(equal_height=False):
with gr.Column(variant='panel'): with gr.Column(variant='panel'):
with gr.Tabs(elem_id="mode_extras"): with gr.Tabs(elem_id="mode_extras"):
with gr.TabItem('Single Image'): with gr.TabItem('Single Image'):
image = gr.Image(label="Source", source="upload", interactive=True, type="pil") extras_image = gr.Image(label="Source", source="upload", interactive=True, type="pil")
with gr.TabItem('Batch Process'): with gr.TabItem('Batch Process'):
image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file") image_batch = gr.File(label="Batch Process", file_count="multiple", interactive=True, type="file")
@@ -760,7 +800,7 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
_js="get_extras_tab_index", _js="get_extras_tab_index",
inputs=[ inputs=[
dummy_component, dummy_component,
image, extras_image,
image_batch, image_batch,
gfpgan_visibility, gfpgan_visibility,
codeformer_visibility, codeformer_visibility,
@@ -791,20 +831,25 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
outputs=[init_img_with_mask], outputs=[init_img_with_mask],
) )
pnginfo_interface = gr.Interface( with gr.Blocks(analytics_enabled=False) as pnginfo_interface:
wrap_gradio_call(run_pnginfo), with gr.Row().style(equal_height=False):
inputs=[ with gr.Column(variant='panel'):
gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil"), image = gr.Image(elem_id="pnginfo_image", label="Source", source="upload", interactive=True, type="pil")
],
outputs=[ with gr.Column(variant='panel'):
gr.HTML(), html = gr.HTML()
gr.HTML(), generation_info = gr.Textbox(visible=False)
gr.HTML(), html2 = gr.HTML()
],
allow_flagging="never", with gr.Row():
analytics_enabled=False, pnginfo_send_to_txt2img = gr.Button('Send to txt2img')
live=True, pnginfo_send_to_img2img = gr.Button('Send to img2img')
)
image.change(
fn=wrap_gradio_call(run_pnginfo),
inputs=[image],
outputs=[html, generation_info, html2],
)
def create_setting_component(key): def create_setting_component(key):
def fun(): def fun():
@@ -853,7 +898,7 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
opts.save(shared.config_filename) opts.save(shared.config_filename)
return f'{changed} settings changed.' return f'{changed} settings changed.', opts.dumpjson()
with gr.Blocks(analytics_enabled=False) as settings_interface: with gr.Blocks(analytics_enabled=False) as settings_interface:
settings_submit = gr.Button(value="Apply settings", variant='primary') settings_submit = gr.Button(value="Apply settings", variant='primary')
@@ -898,12 +943,6 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
if column is not None: if column is not None:
column.__exit__() column.__exit__()
settings_submit.click(
fn=run_settings,
inputs=components,
outputs=[result]
)
interfaces = [ interfaces = [
(txt2img_interface, "txt2img", "txt2img"), (txt2img_interface, "txt2img", "txt2img"),
(img2img_interface, "img2img", "img2img"), (img2img_interface, "img2img", "img2img"),
@@ -931,49 +970,36 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
interface.render() interface.render()
text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False) text_settings = gr.Textbox(elem_id="settings_json", value=lambda: opts.dumpjson(), visible=False)
settings_submit.click( settings_submit.click(
fn=lambda: opts.dumpjson(), fn=run_settings,
inputs=[], inputs=components,
outputs=[text_settings], outputs=[result, text_settings],
)
tabs.change(
fn=lambda x: x,
inputs=[init_img_with_mask],
outputs=[init_img_with_mask],
)
tabs_img2img_mode.change(
fn=lambda x: x,
inputs=[init_img_with_mask],
outputs=[init_img_with_mask],
) )
send_to_img2img.click( send_to_img2img.click(
fn=lambda x: image_from_url_text(x), fn=lambda x: (image_from_url_text(x)),
_js="extract_image_from_gallery_img2img", _js="extract_image_from_gallery_img2img",
inputs=[txt2img_gallery], inputs=[txt2img_gallery],
outputs=[init_img], outputs=[init_img],
) )
send_to_inpaint.click( send_to_inpaint.click(
fn=lambda x: image_from_url_text(x), fn=lambda x: (image_from_url_text(x)),
_js="extract_image_from_gallery_img2img", _js="extract_image_from_gallery_inpaint",
inputs=[txt2img_gallery], inputs=[txt2img_gallery],
outputs=[init_img_with_mask], outputs=[init_img_with_mask],
) )
img2img_send_to_img2img.click( img2img_send_to_img2img.click(
fn=lambda x: image_from_url_text(x), fn=lambda x: image_from_url_text(x),
_js="extract_image_from_gallery", _js="extract_image_from_gallery_img2img",
inputs=[img2img_gallery], inputs=[img2img_gallery],
outputs=[init_img], outputs=[init_img],
) )
img2img_send_to_inpaint.click( img2img_send_to_inpaint.click(
fn=lambda x: image_from_url_text(x), fn=lambda x: image_from_url_text(x),
_js="extract_image_from_gallery", _js="extract_image_from_gallery_inpaint",
inputs=[img2img_gallery], inputs=[img2img_gallery],
outputs=[init_img_with_mask], outputs=[init_img_with_mask],
) )
@@ -982,16 +1008,19 @@ def create_ui(txt2img, img2img, run_extras, run_pnginfo):
fn=lambda x: image_from_url_text(x), fn=lambda x: image_from_url_text(x),
_js="extract_image_from_gallery_extras", _js="extract_image_from_gallery_extras",
inputs=[txt2img_gallery], inputs=[txt2img_gallery],
outputs=[image], outputs=[extras_image],
) )
img2img_send_to_extras.click( img2img_send_to_extras.click(
fn=lambda x: image_from_url_text(x), fn=lambda x: image_from_url_text(x),
_js="extract_image_from_gallery_extras", _js="extract_image_from_gallery_extras",
inputs=[img2img_gallery], inputs=[img2img_gallery],
outputs=[image], outputs=[extras_image],
) )
modules.generation_parameters_copypaste.connect_paste(pnginfo_send_to_txt2img, txt2img_paste_fields, generation_info, 'switch_to_txt2img')
modules.generation_parameters_copypaste.connect_paste(pnginfo_send_to_img2img, img2img_paste_fields, generation_info, 'switch_to_img2img_img2img')
ui_config_file = cmd_opts.ui_config_file ui_config_file = cmd_opts.ui_config_file
ui_settings = {} ui_settings = {}
settings_count = len(ui_settings) settings_count = len(ui_settings)
+1 -1
View File
@@ -2,7 +2,7 @@ transformers==4.19.2
diffusers==0.3.0 diffusers==0.3.0
basicsr==1.4.2 basicsr==1.4.2
gfpgan==1.3.8 gfpgan==1.3.8
gradio==3.3.1 gradio==3.4b3
numpy==1.23.3 numpy==1.23.3
Pillow==9.2.0 Pillow==9.2.0
realesrgan==0.3.0 realesrgan==0.3.0
+25 -9
View File
@@ -2,24 +2,40 @@ function gradioApp(){
return document.getElementsByTagName('gradio-app')[0].shadowRoot; return document.getElementsByTagName('gradio-app')[0].shadowRoot;
} }
function get_uiCurrentTab() {
return gradioApp().querySelector('.tabs button:not(.border-transparent)')
}
uiUpdateCallbacks = [] uiUpdateCallbacks = []
uiTabChangeCallbacks = []
let uiCurrentTab = null
function onUiUpdate(callback){ function onUiUpdate(callback){
uiUpdateCallbacks.push(callback) uiUpdateCallbacks.push(callback)
} }
function onUiTabChange(callback){
uiTabChangeCallbacks.push(callback)
}
function uiUpdate(root){ function runCallback(x){
uiUpdateCallbacks.forEach(function(x){ try {
try { x()
x() } catch (e) {
} catch (e) { (console.error || console.log).call(console, e.message, e);
(console.error || console.log).call(console, e.message, e); }
} }
}) function executeCallbacks(queue) {
queue.forEach(runCallback)
} }
document.addEventListener("DOMContentLoaded", function() { document.addEventListener("DOMContentLoaded", function() {
var mutationObserver = new MutationObserver(function(m){ var mutationObserver = new MutationObserver(function(m){
uiUpdate(gradioApp()); executeCallbacks(uiUpdateCallbacks);
const newTab = get_uiCurrentTab();
if ( newTab && ( newTab !== uiCurrentTab ) ) {
uiCurrentTab = newTab;
executeCallbacks(uiTabChangeCallbacks);
}
}); });
mutationObserver.observe( gradioApp(), { childList:true, subtree:true }) mutationObserver.observe( gradioApp(), { childList:true, subtree:true })
}); });
+35 -8
View File
@@ -74,10 +74,21 @@
height: 100%; height: 100%;
} }
#roll{ #roll_col{
min-width: 1em; min-width: unset !important;
max-width: 4em; flex-grow: 0 !important;
margin: 0.5em; padding: 0.4em 0;
}
#roll, #paste{
min-width: 2em;
min-height: 2em;
max-width: 2em;
max-height: 2em;
flex-grow: 0;
padding-left: 0.25em;
padding-right: 0.25em;
margin: 0.1em 0;
} }
#style_apply, #style_create, #interrogate{ #style_apply, #style_create, #interrogate{
@@ -89,7 +100,7 @@
min-width: 8em !important; min-width: 8em !important;
} }
#style_index, #style2_index{ #txt2img_style_index, #txt2img_style2_index, #img2img_style_index, #img2img_style2_index{
margin-top: 1em; margin-top: 1em;
} }
@@ -143,7 +154,23 @@ button{
right: 0; right: 0;
margin-left: auto; margin-left: auto;
margin-right: auto; margin-right: auto;
margin-top: 34px;
z-index: 100; z-index: 100;
border: none;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
@media screen and (min-width: 768px) {
#txt2img_preview, #img2img_preview {
position: absolute;
}
}
@media screen and (max-width: 767px) {
#txt2img_preview, #img2img_preview {
position: relative;
}
} }
#txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0{ #txt2img_preview div.left-0.top-0, #img2img_preview div.left-0.top-0{
@@ -210,7 +237,7 @@ input[type="range"]{
#txt2img_negative_prompt, #img2img_negative_prompt{ #txt2img_negative_prompt, #img2img_negative_prompt{
} }
#progressbar{ #txt2img_progressbar, #img2img_progressbar{
position: absolute; position: absolute;
z-index: 1000; z-index: 1000;
right: 0; right: 0;
@@ -219,7 +246,7 @@ input[type="range"]{
display: block; display: block;
} }
#progressRow{ #txt2img_progress_row, #img2img_progress_row{
margin-bottom: 10px; margin-bottom: 10px;
margin-top: -18px; margin-top: -18px;
} }
@@ -354,7 +381,7 @@ input[type="range"]{
display:none display:none
} }
#interrupt{ #txt2img_interrupt, #img2img_interrupt{
position: absolute; position: absolute;
width: 100%; width: 100%;
height: 72px; height: 72px;