Image browser

This commit is contained in:
yfszzx 2022-10-18 20:14:11 +08:00
parent 2b5b62e768
commit eb299527b1
6 changed files with 287 additions and 90 deletions

View File

@ -145,9 +145,10 @@ function images_history_enable_del_buttons(){
}
function images_history_init(){
var loaded = gradioApp().getElementById("images_history_reconstruct_directory")
if (loaded){
var init_status = loaded.querySelector("input").checked
// var loaded = gradioApp().getElementById("images_history_reconstruct_directory")
// if (loaded){
// var init_status = loaded.querySelector("input").checked
if (gradioApp().getElementById("images_history_finish_render")){
for (var i in images_history_tab_list ){
tab = images_history_tab_list[i];
gradioApp().getElementById(tab + '_images_history').classList.add("images_history_cantainor");
@ -163,19 +164,17 @@ function images_history_init(){
for (var i in images_history_tab_list){
var tabname = images_history_tab_list[i]
tab_btns[i].setAttribute("tabname", tabname);
if (init_status){
tab_btns[i].addEventListener('click', images_history_click_tab);
}
}
if (init_status){
tab_btns[0].click();
// if (!init_status){
// tab_btns[i].addEventListener('click', images_history_click_tab);
// }
tab_btns[i].addEventListener('click', images_history_click_tab);
}
} else {
setTimeout(images_history_init, 500);
}
}
var images_history_tab_list = ["txt2img", "img2img", "extras", "saved"];
var images_history_tab_list = ["custom", "txt2img", "img2img", "extras", "saved"];
setTimeout(images_history_init, 500);
document.addEventListener("DOMContentLoaded", function() {
var mutationObserver = new MutationObserver(function(m){

View File

@ -4,6 +4,7 @@ import time
import hashlib
import gradio
system_bak_path = "webui_log_and_bak"
browser_tabname = "custom"
def is_valid_date(date):
try:
time.strptime(date, "%Y%m%d")
@ -99,13 +100,15 @@ def auto_sorting(dir_name):
date_list.append(today)
return sorted(date_list, reverse=True)
def archive_images(dir_name, date_to):
def archive_images(dir_name, date_to):
filenames = []
loads_num =int(opts.images_history_num_per_page * opts.images_history_pages_num)
today = time.strftime("%Y%m%d",time.localtime(time.time()))
date_to = today if date_to is None or date_to == "" else date_to
date_to_bak = date_to
if opts.images_history_reconstruct_directory:
date_list = auto_sorting(dir_name)
today = time.strftime("%Y%m%d",time.localtime(time.time()))
date_to = today if date_to is None or date_to == "" else date_to
date_list = auto_sorting(dir_name)
for date in date_list:
if date <= date_to:
path = os.path.join(dir_name, date)
@ -120,7 +123,7 @@ def archive_images(dir_name, date_to):
tmparray = [(os.path.getmtime(file), file) for file in filenames ]
date_stamp = time.mktime(time.strptime(date_to, "%Y%m%d")) + 86400
filenames = []
date_list = {}
date_list = {date_to:None}
date = time.strftime("%Y%m%d",time.localtime(time.time()))
for t, f in tmparray:
date = time.strftime("%Y%m%d",time.localtime(t))
@ -133,22 +136,29 @@ def archive_images(dir_name, date_to):
date = sort_array[loads_num][2]
filenames = [x[1] for x in sort_array]
else:
date = None if len(sort_array) == 0 else sort_array[-1][2]
date = date_to if len(sort_array) == 0 else sort_array[-1][2]
filenames = [x[1] for x in sort_array]
filenames = [x[1] for x in sort_array if x[2]>= date]
_, image_list, _, visible_num = get_recent_images(1, 0, filenames)
filenames = [x[1] for x in sort_array if x[2]>= date]
num = len(filenames)
last_date_from = date_to_bak if num == 0 else time.strftime("%Y%m%d", time.localtime(time.mktime(time.strptime(date, "%Y%m%d")) - 1000))
date = date[:4] + "-" + date[4:6] + "-" + date[6:8]
date_to_bak = date_to_bak[:4] + "-" + date_to_bak[4:6] + "-" + date_to_bak[6:8]
load_info = f"Loaded {(num + 1) // opts.images_history_pages_num} pades, {num} images, during {date} - {date_to_bak}"
_, image_list, _, _, visible_num = get_recent_images(1, 0, filenames)
return (
gradio.Dropdown.update(choices=date_list, value=date_to),
date,
load_info,
filenames,
1,
image_list,
"",
visible_num
"",
visible_num,
last_date_from
)
def newest_click(dir_name, date_to):
return archive_images(dir_name, time.strftime("%Y%m%d",time.localtime(time.time())))
def delete_image(delete_num, name, filenames, image_index, visible_num):
if name == "":
@ -196,7 +206,29 @@ def get_recent_images(page_index, step, filenames):
length = len(filenames)
visible_num = num_of_imgs_per_page if idx_frm + num_of_imgs_per_page <= length else length % num_of_imgs_per_page
visible_num = num_of_imgs_per_page if visible_num == 0 else visible_num
return page_index, image_list, "", visible_num
return page_index, image_list, "", "", visible_num
def newest_click(date_to):
if date_to is None:
return time.strftime("%Y%m%d",time.localtime(time.time())), []
else:
return None, []
def forward_click(last_date_from, date_to_recorder):
if len(date_to_recorder) == 0:
return None, []
if last_date_from == date_to_recorder[-1]:
date_to_recorder = date_to_recorder[:-1]
if len(date_to_recorder) == 0:
return None, []
return date_to_recorder[-1], date_to_recorder[:-1]
def backward_click(last_date_from, date_to_recorder):
if last_date_from is None or last_date_from == "":
return time.strftime("%Y%m%d",time.localtime(time.time())), []
if len(date_to_recorder) == 0 or last_date_from != date_to_recorder[-1]:
date_to_recorder.append(last_date_from)
return last_date_from, date_to_recorder
def first_page_click(page_index, filenames):
return get_recent_images(1, 0, filenames)
@ -214,13 +246,33 @@ def page_index_change(page_index, filenames):
return get_recent_images(page_index, 0, filenames)
def show_image_info(tabname_box, num, page_index, filenames):
file = filenames[int(num) + int((page_index - 1) * int(opts.images_history_num_per_page))]
return file, num, file
file = filenames[int(num) + int((page_index - 1) * int(opts.images_history_num_per_page))]
tm = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(os.path.getmtime(file)))
return file, tm, num, file
def enable_page_buttons():
return gradio.update(visible=True)
def change_dir(img_dir, date_to):
warning = None
try:
if os.path.exists(img_dir):
try:
f = os.listdir(img_dir)
except:
warning = f"'{img_dir} is not a directory"
else:
warning = "The directory is not exist"
except:
warning = "The format of the directory is incorrect"
if warning is None:
today = time.strftime("%Y%m%d",time.localtime(time.time()))
return gradio.update(visible=False), gradio.update(visible=True), None, None if date_to != today else today
else:
return gradio.update(visible=True), gradio.update(visible=False), warning, date_to
def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict):
custom_dir = False
if tabname == "txt2img":
dir_name = opts.outdir_txt2img_samples
elif tabname == "img2img":
@ -229,69 +281,85 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict):
dir_name = opts.outdir_extras_samples
elif tabname == "saved":
dir_name = opts.outdir_save
else:
custom_dir = True
dir_name = None
d = dir_name.split("/")
dir_name = d[0]
for p in d[1:]:
dir_name = os.path.join(dir_name, p)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
if not custom_dir:
d = dir_name.split("/")
dir_name = d[0]
for p in d[1:]:
dir_name = os.path.join(dir_name, p)
if not os.path.exists(dir_name):
os.makedirs(dir_name)
with gr.Column() as page_panel:
with gr.Row(visible=False) as turn_page_buttons:
renew_page = gr.Button('Refresh page', elem_id=tabname + "_images_history_renew_page")
first_page = gr.Button('First Page')
prev_page = gr.Button('Prev Page')
page_index = gr.Number(value=1, label="Page Index")
next_page = gr.Button('Next Page')
end_page = gr.Button('End Page')
with gr.Column() as page_panel:
with gr.Row():
img_path = gr.Textbox(dir_name, label="Images directory", placeholder="Input images directory")
with gr.Row(visible=False) as warning:
warning_box = gr.Textbox("Message", interactive=False)
with gr.Row(elem_id=tabname + "_images_history"):
with gr.Column(scale=2):
with gr.Row():
newest = gr.Button('Reload', elem_id=tabname + "_images_history_start")
date_from = gr.Textbox(label="Date from", interactive=False)
date_to = gr.Dropdown(label="Date to")
history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=6)
with gr.Row():
delete_num = gr.Number(value=1, interactive=True, label="number of images to delete consecutively next")
delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button")
with gr.Column():
with gr.Row():
if tabname != "saved":
save_btn = gr.Button('Save')
pnginfo_send_to_txt2img = gr.Button('Send to txt2img')
pnginfo_send_to_img2img = gr.Button('Send to img2img')
with gr.Row():
with gr.Column():
img_file_info = gr.Textbox(label="Generate Info", interactive=False)
img_file_name = gr.Textbox(value="", label="File Name", interactive=False)
with gr.Row(visible=not custom_dir, elem_id=tabname + "_images_history") as main_panel:
with gr.Column(scale=2):
with gr.Row():
backward = gr.Button('Backward')
date_to = gr.Dropdown(label="Date to")
forward = gr.Button('Forward')
newest = gr.Button('Reload', elem_id=tabname + "_images_history_start")
with gr.Row():
load_info = gr.Textbox(show_label=False, interactive=False)
with gr.Row(visible=False) as turn_page_buttons:
renew_page = gr.Button('Refresh page', elem_id=tabname + "_images_history_renew_page")
first_page = gr.Button('First Page')
prev_page = gr.Button('Prev Page')
page_index = gr.Number(value=1, label="Page Index")
next_page = gr.Button('Next Page')
end_page = gr.Button('End Page')
history_gallery = gr.Gallery(show_label=False, elem_id=tabname + "_images_history_gallery").style(grid=opts.images_history_grid_num)
with gr.Row():
delete_num = gr.Number(value=1, interactive=True, label="number of images to delete consecutively next")
delete = gr.Button('Delete', elem_id=tabname + "_images_history_del_button")
# hiden items
with gr.Row(visible=False):
visible_img_num = gr.Number()
img_path = gr.Textbox(dir_name)
tabname_box = gr.Textbox(tabname)
image_index = gr.Textbox(value=-1)
set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index")
filenames = gr.State()
all_images_list = gr.State()
hidden = gr.Image(type="pil")
info1 = gr.Textbox()
info2 = gr.Textbox()
with gr.Column():
with gr.Row():
if tabname != "saved":
save_btn = gr.Button('Save')
pnginfo_send_to_txt2img = gr.Button('Send to txt2img')
pnginfo_send_to_img2img = gr.Button('Send to img2img')
with gr.Row():
with gr.Column():
img_file_info = gr.Textbox(label="Generate Info", interactive=False)
img_file_name = gr.Textbox(value="", label="File Name", interactive=False)
img_file_time= gr.Textbox(value="", label="Create Time", interactive=False)
# hiden items
with gr.Row(): #visible=False):
visible_img_num = gr.Number()
date_to_recorder = gr.State([])
last_date_from = gr.Textbox()
tabname_box = gr.Textbox(tabname)
image_index = gr.Textbox(value=-1)
set_index = gr.Button('set_index', elem_id=tabname + "_images_history_set_index")
filenames = gr.State()
all_images_list = gr.State()
hidden = gr.Image(type="pil")
info1 = gr.Textbox()
info2 = gr.Textbox()
img_path.submit(change_dir, inputs=[img_path, date_to], outputs=[warning, main_panel, warning_box, date_to])
#change date
change_date_output = [date_to, date_from, filenames, page_index, history_gallery, img_file_name, visible_img_num]
newest.click(newest_click, inputs=[img_path, date_to], outputs=change_date_output)
date_to.change(archive_images, inputs=[img_path, date_to], outputs=change_date_output)
newest.click(fn=None, inputs=[tabname_box], outputs=None, _js="images_history_turnpage")
date_to.change(fn=None, inputs=[tabname_box], outputs=None, _js="images_history_turnpage")
date_to.change(enable_page_buttons, inputs=None, outputs=[turn_page_buttons])
newest.click(enable_page_buttons, inputs=None, outputs=[turn_page_buttons])
change_date_output = [date_to, load_info, filenames, page_index, history_gallery, img_file_name, img_file_time, visible_img_num, last_date_from]
date_to.change(archive_images, inputs=[img_path, date_to], outputs=change_date_output)
date_to.change(enable_page_buttons, inputs=None, outputs=[turn_page_buttons])
date_to.change(fn=None, inputs=[tabname_box], outputs=None, _js="images_history_turnpage")
newest.click(newest_click, inputs=[date_to], outputs=[date_to, date_to_recorder])
forward.click(forward_click, inputs=[last_date_from, date_to_recorder], outputs=[date_to, date_to_recorder])
backward.click(backward_click, inputs=[last_date_from, date_to_recorder], outputs=[date_to, date_to_recorder])
#delete
delete.click(delete_image, inputs=[delete_num, img_file_name, filenames, image_index, visible_img_num], outputs=[filenames, delete_num, visible_img_num])
@ -301,7 +369,7 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict):
#turn page
gallery_inputs = [page_index, filenames]
gallery_outputs = [page_index, history_gallery, img_file_name, visible_img_num]
gallery_outputs = [page_index, history_gallery, img_file_name, img_file_time, visible_img_num]
first_page.click(first_page_click, inputs=gallery_inputs, outputs=gallery_outputs)
next_page.click(next_page_click, inputs=gallery_inputs, outputs=gallery_outputs)
prev_page.click(prev_page_click, inputs=gallery_inputs, outputs=gallery_outputs)
@ -317,12 +385,14 @@ def show_images_history(gr, opts, tabname, run_pnginfo, switch_dict):
renew_page.click(fn=None, inputs=[tabname_box], outputs=None, _js="images_history_turnpage")
# other funcitons
set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, image_index, page_index, filenames], outputs=[img_file_name, image_index, hidden])
set_index.click(show_image_info, _js="images_history_get_current_img", inputs=[tabname_box, image_index, page_index, filenames], outputs=[img_file_name, img_file_time, image_index, hidden])
img_file_name.change(fn=None, _js="images_history_enable_del_buttons", inputs=None, outputs=None)
hidden.change(fn=run_pnginfo, inputs=[hidden], outputs=[info1, img_file_info, info2])
switch_dict["fn"](pnginfo_send_to_txt2img, switch_dict["t2i"], img_file_info, 'switch_to_txt2img')
switch_dict["fn"](pnginfo_send_to_img2img, switch_dict["i2i"], img_file_info, 'switch_to_img2img_img2img')
def create_history_tabs(gr, sys_opts, run_pnginfo, switch_dict):
global opts;
opts = sys_opts
@ -330,10 +400,11 @@ def create_history_tabs(gr, sys_opts, run_pnginfo, switch_dict):
num_of_imgs_per_page = int(opts.images_history_num_per_page * opts.images_history_pages_num)
with gr.Blocks(analytics_enabled=False) as images_history:
with gr.Tabs() as tabs:
for tab in ["txt2img", "img2img", "extras", "saved"]:
for tab in [browser_tabname, "txt2img", "img2img", "extras", "saved"]:
with gr.Tab(tab):
with gr.Blocks(analytics_enabled=False) as images_history_img2img:
with gr.Blocks(analytics_enabled=False) :
show_images_history(gr, opts, tab, run_pnginfo, switch_dict)
gradio.Checkbox(opts.images_history_reconstruct_directory, elem_id="images_history_reconstruct_directory", visible=False)
#gradio.Checkbox(opts.images_history_reconstruct_directory, elem_id="images_history_reconstruct_directory", visible=False)
gradio.Checkbox(opts.images_history_reconstruct_directory, elem_id="images_history_finish_render", visible=False)
return images_history

