From d7ad69fe5e7c0b78a0dbfd619cde54748a6d4f3f Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Sun, 3 Mar 2024 16:07:55 +0530 Subject: [PATCH 1/7] added the download_model_from_url_feature --- .gitignore | 1 + launch.py | 4 + modules/download_models.py | 31 ++++ modules/load_paths.py | 96 +++++++++++++ modules/model_loader.py | 34 ++++- modules/shared_module.py | 14 ++ webui.py | 285 +++++++++++++++++++++++++++---------- 7 files changed, 383 insertions(+), 82 deletions(-) create mode 100644 modules/download_models.py create mode 100644 modules/load_paths.py create mode 100644 modules/shared_module.py diff --git a/.gitignore b/.gitignore index de2f577..d5ab92d 100644 --- a/.gitignore +++ b/.gitignore @@ -51,3 +51,4 @@ user_path_config-deprecated.txt /package-lock.json /.coverage* /auth.json +/model_config_path.json diff --git a/launch.py b/launch.py index db174f5..eda4bbc 100644 --- a/launch.py +++ b/launch.py @@ -2,6 +2,8 @@ import os import sys import ssl +from modules.load_paths import get_model_paths + print('[System ARGV] ' + str(sys.argv)) root = os.path.dirname(os.path.abspath(__file__)) @@ -75,6 +77,8 @@ def ini_args(): prepare_environment() +# this will get all the folder path of models and store it in json automatically +get_model_paths() build_launcher() args = ini_args() diff --git a/modules/download_models.py b/modules/download_models.py new file mode 100644 index 0000000..2135687 --- /dev/null +++ b/modules/download_models.py @@ -0,0 +1,31 @@ +# download_models.py +from modules.model_loader import load_file_from_url +from modules.shared_module import read_model_config_path + +def download_models(url, selected, file_name=None): + """ + This function downloads models from a given URL and saves them to a specified path. + + 'url' is the URL from which the model will be downloaded. + + 'selected' is the key to get the path from the 'model_paths' dictionary where the downloaded model will be saved. + + 'file_name' is an optional parameter. If provided, the downloaded file will be saved with this name. If not provided, the original file name from the URL will be used. + + The function first reads the 'model_config_path.json' file to get the 'model_paths' dictionary. + + The function then gets the path where the model will be saved from the 'model_paths' dictionary using the 'selected' key. + + The function then tries to download the file from the URL and save it to the path. If the download is successful, a success message is returned. If the download fails, an error message is returned. + """ + model_paths = read_model_config_path("./model_config_path.json") + path = model_paths.get(selected) + + try: + + load_file_from_url(url, model_dir=path, progress=True, file_name=file_name) + success_message = f"Download successful! Model saved to {path}." + except Exception as e: + success_message = f"Download failed! please check url if it is correct." + + return success_message \ No newline at end of file diff --git a/modules/load_paths.py b/modules/load_paths.py new file mode 100644 index 0000000..20f6b1c --- /dev/null +++ b/modules/load_paths.py @@ -0,0 +1,96 @@ +""" +This script contains functions for handling folders and paths. + +Importing the 'os' module which provides a way of using operating system dependent functionality. +The 'os' module provides a portable way of using operating system dependent functionality such as reading or writing to the file system, starting or killing processes, etc. + +Importing the 'json' module which provides a way of working with JSON data. +The 'json' module provides a way of encoding and decoding JSON data. +""" +import os +import json + +def get_folders_and_paths(root_folder): + """ + This function takes a root folder as input and returns a dictionary containing all the folders and their paths in the root folder and its subdirectories. + + 'root_folder' is the path to the root folder. + + 'folder_data' is a dictionary that will contain the folders and their paths. + + The function iterates over all the items in the root folder. If an item is a directory, its name and path are added to the 'folder_data' dictionary. + + The function is called recursively to handle subdirectories. + """ + folder_data = {} + + for folder_name in os.listdir(root_folder): + folder_path = os.path.join(root_folder, folder_name) + if os.path.isdir(folder_path): + folder_data[folder_name] = folder_path + + subfolder_data = get_folders_and_paths(folder_path) + folder_data.update(subfolder_data) + + return folder_data + +def save_to_json(data, json_file): + """ + This function takes data and a json file as input and writes the data to the json file. + + 'data' is the data to be written to the json file. + + 'json_file' is the path to the json file. + + The data is written to the json file with an indentation of 4 spaces. + """ + with open(json_file, 'w') as f: + json.dump(data, f, indent=4) + +def get_model_paths(): + """ + This function gets the paths of all the models in the 'models' directory and its subdirectories and saves them to a json file. + + The function first gets the absolute path of the script's directory. + + The root folder is set to the 'models' directory in the script's directory. + + If the root folder does not exist, an error message is printed and the function returns. + + The function then gets all the folders and their paths in the root folder and its subdirectories. + + The function then iterates over all the folders and their paths. If a folder name contains a path separator, the folder is a subdirectory. The function then updates the 'folder_data' dictionary to contain the subdirectory and its path and adds the parent directory to the 'items_to_delete' list. + + The function then deletes all the items in the 'items_to_delete' list from the 'folder_data' dictionary. + + The function then saves the 'folder_data' dictionary to a json file. + + The function then prints a message indicating that the folder data has been saved to the json file. + """ + script_directory = os.path.dirname(os.path.abspath(__file__)) + + root_folder = os.path.join(script_directory, "../models/") + + if not os.path.exists(root_folder): + print("Error: The specified folder does not exist.") + return + + folder_data = get_folders_and_paths(root_folder) + + items_to_delete = [] + for folder_name, folder_path in folder_data.items(): + if os.path.sep in folder_name: + parent_folder_name, subfolder_name = folder_name.split(os.path.sep, 1) + parent_folder_path = folder_data[parent_folder_name] + folder_data[subfolder_name] = os.path.join(parent_folder_path, folder_name) + items_to_delete.append(folder_name) + + for item in items_to_delete: + del folder_data[item] + + json_file_name = "model_config_path.json" + json_file_path = os.path.join('./', json_file_name) + + save_to_json(folder_data, json_file_path) + + print(f"Folder data has been saved to {json_file_path}.") \ No newline at end of file diff --git a/modules/model_loader.py b/modules/model_loader.py index 8ba336a..4d0f18a 100644 --- a/modules/model_loader.py +++ b/modules/model_loader.py @@ -10,17 +10,39 @@ def load_file_from_url( progress: bool = True, file_name: Optional[str] = None, ) -> str: - """Download a file from `url` into `model_dir`, using the file present if possible. + """ + This function downloads a file from a given URL and saves it to a specified directory. - Returns the path to the downloaded file. + 'url' is the URL from which the file will be downloaded. + + 'model_dir' is the directory where the downloaded file will be saved. + + 'progress' is a boolean that indicates whether to display a progress bar during the download. The default value is True. + + 'file_name' is an optional parameter. If provided, the downloaded file will be saved with this name. If not provided, the original file name from the URL will be used. + + The function first creates the 'model_dir' directory if it does not exist. + + If 'file_name' is not provided, the function parses the 'url' to get the file name. + + The function then checks if the file already exists in the 'model_dir' directory. If the file does not exist, the function tries to download the file from the 'url' and save it to the 'model_dir' directory. If the download fails, an error message is printed. + + The function returns the path to the downloaded file. """ os.makedirs(model_dir, exist_ok=True) if not file_name: + # if file_name is not provided, the file name is extracted from the url. parts = urlparse(url) file_name = os.path.basename(parts.path) cached_file = os.path.abspath(os.path.join(model_dir, file_name)) if not os.path.exists(cached_file): - print(f'Downloading: "{url}" to {cached_file}\n') - from torch.hub import download_url_to_file - download_url_to_file(url, cached_file, progress=progress) - return cached_file + try: + # if the file does not exist, it is downloaded from the url and saved to the model_dir directory. + print(f'Downloading: "{url}" to {cached_file}\n') + from torch.hub import download_url_to_file + download_url_to_file(url, cached_file, progress=progress) + except Exception as e: + # if the download fails, an error message is printed. + print(f"Failed to download {url} to {cached_file}: {e}") + + return cached_file \ No newline at end of file diff --git a/modules/shared_module.py b/modules/shared_module.py new file mode 100644 index 0000000..487f022 --- /dev/null +++ b/modules/shared_module.py @@ -0,0 +1,14 @@ +# shared_module.py +import json + +def read_model_config_path(json_file_path): + """ + This function reads a JSON file and returns its content. + + 'json_file_path' is the path to the JSON file. + + The function opens the JSON file in read mode, loads its content into the 'model_paths' variable, and then returns 'model_paths'. + """ + with open(json_file_path, 'r') as f: + model_paths = json.load(f) + return model_paths \ No newline at end of file diff --git a/webui.py b/webui.py index b9b620d..7e4856f 100644 --- a/webui.py +++ b/webui.py @@ -17,6 +17,7 @@ import modules.meta_parser import args_manager import copy +from modules.download_models import download_models from modules.sdxl_styles import legal_style_names from modules.private_logger import get_current_html_path from modules.ui_gradio_extensions import reload_javascript @@ -50,7 +51,7 @@ def generate_clicked(*args): # help bad internet connection by skipping duplicated preview if len(task.yields) > 0: # if we have the next item - if task.yields[0][0] == 'preview': # if the next item is also a preview + if task.yields[0][0] == 'preview': # if the next item is also a preview # print('Skipped one preview for better internet connection.') continue @@ -102,7 +103,8 @@ with shared.gradio_root: elem_id='final_gallery') with gr.Row(elem_classes='type_row'): with gr.Column(scale=17): - prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", elem_id='positive_prompt', + prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", + elem_id='positive_prompt', container=False, autofocus=True, elem_classes='type_row', lines=1024) default_prompt = modules.config.default_prompt @@ -110,10 +112,15 @@ with shared.gradio_root: shared.gradio_root.load(lambda: default_prompt, outputs=prompt) with gr.Column(scale=3, min_width=0): - generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', elem_id='generate_button', visible=True) - load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", elem_classes='type_row', elem_id='load_parameter_button', visible=False) + generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', + elem_id='generate_button', visible=True) + load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", + elem_classes='type_row', elem_id='load_parameter_button', + visible=False) skip_button = gr.Button(label="Skip", value="Skip", elem_classes='type_row_half', visible=False) - stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', elem_id='stop_button', visible=False) + stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', + elem_id='stop_button', visible=False) + def stop_clicked(): import ldm_patched.modules.model_management as model_management @@ -121,27 +128,34 @@ with shared.gradio_root: model_management.interrupt_current_processing() return [gr.update(interactive=False)] * 2 + def skip_clicked(): import ldm_patched.modules.model_management as model_management shared.last_stop = 'skip' model_management.interrupt_current_processing() return + stop_button.click(stop_clicked, outputs=[skip_button, stop_button], queue=False, show_progress=False, _js='cancelGenerateForever') skip_button.click(skip_clicked, queue=False, show_progress=False) with gr.Row(elem_classes='advanced_check_row'): - input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check') - advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, container=False, elem_classes='min_check') + input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, + elem_classes='min_check') + advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, + container=False, elem_classes='min_check') with gr.Row(visible=False) as image_input_panel: with gr.Tabs(): with gr.TabItem(label='Upscale or Variation') as uov_tab: with gr.Row(): with gr.Column(): - uov_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy') + uov_input_image = grh.Image(label='Drag above image to here', source='upload', + type='numpy') with gr.Column(): - uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, value=flags.disabled) - gr.HTML('\U0001F4D4 Document') + uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, + value=flags.disabled) + gr.HTML( + '\U0001F4D4 Document') with gr.TabItem(label='Image Prompt') as ip_tab: with gr.Row(): ip_images = [] @@ -152,29 +166,36 @@ with shared.gradio_root: ip_ad_cols = [] for _ in range(4): with gr.Column(): - ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, height=300) + ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, + height=300) ip_images.append(ip_image) ip_ctrls.append(ip_image) with gr.Column(visible=False) as ad_col: with gr.Row(): default_end, default_weight = flags.default_parameters[flags.default_ip] - ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, value=default_end) + ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, + value=default_end) ip_stops.append(ip_stop) ip_ctrls.append(ip_stop) - ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, value=default_weight) + ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, + value=default_weight) ip_weights.append(ip_weight) ip_ctrls.append(ip_weight) - ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, container=False) + ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, + container=False) ip_types.append(ip_type) ip_ctrls.append(ip_type) - ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], outputs=[ip_stop, ip_weight], queue=False, show_progress=False) + ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], + outputs=[ip_stop, ip_weight], queue=False, show_progress=False) ip_ad_cols.append(ad_col) ip_advanced = gr.Checkbox(label='Advanced', value=False, container=False) - gr.HTML('* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). \U0001F4D4 Document') + gr.HTML( + '* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). \U0001F4D4 Document') + def ip_advance_checked(x): return [gr.update(visible=x)] * len(ip_ad_cols) + \ @@ -182,32 +203,47 @@ with shared.gradio_root: [flags.default_parameters[flags.default_ip][0]] * len(ip_stops) + \ [flags.default_parameters[flags.default_ip][1]] * len(ip_weights) + ip_advanced.change(ip_advance_checked, inputs=ip_advanced, outputs=ip_ad_cols + ip_types + ip_stops + ip_weights, queue=False, show_progress=False) with gr.TabItem(label='Inpaint or Outpaint') as inpaint_tab: with gr.Row(): - inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', source='upload', type='numpy', tool='sketch', height=500, brush_color="#FFFFFF", elem_id='inpaint_canvas') - inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', height=500, visible=False) + inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', + source='upload', type='numpy', tool='sketch', height=500, + brush_color="#FFFFFF", elem_id='inpaint_canvas') + inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', + height=500, visible=False) with gr.Row(): - inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", elem_id='inpaint_additional_prompt', label='Inpaint Additional Prompt', visible=False) - outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], label='Outpaint Direction') - inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, value=modules.flags.inpaint_option_default, label='Method') - example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, label='Additional Prompt Quick List', components=[inpaint_additional_prompt], visible=False) - gr.HTML('* Powered by Fooocus Inpaint Engine \U0001F4D4 Document') - example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, outputs=inpaint_additional_prompt, show_progress=False, queue=False) + inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", + elem_id='inpaint_additional_prompt', + label='Inpaint Additional Prompt', visible=False) + outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], + label='Outpaint Direction') + inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, + value=modules.flags.inpaint_option_default, label='Method') + example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, + label='Additional Prompt Quick List', + components=[inpaint_additional_prompt], visible=False) + gr.HTML( + '* Powered by Fooocus Inpaint Engine \U0001F4D4 Document') + example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, + outputs=inpaint_additional_prompt, show_progress=False, + queue=False) with gr.TabItem(label='Describe') as desc_tab: with gr.Row(): with gr.Column(): - desc_input_image = grh.Image(label='Drag any image to here', source='upload', type='numpy') + desc_input_image = grh.Image(label='Drag any image to here', source='upload', + type='numpy') with gr.Column(): desc_method = gr.Radio( label='Content Type', choices=[flags.desc_type_photo, flags.desc_type_anime], value=flags.desc_type_photo) desc_btn = gr.Button(value='Describe this Image into Prompt') - gr.HTML('\U0001F4D4 Document') + gr.HTML( + '\U0001F4D4 Document') switch_js = "(x) => {if(x){viewer_to_bottom(100);viewer_to_bottom(500);}else{viewer_to_top();} return x;}" down_js = "() => {viewer_to_bottom();}" @@ -226,20 +262,26 @@ with shared.gradio_root: performance_selection = gr.Radio(label='Performance', choices=modules.flags.performance_selections, value=modules.config.default_performance) - aspect_ratios_selection = gr.Radio(label='Aspect Ratios', choices=modules.config.available_aspect_ratios, + aspect_ratios_selection = gr.Radio(label='Aspect Ratios', + choices=modules.config.available_aspect_ratios, value=modules.config.default_aspect_ratio, info='width × height', elem_classes='aspect_ratios') - image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number) + image_number = gr.Slider(label='Image Number', minimum=1, + maximum=modules.config.default_max_image_number, step=1, + value=modules.config.default_image_number) negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.", info='Describing what you do not want to see.', lines=2, elem_id='negative_prompt', value=modules.config.default_prompt_negative) seed_random = gr.Checkbox(label='Random', value=True) - image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354 + image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, + visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354 + def random_checked(r): return gr.update(visible=not r) + def refresh_seed(r, seed_string): if r: return random.randint(constants.MIN_SEED, constants.MAX_SEED) @@ -252,14 +294,18 @@ with shared.gradio_root: pass return random.randint(constants.MIN_SEED, constants.MAX_SEED) + seed_random.change(random_checked, inputs=[seed_random], outputs=[image_seed], queue=False, show_progress=False) + def update_history_link(): if args_manager.args.disable_image_log: return gr.update(value='') - - return gr.update(value=f'\U0001F4DA History Log') + + return gr.update( + value=f'\U0001F4DA History Log') + history_link = gr.HTML() shared.gradio_root.load(update_history_link, outputs=history_link, queue=False, show_progress=False) @@ -296,12 +342,73 @@ with shared.gradio_root: queue=False, show_progress=False).then( lambda: None, _js='()=>{refresh_style_localization();}') + with gr.Tab(label='download'): + """ + This creates a new tab in the Gradio interface with the label 'download'. + """ + with gr.Group(): + """ + This creates a new group in the 'download' tab. A group is a container for other Gradio components. + """ + from modules.shared_module import read_model_config_path + + model_paths = read_model_config_path("./model_config_path.json") + """ + This reads the 'model_config_path.json' file and stores its content in the 'model_paths' variable. + """ + + choices = list(model_paths.keys()) + values = list(model_paths.values()) + """ + This creates two lists: 'choices' and 'values'. 'choices' contains the keys of the 'model_paths' dictionary and 'values' contains the values of the 'model_paths' dictionary. + """ + + with gr.Row(): + url_input = gr.Textbox(label="Enter URL:") + """ + This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Enter URL:' and is used for the user to input the URL from which the model will be downloaded. + """ + + with gr.Row(): + file_name = gr.Textbox(label="Enter File Name:", placeholder="Enter the File Name " + "With its Extension.(Optional)") + """ + This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Enter File Name:' and is used for the user to input the name of the file to be downloaded. If the user does not provide a file name, the original file name from the URL will be used. + """ + + with gr.Row(): + selected_path = gr.Dropdown(label='Select Path', choices=choices, + show_label=True) + """ + This creates a new row in the group and adds a dropdown to it. The dropdown is labeled 'Select Path' and its options are the keys of the 'model_paths' dictionary. The user can select a key from the dropdown, and the corresponding value from the 'model_paths' dictionary will be used as the path where the downloaded file will be saved. + """ + + with gr.Row(): + output = gr.Textbox(value="", label="Output") + """ + This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Output' and is used to display the output of the download operation. + """ + + with gr.Row(): + start_download = gr.Button("download",label="Download") + """ + This creates a new row in the group and adds a button to it. The button is labeled 'Download (URL)' and is used to start the download operation when clicked. + """ + start_download.click(download_models, inputs=[url_input, selected_path, file_name], outputs=[output], + queue=True, + show_progress=True ) + """ + This sets the 'click' event handler of the 'start_download' button. When the button is clicked, the 'download_models' function is called with the values of the 'url_input', 'selected_path', and 'file_name' components as inputs. The output of the 'download_models' function is displayed in the 'output' component. The 'queue=True' argument means that if the button is clicked multiple times, the clicks will be queued and handled one at a time. The 'show_progress=True' argument means that a progress bar will be displayed while the 'download_models' function is running. + """ with gr.Tab(label='Model'): with gr.Group(): with gr.Row(): - base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, value=modules.config.default_base_model_name, show_label=True) - refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', choices=['None'] + modules.config.model_filenames, value=modules.config.default_refiner_model_name, show_label=True) + base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, + value=modules.config.default_base_model_name, show_label=True) + refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', + choices=['None'] + modules.config.model_filenames, + value=modules.config.default_refiner_model_name, show_label=True) refiner_switch = gr.Slider(label='Refiner Switch At', minimum=0.1, maximum=1.0, step=0.0001, info='Use 0.4 for SD1.5 realistic models; ' @@ -326,7 +433,8 @@ with shared.gradio_root: lora_ctrls += [lora_model, lora_weight] with gr.Row(): - model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', variant='secondary', elem_classes='refresh_button') + model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', + variant='secondary', elem_classes='refresh_button') with gr.Tab(label='Advanced'): guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=30.0, step=0.01, value=modules.config.default_cfg_scale, @@ -334,15 +442,18 @@ with shared.gradio_root: sharpness = gr.Slider(label='Image Sharpness', minimum=0.0, maximum=30.0, step=0.001, value=modules.config.default_sample_sharpness, info='Higher value means image and texture are sharper.') - gr.HTML('\U0001F4D4 Document') + gr.HTML( + '\U0001F4D4 Document') dev_mode = gr.Checkbox(label='Developer Debug Mode', value=False, container=False) with gr.Column(visible=False) as dev_tools: with gr.Tab(label='Debug Tools'): adm_scaler_positive = gr.Slider(label='Positive ADM Guidance Scaler', minimum=0.1, maximum=3.0, - step=0.001, value=1.5, info='The scaler multiplied to positive ADM (use 1.0 to disable). ') + step=0.001, value=1.5, + info='The scaler multiplied to positive ADM (use 1.0 to disable). ') adm_scaler_negative = gr.Slider(label='Negative ADM Guidance Scaler', minimum=0.1, maximum=3.0, - step=0.001, value=0.8, info='The scaler multiplied to negative ADM (use 1.0 to disable). ') + step=0.001, value=0.8, + info='The scaler multiplied to negative ADM (use 1.0 to disable). ') adm_scaler_end = gr.Slider(label='ADM Guidance End At Step', minimum=0.0, maximum=1.0, step=0.001, value=0.3, info='When to end the guidance from positive/negative ADM. ') @@ -382,9 +493,10 @@ with shared.gradio_root: overwrite_vary_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Vary"', minimum=-1, maximum=1.0, step=0.001, value=-1, info='Set as negative number to disable. For developer debugging.') - overwrite_upscale_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Upscale"', - minimum=-1, maximum=1.0, step=0.001, value=-1, - info='Set as negative number to disable. For developer debugging.') + overwrite_upscale_strength = gr.Slider( + label='Forced Overwrite of Denoising Strength of "Upscale"', + minimum=-1, maximum=1.0, step=0.001, value=-1, + info='Set as negative number to disable. For developer debugging.') disable_preview = gr.Checkbox(label='Disable Preview', value=False, info='Disable preview during generation.') @@ -411,7 +523,8 @@ with shared.gradio_root: with gr.Tab(label='Inpaint'): debugging_inpaint_preprocessor = gr.Checkbox(label='Debug Inpaint Preprocessing', value=False) - inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', value=False) + inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', + value=False) inpaint_engine = gr.Dropdown(label='Inpaint Engine', value=modules.config.default_inpaint_engine_version, choices=flags.inpaint_engine_versions, @@ -435,14 +548,15 @@ with shared.gradio_root: '(default is 0, always process before any mask invert)') inpaint_mask_upload_checkbox = gr.Checkbox(label='Enable Mask Upload', value=False) invert_mask_checkbox = gr.Checkbox(label='Invert Mask', value=False) - + inpaint_ctrls = [debugging_inpaint_preprocessor, inpaint_disable_initial_latent, inpaint_engine, inpaint_strength, inpaint_respective_field, inpaint_mask_upload_checkbox, invert_mask_checkbox, inpaint_erode_or_dilate] inpaint_mask_upload_checkbox.change(lambda x: gr.update(visible=x), - inputs=inpaint_mask_upload_checkbox, - outputs=inpaint_mask_image, queue=False, show_progress=False) + inputs=inpaint_mask_upload_checkbox, + outputs=inpaint_mask_image, queue=False, + show_progress=False) with gr.Tab(label='FreeU'): freeu_enabled = gr.Checkbox(label='Enabled', value=False) @@ -452,8 +566,10 @@ with shared.gradio_root: freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95) freeu_ctrls = [freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2] - adps = [disable_preview, adm_scaler_positive, adm_scaler_negative, adm_scaler_end, adaptive_cfg, sampler_name, - scheduler_name, generate_image_grid, overwrite_step, overwrite_switch, overwrite_width, overwrite_height, + adps = [disable_preview, adm_scaler_positive, adm_scaler_negative, adm_scaler_end, adaptive_cfg, + sampler_name, + scheduler_name, generate_image_grid, overwrite_step, overwrite_switch, overwrite_width, + overwrite_height, overwrite_vary_strength, overwrite_upscale_strength, mixing_image_prompt_and_vary_upscale, mixing_image_prompt_and_inpaint, debugging_cn_preprocessor, skipping_cn_preprocessor, controlnet_softness, @@ -461,6 +577,7 @@ with shared.gradio_root: adps += freeu_ctrls adps += inpaint_ctrls + def dev_mode_checked(r): return gr.update(visible=r) @@ -468,14 +585,17 @@ with shared.gradio_root: dev_mode.change(dev_mode_checked, inputs=[dev_mode], outputs=[dev_tools], queue=False, show_progress=False) + def model_refresh_clicked(): modules.config.update_all_model_names() results = [] - results += [gr.update(choices=modules.config.model_filenames), gr.update(choices=['None'] + modules.config.model_filenames)] + results += [gr.update(choices=modules.config.model_filenames), + gr.update(choices=['None'] + modules.config.model_filenames)] for i in range(5): results += [gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()] return results + model_refresh.click(model_refresh_clicked, [], [base_model, refiner_model] + lora_ctrls, queue=False, show_progress=False) @@ -492,6 +612,7 @@ with shared.gradio_root: queue=False, show_progress=False) \ .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False) + def inpaint_mode_change(mode): assert mode in modules.flags.inpaint_options @@ -519,6 +640,7 @@ with shared.gradio_root: False, modules.config.default_inpaint_engine_version, 1.0, 0.618 ] + inpaint_mode.input(inpaint_mode_change, inputs=inpaint_mode, outputs=[ inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts, inpaint_disable_initial_latent, inpaint_engine, @@ -538,6 +660,7 @@ with shared.gradio_root: state_is_generating = gr.State(False) + def parse_meta(raw_prompt_txt, is_generating): loaded_json = None try: @@ -557,40 +680,48 @@ with shared.gradio_root: return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True) - prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) - load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=[ - advanced_checkbox, - image_number, - prompt, - negative_prompt, - style_selections, - performance_selection, - aspect_ratios_selection, - overwrite_width, - overwrite_height, - sharpness, - guidance_scale, - adm_scaler_positive, - adm_scaler_negative, - adm_scaler_end, - base_model, - refiner_model, - refiner_switch, - sampler_name, - scheduler_name, - seed_random, - image_seed, - generate_button, - load_parameter_button - ] + lora_ctrls, queue=False, show_progress=False) + prompt.input(parse_meta, inputs=[prompt, state_is_generating], + outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) - generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True), + load_parameter_button.click(modules.meta_parser.load_parameter_button_click, + inputs=[prompt, state_is_generating], outputs=[ + advanced_checkbox, + image_number, + prompt, + negative_prompt, + style_selections, + performance_selection, + aspect_ratios_selection, + overwrite_width, + overwrite_height, + sharpness, + guidance_scale, + adm_scaler_positive, + adm_scaler_negative, + adm_scaler_end, + base_model, + refiner_model, + refiner_switch, + sampler_name, + scheduler_name, + seed_random, + image_seed, + generate_button, + load_parameter_button + ] + lora_ctrls, queue=False, + show_progress=False) + + generate_button.click(lambda: ( + gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), + gr.update(visible=False, interactive=False), [], True), outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \ .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \ .then(advanced_parameters.set_all_advanced_parameters, inputs=adps) \ - .then(fn=generate_clicked, inputs=ctrls, outputs=[progress_html, progress_window, progress_gallery, gallery]) \ - .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False), + .then(fn=generate_clicked, inputs=ctrls, + outputs=[progress_html, progress_window, progress_gallery, gallery]) \ + .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), + gr.update(visible=False, interactive=False), False), outputs=[generate_button, stop_button, skip_button, state_is_generating]) \ .then(fn=update_history_link, outputs=history_link) \ .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed') @@ -600,6 +731,7 @@ with shared.gradio_root: gr.Audio(interactive=False, value=notification_file, elem_id='audio_notification', visible=False) break + def trigger_describe(mode, img): if mode == flags.desc_type_photo: from extras.interrogate import default_interrogator as default_interrogator_photo @@ -609,6 +741,7 @@ with shared.gradio_root: return default_interrogator_anime(img), ["Fooocus V2", "Fooocus Masterpiece"] return mode, ["Fooocus V2"] + desc_btn.click(trigger_describe, inputs=[desc_method, desc_input_image], outputs=[prompt, style_selections], show_progress=True, queue=True) From af13c4660734403f56bb4bcd175c7e5480e7aca7 Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Sun, 3 Mar 2024 23:20:52 +0530 Subject: [PATCH 2/7] removed unwanted comments and reduced codebase simpler --- .gitignore | 4 +- launch.py | 6 +- model_config_path.json | 20 +++++ modules/download_models.py | 30 +++----- modules/load_paths.py | 96 ----------------------- modules/model_loader.py | 23 +----- modules/shared_module.py | 14 ---- webui.py | 153 +++++++++++++++++-------------------- 8 files changed, 105 insertions(+), 241 deletions(-) create mode 100644 model_config_path.json delete mode 100644 modules/load_paths.py delete mode 100644 modules/shared_module.py diff --git a/.gitignore b/.gitignore index eefcfeb..d1eab80 100644 --- a/.gitignore +++ b/.gitignore @@ -51,6 +51,4 @@ user_path_config-deprecated.txt /package-lock.json /.coverage* /auth.json -/model_config_path.json -.DS_Store - +.DS_Store \ No newline at end of file diff --git a/launch.py b/launch.py index a755487..b965759 100644 --- a/launch.py +++ b/launch.py @@ -2,8 +2,6 @@ import os import sys import ssl -from modules.load_paths import get_model_paths - print('[System ARGV] ' + str(sys.argv)) root = os.path.dirname(os.path.abspath(__file__)) @@ -76,8 +74,6 @@ def ini_args(): prepare_environment() -# this will get all the folder path of models and store it in json automatically -get_model_paths() build_launcher() args = ini_args() @@ -128,4 +124,4 @@ def download_models(): download_models() -from webui import * +from webui import * \ No newline at end of file diff --git a/model_config_path.json b/model_config_path.json new file mode 100644 index 0000000..7764f43 --- /dev/null +++ b/model_config_path.json @@ -0,0 +1,20 @@ +{ + "checkpoints": "../models/checkpoints", + "clip": "../models/clip", + "clip_vision": "../models/clip_vision", + "configs": "../models/configs", + "controlnet": "../models/controlnet", + "diffusers": "../models/diffusers", + "embeddings": "../models/embeddings", + "gligen": "../models/gligen", + "hypernetworks": "../models/hypernetworks", + "inpaint": "../models/inpaint", + "loras": "../models/loras", + "prompt_expansion": "../models/prompt_expansion", + "fooocus_expansion": "../models/prompt_expansion/fooocus_expansion", + "style_models": "../models/style_models", + "unet": "../models/unet", + "upscale_models": "../models/upscale_models", + "vae": "../models/vae", + "vae_approx": "../models/vae_approx" +} \ No newline at end of file diff --git a/modules/download_models.py b/modules/download_models.py index 2135687..25a26d0 100644 --- a/modules/download_models.py +++ b/modules/download_models.py @@ -1,31 +1,21 @@ # download_models.py +import json +import os + from modules.model_loader import load_file_from_url -from modules.shared_module import read_model_config_path + def download_models(url, selected, file_name=None): - """ - This function downloads models from a given URL and saves them to a specified path. + with open('./model_config_path.json', 'r') as f: + model_paths = json.load(f) - 'url' is the URL from which the model will be downloaded. - - 'selected' is the key to get the path from the 'model_paths' dictionary where the downloaded model will be saved. - - 'file_name' is an optional parameter. If provided, the downloaded file will be saved with this name. If not provided, the original file name from the URL will be used. - - The function first reads the 'model_config_path.json' file to get the 'model_paths' dictionary. - - The function then gets the path where the model will be saved from the 'model_paths' dictionary using the 'selected' key. - - The function then tries to download the file from the URL and save it to the path. If the download is successful, a success message is returned. If the download fails, an error message is returned. - """ - model_paths = read_model_config_path("./model_config_path.json") path = model_paths.get(selected) + path = os.path.abspath(path) try: - load_file_from_url(url, model_dir=path, progress=True, file_name=file_name) - success_message = f"Download successful! Model saved to {path}." + message = f"Download successful! Model saved to {path}." except Exception as e: - success_message = f"Download failed! please check url if it is correct." + message = f"Download failed! Please check the URL and try again." - return success_message \ No newline at end of file + return message diff --git a/modules/load_paths.py b/modules/load_paths.py deleted file mode 100644 index 20f6b1c..0000000 --- a/modules/load_paths.py +++ /dev/null @@ -1,96 +0,0 @@ -""" -This script contains functions for handling folders and paths. - -Importing the 'os' module which provides a way of using operating system dependent functionality. -The 'os' module provides a portable way of using operating system dependent functionality such as reading or writing to the file system, starting or killing processes, etc. - -Importing the 'json' module which provides a way of working with JSON data. -The 'json' module provides a way of encoding and decoding JSON data. -""" -import os -import json - -def get_folders_and_paths(root_folder): - """ - This function takes a root folder as input and returns a dictionary containing all the folders and their paths in the root folder and its subdirectories. - - 'root_folder' is the path to the root folder. - - 'folder_data' is a dictionary that will contain the folders and their paths. - - The function iterates over all the items in the root folder. If an item is a directory, its name and path are added to the 'folder_data' dictionary. - - The function is called recursively to handle subdirectories. - """ - folder_data = {} - - for folder_name in os.listdir(root_folder): - folder_path = os.path.join(root_folder, folder_name) - if os.path.isdir(folder_path): - folder_data[folder_name] = folder_path - - subfolder_data = get_folders_and_paths(folder_path) - folder_data.update(subfolder_data) - - return folder_data - -def save_to_json(data, json_file): - """ - This function takes data and a json file as input and writes the data to the json file. - - 'data' is the data to be written to the json file. - - 'json_file' is the path to the json file. - - The data is written to the json file with an indentation of 4 spaces. - """ - with open(json_file, 'w') as f: - json.dump(data, f, indent=4) - -def get_model_paths(): - """ - This function gets the paths of all the models in the 'models' directory and its subdirectories and saves them to a json file. - - The function first gets the absolute path of the script's directory. - - The root folder is set to the 'models' directory in the script's directory. - - If the root folder does not exist, an error message is printed and the function returns. - - The function then gets all the folders and their paths in the root folder and its subdirectories. - - The function then iterates over all the folders and their paths. If a folder name contains a path separator, the folder is a subdirectory. The function then updates the 'folder_data' dictionary to contain the subdirectory and its path and adds the parent directory to the 'items_to_delete' list. - - The function then deletes all the items in the 'items_to_delete' list from the 'folder_data' dictionary. - - The function then saves the 'folder_data' dictionary to a json file. - - The function then prints a message indicating that the folder data has been saved to the json file. - """ - script_directory = os.path.dirname(os.path.abspath(__file__)) - - root_folder = os.path.join(script_directory, "../models/") - - if not os.path.exists(root_folder): - print("Error: The specified folder does not exist.") - return - - folder_data = get_folders_and_paths(root_folder) - - items_to_delete = [] - for folder_name, folder_path in folder_data.items(): - if os.path.sep in folder_name: - parent_folder_name, subfolder_name = folder_name.split(os.path.sep, 1) - parent_folder_path = folder_data[parent_folder_name] - folder_data[subfolder_name] = os.path.join(parent_folder_path, folder_name) - items_to_delete.append(folder_name) - - for item in items_to_delete: - del folder_data[item] - - json_file_name = "model_config_path.json" - json_file_path = os.path.join('./', json_file_name) - - save_to_json(folder_data, json_file_path) - - print(f"Folder data has been saved to {json_file_path}.") \ No newline at end of file diff --git a/modules/model_loader.py b/modules/model_loader.py index 4d0f18a..2ad56ab 100644 --- a/modules/model_loader.py +++ b/modules/model_loader.py @@ -10,39 +10,22 @@ def load_file_from_url( progress: bool = True, file_name: Optional[str] = None, ) -> str: - """ - This function downloads a file from a given URL and saves it to a specified directory. + """Download a file from `url` into `model_dir`, using the file present if possible. - 'url' is the URL from which the file will be downloaded. - - 'model_dir' is the directory where the downloaded file will be saved. - - 'progress' is a boolean that indicates whether to display a progress bar during the download. The default value is True. - - 'file_name' is an optional parameter. If provided, the downloaded file will be saved with this name. If not provided, the original file name from the URL will be used. - - The function first creates the 'model_dir' directory if it does not exist. - - If 'file_name' is not provided, the function parses the 'url' to get the file name. - - The function then checks if the file already exists in the 'model_dir' directory. If the file does not exist, the function tries to download the file from the 'url' and save it to the 'model_dir' directory. If the download fails, an error message is printed. - - The function returns the path to the downloaded file. + Returns the path to the downloaded file. """ os.makedirs(model_dir, exist_ok=True) if not file_name: - # if file_name is not provided, the file name is extracted from the url. parts = urlparse(url) file_name = os.path.basename(parts.path) cached_file = os.path.abspath(os.path.join(model_dir, file_name)) if not os.path.exists(cached_file): try: - # if the file does not exist, it is downloaded from the url and saved to the model_dir directory. + print(f'Downloading: "{url}" to {cached_file}\n') from torch.hub import download_url_to_file download_url_to_file(url, cached_file, progress=progress) except Exception as e: - # if the download fails, an error message is printed. print(f"Failed to download {url} to {cached_file}: {e}") return cached_file \ No newline at end of file diff --git a/modules/shared_module.py b/modules/shared_module.py deleted file mode 100644 index 487f022..0000000 --- a/modules/shared_module.py +++ /dev/null @@ -1,14 +0,0 @@ -# shared_module.py -import json - -def read_model_config_path(json_file_path): - """ - This function reads a JSON file and returns its content. - - 'json_file_path' is the path to the JSON file. - - The function opens the JSON file in read mode, loads its content into the 'model_paths' variable, and then returns 'model_paths'. - """ - with open(json_file_path, 'r') as f: - model_paths = json.load(f) - return model_paths \ No newline at end of file diff --git a/webui.py b/webui.py index d900bbb..4b3cb67 100644 --- a/webui.py +++ b/webui.py @@ -23,12 +23,14 @@ from modules.ui_gradio_extensions import reload_javascript from modules.auth import auth_enabled, check_auth from modules.util import is_json + def get_task(*args): args = list(args) args.pop(0) return worker.AsyncTask(args=args) + def generate_clicked(task): import ldm_patched.modules.model_management as model_management @@ -137,8 +139,8 @@ with shared.gradio_root: model_management.interrupt_current_processing() return currentTask - def skip_clicked(currentTask): + def skip_clicked(currentTask): import ldm_patched.modules.model_management as model_management currentTask.last_stop = 'skip' if (currentTask.processing): @@ -146,9 +148,10 @@ with shared.gradio_root: return currentTask - stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False, _js='cancelGenerateForever') - skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False) - + stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, + show_progress=False, _js='cancelGenerateForever') + skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, + show_progress=False) with gr.Row(elem_classes='advanced_check_row'): input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check') @@ -252,14 +255,16 @@ with shared.gradio_root: choices=[flags.desc_type_photo, flags.desc_type_anime], value=flags.desc_type_photo) desc_btn = gr.Button(value='Describe this Image into Prompt') - - gr.HTML('\U0001F4D4 Document') + gr.HTML( + '\U0001F4D4 Document') with gr.TabItem(label='Metadata') as load_tab: with gr.Column(): - metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', source='upload', type='filepath') + metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', + source='upload', type='filepath') metadata_json = gr.JSON(label='Metadata') metadata_import_button = gr.Button(value='Apply Metadata') + def trigger_metadata_preview(filepath): parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath) @@ -272,10 +277,10 @@ with shared.gradio_root: return results + metadata_input_image.upload(trigger_metadata_preview, inputs=metadata_input_image, outputs=metadata_json, queue=False, show_progress=True) - switch_js = "(x) => {if(x){viewer_to_bottom(100);viewer_to_bottom(500);}else{viewer_to_top();} return x;}" down_js = "() => {viewer_to_bottom();}" @@ -298,13 +303,13 @@ with shared.gradio_root: choices=modules.config.available_aspect_ratios, value=modules.config.default_aspect_ratio, info='width × height', elem_classes='aspect_ratios') - - image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number) + image_number = gr.Slider(label='Image Number', minimum=1, + maximum=modules.config.default_max_image_number, step=1, + value=modules.config.default_image_number) output_format = gr.Radio(label='Output Format', - choices=modules.flags.output_formats, - value=modules.config.default_output_format) - + choices=modules.flags.output_formats, + value=modules.config.default_output_format) negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.", info='Describing what you do not want to see.', lines=2, @@ -340,8 +345,8 @@ with shared.gradio_root: if args_manager.args.disable_image_log: return gr.update(value='') - - return gr.update(value=f'\U0001F4DA History Log') + return gr.update( + value=f'\U0001F4DA History Log') history_link = gr.HTML() @@ -379,64 +384,31 @@ with shared.gradio_root: queue=False, show_progress=False).then( lambda: None, _js='()=>{refresh_style_localization();}') - with gr.Tab(label='download'): - """ - This creates a new tab in the Gradio interface with the label 'download'. - """ - with gr.Group(): - """ - This creates a new group in the 'download' tab. A group is a container for other Gradio components. - """ - from modules.shared_module import read_model_config_path - model_paths = read_model_config_path("./model_config_path.json") - """ - This reads the 'model_config_path.json' file and stores its content in the 'model_paths' variable. - """ + with gr.Tab(label='download'): + with gr.Group(): + with open('./model_config_path.json', 'r') as f: + model_paths = json.load(f) + + for key, value in model_paths.items(): + model_paths[key] = os.path.abspath(value) choices = list(model_paths.keys()) - values = list(model_paths.values()) - """ - This creates two lists: 'choices' and 'values'. 'choices' contains the keys of the 'model_paths' dictionary and 'values' contains the values of the 'model_paths' dictionary. - """ - with gr.Row(): url_input = gr.Textbox(label="Enter URL:") - """ - This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Enter URL:' and is used for the user to input the URL from which the model will be downloaded. - """ - with gr.Row(): file_name = gr.Textbox(label="Enter File Name:", placeholder="Enter the File Name " "With its Extension.(Optional)") - """ - This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Enter File Name:' and is used for the user to input the name of the file to be downloaded. If the user does not provide a file name, the original file name from the URL will be used. - """ - with gr.Row(): selected_path = gr.Dropdown(label='Select Path', choices=choices, show_label=True) - """ - This creates a new row in the group and adds a dropdown to it. The dropdown is labeled 'Select Path' and its options are the keys of the 'model_paths' dictionary. The user can select a key from the dropdown, and the corresponding value from the 'model_paths' dictionary will be used as the path where the downloaded file will be saved. - """ - with gr.Row(): output = gr.Textbox(value="", label="Output") - """ - This creates a new row in the group and adds a textbox to it. The textbox is labeled 'Output' and is used to display the output of the download operation. - """ - with gr.Row(): - start_download = gr.Button("download",label="Download") - """ - This creates a new row in the group and adds a button to it. The button is labeled 'Download (URL)' and is used to start the download operation when clicked. - """ - start_download.click(download_models, inputs=[url_input, selected_path, file_name], outputs=[output], - queue=True, - show_progress=True ) - """ - This sets the 'click' event handler of the 'start_download' button. When the button is clicked, the 'download_models' function is called with the values of the 'url_input', 'selected_path', and 'file_name' components as inputs. The output of the 'download_models' function is displayed in the 'output' component. The 'queue=True' argument means that if the button is clicked multiple times, the clicks will be queued and handled one at a time. The 'show_progress=True' argument means that a progress bar will be displayed while the 'download_models' function is running. - """ + start_download = gr.Button("download", label="Download") + + start_download.click(download_models, inputs=[url_input, selected_path, file_name], + outputs=[output], queue=True, show_progress=True) with gr.Tab(label='Model'): with gr.Group(): @@ -540,22 +512,25 @@ with shared.gradio_root: info='Set as negative number to disable. For developer debugging.') disable_preview = gr.Checkbox(label='Disable Preview', value=False, info='Disable preview during generation.') - disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results', - value=modules.config.default_performance == 'Extreme Speed', - interactive=modules.config.default_performance != 'Extreme Speed', - info='Disable intermediate results during generation, only show final gallery.') + disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results', + value=modules.config.default_performance == 'Extreme Speed', + interactive=modules.config.default_performance != 'Extreme Speed', + info='Disable intermediate results during generation, only show final gallery.') disable_seed_increment = gr.Checkbox(label='Disable seed increment', info='Disable automatic seed increment when image number is > 1.', value=False) if not args_manager.args.disable_metadata: - save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', value=modules.config.default_save_metadata_to_images, + save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', + value=modules.config.default_save_metadata_to_images, info='Adds parameters to generated images allowing manual regeneration.') - metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, value=modules.config.default_metadata_scheme, + metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, + value=modules.config.default_metadata_scheme, info='Image Prompt parameters are not included. Use a1111 for compatibility with Civitai.', visible=modules.config.default_save_metadata_to_images) - save_metadata_to_images.change(lambda x: gr.update(visible=x), inputs=[save_metadata_to_images], outputs=[metadata_scheme], + save_metadata_to_images.change(lambda x: gr.update(visible=x), + inputs=[save_metadata_to_images], outputs=[metadata_scheme], queue=False, show_progress=False) with gr.Tab(label='Control'): @@ -635,12 +610,11 @@ with shared.gradio_root: def model_refresh_clicked(): modules.config.update_all_model_names() - results = [gr.update(choices=modules.config.model_filenames)] results += [gr.update(choices=['None'] + modules.config.model_filenames)] for i in range(modules.config.default_max_lora_number): - results += [gr.update(interactive=True), gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()] - + results += [gr.update(interactive=True), + gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()] return results @@ -649,16 +623,18 @@ with shared.gradio_root: performance_selection.change(lambda x: [gr.update(interactive=x != 'Extreme Speed')] * 11 + [gr.update(visible=x != 'Extreme Speed')] * 1 + - [gr.update(interactive=x != 'Extreme Speed', value=x == 'Extreme Speed', )] * 1, + [gr.update(interactive=x != 'Extreme Speed', + value=x == 'Extreme Speed', )] * 1, inputs=performance_selection, outputs=[ guidance_scale, sharpness, adm_scaler_end, adm_scaler_positive, adm_scaler_negative, refiner_switch, refiner_model, sampler_name, - scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, disable_intermediate_results + scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, + disable_intermediate_results ], queue=False, show_progress=False) - + output_format.input(lambda x: gr.update(output_format=x), inputs=output_format) - + advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column, queue=False, show_progress=False) \ .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False) @@ -701,7 +677,8 @@ with shared.gradio_root: ctrls = [currentTask, generate_image_grid] ctrls += [ prompt, negative_prompt, style_selections, - performance_selection, aspect_ratios_selection, image_number, output_format, image_seed, sharpness, guidance_scale + performance_selection, aspect_ratios_selection, image_number, output_format, image_seed, sharpness, + guidance_scale ] ctrls += [base_model, refiner_model, refiner_switch] + lora_ctrls @@ -739,7 +716,9 @@ with shared.gradio_root: return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True) - prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) + + prompt.input(parse_meta, inputs=[prompt, state_is_generating], + outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) load_data_outputs = [advanced_checkbox, image_number, prompt, negative_prompt, style_selections, performance_selection, overwrite_step, overwrite_switch, aspect_ratios_selection, @@ -748,7 +727,10 @@ with shared.gradio_root: refiner_model, refiner_switch, sampler_name, scheduler_name, seed_random, image_seed, generate_button, load_parameter_button] + freeu_ctrls + lora_ctrls - load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=False) + load_parameter_button.click(modules.meta_parser.load_parameter_button_click, + inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, + show_progress=False) + def trigger_metadata_import(filepath, state_is_generating): parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath) @@ -762,16 +744,21 @@ with shared.gradio_root: return modules.meta_parser.load_parameter_button_click(parsed_parameters, state_is_generating) - metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=True) \ - .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, show_progress=False) + metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], + outputs=load_data_outputs, queue=False, show_progress=True) \ + .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, + show_progress=False) - generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True), + generate_button.click(lambda: ( + gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), + gr.update(visible=False, interactive=False), [], True), outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \ .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \ .then(fn=get_task, inputs=ctrls, outputs=currentTask) \ - .then(fn=generate_clicked, inputs=currentTask, outputs=[progress_html, progress_window, progress_gallery, gallery]) \ - .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False), - + .then(fn=generate_clicked, inputs=currentTask, + outputs=[progress_html, progress_window, progress_gallery, gallery]) \ + .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), + gr.update(visible=False, interactive=False), False), outputs=[generate_button, stop_button, skip_button, state_is_generating]) \ .then(fn=update_history_link, outputs=history_link) \ .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed') @@ -811,4 +798,4 @@ shared.gradio_root.launch( auth=check_auth if (args_manager.args.share or args_manager.args.listen) and auth_enabled else None, allowed_paths=[modules.config.path_outputs], blocked_paths=[constants.AUTH_FILENAME] -) +) \ No newline at end of file From b07057a0e964e9c70a31125c7a6b3b07891ab5ab Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Sun, 3 Mar 2024 23:38:31 +0530 Subject: [PATCH 3/7] fixed the codebase formatted --- webui.py | 229 +++++++++++++++++-------------------------------------- 1 file changed, 71 insertions(+), 158 deletions(-) diff --git a/webui.py b/webui.py index 4b3cb67..dd535a6 100644 --- a/webui.py +++ b/webui.py @@ -23,14 +23,12 @@ from modules.ui_gradio_extensions import reload_javascript from modules.auth import auth_enabled, check_auth from modules.util import is_json - def get_task(*args): args = list(args) args.pop(0) return worker.AsyncTask(args=args) - def generate_clicked(task): import ldm_patched.modules.model_management as model_management @@ -55,7 +53,7 @@ def generate_clicked(task): # help bad internet connection by skipping duplicated preview if len(task.yields) > 0: # if we have the next item - if task.yields[0][0] == 'preview': # if the next item is also a preview + if task.yields[0][0] == 'preview': # if the next item is also a preview # print('Skipped one preview for better internet connection.') continue @@ -113,8 +111,7 @@ with shared.gradio_root: elem_id='final_gallery') with gr.Row(elem_classes='type_row'): with gr.Column(scale=17): - prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", - elem_id='positive_prompt', + prompt = gr.Textbox(show_label=False, placeholder="Type prompt here or paste parameters.", elem_id='positive_prompt', container=False, autofocus=True, elem_classes='type_row', lines=1024) default_prompt = modules.config.default_prompt @@ -122,15 +119,10 @@ with shared.gradio_root: shared.gradio_root.load(lambda: default_prompt, outputs=prompt) with gr.Column(scale=3, min_width=0): - generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', - elem_id='generate_button', visible=True) - load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", - elem_classes='type_row', elem_id='load_parameter_button', - visible=False) + generate_button = gr.Button(label="Generate", value="Generate", elem_classes='type_row', elem_id='generate_button', visible=True) + load_parameter_button = gr.Button(label="Load Parameters", value="Load Parameters", elem_classes='type_row', elem_id='load_parameter_button', visible=False) skip_button = gr.Button(label="Skip", value="Skip", elem_classes='type_row_half', visible=False) - stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', - elem_id='stop_button', visible=False) - + stop_button = gr.Button(label="Stop", value="Stop", elem_classes='type_row_half', elem_id='stop_button', visible=False) def stop_clicked(currentTask): import ldm_patched.modules.model_management as model_management @@ -139,7 +131,6 @@ with shared.gradio_root: model_management.interrupt_current_processing() return currentTask - def skip_clicked(currentTask): import ldm_patched.modules.model_management as model_management currentTask.last_stop = 'skip' @@ -147,28 +138,20 @@ with shared.gradio_root: model_management.interrupt_current_processing() return currentTask - - stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, - show_progress=False, _js='cancelGenerateForever') - skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, - show_progress=False) + stop_button.click(stop_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False, _js='cancelGenerateForever') + skip_button.click(skip_clicked, inputs=currentTask, outputs=currentTask, queue=False, show_progress=False) with gr.Row(elem_classes='advanced_check_row'): - input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, - elem_classes='min_check') - advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, - container=False, elem_classes='min_check') + input_image_checkbox = gr.Checkbox(label='Input Image', value=False, container=False, elem_classes='min_check') + advanced_checkbox = gr.Checkbox(label='Advanced', value=modules.config.default_advanced_checkbox, container=False, elem_classes='min_check') with gr.Row(visible=False) as image_input_panel: with gr.Tabs(): with gr.TabItem(label='Upscale or Variation') as uov_tab: with gr.Row(): with gr.Column(): - uov_input_image = grh.Image(label='Drag above image to here', source='upload', - type='numpy') + uov_input_image = grh.Image(label='Drag above image to here', source='upload', type='numpy') with gr.Column(): - uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, - value=flags.disabled) - gr.HTML( - '\U0001F4D4 Document') + uov_method = gr.Radio(label='Upscale or Variation:', choices=flags.uov_list, value=flags.disabled) + gr.HTML('\U0001F4D4 Document') with gr.TabItem(label='Image Prompt') as ip_tab: with gr.Row(): ip_images = [] @@ -179,36 +162,29 @@ with shared.gradio_root: ip_ad_cols = [] for _ in range(flags.controlnet_image_count): with gr.Column(): - ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, - height=300) + ip_image = grh.Image(label='Image', source='upload', type='numpy', show_label=False, height=300) ip_images.append(ip_image) ip_ctrls.append(ip_image) with gr.Column(visible=False) as ad_col: with gr.Row(): default_end, default_weight = flags.default_parameters[flags.default_ip] - ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, - value=default_end) + ip_stop = gr.Slider(label='Stop At', minimum=0.0, maximum=1.0, step=0.001, value=default_end) ip_stops.append(ip_stop) ip_ctrls.append(ip_stop) - ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, - value=default_weight) + ip_weight = gr.Slider(label='Weight', minimum=0.0, maximum=2.0, step=0.001, value=default_weight) ip_weights.append(ip_weight) ip_ctrls.append(ip_weight) - ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, - container=False) + ip_type = gr.Radio(label='Type', choices=flags.ip_list, value=flags.default_ip, container=False) ip_types.append(ip_type) ip_ctrls.append(ip_type) - ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], - outputs=[ip_stop, ip_weight], queue=False, show_progress=False) + ip_type.change(lambda x: flags.default_parameters[x], inputs=[ip_type], outputs=[ip_stop, ip_weight], queue=False, show_progress=False) ip_ad_cols.append(ad_col) ip_advanced = gr.Checkbox(label='Advanced', value=False, container=False) - gr.HTML( - '* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). \U0001F4D4 Document') - + gr.HTML('* \"Image Prompt\" is powered by Fooocus Image Mixture Engine (v1.0.1). \U0001F4D4 Document') def ip_advance_checked(x): return [gr.update(visible=x)] * len(ip_ad_cols) + \ @@ -216,55 +192,38 @@ with shared.gradio_root: [flags.default_parameters[flags.default_ip][0]] * len(ip_stops) + \ [flags.default_parameters[flags.default_ip][1]] * len(ip_weights) - ip_advanced.change(ip_advance_checked, inputs=ip_advanced, outputs=ip_ad_cols + ip_types + ip_stops + ip_weights, queue=False, show_progress=False) with gr.TabItem(label='Inpaint or Outpaint') as inpaint_tab: with gr.Row(): - inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', - source='upload', type='numpy', tool='sketch', height=500, - brush_color="#FFFFFF", elem_id='inpaint_canvas') - inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', - height=500, visible=False) + inpaint_input_image = grh.Image(label='Drag inpaint or outpaint image to here', source='upload', type='numpy', tool='sketch', height=500, brush_color="#FFFFFF", elem_id='inpaint_canvas') + inpaint_mask_image = grh.Image(label='Mask Upload', source='upload', type='numpy', height=500, visible=False) with gr.Row(): - inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", - elem_id='inpaint_additional_prompt', - label='Inpaint Additional Prompt', visible=False) - outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], - label='Outpaint Direction') - inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, - value=modules.flags.inpaint_option_default, label='Method') - example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, - label='Additional Prompt Quick List', - components=[inpaint_additional_prompt], visible=False) - gr.HTML( - '* Powered by Fooocus Inpaint Engine \U0001F4D4 Document') - example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, - outputs=inpaint_additional_prompt, show_progress=False, - queue=False) + inpaint_additional_prompt = gr.Textbox(placeholder="Describe what you want to inpaint.", elem_id='inpaint_additional_prompt', label='Inpaint Additional Prompt', visible=False) + outpaint_selections = gr.CheckboxGroup(choices=['Left', 'Right', 'Top', 'Bottom'], value=[], label='Outpaint Direction') + inpaint_mode = gr.Dropdown(choices=modules.flags.inpaint_options, value=modules.flags.inpaint_option_default, label='Method') + example_inpaint_prompts = gr.Dataset(samples=modules.config.example_inpaint_prompts, label='Additional Prompt Quick List', components=[inpaint_additional_prompt], visible=False) + gr.HTML('* Powered by Fooocus Inpaint Engine \U0001F4D4 Document') + example_inpaint_prompts.click(lambda x: x[0], inputs=example_inpaint_prompts, outputs=inpaint_additional_prompt, show_progress=False, queue=False) with gr.TabItem(label='Describe') as desc_tab: with gr.Row(): with gr.Column(): - desc_input_image = grh.Image(label='Drag any image to here', source='upload', - type='numpy') + desc_input_image = grh.Image(label='Drag any image to here', source='upload', type='numpy') with gr.Column(): desc_method = gr.Radio( label='Content Type', choices=[flags.desc_type_photo, flags.desc_type_anime], value=flags.desc_type_photo) desc_btn = gr.Button(value='Describe this Image into Prompt') - gr.HTML( - '\U0001F4D4 Document') + gr.HTML('\U0001F4D4 Document') with gr.TabItem(label='Metadata') as load_tab: with gr.Column(): - metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', - source='upload', type='filepath') + metadata_input_image = grh.Image(label='Drag any image generated by Fooocus here', source='upload', type='filepath') metadata_json = gr.JSON(label='Metadata') metadata_import_button = gr.Button(value='Apply Metadata') - def trigger_metadata_preview(filepath): parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath) @@ -277,7 +236,6 @@ with shared.gradio_root: return results - metadata_input_image.upload(trigger_metadata_preview, inputs=metadata_input_image, outputs=metadata_json, queue=False, show_progress=True) @@ -299,31 +257,25 @@ with shared.gradio_root: performance_selection = gr.Radio(label='Performance', choices=modules.flags.performance_selections, value=modules.config.default_performance) - aspect_ratios_selection = gr.Radio(label='Aspect Ratios', - choices=modules.config.available_aspect_ratios, + aspect_ratios_selection = gr.Radio(label='Aspect Ratios', choices=modules.config.available_aspect_ratios, value=modules.config.default_aspect_ratio, info='width × height', elem_classes='aspect_ratios') - image_number = gr.Slider(label='Image Number', minimum=1, - maximum=modules.config.default_max_image_number, step=1, - value=modules.config.default_image_number) + image_number = gr.Slider(label='Image Number', minimum=1, maximum=modules.config.default_max_image_number, step=1, value=modules.config.default_image_number) output_format = gr.Radio(label='Output Format', - choices=modules.flags.output_formats, - value=modules.config.default_output_format) + choices=modules.flags.output_formats, + value=modules.config.default_output_format) negative_prompt = gr.Textbox(label='Negative Prompt', show_label=True, placeholder="Type prompt here.", info='Describing what you do not want to see.', lines=2, elem_id='negative_prompt', value=modules.config.default_prompt_negative) seed_random = gr.Checkbox(label='Random', value=True) - image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, - visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354 - + image_seed = gr.Textbox(label='Seed', value=0, max_lines=1, visible=False) # workaround for https://github.com/gradio-app/gradio/issues/5354 def random_checked(r): return gr.update(visible=not r) - def refresh_seed(r, seed_string): if r: return random.randint(constants.MIN_SEED, constants.MAX_SEED) @@ -336,18 +288,14 @@ with shared.gradio_root: pass return random.randint(constants.MIN_SEED, constants.MAX_SEED) - seed_random.change(random_checked, inputs=[seed_random], outputs=[image_seed], queue=False, show_progress=False) - def update_history_link(): if args_manager.args.disable_image_log: return gr.update(value='') - - return gr.update( - value=f'\U0001F4DA History Log') - + + return gr.update(value=f'\U0001F4DA History Log') history_link = gr.HTML() shared.gradio_root.load(update_history_link, outputs=history_link, queue=False, show_progress=False) @@ -385,6 +333,7 @@ with shared.gradio_root: show_progress=False).then( lambda: None, _js='()=>{refresh_style_localization();}') + with gr.Tab(label='download'): with gr.Group(): with open('./model_config_path.json', 'r') as f: @@ -397,7 +346,7 @@ with shared.gradio_root: with gr.Row(): url_input = gr.Textbox(label="Enter URL:") with gr.Row(): - file_name = gr.Textbox(label="Enter File Name:", placeholder="Enter the File Name " + file_name = gr.Textbox(label="Enter File Name:", placeholder="File Name" "With its Extension.(Optional)") with gr.Row(): selected_path = gr.Dropdown(label='Select Path', choices=choices, @@ -413,11 +362,8 @@ with shared.gradio_root: with gr.Tab(label='Model'): with gr.Group(): with gr.Row(): - base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, - value=modules.config.default_base_model_name, show_label=True) - refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', - choices=['None'] + modules.config.model_filenames, - value=modules.config.default_refiner_model_name, show_label=True) + base_model = gr.Dropdown(label='Base Model (SDXL only)', choices=modules.config.model_filenames, value=modules.config.default_base_model_name, show_label=True) + refiner_model = gr.Dropdown(label='Refiner (SDXL or SD 1.5)', choices=['None'] + modules.config.model_filenames, value=modules.config.default_refiner_model_name, show_label=True) refiner_switch = gr.Slider(label='Refiner Switch At', minimum=0.1, maximum=1.0, step=0.0001, info='Use 0.4 for SD1.5 realistic models; ' @@ -446,8 +392,7 @@ with shared.gradio_root: lora_ctrls += [lora_enabled, lora_model, lora_weight] with gr.Row(): - model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', - variant='secondary', elem_classes='refresh_button') + model_refresh = gr.Button(label='Refresh', value='\U0001f504 Refresh All Files', variant='secondary', elem_classes='refresh_button') with gr.Tab(label='Advanced'): guidance_scale = gr.Slider(label='Guidance Scale', minimum=1.0, maximum=30.0, step=0.01, value=modules.config.default_cfg_scale, @@ -455,18 +400,15 @@ with shared.gradio_root: sharpness = gr.Slider(label='Image Sharpness', minimum=0.0, maximum=30.0, step=0.001, value=modules.config.default_sample_sharpness, info='Higher value means image and texture are sharper.') - gr.HTML( - '\U0001F4D4 Document') + gr.HTML('\U0001F4D4 Document') dev_mode = gr.Checkbox(label='Developer Debug Mode', value=False, container=False) with gr.Column(visible=False) as dev_tools: with gr.Tab(label='Debug Tools'): adm_scaler_positive = gr.Slider(label='Positive ADM Guidance Scaler', minimum=0.1, maximum=3.0, - step=0.001, value=1.5, - info='The scaler multiplied to positive ADM (use 1.0 to disable). ') + step=0.001, value=1.5, info='The scaler multiplied to positive ADM (use 1.0 to disable). ') adm_scaler_negative = gr.Slider(label='Negative ADM Guidance Scaler', minimum=0.1, maximum=3.0, - step=0.001, value=0.8, - info='The scaler multiplied to negative ADM (use 1.0 to disable). ') + step=0.001, value=0.8, info='The scaler multiplied to negative ADM (use 1.0 to disable). ') adm_scaler_end = gr.Slider(label='ADM Guidance End At Step', minimum=0.0, maximum=1.0, step=0.001, value=0.3, info='When to end the guidance from positive/negative ADM. ') @@ -506,31 +448,27 @@ with shared.gradio_root: overwrite_vary_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Vary"', minimum=-1, maximum=1.0, step=0.001, value=-1, info='Set as negative number to disable. For developer debugging.') - overwrite_upscale_strength = gr.Slider( - label='Forced Overwrite of Denoising Strength of "Upscale"', - minimum=-1, maximum=1.0, step=0.001, value=-1, - info='Set as negative number to disable. For developer debugging.') + overwrite_upscale_strength = gr.Slider(label='Forced Overwrite of Denoising Strength of "Upscale"', + minimum=-1, maximum=1.0, step=0.001, value=-1, + info='Set as negative number to disable. For developer debugging.') disable_preview = gr.Checkbox(label='Disable Preview', value=False, info='Disable preview during generation.') - disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results', - value=modules.config.default_performance == 'Extreme Speed', - interactive=modules.config.default_performance != 'Extreme Speed', - info='Disable intermediate results during generation, only show final gallery.') + disable_intermediate_results = gr.Checkbox(label='Disable Intermediate Results', + value=modules.config.default_performance == 'Extreme Speed', + interactive=modules.config.default_performance != 'Extreme Speed', + info='Disable intermediate results during generation, only show final gallery.') disable_seed_increment = gr.Checkbox(label='Disable seed increment', info='Disable automatic seed increment when image number is > 1.', value=False) if not args_manager.args.disable_metadata: - save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', - value=modules.config.default_save_metadata_to_images, + save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', value=modules.config.default_save_metadata_to_images, info='Adds parameters to generated images allowing manual regeneration.') - metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, - value=modules.config.default_metadata_scheme, + metadata_scheme = gr.Radio(label='Metadata Scheme', choices=flags.metadata_scheme, value=modules.config.default_metadata_scheme, info='Image Prompt parameters are not included. Use a1111 for compatibility with Civitai.', visible=modules.config.default_save_metadata_to_images) - save_metadata_to_images.change(lambda x: gr.update(visible=x), - inputs=[save_metadata_to_images], outputs=[metadata_scheme], + save_metadata_to_images.change(lambda x: gr.update(visible=x), inputs=[save_metadata_to_images], outputs=[metadata_scheme], queue=False, show_progress=False) with gr.Tab(label='Control'): @@ -556,8 +494,7 @@ with shared.gradio_root: with gr.Tab(label='Inpaint'): debugging_inpaint_preprocessor = gr.Checkbox(label='Debug Inpaint Preprocessing', value=False) - inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', - value=False) + inpaint_disable_initial_latent = gr.Checkbox(label='Disable initial latent in inpaint', value=False) inpaint_engine = gr.Dropdown(label='Inpaint Engine', value=modules.config.default_inpaint_engine_version, choices=flags.inpaint_engine_versions, @@ -587,9 +524,8 @@ with shared.gradio_root: inpaint_mask_upload_checkbox, invert_mask_checkbox, inpaint_erode_or_dilate] inpaint_mask_upload_checkbox.change(lambda x: gr.update(visible=x), - inputs=inpaint_mask_upload_checkbox, - outputs=inpaint_mask_image, queue=False, - show_progress=False) + inputs=inpaint_mask_upload_checkbox, + outputs=inpaint_mask_image, queue=False, show_progress=False) with gr.Tab(label='FreeU'): freeu_enabled = gr.Checkbox(label='Enabled', value=False) @@ -599,7 +535,6 @@ with shared.gradio_root: freeu_s2 = gr.Slider(label='S2', minimum=0, maximum=4, step=0.01, value=0.95) freeu_ctrls = [freeu_enabled, freeu_b1, freeu_b2, freeu_s1, freeu_s2] - def dev_mode_checked(r): return gr.update(visible=r) @@ -607,39 +542,33 @@ with shared.gradio_root: dev_mode.change(dev_mode_checked, inputs=[dev_mode], outputs=[dev_tools], queue=False, show_progress=False) - def model_refresh_clicked(): modules.config.update_all_model_names() results = [gr.update(choices=modules.config.model_filenames)] results += [gr.update(choices=['None'] + modules.config.model_filenames)] for i in range(modules.config.default_max_lora_number): - results += [gr.update(interactive=True), - gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()] + results += [gr.update(interactive=True), gr.update(choices=['None'] + modules.config.lora_filenames), gr.update()] return results - model_refresh.click(model_refresh_clicked, [], [base_model, refiner_model] + lora_ctrls, queue=False, show_progress=False) performance_selection.change(lambda x: [gr.update(interactive=x != 'Extreme Speed')] * 11 + [gr.update(visible=x != 'Extreme Speed')] * 1 + - [gr.update(interactive=x != 'Extreme Speed', - value=x == 'Extreme Speed', )] * 1, + [gr.update(interactive=x != 'Extreme Speed', value=x == 'Extreme Speed', )] * 1, inputs=performance_selection, outputs=[ guidance_scale, sharpness, adm_scaler_end, adm_scaler_positive, adm_scaler_negative, refiner_switch, refiner_model, sampler_name, - scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, - disable_intermediate_results + scheduler_name, adaptive_cfg, refiner_swap_method, negative_prompt, disable_intermediate_results ], queue=False, show_progress=False) - + output_format.input(lambda x: gr.update(output_format=x), inputs=output_format) - + advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column, queue=False, show_progress=False) \ .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False) - def inpaint_mode_change(mode): assert mode in modules.flags.inpaint_options @@ -667,7 +596,6 @@ with shared.gradio_root: False, modules.config.default_inpaint_engine_version, 1.0, 0.618 ] - inpaint_mode.input(inpaint_mode_change, inputs=inpaint_mode, outputs=[ inpaint_additional_prompt, outpaint_selections, example_inpaint_prompts, inpaint_disable_initial_latent, inpaint_engine, @@ -677,8 +605,7 @@ with shared.gradio_root: ctrls = [currentTask, generate_image_grid] ctrls += [ prompt, negative_prompt, style_selections, - performance_selection, aspect_ratios_selection, image_number, output_format, image_seed, sharpness, - guidance_scale + performance_selection, aspect_ratios_selection, image_number, output_format, image_seed, sharpness, guidance_scale ] ctrls += [base_model, refiner_model, refiner_switch] + lora_ctrls @@ -702,7 +629,6 @@ with shared.gradio_root: state_is_generating = gr.State(False) - def parse_meta(raw_prompt_txt, is_generating): loaded_json = None if is_json(raw_prompt_txt): @@ -716,9 +642,7 @@ with shared.gradio_root: return json.dumps(loaded_json), gr.update(visible=False), gr.update(visible=True) - - prompt.input(parse_meta, inputs=[prompt, state_is_generating], - outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) + prompt.input(parse_meta, inputs=[prompt, state_is_generating], outputs=[prompt, generate_button, load_parameter_button], queue=False, show_progress=False) load_data_outputs = [advanced_checkbox, image_number, prompt, negative_prompt, style_selections, performance_selection, overwrite_step, overwrite_switch, aspect_ratios_selection, @@ -727,10 +651,7 @@ with shared.gradio_root: refiner_model, refiner_switch, sampler_name, scheduler_name, seed_random, image_seed, generate_button, load_parameter_button] + freeu_ctrls + lora_ctrls - load_parameter_button.click(modules.meta_parser.load_parameter_button_click, - inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, - show_progress=False) - + load_parameter_button.click(modules.meta_parser.load_parameter_button_click, inputs=[prompt, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=False) def trigger_metadata_import(filepath, state_is_generating): parameters, metadata_scheme = modules.meta_parser.read_info_from_image(filepath) @@ -744,21 +665,15 @@ with shared.gradio_root: return modules.meta_parser.load_parameter_button_click(parsed_parameters, state_is_generating) - metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], - outputs=load_data_outputs, queue=False, show_progress=True) \ - .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, - show_progress=False) + metadata_import_button.click(trigger_metadata_import, inputs=[metadata_input_image, state_is_generating], outputs=load_data_outputs, queue=False, show_progress=True) \ + .then(style_sorter.sort_styles, inputs=style_selections, outputs=style_selections, queue=False, show_progress=False) - generate_button.click(lambda: ( - gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), - gr.update(visible=False, interactive=False), [], True), + generate_button.click(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), [], True), outputs=[stop_button, skip_button, generate_button, gallery, state_is_generating]) \ .then(fn=refresh_seed, inputs=[seed_random, image_seed], outputs=image_seed) \ .then(fn=get_task, inputs=ctrls, outputs=currentTask) \ - .then(fn=generate_clicked, inputs=currentTask, - outputs=[progress_html, progress_window, progress_gallery, gallery]) \ - .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), - gr.update(visible=False, interactive=False), False), + .then(fn=generate_clicked, inputs=currentTask, outputs=[progress_html, progress_window, progress_gallery, gallery]) \ + .then(lambda: (gr.update(visible=True, interactive=True), gr.update(visible=False, interactive=False), gr.update(visible=False, interactive=False), False), outputs=[generate_button, stop_button, skip_button, state_is_generating]) \ .then(fn=update_history_link, outputs=history_link) \ .then(fn=lambda: None, _js='playNotification').then(fn=lambda: None, _js='refresh_grid_delayed') @@ -768,7 +683,6 @@ with shared.gradio_root: gr.Audio(interactive=False, value=notification_file, elem_id='audio_notification', visible=False) break - def trigger_describe(mode, img): if mode == flags.desc_type_photo: from extras.interrogate import default_interrogator as default_interrogator_photo @@ -778,7 +692,6 @@ with shared.gradio_root: return default_interrogator_anime(img), ["Fooocus V2", "Fooocus Masterpiece"] return mode, ["Fooocus V2"] - desc_btn.click(trigger_describe, inputs=[desc_method, desc_input_image], outputs=[prompt, style_selections], show_progress=True, queue=True) @@ -798,4 +711,4 @@ shared.gradio_root.launch( auth=check_auth if (args_manager.args.share or args_manager.args.listen) and auth_enabled else None, allowed_paths=[modules.config.path_outputs], blocked_paths=[constants.AUTH_FILENAME] -) \ No newline at end of file +) From 84214402ce26b80a425e879dc78cfa9a30ad689b Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Sun, 3 Mar 2024 23:41:45 +0530 Subject: [PATCH 4/7] fixed the codebase formatted remaining --- .gitignore | 2 +- launch.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index d1eab80..8591498 100644 --- a/.gitignore +++ b/.gitignore @@ -51,4 +51,4 @@ user_path_config-deprecated.txt /package-lock.json /.coverage* /auth.json -.DS_Store \ No newline at end of file +.DS_Store diff --git a/launch.py b/launch.py index b965759..4269f1f 100644 --- a/launch.py +++ b/launch.py @@ -124,4 +124,4 @@ def download_models(): download_models() -from webui import * \ No newline at end of file +from webui import * From eb352812b415bcac4ca78e1f92f1fc7c5379eb4d Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Mon, 4 Mar 2024 19:01:47 +0530 Subject: [PATCH 5/7] added disable download tab using argument --- args_manager.py | 3 +++ modules/config.py | 5 +++++ modules/model_loader.py | 3 +-- webui.py | 48 ++++++++++++++++++++++------------------- 4 files changed, 35 insertions(+), 24 deletions(-) diff --git a/args_manager.py b/args_manager.py index c7c1b7a..2815c8e 100644 --- a/args_manager.py +++ b/args_manager.py @@ -4,6 +4,9 @@ import os from tempfile import gettempdir args_parser.parser.add_argument("--share", action='store_true', help="Set whether to share on Gradio.") +args_parser.parser.add_argument("--disable-download-tab", action='store_true', + help="Disables Download Tabs in the UI.") + args_parser.parser.add_argument("--preset", type=str, default=None, help="Apply specified UI preset.") args_parser.parser.add_argument("--language", type=str, default='default', diff --git a/modules/config.py b/modules/config.py index 09c8fd7..a0e4de5 100644 --- a/modules/config.py +++ b/modules/config.py @@ -318,6 +318,11 @@ default_advanced_checkbox = get_config_item_or_set_default( default_value=False, validator=lambda x: isinstance(x, bool) ) +default_download_tab_checkbox = get_config_item_or_set_default( + key='default_download_tab_checkbox', + default_value=True, + validator=lambda x: isinstance(x, bool) +) default_max_image_number = get_config_item_or_set_default( key='default_max_image_number', default_value=32, diff --git a/modules/model_loader.py b/modules/model_loader.py index 2ad56ab..f8343ad 100644 --- a/modules/model_loader.py +++ b/modules/model_loader.py @@ -21,11 +21,10 @@ def load_file_from_url( cached_file = os.path.abspath(os.path.join(model_dir, file_name)) if not os.path.exists(cached_file): try: - print(f'Downloading: "{url}" to {cached_file}\n') from torch.hub import download_url_to_file download_url_to_file(url, cached_file, progress=progress) except Exception as e: - print(f"Failed to download {url} to {cached_file}: {e}") + print(f"Failed to download \"{url}\" to {cached_file}, reason : {e}") return cached_file \ No newline at end of file diff --git a/webui.py b/webui.py index dd535a6..870d0a3 100644 --- a/webui.py +++ b/webui.py @@ -333,31 +333,31 @@ with shared.gradio_root: show_progress=False).then( lambda: None, _js='()=>{refresh_style_localization();}') + if not args_manager.args.disable_download_tab: + with gr.Column(visible=modules.config.default_download_tab_checkbox)as download_tab: + with gr.Tab(label='Download'): + with gr.Group(): + with open('./model_config_path.json', 'r') as f: + model_paths = json.load(f) - with gr.Tab(label='download'): - with gr.Group(): - with open('./model_config_path.json', 'r') as f: - model_paths = json.load(f) + for key, value in model_paths.items(): + model_paths[key] = os.path.abspath(value) - for key, value in model_paths.items(): - model_paths[key] = os.path.abspath(value) + choices = list(model_paths.keys()) + with gr.Row(): + url_input = gr.Textbox(label="URL") + with gr.Row(): + file_name = gr.Textbox(label="File Name with its Extension (Optional)") + with gr.Row(): + selected_path = gr.Dropdown(label='Select Path', choices=choices, + show_label=True) + with gr.Row(): + output = gr.Textbox(value="", label="Output") + with gr.Row(): + start_download = gr.Button("download", label="Download") - choices = list(model_paths.keys()) - with gr.Row(): - url_input = gr.Textbox(label="Enter URL:") - with gr.Row(): - file_name = gr.Textbox(label="Enter File Name:", placeholder="File Name" - "With its Extension.(Optional)") - with gr.Row(): - selected_path = gr.Dropdown(label='Select Path', choices=choices, - show_label=True) - with gr.Row(): - output = gr.Textbox(value="", label="Output") - with gr.Row(): - start_download = gr.Button("download", label="Download") - - start_download.click(download_models, inputs=[url_input, selected_path, file_name], - outputs=[output], queue=True, show_progress=True) + start_download.click(download_models, inputs=[url_input, selected_path, file_name], + outputs=[output], queue=True, show_progress=True) with gr.Tab(label='Model'): with gr.Group(): @@ -460,6 +460,7 @@ with shared.gradio_root: disable_seed_increment = gr.Checkbox(label='Disable seed increment', info='Disable automatic seed increment when image number is > 1.', value=False) + disable_download_checkbox = gr.Checkbox(label='Disable Download Tab',info='Disable the download tab when clicked',value=modules.config.default_download_tab_checkbox,elem_classes='min_check') if not args_manager.args.disable_metadata: save_metadata_to_images = gr.Checkbox(label='Save Metadata to Images', value=modules.config.default_save_metadata_to_images, @@ -568,6 +569,9 @@ with shared.gradio_root: advanced_checkbox.change(lambda x: gr.update(visible=x), advanced_checkbox, advanced_column, queue=False, show_progress=False) \ .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False) + disable_download_checkbox.change(lambda x: gr.update(visible=x), disable_download_checkbox, download_tab) \ + .then(fn=lambda: None, _js='refresh_grid_delayed', queue=False, show_progress=False) + def inpaint_mode_change(mode): assert mode in modules.flags.inpaint_options From 4820f3104b4ea0d002e36abf37f402a64a04ad3d Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Mon, 4 Mar 2024 20:00:11 +0530 Subject: [PATCH 6/7] fixed for previous commit --- model_config_path.json | 20 ---------------- modules/config.py | 47 ++++++++++++++++++++++++++++++-------- modules/download_models.py | 14 ++++++------ webui.py | 11 ++------- 4 files changed, 47 insertions(+), 45 deletions(-) delete mode 100644 model_config_path.json diff --git a/model_config_path.json b/model_config_path.json deleted file mode 100644 index 7764f43..0000000 --- a/model_config_path.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "checkpoints": "../models/checkpoints", - "clip": "../models/clip", - "clip_vision": "../models/clip_vision", - "configs": "../models/configs", - "controlnet": "../models/controlnet", - "diffusers": "../models/diffusers", - "embeddings": "../models/embeddings", - "gligen": "../models/gligen", - "hypernetworks": "../models/hypernetworks", - "inpaint": "../models/inpaint", - "loras": "../models/loras", - "prompt_expansion": "../models/prompt_expansion", - "fooocus_expansion": "../models/prompt_expansion/fooocus_expansion", - "style_models": "../models/style_models", - "unet": "../models/unet", - "upscale_models": "../models/upscale_models", - "vae": "../models/vae", - "vae_approx": "../models/vae_approx" -} \ No newline at end of file diff --git a/modules/config.py b/modules/config.py index a0e4de5..fe70b95 100644 --- a/modules/config.py +++ b/modules/config.py @@ -166,16 +166,45 @@ def get_dir_or_set_default(key, default_value, as_array=False, make_directory=Fa config_dict[key] = dp return dp +config_paths = { + 'checkpoints': get_dir_or_set_default('path_checkpoints', ['../models/checkpoints/'], True), + 'clip': get_dir_or_set_default('path_clip', ['../models/clip/']), + 'config': get_dir_or_set_default('path_config', '../models/configs/'), + 'diffusers': get_dir_or_set_default('path_diffusers', ['../models/diffusers/']), + 'gligen': get_dir_or_set_default('path_gligen', ['../models/gligen/']), + 'hypernetworks': get_dir_or_set_default('path_hypernetworks', ['../models/hypernetworks/']), + 'prompt_expansion': get_dir_or_set_default('path_prompt_expansion', '../models/prompt_expansion/'), + 'style_models': get_dir_or_set_default('path_style_models', '../models/style_models/'), + 'unet': get_dir_or_set_default('path_unet', '../models/unet/'), + 'vae': get_dir_or_set_default('path_vae', '../models/vae/'), + 'loras': get_dir_or_set_default('path_loras', ['../models/loras/'], True), + 'embeddings': get_dir_or_set_default('path_embeddings', '../models/embeddings/'), + 'vae_approx': get_dir_or_set_default('path_vae_approx', '../models/vae_approx/'), + 'upscale_models': get_dir_or_set_default('path_upscale_models', '../models/upscale_models/'), + 'inpaint': get_dir_or_set_default('path_inpaint', '../models/inpaint/'), + 'controlnet': get_dir_or_set_default('path_controlnet', '../models/controlnet/'), + 'clip_vision': get_dir_or_set_default('path_clip_vision', '../models/clip_vision/'), + 'fooocus_expansion': get_dir_or_set_default('path_fooocus_expansion', '../models/prompt_expansion/fooocus_expansion') +} -paths_checkpoints = get_dir_or_set_default('path_checkpoints', ['../models/checkpoints/'], True) -paths_loras = get_dir_or_set_default('path_loras', ['../models/loras/'], True) -path_embeddings = get_dir_or_set_default('path_embeddings', '../models/embeddings/') -path_vae_approx = get_dir_or_set_default('path_vae_approx', '../models/vae_approx/') -path_upscale_models = get_dir_or_set_default('path_upscale_models', '../models/upscale_models/') -path_inpaint = get_dir_or_set_default('path_inpaint', '../models/inpaint/') -path_controlnet = get_dir_or_set_default('path_controlnet', '../models/controlnet/') -path_clip_vision = get_dir_or_set_default('path_clip_vision', '../models/clip_vision/') -path_fooocus_expansion = get_dir_or_set_default('path_fooocus_expansion', '../models/prompt_expansion/fooocus_expansion') +paths_checkpoints = config_paths['checkpoints'] +paths_clip = config_paths['clip'] +paths_config = config_paths['config'] +paths_diffusers = config_paths['diffusers'] +paths_gligen = config_paths['gligen'] +paths_hypernetworks = config_paths['hypernetworks'] +paths_prompt_expansion = config_paths['prompt_expansion'] +paths_style_models = config_paths['style_models'] +paths_unet = config_paths['unet'] +paths_vae = config_paths['vae'] +paths_loras = config_paths['loras'] +path_embeddings = config_paths['embeddings'] +path_vae_approx = config_paths['vae_approx'] +path_upscale_models = config_paths['upscale_models'] +path_inpaint = config_paths['inpaint'] +path_controlnet = config_paths['controlnet'] +path_clip_vision = config_paths['clip_vision'] +path_fooocus_expansion = config_paths['fooocus_expansion'] path_outputs = get_path_output() def get_config_item_or_set_default(key, default_value, validator, disable_empty_as_none=False): diff --git a/modules/download_models.py b/modules/download_models.py index 25a26d0..97b26ad 100644 --- a/modules/download_models.py +++ b/modules/download_models.py @@ -1,17 +1,17 @@ # download_models.py -import json import os +from modules import config from modules.model_loader import load_file_from_url def download_models(url, selected, file_name=None): - with open('./model_config_path.json', 'r') as f: - model_paths = json.load(f) - - path = model_paths.get(selected) - path = os.path.abspath(path) - + model_paths = config.config_paths + paths = model_paths[selected] + if isinstance(paths, list): + path = os.path.join(*paths) + else: + path = paths try: load_file_from_url(url, model_dir=path, progress=True, file_name=file_name) message = f"Download successful! Model saved to {path}." diff --git a/webui.py b/webui.py index 870d0a3..15e734a 100644 --- a/webui.py +++ b/webui.py @@ -334,16 +334,9 @@ with shared.gradio_root: lambda: None, _js='()=>{refresh_style_localization();}') if not args_manager.args.disable_download_tab: - with gr.Column(visible=modules.config.default_download_tab_checkbox)as download_tab: - with gr.Tab(label='Download'): + with gr.Tab(label='Download',visible=modules.config.default_download_tab_checkbox)as download_tab: with gr.Group(): - with open('./model_config_path.json', 'r') as f: - model_paths = json.load(f) - - for key, value in model_paths.items(): - model_paths[key] = os.path.abspath(value) - - choices = list(model_paths.keys()) + choices = list(modules.config.config_paths.keys()) with gr.Row(): url_input = gr.Textbox(label="URL") with gr.Row(): From 56d0af5f1a764d7a17b7a8840c2b9b69b1aae312 Mon Sep 17 00:00:00 2001 From: codezeros <156826608+codezeros@users.noreply.github.com> Date: Mon, 4 Mar 2024 20:25:21 +0530 Subject: [PATCH 7/7] added translations to en.json --- language/en.json | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/language/en.json b/language/en.json index cb5603f..9536a3b 100644 --- a/language/en.json +++ b/language/en.json @@ -381,5 +381,18 @@ "Metadata Scheme": "Metadata Scheme", "Image Prompt parameters are not included. Use a1111 for compatibility with Civitai.": "Image Prompt parameters are not included. Use a1111 for compatibility with Civitai.", "fooocus (json)": "fooocus (json)", - "a1111 (plain text)": "a1111 (plain text)" + "a1111 (plain text)": "a1111 (plain text)", + "Download": "Download", + "URL": "URL", + "File Name with its Extension (Optional)": "File Name with its Extension (Optional)", + "Select Path": "Select Path", + "Output": "Output", + "download": "download", + "Download successful! Model saved to": "Download successful! Model saved to", + "Download failed! Please check the URL and try again.": "Download failed! Please check the URL and try again.", + "Downloading: ": "Downloading: ", + "to": "to", + "Failed to download": "Failed to download", + "reason": "reason" + } \ No newline at end of file