View File

@ -309,10 +309,11 @@ options_templates.update(options_section(('sampler-params', "Sampler parameters"
'eta_noise_seed_delta': OptionInfo(0, "Eta noise seed delta", gr.Number, {"precision": 0}),
}))
options_templates.update(options_section(('images-history', "Images history"), {
"images_history_reconstruct_directory": OptionInfo(False, "Reconstruct output directory structure.This can greatly improve the speed of loading , but will change the original output directory structure"),
options_templates.update(options_section(('images-history', "Images Browser"), {
#"images_history_reconstruct_directory": OptionInfo(False, "Reconstruct output directory structure.This can greatly improve the speed of loading , but will change the original output directory structure"),
"images_history_num_per_page": OptionInfo(36, "Number of pictures displayed on each page"),
"images_history_pages_num": OptionInfo(6, "Maximum number of pages per load "),
"images_history_pages_num": OptionInfo(6, "Minimum number of pages per load "),
"images_history_grid_num": OptionInfo(6, "Number of grids in each row"),
}))

View File

@ -1548,7 +1548,7 @@ Requested path was: {f}
(img2img_interface, "img2img", "img2img"),
(extras_interface, "Extras", "extras"),
(pnginfo_interface, "PNG Info", "pnginfo"),
(images_history, "History", "images_history"),
(images_history, "Image Browser", "images_history"),
(modelmerger_interface, "Checkpoint Merger", "modelmerger"),
(train_interface, "Train", "ti"),
(settings_interface, "Settings", "settings"),

2
uitest.bat Normal file
View File

@ -0,0 +1,2 @@
venv\Scripts\python.exe uitest.py
pause

124
uitest.py Normal file
View File

@ -0,0 +1,124 @@
import os
import threading
import time
import importlib
import signal
import threading
from modules.paths import script_path
from modules import devices, sd_samplers
import modules.codeformer_model as codeformer
import modules.extras
import modules.face_restoration
import modules.gfpgan_model as gfpgan
import modules.img2img
import modules.lowvram
import modules.paths
import modules.scripts
import modules.sd_hijack
import modules.sd_models
import modules.shared as shared
import modules.txt2img
import modules.ui
from modules import devices
from modules import modelloader
from modules.paths import script_path
from modules.shared import cmd_opts
modelloader.cleanup_models()
modules.sd_models.setup_model()
codeformer.setup_model(cmd_opts.codeformer_models_path)
gfpgan.setup_model(cmd_opts.gfpgan_models_path)
shared.face_restorers.append(modules.face_restoration.FaceRestoration())
modelloader.load_upscalers()
queue_lock = threading.Lock()
def wrap_queued_call(func):
def f(*args, **kwargs):
with queue_lock:
res = func(*args, **kwargs)
return res
return f
def wrap_gradio_gpu_call(func, extra_outputs=None):
def f(*args, **kwargs):
devices.torch_gc()
shared.state.sampling_step = 0
shared.state.job_count = -1
shared.state.job_no = 0
shared.state.job_timestamp = shared.state.get_job_timestamp()
shared.state.current_latent = None
shared.state.current_image = None
shared.state.current_image_sampling_step = 0
shared.state.interrupted = False
shared.state.textinfo = None
with queue_lock:
res = func(*args, **kwargs)
shared.state.job = ""
shared.state.job_count = 0
devices.torch_gc()
return res
return modules.ui.wrap_gradio_call(f, extra_outputs=extra_outputs)
modules.scripts.load_scripts(os.path.join(script_path, "scripts"))
shared.sd_model = None #modules.sd_models.load_model()
#shared.opts.onchange("sd_model_checkpoint", wrap_queued_call(lambda: modules.sd_models.reload_model_weights(shared.sd_model)))
def webui():
# make the program just exit at ctrl+c without waiting for anything
def sigint_handler(sig, frame):
print(f'Interrupted with signal {sig} in {frame}')
os._exit(0)
signal.signal(signal.SIGINT, sigint_handler)
while 1:
demo = modules.ui.create_ui(wrap_gradio_gpu_call=wrap_gradio_gpu_call)
demo.launch(
share=cmd_opts.share,
server_name="0.0.0.0" if cmd_opts.listen else None,
server_port=cmd_opts.port,
debug=cmd_opts.gradio_debug,
auth=[tuple(cred.split(':')) for cred in cmd_opts.gradio_auth.strip('"').split(',')] if cmd_opts.gradio_auth else None,
inbrowser=cmd_opts.autolaunch,
prevent_thread_lock=True
)
while 1:
time.sleep(0.5)
if getattr(demo, 'do_restart', False):
time.sleep(0.5)
demo.close()
time.sleep(0.5)
break
sd_samplers.set_samplers()
print('Reloading Custom Scripts')
modules.scripts.reload_scripts(os.path.join(script_path, "scripts"))
print('Reloading modules: modules.ui')
importlib.reload(modules.ui)
print('Restarting Gradio')
if __name__ == "__main__":
webui()