Spaces:
Running on Zero
Running on Zero
Upload 6 files
Browse filesFiles changed (6)
- app.py+252-167
- constants.py+77-82
- image_processor.pyAdded+130
- modutils.py+65-21
- requirements.txt+1-1
- utils.py+4
4 unmodified lines56789101112133 unmodified lines17181920212219 unmodified lines4243444546474849505152535455564 unmodified lines6162636465666748 unmodified lines11611711811912012112212312412512612712812913013113213313413513636 unmodified lines17317417517617717817918018118218318445 unmodified lines2302312322332342352362372382392402412422432442452462 unmodified lines24925025125225325430 unmodified lines28528628728828929014 unmodified lines30530630730830931010 unmodified lines32132232332432532635 unmodified lines36236336436536636710 unmodified lines3783793803813823833841 unmodified line38638738838939039139239339495 unmodified lines4904914924934944954 unmodified lines50050150250350450537 unmodified lines5435445455465475481 unmodified line55055155255355455555655721 unmodified lines57958058158258358458528 unmodified lines6146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496507 unmodified lines65865966066166266366450 unmodified lines71571671771871972019 unmodified lines74074174274374474574634 unmodified lines78178278378478578678731 unmodified lines81982082182282382482582682782882916 unmodified lines8468478488498508518522 unmodified lines8558568578588598603 unmodified lines86486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098139 unmodified lines10211022102310241025102610 unmodified lines103710381039104010411042104311 unmodified lines10551056105710581059106060 unmodified lines112111221123112411251126112711281129113011311132113311341 unmodified line113611371138113911401141114211431144114511461147114811491150115152 unmodified lines120412051206120712081209121078 unmodified lines12891290129112921293129412951296129712981299130013011302130341 unmodified lines13451346134713481349135028 unmodified lines1379138013811382138313841385138613871388138913901391139213932 unmodified lines1396139713981399140014015 unmodified lines14071408140914101411141214131414141538 unmodified lines145414551456145714581459146018 unmodified lines14791480148114821483148414 unmodified lines14991500150115021503150410 unmodified lines15151516151715181519152035 unmodified lines1556155715581559156015614 unmodified linesSCHEDULE_TYPE_OPTIONS,SCHEDULE_PREDICTION_TYPE_OPTIONS,check_scheduler_compatibility,)from constants import (PREPROCESSOR_CONTROLNET,TASK_STABLEPY,TASK_MODEL_LIST,UPSCALER_DICT_GUI,3 unmodified linesSDXL_TASK,MODEL_TYPE_TASK,POST_PROCESSING_SAMPLER,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES19 unmodified lineshtml_template_message,escape_html,)from datetime import datetimeimport gradio as grimport loggingimport diffusersimport warningsfrom stablepy import logger# import urllib.parseImageFile.LOAD_TRUNCATED_IMAGES = True# os.environ["PYTORCH_NO_CUDA_MEMORY_CACHING"] = "1"print(os.getenv("SPACES_ZERO_GPU"))4 unmodified linesupdate_civitai_selection, get_civitai_tag, CIVITAI_SORT, CIVITAI_PERIOD, CIVITAI_BASEMODEL,set_textual_inversion_prompt, get_model_pipeline, change_interface_mode, get_t2i_model_info,get_tupled_model_list, save_gallery_images, save_gallery_history, set_optimization, set_sampler_settings,set_quick_presets, process_style_prompt, optimization_list, save_images, download_things,preset_styles, preset_quality, preset_sampler_setting, translate_to_en, EXAMPLES_GUI, RESOURCES)from env import (HF_TOKEN, CIVITAI_API_KEY, HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,48 unmodified linesprint('\033[33m🏁 Download and listing of valid models completed.\033[0m')######################## GUI#######################import gradio as grimport logginglogging.getLogger("diffusers").setLevel(logging.ERROR)import diffusersdiffusers.utils.logging.set_verbosity(40)import warningswarnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")## BEGIN MODfrom stablepy import logger#logger.setLevel(logging.CRITICAL)logger.setLevel(logging.DEBUG)36 unmodified lines] + [model_name]print(self.inventory)def load_new_model(self, model_name, vae_model, task, progress=gr.Progress(track_tqdm=True)):self.update_storage_models()# download link model > model_namevae_model = vae_model if vae_model != "None" else Nonemodel_type = get_model_type(model_name)dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float1645 unmodified linesvae_model=vae_model,type_model_precision=dtype_model,retain_task_model_in_cache=False,device="cpu",)else:if self.model.base_model_id != model_name:load_now_time = datetime.now()elapsed_time = max((load_now_time - self.last_load).total_seconds(), 0)if elapsed_time <= 8:print("Waiting for the previous model's time ops...")time.sleep(8-elapsed_time)self.model.device = torch.device("cpu")self.model.load_pipe(2 unmodified linesvae_model=vae_model,type_model_precision=dtype_model,retain_task_model_in_cache=False,)end_time = time.time()30 unmodified lineslora_scale4,lora5,lora_scale5,sampler,schedule_type,schedule_prediction_type,14 unmodified lineshigh_threshold,value_threshold,distance_threshold,controlnet_output_scaling_in_unet,controlnet_start_threshold,controlnet_stop_threshold,10 unmodified lineshires_negative_prompt,hires_before_adetailer,hires_after_adetailer,loop_generation,leave_progress_bar,disable_progress_bar,35 unmodified linesmask_blur_b,mask_padding_b,retain_task_cache_gui,image_ip1,mask_ip1,model_ip1,10 unmodified linesyield info_state, gr.update(), gr.update()vae_model = vae_model if vae_model != "None" else Noneloras_list = [lora1, lora2, lora3, lora4, lora5]vae_msg = f"VAE: {vae_model}" if vae_model else ""msg_lora = ""1 unmodified lineloras_list = [s if s else "None" for s in loras_list]global lora_model_listlora_model_list = get_lora_model_list()lora1, lora_scale1, lora2, lora_scale2, lora3, lora_scale3, lora4, lora_scale4, lora5, lora_scale5 = \set_prompt_loras(prompt, syntax_weights, model_name, lora1, lora_scale1, lora2, lora_scale2, lora3,lora_scale3, lora4, lora_scale4, lora5, lora_scale5)## END MODprint("Config model:", model_name, vae_model, loras_list)95 unmodified lines"high_threshold": high_threshold,"value_threshold": value_threshold,"distance_threshold": distance_threshold,"lora_A": lora1 if lora1 != "None" else None,"lora_scale_A": lora_scale1,"lora_B": lora2 if lora2 != "None" else None,4 unmodified lines"lora_scale_D": lora_scale4,"lora_E": lora5 if lora5 != "None" else None,"lora_scale_E": lora_scale5,## BEGIN MOD"textual_inversion": get_embed_list(self.model.class_name) if textual_inversion else [],## END MOD37 unmodified lines"hires_sampler": hires_sampler,"hires_before_adetailer": hires_before_adetailer,"hires_after_adetailer": hires_after_adetailer,"ip_adapter_image": params_ip_img,"ip_adapter_mask": params_ip_msk,"ip_adapter_model": params_ip_model,1 unmodified line"ip_adapter_scale": params_ip_scale,}self.model.device = torch.device("cuda:0")if hasattr(self.model.pipe, "transformer") and loras_list != ["None"] * 5:self.model.pipe.transformer.to(self.model.device)print("transformer to cuda")21 unmodified linesif msg_lora:info_images += msg_lorainfo_images = info_images + "<br>" + "GENERATION DATA:<br>" + escape_html(metadata[0]) + "<br>-------<br>"download_links = "<br>".join([28 unmodified linesdef sd_gen_generate_pipeline(*args):gpu_duration_arg = int(args[-1]) if args[-1] else 59verbose_arg = int(args[-2])load_lora_cpu = args[-3]generation_args = args[:-3]lora_list = [None if item == "None" or item == "" else item # MODfor item in [args[7], args[9], args[11], args[13], args[15]]]lora_status = [None] * 5msg_load_lora = "Updating LoRAs in GPU..."if load_lora_cpu:msg_load_lora = "Updating LoRAs in CPU (Slow but saves GPU usage)..."if lora_list != sd_gen.model.lora_memory and lora_list != [None] * 5:yield msg_load_lora, gr.update(), gr.update()# Load lora in CPUif load_lora_cpu:lora_status = sd_gen.model.lora_merge(lora_A=lora_list[0], lora_scale_A=args[8],lora_B=lora_list[1], lora_scale_B=args[10],lora_C=lora_list[2], lora_scale_C=args[12],lora_D=lora_list[3], lora_scale_D=args[14],lora_E=lora_list[4], lora_scale_E=args[16],)print(lora_status)sampler_name = args[17]schedule_type_name = args[18]_, _, msg_sampler = check_scheduler_compatibility(sd_gen.model.class_name, sampler_name, schedule_type_name)7 unmodified lineselif status is not None:gr.Warning(f"Failed to load LoRA: {lora}")if lora_status == [None] * 5 and sd_gen.model.lora_memory != [None] * 5 and load_lora_cpu:lora_cache_msg = ", ".join(str(x) for x in sd_gen.model.lora_memory if x is not None)50 unmodified linesreturn image_pathdynamic_gpu_duration.zerogpu = Truesd_gen_generate_pipeline.zerogpu = Truesd_gen = GuiSD()19 unmodified lineswith gr.Column():with gr.Tab("Generation"):with gr.Row():with gr.Column(scale=2):def update_task_options(model_name, task_name):new_choices = MODEL_TYPE_TASK[get_model_type(model_name)]34 unmodified linesgenerate_from_image_btn_gui = gr.Button(value="GENERATE TAGS FROM IMAGE")prompt_gui = gr.Textbox(lines=6, placeholder="1girl, solo, ...", label="Prompt", show_copy_button=True)with gr.Accordion("Negative prompt, etc.", open=False) as menu_negative:neg_prompt_gui = gr.Textbox(lines=3, placeholder="lowres, (bad), ...", label="Negative prompt", show_copy_button=True)translate_prompt_button = gr.Button(value="Translate prompt to English", size="sm", variant="secondary")with gr.Row():insert_prompt_gui = gr.Radio(label="Insert reccomended positive / negative prompt", choices=["None", "Auto", "Animagine", "Pony"], value="Auto", interactive=True)31 unmodified lineslabel="Generated images",show_label=False,elem_id="gallery",columns=[2],rows=[2],object_fit="contain",# height="auto",interactive=False,preview=False,show_share_button=False,show_download_button=True,16 unmodified linesgpu_duration_gui = gr.Number(minimum=5, maximum=240, value=59, show_label=False, container=False, info="GPU time duration (seconds)")with gr.Column():verbose_info_gui = gr.Checkbox(value=False, container=False, label="Status info")load_lora_cpu_gui = gr.Checkbox(value=False, container=False, label="Load LoRAs on CPU (Save GPU time)")with gr.Column(scale=1):with gr.Accordion("Generation settings", open=False, visible=True) as menu_gen:2 unmodified linesimg_height_gui = gr.Slider(minimum=64, maximum=4096, step=8, value=1024, label="Img Height")steps_gui = gr.Slider(minimum=1, maximum=100, step=1, value=28, label="Steps")cfg_gui = gr.Slider(minimum=0, maximum=30, step=0.5, value=7.0, label="CFG")with gr.Row():seed_gui = gr.Number(minimum=-1, maximum=2**32-1, value=-1, label="Seed")pag_scale_gui = gr.Slider(minimum=0.0, maximum=10.0, step=0.1, value=0.0, label="PAG Scale")3 unmodified lineswith gr.Row():sampler_gui = gr.Dropdown(label="Sampler", choices=scheduler_names, value="Euler")schedule_type_gui = gr.Dropdown(label="Schedule type", choices=SCHEDULE_TYPE_OPTIONS, value=SCHEDULE_TYPE_OPTIONS[0])vae_model_gui = gr.Dropdown(label="VAE Model", choices=vae_model_list, value=vae_model_list[0])prompt_syntax_gui = gr.Dropdown(label="Prompt Syntax", choices=PROMPT_W_OPTIONS, value=PROMPT_W_OPTIONS[1][1])with gr.Row(equal_height=False):def run_set_params_gui(base_prompt, name_model):valid_receptors = { # default values"prompt": gr.update(value=base_prompt),"neg_prompt": gr.update(value=""),"Steps": gr.update(value=30),"width": gr.update(value=1024),"height": gr.update(value=1024),"Seed": gr.update(value=-1),"Sampler": gr.update(value="Euler"),"CFG scale": gr.update(value=7.), # cfg"Clip skip": gr.update(value=True),"Model": gr.update(value=name_model),"Schedule type": gr.update(value="Automatic"),"PAG": gr.update(value=.0),"FreeU": gr.update(value=False),}valid_keys = list(valid_receptors.keys())parameters = extract_parameters(base_prompt)# print(parameters)if "Sampler" in parameters:value_sampler = parameters["Sampler"]for s_type in SCHEDULE_TYPE_OPTIONS:if s_type in value_sampler:value_sampler = value_sampler.replace(s_type, "").strip()parameters["Sampler"] = value_samplerparameters["Schedule type"] = s_typefor key, val in parameters.items():# print(val)if key in valid_keys:try:if key == "Sampler":if val not in scheduler_names:continueif key == "Schedule type":if val not in SCHEDULE_TYPE_OPTIONS:val = "Automatic"elif key == "Clip skip":if "," in str(val):val = val.replace(",", "")if int(val) >= 2:val = Trueif key == "prompt":if ">" in val and "<" in val:val = re.sub(r'<[^>]+>', '', val)print("Removed LoRA written in the prompt")if key in ["prompt", "neg_prompt"]:val = re.sub(r'\s+', ' ', re.sub(r',+', ',', val)).strip()if key in ["Steps", "width", "height", "Seed"]:val = int(val)if key == "FreeU":val = Trueif key in ["CFG scale", "PAG"]:val = float(val)if key == "Model":filtered_models = [m for m in model_list if val in m]if filtered_models:val = filtered_models[0]else:val = name_modelif key == "Seed":continuevalid_receptors[key] = gr.update(value=val)# print(val, type(val))# print(valid_receptors)except Exception as e:print(str(e))return [value for value in valid_receptors.values()]set_params_gui.click(run_set_params_gui, [prompt_gui, model_name_gui], [prompt_gui,neg_prompt_gui,steps_gui,img_width_gui,img_height_gui,seed_gui,sampler_gui,cfg_gui,clip_skip_gui,model_name_gui,schedule_type_gui,pag_scale_gui,free_u_gui,],)def run_clear_prompt_gui():return gr.update(value=""), gr.update(value="")clear_prompt_gui.click(run_clear_prompt_gui, [], [prompt_gui, neg_prompt_gui])def run_set_random_seed():return -1set_random_seed.click(run_set_random_seed, [], seed_gui)with gr.Accordion("LoRA", open=False, visible=True) as menu_lora:def lora_dropdown(label):return gr.Dropdown(label=label, choices=get_all_lora_tupled_list(), value="", allow_custom_value=True, elem_classes="lora", min_width=320)def lora_scale_slider(label):return gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label=label)def lora_textbox(label):return gr.Textbox(label=label, info="Example of prompt:", value="None", show_copy_button=True, interactive=False, visible=False)39 unmodified lineslora5_info_gui = lora_textbox("LoRA5 prompts")lora5_copy_gui = gr.Button(value="Copy example to prompt", visible=False)lora5_desc_gui = gr.Markdown(value="", visible=False)with gr.Accordion("From URL", open=True, visible=True):with gr.Row():search_civitai_basemodel_lora = gr.CheckboxGroup(label="Search LoRA for", choices=CIVITAI_BASEMODEL, value=["Pony", "Illustrious", "SDXL 1.0"])10 unmodified linessearch_civitai_result_lora = gr.Dropdown(label="Search Results", choices=[("", "")], value="", allow_custom_value=True, visible=False)with gr.Row():text_lora = gr.Textbox(label="LoRA's download URL", placeholder="https://civitai.com/api/download/models/28907", info="It has to be .safetensors files, and you can also download them from Hugging Face.", lines=1, scale=4)romanize_text = gr.Checkbox(value=False, label="Transliterate name", scale=1)button_lora = gr.Button("Get and Refresh the LoRA Lists")new_lora_status = gr.HTML()with gr.Accordion("From Local", open=True, visible=True):11 unmodified lineshires_steps_gui = gr.Slider(minimum=0, value=30, maximum=100, step=1, label="Hires Steps")hires_denoising_strength_gui = gr.Slider(minimum=0.1, maximum=1.0, step=0.01, value=0.55, label="Hires Denoising Strength")hires_sampler_gui = gr.Dropdown(label="Hires Sampler", choices=POST_PROCESSING_SAMPLER, value=POST_PROCESSING_SAMPLER[0])hires_prompt_gui = gr.Textbox(label="Hires Prompt", placeholder="Main prompt will be use", lines=3)hires_negative_prompt_gui = gr.Textbox(label="Hires Negative Prompt", placeholder="Main negative prompt will be use", lines=3)60 unmodified linesminimum=64, maximum=2048, step=64, value=1024, label="Image Resolution",info="The maximum proportional size of the generated image based on the uploaded image.")preprocessor_name_gui = gr.Dropdown(label="Preprocessor Name", choices=PREPROCESSOR_CONTROLNET["canny"])def change_preprocessor_choices(task):task = TASK_STABLEPY[task]if task in PREPROCESSOR_CONTROLNET.keys():choices_task = PREPROCESSOR_CONTROLNET[task]else:choices_task = PREPROCESSOR_CONTROLNET["canny"]return gr.update(choices=choices_task, value=choices_task[0])task_gui.change(1 unmodified line[task_gui],[preprocessor_name_gui],)with gr.Row():preprocess_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocess Resolution")low_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="Canny low threshold")high_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="Canny high threshold")value_threshold_gui = gr.Slider(minimum=1, maximum=2.0, step=0.01, value=0.1, label="Hough value threshold (MLSD)")with gr.Row():distance_threshold_gui = gr.Slider(minimum=1, maximum=20.0, step=0.01, value=0.1, label="Hough distance threshold (MLSD)")control_net_output_scaling_gui = gr.Slider(minimum=0, maximum=5.0, step=0.1, value=1, label="ControlNet Output Scaling in UNet")control_net_start_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=0, label="ControlNet Start Threshold (%)")control_net_stop_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=1, label="ControlNet Stop Threshold (%)")with gr.Accordion("IP-Adapter", open=False, visible=True) as menu_ipa:52 unmodified linesstyle_button.click(load_json_style_file, [style_json_gui], [style_prompt_gui])with gr.Accordion("Other settings", open=False, visible=True) as menu_other:schedule_prediction_type_gui = gr.Dropdown(label="Discrete Sampling Type", choices=SCHEDULE_PREDICTION_TYPE_OPTIONS, value=SCHEDULE_PREDICTION_TYPE_OPTIONS[0])with gr.Row():save_generated_images_gui = gr.Checkbox(value=False, label="Save Generated Images")filename_pattern_gui = gr.Textbox(label="Filename pattern", value="model,seed", placeholder="model,seed,sampler,schedule_type,img_width,img_height,guidance_scale,num_steps,vae,prompt_section,neg_prompt_section", lines=1)78 unmodified lines# enable crop (or disable it)# transforms=["crop"],brush=gr.Brush(default_size="16", # or leave it as 'auto'color_mode="fixed", # 'fixed' hides the user swatches and colorpicker, 'defaults' shows it# default_color="black", # html names are supportedcolors=["rgba(0, 0, 0, 1)", # rgb(a)"rgba(0, 0, 0, 0.1)","rgba(255, 255, 255, 0.1)",# "hsl(360, 120, 120)" # in fact any valid colorstring]),eraser=gr.Eraser(default_size="16"))41 unmodified linesoutputs=[result_up_tab],)## BEGIN MODinterface_mode_gui.change(change_interface_mode,28 unmodified linesgr.on(triggers=[lora1_gui.change, lora_scale_1_gui.change, lora2_gui.change, lora_scale_2_gui.change,lora3_gui.change, lora_scale_3_gui.change, lora4_gui.change, lora_scale_4_gui.change,lora5_gui.change, lora_scale_5_gui.change, prompt_syntax_gui.change],fn=update_loras,inputs=[prompt_gui, prompt_syntax_gui, lora1_gui, lora_scale_1_gui, lora2_gui, lora_scale_2_gui,lora3_gui, lora_scale_3_gui, lora4_gui, lora_scale_4_gui, lora5_gui, lora_scale_5_gui],outputs=[prompt_gui, lora1_gui, lora_scale_1_gui, lora1_info_gui, lora1_copy_gui, lora1_desc_gui,lora2_gui, lora_scale_2_gui, lora2_info_gui, lora2_copy_gui, lora2_desc_gui,lora3_gui, lora_scale_3_gui, lora3_info_gui, lora3_copy_gui, lora3_desc_gui,lora4_gui, lora_scale_4_gui, lora4_info_gui, lora4_copy_gui, lora4_desc_gui,lora5_gui, lora_scale_5_gui, lora5_info_gui, lora5_copy_gui, lora5_desc_gui],queue=False,trigger_mode="once",)2 unmodified lineslora3_copy_gui.click(apply_lora_prompt, [prompt_gui, lora3_info_gui], [prompt_gui], queue=False)lora4_copy_gui.click(apply_lora_prompt, [prompt_gui, lora4_info_gui], [prompt_gui], queue=False)lora5_copy_gui.click(apply_lora_prompt, [prompt_gui, lora5_info_gui], [prompt_gui], queue=False)gr.on(triggers=[search_civitai_button_lora.click, search_civitai_query_lora.submit],fn=search_civitai_lora,5 unmodified lines)search_civitai_result_lora.change(select_civitai_lora, [search_civitai_result_lora], [text_lora, search_civitai_desc_lora], queue=False, scroll_to_output=True)search_civitai_gallery_lora.select(update_civitai_selection, None, [search_civitai_result_lora], queue=False, show_api=False)button_lora.click(get_my_lora, [text_lora, romanize_text], [lora1_gui, lora2_gui, lora3_gui, lora4_gui, lora5_gui, new_lora_status], scroll_to_output=True)upload_button_lora.upload(upload_file_lora, [upload_button_lora], [file_output_lora, upload_button_lora]).success(move_file_lora, [file_output_lora], [lora1_gui, lora2_gui, lora3_gui, lora4_gui, lora5_gui], scroll_to_output=True)use_textual_inversion_gui.change(set_textual_inversion_prompt, [use_textual_inversion_gui, prompt_gui, neg_prompt_gui, prompt_syntax_gui], [prompt_gui, neg_prompt_gui])38 unmodified linesinputs=[model_name_gui,vae_model_gui,task_gui],outputs=[load_model_gui],queue=True,18 unmodified lineslora_scale_4_gui,lora5_gui,lora_scale_5_gui,sampler_gui,schedule_type_gui,schedule_prediction_type_gui,14 unmodified lineshigh_threshold_gui,value_threshold_gui,distance_threshold_gui,control_net_output_scaling_gui,control_net_start_threshold_gui,control_net_stop_threshold_gui,10 unmodified lineshires_negative_prompt_gui,hires_before_adetailer_gui,hires_after_adetailer_gui,loop_generation_gui,leave_progress_bar_gui,disable_progress_bar_gui,35 unmodified linesmask_blur_b_gui,mask_padding_b_gui,retain_task_cache_gui,image_ip1,mask_ip1,model_ip1,4 unmodified lines56789101112133 unmodified lines1718192021222319 unmodified lines4344454647484950515253545556575859604 unmodified lines6566676869707148 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314436 unmodified lines18118218318418518618718818919019119219319445 unmodified lines2402412422432442452462472482492502512522532542552562572582 unmodified lines26126226326426526626730 unmodified lines29829930030130230330430530630714 unmodified lines32232332432532632732832910 unmodified lines34034134234334434534634734835 unmodified lines38438538638738838939010 unmodified lines4014024034044054064071 unmodified line40941041141241341441541641795 unmodified lines5135145155165175185195204 unmodified lines52552652752852953053153253353437 unmodified lines5725735745755765775785791 unmodified line58158258358458558658758858959059159221 unmodified lines61461561661761861962028 unmodified lines6496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856867 unmodified lines69469569669769869970050 unmodified lines75175275375475575675719 unmodified lines77777877978078178278334 unmodified lines81881982082182282382431 unmodified lines85685785885986086186286386486586686786886916 unmodified lines8868878888898908918922 unmodified lines8958968978988999009013 unmodified lines90590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102339 unmodified lines106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410 unmodified lines109510961097109810991100110111 unmodified lines11131114111511161117111811191120112160 unmodified lines118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041 unmodified line12061207120812091210121112121213121412151216121752 unmodified lines12701271127212731274127578 unmodified lines13541355135613571358135913601361136213631364136513661367136841 unmodified lines14101411141214131414141514161417141828 unmodified lines14471448144914501451145214531454145514561457145814591460146114621463146414652 unmodified lines146814691470147114721473147414755 unmodified lines14811482148314841485148614871488148938 unmodified lines1528152915301531153215331534153518 unmodified lines155415551556155715581559156015611562156314 unmodified lines1578157915801581158215831584158510 unmodified lines15961597159815991600160116021603160435 unmodified lines16401641164216431644164516464 unmodified linesSCHEDULE_TYPE_OPTIONS,SCHEDULE_PREDICTION_TYPE_OPTIONS,check_scheduler_compatibility,TASK_AND_PREPROCESSORS,)from constants import (TASK_STABLEPY,TASK_MODEL_LIST,UPSCALER_DICT_GUI,3 unmodified linesSDXL_TASK,MODEL_TYPE_TASK,POST_PROCESSING_SAMPLER,DIFFUSERS_CONTROLNET_MODEL,)from stablepy.diffusers_vanilla.style_prompt_config import STYLE_NAMES19 unmodified lineshtml_template_message,escape_html,)from image_processor import preprocessor_tabfrom datetime import datetimeimport gradio as grimport loggingimport diffusersimport warningsfrom stablepy import loggerfrom diffusers import FluxPipeline# import urllib.parseImageFile.LOAD_TRUNCATED_IMAGES = Truetorch.backends.cuda.matmul.allow_tf32 = True# os.environ["PYTORCH_NO_CUDA_MEMORY_CACHING"] = "1"print(os.getenv("SPACES_ZERO_GPU"))4 unmodified linesupdate_civitai_selection, get_civitai_tag, CIVITAI_SORT, CIVITAI_PERIOD, CIVITAI_BASEMODEL,set_textual_inversion_prompt, get_model_pipeline, change_interface_mode, get_t2i_model_info,get_tupled_model_list, save_gallery_images, save_gallery_history, set_optimization, set_sampler_settings,set_quick_presets, process_style_prompt, optimization_list, save_images, download_things, valid_model_name,preset_styles, preset_quality, preset_sampler_setting, translate_to_en, EXAMPLES_GUI, RESOURCES)from env import (HF_TOKEN, CIVITAI_API_KEY, HF_LORA_ESSENTIAL_PRIVATE_REPO, HF_VAE_PRIVATE_REPO,HF_SDXL_EMBEDS_NEGATIVE_PRIVATE_REPO, HF_SDXL_EMBEDS_POSITIVE_PRIVATE_REPO,48 unmodified linesprint('\033[33m🏁 Download and listing of valid models completed.\033[0m')flux_repo = "camenduru/FLUX.1-dev-diffusers"flux_pipe = FluxPipeline.from_pretrained(flux_repo,transformer=None,torch_dtype=torch.bfloat16,).to("cuda")components = flux_pipe.componentscomponents.pop("transformer", None)delete_model(flux_repo)######################## GUI#######################logging.getLogger("diffusers").setLevel(logging.ERROR)diffusers.utils.logging.set_verbosity(40)warnings.filterwarnings(action="ignore", category=FutureWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=UserWarning, module="diffusers")warnings.filterwarnings(action="ignore", category=FutureWarning, module="transformers")## BEGIN MOD#logger.setLevel(logging.CRITICAL)logger.setLevel(logging.DEBUG)36 unmodified lines] + [model_name]print(self.inventory)def load_new_model(self, model_name, vae_model, task, controlnet_model, progress=gr.Progress(track_tqdm=True)):# download link model > model_namemodel_name = valid_model_name(model_name) # MODself.update_storage_models()vae_model = vae_model if vae_model != "None" else Nonemodel_type = get_model_type(model_name)dtype_model = torch.bfloat16 if model_type == "FLUX" else torch.float1645 unmodified linesvae_model=vae_model,type_model_precision=dtype_model,retain_task_model_in_cache=False,controlnet_model=controlnet_model,device="cpu",env_components=components,)self.model.advanced_params(image_preprocessor_cuda_active=True)else:if self.model.base_model_id != model_name:load_now_time = datetime.now()elapsed_time = max((load_now_time - self.last_load).total_seconds(), 0)if elapsed_time <= 9:print("Waiting for the previous model's time ops...")time.sleep(9 - elapsed_time)self.model.device = torch.device("cpu")self.model.load_pipe(2 unmodified linesvae_model=vae_model,type_model_precision=dtype_model,retain_task_model_in_cache=False,controlnet_model=controlnet_model,)end_time = time.time()30 unmodified lineslora_scale4,lora5,lora_scale5,lora6,lora_scale6,lora7,lora_scale7,sampler,schedule_type,schedule_prediction_type,14 unmodified lineshigh_threshold,value_threshold,distance_threshold,recolor_gamma_correction,tile_blur_sigma,controlnet_output_scaling_in_unet,controlnet_start_threshold,controlnet_stop_threshold,10 unmodified lineshires_negative_prompt,hires_before_adetailer,hires_after_adetailer,hires_schedule_type,hires_guidance_scale,controlnet_model,loop_generation,leave_progress_bar,disable_progress_bar,35 unmodified linesmask_blur_b,mask_padding_b,retain_task_cache_gui,guidance_rescale,image_ip1,mask_ip1,model_ip1,10 unmodified linesyield info_state, gr.update(), gr.update()vae_model = vae_model if vae_model != "None" else Noneloras_list = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]vae_msg = f"VAE: {vae_model}" if vae_model else ""msg_lora = ""1 unmodified lineloras_list = [s if s else "None" for s in loras_list]global lora_model_listlora_model_list = get_lora_model_list()lora1, lora_scale1, lora2, lora_scale2, lora3, lora_scale3, lora4, lora_scale4, lora5, lora_scale5, lora6, lora_scale6, lora7, lora_scale7 = \set_prompt_loras(prompt, syntax_weights, model_name, lora1, lora_scale1, lora2, lora_scale2, lora3,lora_scale3, lora4, lora_scale4, lora5, lora_scale5, lora6, lora_scale6, lora7, lora_scale7)## END MODprint("Config model:", model_name, vae_model, loras_list)95 unmodified lines"high_threshold": high_threshold,"value_threshold": value_threshold,"distance_threshold": distance_threshold,"recolor_gamma_correction": float(recolor_gamma_correction),"tile_blur_sigma": int(tile_blur_sigma),"lora_A": lora1 if lora1 != "None" else None,"lora_scale_A": lora_scale1,"lora_B": lora2 if lora2 != "None" else None,4 unmodified lines"lora_scale_D": lora_scale4,"lora_E": lora5 if lora5 != "None" else None,"lora_scale_E": lora_scale5,"lora_F": lora6 if lora6 != "None" else None,"lora_scale_F": lora_scale6,"lora_G": lora7 if lora7 != "None" else None,"lora_scale_G": lora_scale7,## BEGIN MOD"textual_inversion": get_embed_list(self.model.class_name) if textual_inversion else [],## END MOD37 unmodified lines"hires_sampler": hires_sampler,"hires_before_adetailer": hires_before_adetailer,"hires_after_adetailer": hires_after_adetailer,"hires_schedule_type": hires_schedule_type,"hires_guidance_scale": hires_guidance_scale,"ip_adapter_image": params_ip_img,"ip_adapter_mask": params_ip_msk,"ip_adapter_model": params_ip_model,1 unmodified line"ip_adapter_scale": params_ip_scale,}# kwargs for diffusers pipelineif guidance_rescale:pipe_params["guidance_rescale"] = guidance_rescaleself.model.device = torch.device("cuda:0")if hasattr(self.model.pipe, "transformer") and loras_list != ["None"] * self.model.num_loras:self.model.pipe.transformer.to(self.model.device)print("transformer to cuda")21 unmodified linesif msg_lora:info_images += msg_lorainfo_images = info_images + "<br>" + "GENERATION DATA:<br>" + escape_html(metadata[-1]) + "<br>-------<br>"download_links = "<br>".join([28 unmodified linesdef sd_gen_generate_pipeline(*args):gpu_duration_arg = int(args[-1]) if args[-1] else 59verbose_arg = int(args[-2])load_lora_cpu = args[-3]generation_args = args[:-3]lora_list = [None if item == "None" or item == "" else item # MODfor item in [args[7], args[9], args[11], args[13], args[15], args[17], args[19]]]lora_status = [None] * sd_gen.model.num_lorasmsg_load_lora = "Updating LoRAs in GPU..."if load_lora_cpu:msg_load_lora = "Updating LoRAs in CPU..."if lora_list != sd_gen.model.lora_memory and lora_list != [None] * sd_gen.model.num_loras:yield msg_load_lora, gr.update(), gr.update()# Load lora in CPUif load_lora_cpu:lora_status = sd_gen.model.load_lora_on_the_fly(lora_A=lora_list[0], lora_scale_A=args[8],lora_B=lora_list[1], lora_scale_B=args[10],lora_C=lora_list[2], lora_scale_C=args[12],lora_D=lora_list[3], lora_scale_D=args[14],lora_E=lora_list[4], lora_scale_E=args[16],lora_F=lora_list[5], lora_scale_F=args[18],lora_G=lora_list[6], lora_scale_G=args[20],)print(lora_status)sampler_name = args[21]schedule_type_name = args[22]_, _, msg_sampler = check_scheduler_compatibility(sd_gen.model.class_name, sampler_name, schedule_type_name)7 unmodified lineselif status is not None:gr.Warning(f"Failed to load LoRA: {lora}")if lora_status == [None] * sd_gen.model.num_loras and sd_gen.model.lora_memory != [None] * sd_gen.model.num_loras and load_lora_cpu:lora_cache_msg = ", ".join(str(x) for x in sd_gen.model.lora_memory if x is not None)50 unmodified linesreturn image_path# https://huggingface.co/spaces/BestWishYsh/ConsisID-preview-Space/discussions/1#674969a022b99c122af5d407dynamic_gpu_duration.zerogpu = Truesd_gen_generate_pipeline.zerogpu = Truesd_gen = GuiSD()19 unmodified lineswith gr.Column():with gr.Tab("Generation"):with gr.Row():with gr.Column(scale=1):def update_task_options(model_name, task_name):new_choices = MODEL_TYPE_TASK[get_model_type(model_name)]34 unmodified linesgenerate_from_image_btn_gui = gr.Button(value="GENERATE TAGS FROM IMAGE")prompt_gui = gr.Textbox(lines=6, placeholder="1girl, solo, ...", label="Prompt", show_copy_button=True)with gr.Accordion("Negative prompt, etc.", open=False) as menu_negative:neg_prompt_gui = gr.Textbox(lines=3, placeholder="Enter Neg prompt", label="Negative prompt", value="lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, worst quality, low quality, very displeasing, (bad)", show_copy_button=True)translate_prompt_button = gr.Button(value="Translate prompt to English", size="sm", variant="secondary")with gr.Row():insert_prompt_gui = gr.Radio(label="Insert reccomended positive / negative prompt", choices=["None", "Auto", "Animagine", "Pony"], value="Auto", interactive=True)31 unmodified lineslabel="Generated images",show_label=False,elem_id="gallery",#columns=[2],columns=[1],#rows=[2],rows=[1],object_fit="contain",# height="auto",interactive=False,#preview=False,preview=False,show_share_button=False,show_download_button=True,16 unmodified linesgpu_duration_gui = gr.Number(minimum=5, maximum=240, value=59, show_label=False, container=False, info="GPU time duration (seconds)")with gr.Column():verbose_info_gui = gr.Checkbox(value=False, container=False, label="Status info")load_lora_cpu_gui = gr.Checkbox(value=False, container=False, label="Load LoRAs on CPU")with gr.Column(scale=1):with gr.Accordion("Generation settings", open=False, visible=True) as menu_gen:2 unmodified linesimg_height_gui = gr.Slider(minimum=64, maximum=4096, step=8, value=1024, label="Img Height")steps_gui = gr.Slider(minimum=1, maximum=100, step=1, value=28, label="Steps")cfg_gui = gr.Slider(minimum=0, maximum=30, step=0.5, value=7.0, label="CFG")guidance_rescale_gui = gr.Slider(label="CFG rescale:", value=0., step=0.01, minimum=0., maximum=1.5)with gr.Row():seed_gui = gr.Number(minimum=-1, maximum=2**32-1, value=-1, label="Seed")pag_scale_gui = gr.Slider(minimum=0.0, maximum=10.0, step=0.1, value=0.0, label="PAG Scale")3 unmodified lineswith gr.Row():sampler_gui = gr.Dropdown(label="Sampler", choices=scheduler_names, value="Euler")schedule_type_gui = gr.Dropdown(label="Schedule type", choices=SCHEDULE_TYPE_OPTIONS, value=SCHEDULE_TYPE_OPTIONS[0])schedule_prediction_type_gui = gr.Dropdown(label="Discrete Sampling Type", choices=SCHEDULE_PREDICTION_TYPE_OPTIONS, value=SCHEDULE_PREDICTION_TYPE_OPTIONS[0])vae_model_gui = gr.Dropdown(label="VAE Model", choices=vae_model_list, value=vae_model_list[0])prompt_syntax_gui = gr.Dropdown(label="Prompt Syntax", choices=PROMPT_W_OPTIONS, value=PROMPT_W_OPTIONS[1][1])with gr.Row(equal_height=False):def run_set_params_gui(base_prompt, name_model):valid_receptors = { # default values"prompt": gr.update(value=base_prompt),"neg_prompt": gr.update(value=""),"Steps": gr.update(value=30),"width": gr.update(value=1024),"height": gr.update(value=1024),"Seed": gr.update(value=-1),"Sampler": gr.update(value="Euler"),"CFG scale": gr.update(value=7.), # cfg"Clip skip": gr.update(value=True),"Model": gr.update(value=name_model),"Schedule type": gr.update(value="Automatic"),"PAG": gr.update(value=.0),"FreeU": gr.update(value=False),}valid_keys = list(valid_receptors.keys())parameters = extract_parameters(base_prompt)# print(parameters)if "Sampler" in parameters:value_sampler = parameters["Sampler"]for s_type in SCHEDULE_TYPE_OPTIONS:if s_type in value_sampler:value_sampler = value_sampler.replace(s_type, "").strip()parameters["Sampler"] = value_samplerparameters["Schedule type"] = s_typefor key, val in parameters.items():# print(val)if key in valid_keys:try:if key == "Sampler":if val not in scheduler_names:continueif key == "Schedule type":if val not in SCHEDULE_TYPE_OPTIONS:val = "Automatic"elif key == "Clip skip":if "," in str(val):val = val.replace(",", "")if int(val) >= 2:val = Trueif key == "prompt":if ">" in val and "<" in val:val = re.sub(r'<[^>]+>', '', val)print("Removed LoRA written in the prompt")if key in ["prompt", "neg_prompt"]:val = re.sub(r'\s+', ' ', re.sub(r',+', ',', val)).strip()if key in ["Steps", "width", "height", "Seed"]:val = int(val)if key == "FreeU":val = Trueif key in ["CFG scale", "PAG"]:val = float(val)if key == "Model":filtered_models = [m for m in model_list if val in m]if filtered_models:val = filtered_models[0]else:val = name_modelif key == "Seed":continuevalid_receptors[key] = gr.update(value=val)# print(val, type(val))# print(valid_receptors)except Exception as e:print(str(e))return [value for value in valid_receptors.values()]set_params_gui.click(run_set_params_gui, [prompt_gui, model_name_gui], [prompt_gui,neg_prompt_gui,steps_gui,img_width_gui,img_height_gui,seed_gui,sampler_gui,cfg_gui,clip_skip_gui,model_name_gui,schedule_type_gui,pag_scale_gui,free_u_gui,],)def run_clear_prompt_gui():return gr.update(value=""), gr.update(value="")clear_prompt_gui.click(run_clear_prompt_gui, [], [prompt_gui, neg_prompt_gui])def run_set_random_seed():return -1set_random_seed.click(run_set_random_seed, [], seed_gui)with gr.Accordion("LoRA", open=False, visible=True) as menu_lora:def lora_dropdown(label, visible=True):return gr.Dropdown(label=label, choices=get_all_lora_tupled_list(), value="", allow_custom_value=True, elem_classes="lora", min_width=320, visible=visible)def lora_scale_slider(label, visible=True):return gr.Slider(minimum=-2, maximum=2, step=0.01, value=1.00, label=label, visible=visible)def lora_textbox(label):return gr.Textbox(label=label, info="Example of prompt:", value="None", show_copy_button=True, interactive=False, visible=False)39 unmodified lineslora5_info_gui = lora_textbox("LoRA5 prompts")lora5_copy_gui = gr.Button(value="Copy example to prompt", visible=False)lora5_desc_gui = gr.Markdown(value="", visible=False)with gr.Column():lora6_gui = lora_dropdown("LoRA6", visible=False)lora_scale_6_gui = lora_scale_slider("LoRA Scale 6", visible=False)with gr.Row():with gr.Group():lora6_info_gui = lora_textbox("LoRA6 prompts")lora6_copy_gui = gr.Button(value="Copy example to prompt", visible=False)lora6_desc_gui = gr.Markdown(value="", visible=False)with gr.Column():lora7_gui = lora_dropdown("LoRA7", visible=False)lora_scale_7_gui = lora_scale_slider("LoRA Scale 7", visible=False)with gr.Row():with gr.Group():lora7_info_gui = lora_textbox("LoRA7 prompts")lora7_copy_gui = gr.Button(value="Copy example to prompt", visible=False)lora7_desc_gui = gr.Markdown(value="", visible=False)with gr.Accordion("From URL", open=True, visible=True):with gr.Row():search_civitai_basemodel_lora = gr.CheckboxGroup(label="Search LoRA for", choices=CIVITAI_BASEMODEL, value=["Pony", "Illustrious", "SDXL 1.0"])10 unmodified linessearch_civitai_result_lora = gr.Dropdown(label="Search Results", choices=[("", "")], value="", allow_custom_value=True, visible=False)with gr.Row():text_lora = gr.Textbox(label="LoRA's download URL", placeholder="https://civitai.com/api/download/models/28907", info="It has to be .safetensors files, and you can also download them from Hugging Face.", lines=1, scale=4)romanize_text = gr.Checkbox(value=False, label="Transliterate name", scale=1, visible=False)button_lora = gr.Button("Get and Refresh the LoRA Lists")new_lora_status = gr.HTML()with gr.Accordion("From Local", open=True, visible=True):11 unmodified lineshires_steps_gui = gr.Slider(minimum=0, value=30, maximum=100, step=1, label="Hires Steps")hires_denoising_strength_gui = gr.Slider(minimum=0.1, maximum=1.0, step=0.01, value=0.55, label="Hires Denoising Strength")hires_sampler_gui = gr.Dropdown(label="Hires Sampler", choices=POST_PROCESSING_SAMPLER, value=POST_PROCESSING_SAMPLER[0])hires_schedule_list = ["Use same schedule type"] + SCHEDULE_TYPE_OPTIONShires_schedule_type_gui = gr.Dropdown(label="Hires Schedule type", choices=hires_schedule_list, value=hires_schedule_list[0])hires_guidance_scale_gui = gr.Slider(minimum=-1., maximum=30., step=0.5, value=-1., label="Hires CFG", info="If the value is -1, the main CFG will be used")hires_prompt_gui = gr.Textbox(label="Hires Prompt", placeholder="Main prompt will be use", lines=3)hires_negative_prompt_gui = gr.Textbox(label="Hires Negative Prompt", placeholder="Main negative prompt will be use", lines=3)60 unmodified linesminimum=64, maximum=2048, step=64, value=1024, label="Image Resolution",info="The maximum proportional size of the generated image based on the uploaded image.")with gr.Row():controlnet_model_gui = gr.Dropdown(label="ControlNet model", choices=DIFFUSERS_CONTROLNET_MODEL, value=DIFFUSERS_CONTROLNET_MODEL[0])control_net_output_scaling_gui = gr.Slider(minimum=0, maximum=5.0, step=0.1, value=1, label="ControlNet Output Scaling in UNet")control_net_start_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=0, label="ControlNet Start Threshold (%)")control_net_stop_threshold_gui = gr.Slider(minimum=0, maximum=1, step=0.01, value=1, label="ControlNet Stop Threshold (%)")with gr.Row():preprocessor_name_gui = gr.Dropdown(label="Preprocessor Name", choices=TASK_AND_PREPROCESSORS["canny"])preprocess_resolution_gui = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocessor Resolution")low_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="'CANNY' low threshold")high_threshold_gui = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="'CANNY' high threshold")def change_preprocessor_choices(task):task = TASK_STABLEPY[task]if task in TASK_AND_PREPROCESSORS.keys():choices_task = TASK_AND_PREPROCESSORS[task]else:choices_task = TASK_AND_PREPROCESSORS["canny"]return gr.update(choices=choices_task, value=choices_task[0])task_gui.change(1 unmodified line[task_gui],[preprocessor_name_gui],)with gr.Row():value_threshold_gui = gr.Slider(minimum=1, maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold")distance_threshold_gui = gr.Slider(minimum=1, maximum=20.0, step=0.01, value=0.1, label="'MLSD' Hough distance threshold")recolor_gamma_correction_gui = gr.Number(minimum=0., maximum=25., value=1., step=0.001, label="'RECOLOR' gamma correction")tile_blur_sigma_gui = gr.Number(minimum=0, maximum=100, value=9, step=1, label="'TILE' blur sigma")with gr.Accordion("IP-Adapter", open=False, visible=True) as menu_ipa:52 unmodified linesstyle_button.click(load_json_style_file, [style_json_gui], [style_prompt_gui])with gr.Accordion("Other settings", open=False, visible=True) as menu_other:with gr.Row():save_generated_images_gui = gr.Checkbox(value=False, label="Save Generated Images")filename_pattern_gui = gr.Textbox(label="Filename pattern", value="model,seed", placeholder="model,seed,sampler,schedule_type,img_width,img_height,guidance_scale,num_steps,vae,prompt_section,neg_prompt_section", lines=1)78 unmodified lines# enable crop (or disable it)# transforms=["crop"],brush=gr.Brush(default_size="16", # or leave it as 'auto'color_mode="fixed", # 'fixed' hides the user swatches and colorpicker, 'defaults' shows it# default_color="black", # html names are supportedcolors=["rgba(0, 0, 0, 1)", # rgb(a)"rgba(0, 0, 0, 0.1)","rgba(255, 255, 255, 0.1)",# "hsl(360, 120, 120)" # in fact any valid colorstring]),eraser=gr.Eraser(default_size="16"))41 unmodified linesoutputs=[result_up_tab],)with gr.Tab("Preprocessor", render=True):preprocessor_tab()## BEGIN MODinterface_mode_gui.change(change_interface_mode,28 unmodified linesgr.on(triggers=[lora1_gui.change, lora_scale_1_gui.change, lora2_gui.change, lora_scale_2_gui.change,lora3_gui.change, lora_scale_3_gui.change, lora4_gui.change, lora_scale_4_gui.change,lora5_gui.change, lora_scale_5_gui.change, lora6_gui.change, lora_scale_6_gui.change,lora7_gui.change, lora_scale_7_gui.change, prompt_syntax_gui.change],fn=update_loras,inputs=[prompt_gui, prompt_syntax_gui, lora1_gui, lora_scale_1_gui, lora2_gui, lora_scale_2_gui,lora3_gui, lora_scale_3_gui, lora4_gui, lora_scale_4_gui, lora5_gui, lora_scale_5_gui,lora6_gui, lora_scale_6_gui, lora7_gui, lora_scale_7_gui],outputs=[prompt_gui, lora1_gui, lora_scale_1_gui, lora1_info_gui, lora1_copy_gui, lora1_desc_gui,lora2_gui, lora_scale_2_gui, lora2_info_gui, lora2_copy_gui, lora2_desc_gui,lora3_gui, lora_scale_3_gui, lora3_info_gui, lora3_copy_gui, lora3_desc_gui,lora4_gui, lora_scale_4_gui, lora4_info_gui, lora4_copy_gui, lora4_desc_gui,lora5_gui, lora_scale_5_gui, lora5_info_gui, lora5_copy_gui, lora5_desc_gui,lora6_gui, lora_scale_6_gui, lora6_info_gui, lora6_copy_gui, lora6_desc_gui,lora7_gui, lora_scale_7_gui, lora7_info_gui, lora7_copy_gui, lora7_desc_gui],queue=False,trigger_mode="once",)2 unmodified lineslora3_copy_gui.click(apply_lora_prompt, [prompt_gui, lora3_info_gui], [prompt_gui], queue=False)lora4_copy_gui.click(apply_lora_prompt, [prompt_gui, lora4_info_gui], [prompt_gui], queue=False)lora5_copy_gui.click(apply_lora_prompt, [prompt_gui, lora5_info_gui], [prompt_gui], queue=False)lora6_copy_gui.click(apply_lora_prompt, [prompt_gui, lora6_info_gui], [prompt_gui], queue=False)lora7_copy_gui.click(apply_lora_prompt, [prompt_gui, lora7_info_gui], [prompt_gui], queue=False)gr.on(triggers=[search_civitai_button_lora.click, search_civitai_query_lora.submit],fn=search_civitai_lora,5 unmodified lines)search_civitai_result_lora.change(select_civitai_lora, [search_civitai_result_lora], [text_lora, search_civitai_desc_lora], queue=False, scroll_to_output=True)search_civitai_gallery_lora.select(update_civitai_selection, None, [search_civitai_result_lora], queue=False, show_api=False)button_lora.click(get_my_lora, [text_lora, romanize_text], [lora1_gui, lora2_gui, lora3_gui, lora4_gui, lora5_gui, lora6_gui, lora7_gui, new_lora_status], scroll_to_output=True)upload_button_lora.upload(upload_file_lora, [upload_button_lora], [file_output_lora, upload_button_lora]).success(move_file_lora, [file_output_lora], [lora1_gui, lora2_gui, lora3_gui, lora4_gui, lora5_gui, lora6_gui, lora7_gui], scroll_to_output=True)use_textual_inversion_gui.change(set_textual_inversion_prompt, [use_textual_inversion_gui, prompt_gui, neg_prompt_gui, prompt_syntax_gui], [prompt_gui, neg_prompt_gui])38 unmodified linesinputs=[model_name_gui,vae_model_gui,task_gui,controlnet_model_gui,],outputs=[load_model_gui],queue=True,18 unmodified lineslora_scale_4_gui,lora5_gui,lora_scale_5_gui,lora6_gui,lora_scale_6_gui,lora7_gui,lora_scale_7_gui,sampler_gui,schedule_type_gui,schedule_prediction_type_gui,14 unmodified lineshigh_threshold_gui,value_threshold_gui,distance_threshold_gui,recolor_gamma_correction_gui,tile_blur_sigma_gui,control_net_output_scaling_gui,control_net_start_threshold_gui,control_net_stop_threshold_gui,10 unmodified lineshires_negative_prompt_gui,hires_before_adetailer_gui,hires_after_adetailer_gui,hires_schedule_type_gui,hires_guidance_scale_gui,controlnet_model_gui,loop_generation_gui,leave_progress_bar_gui,disable_progress_bar_gui,35 unmodified linesmask_blur_b_gui,mask_padding_b_gui,retain_task_cache_gui,guidance_rescale_gui,image_ip1,mask_ip1,model_ip1,
16 unmodified lines171819202122237 unmodified lines3132333435363 unmodified lines4041424344454647487 unmodified lines56575859606120 unmodified lines82838485868788899023 unmodified lines11411511611711811912021 unmodified lines1421431441451461471486 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223350 unmodified lines28428528628728828929029129229329476 unmodified lines3713723733743753763776 unmodified lines38438538638738838939017 unmodified lines40840941041141241341476 unmodified lines49149249349449549649716 unmodified linesLOAD_DIFFUSERS_FORMAT_MODEL = ['stabilityai/stable-diffusion-xl-base-1.0','Laxhar/noobai-XL-1.0','black-forest-labs/FLUX.1-dev','John6666/blue-pencil-flux1-v021-fp8-flux','John6666/wai-ani-flux-v10forfp8-fp8-flux',7 unmodified lines'terminusresearch/FluxBooru-v0.3','ostris/OpenFLUX.1','shuttleai/shuttle-3-diffusion','John6666/noobai-xl-nai-xl-epsilonpred10version-sdxl','Laxhar/noobai-XL-0.77','John6666/noobai-xl-nai-xl-epsilonpred075version-sdxl',3 unmodified lines'John6666/noobaiiter-xl-vpred-v075-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-v40-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-ntrmix35-sdxl','John6666/haruki-mix-illustrious-v10-sdxl','John6666/noobreal-v10-sdxl','John6666/complicated-noobai-merge-vprediction-sdxl','Laxhar/noobai-XL-Vpred-0.6','John6666/noobai-xl-nai-xl-vpred05version-sdxl','John6666/noobai-fusion2-vpred-itercomp-v1-sdxl',7 unmodified lines'John6666/wai-nsfw-illustrious-v70-sdxl','John6666/illustrious-pony-mix-v3-sdxl','John6666/nova-anime-xl-illustriousv10-sdxl','John6666/silvermoon-mix03-illustrious-v10-sdxl','eienmojiki/Anything-XL','eienmojiki/Starry-XL-v5.2',20 unmodified lines'John6666/prefect-pony-xl-v4-sdxl','John6666/mala-anime-mix-nsfw-pony-xl-v5-sdxl','John6666/wai-ani-nsfw-ponyxl-v10-sdxl','John6666/wai-ani-nsfw-ponyxl-v9-sdxl','John6666/wai-real-mix-v11-sdxl','John6666/babes-by-stable-yogi-ponyv3-sdxl','John6666/wai-c-v6-sdxl','John6666/iniverse-mix-xl-sfwnsfw-pony-guofeng-v43-sdxl','John6666/sifw-annihilation-xl-v2-sdxl',23 unmodified lines'digiplay/DarkSushi2.5D_v1','digiplay/darkphoenix3D_v1.1','digiplay/BeenYouLiteL11_diffusers','Yntec/RevAnimatedV2Rebirth','youknownothing/cyberrealistic_v50','youknownothing/deliberate-v6','GraydientPlatformAPI/deliberate-cyber3',21 unmodified lines'https://huggingface.co/datasets/Nerfgun3/bad_prompt/blob/main/bad_prompt_version2.pt',# 'https://huggingface.co/embed/negative/resolve/main/EasyNegativeV2.safetensors',# 'https://huggingface.co/embed/negative/resolve/main/bad-hands-5.pt',]CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")HF_TOKEN = os.environ.get("HF_READ_TOKEN")6 unmodified linesCACHE_HF = "/home/user/.cache/huggingface/hub/"STORAGE_ROOT = "/home/user/"PREPROCESSOR_CONTROLNET = {"openpose": ["Openpose","None",],"scribble": ["HED","PidiNet","None",],"softedge": ["PidiNet","HED","HED safe","PidiNet safe","None",],"segmentation": ["UPerNet","None",],"depth": ["DPT","Midas","None",],"normalbae": ["NormalBae","None",],"lineart": ["Lineart","Lineart coarse","Lineart (anime)","None","None (anime)",],"lineart_anime": ["Lineart","Lineart coarse","Lineart (anime)","None","None (anime)",],"shuffle": ["ContentShuffle","None",],"canny": ["Canny","None",],"mlsd": ["MLSD","None",],"ip2p": ["ip2p"],"recolor": ["Recolor luminance","Recolor intensity","None",],"tile": ["Mild Blur","Moderate Blur","Heavy Blur","None",],}TASK_STABLEPY = {'txt2img': 'txt2img','img2img': 'img2img',50 unmodified linesUPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())PROMPT_W_OPTIONS = [("Compel format: (word)weight", "Compel"),("Classic format: (word:weight)", "Classic"),("Classic-original format: (word:weight)", "Classic-original"),("Classic-no_norm format: (word:weight)", "Classic-no_norm"),("Classic-ignore", "Classic-ignore"),("None", "None"),]76 unmodified lines1.0, # cn scale0.0, # cn start1.0, # cn end"Classic","Nearest",45,False,6 unmodified lines-1,"None",0.33,"FlowMatchEuler",1152,896,"black-forest-labs/FLUX.1-dev",17 unmodified lines-1,"None",0.33,"DPM++ 2M SDE Lu",1024,1024,"John6666/epicrealism-xl-v10kiss2-sdxl",76 unmodified lines1.0, # cn scale0.0, # cn start0.9, # cn end"Compel","Latent (antialiased)",46,False,16 unmodified lines171819202122237 unmodified lines313233343536373 unmodified lines414243444546474849505152537 unmodified lines6162636465666720 unmodified lines888990919293949523 unmodified lines11912012112212312412521 unmodified lines1471481491501511521536 unmodified lines16016116216316416550 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828976 unmodified lines3663673683693703713726 unmodified lines37938038138238338438517 unmodified lines40340440540640740840976 unmodified lines48648748848949049149216 unmodified linesLOAD_DIFFUSERS_FORMAT_MODEL = ['stabilityai/stable-diffusion-xl-base-1.0','Laxhar/noobai-XL-1.1','black-forest-labs/FLUX.1-dev','John6666/blue-pencil-flux1-v021-fp8-flux','John6666/wai-ani-flux-v10forfp8-fp8-flux',7 unmodified lines'terminusresearch/FluxBooru-v0.3','ostris/OpenFLUX.1','shuttleai/shuttle-3-diffusion','Laxhar/noobai-XL-1.0','John6666/noobai-xl-nai-xl-epsilonpred10version-sdxl','Laxhar/noobai-XL-0.77','John6666/noobai-xl-nai-xl-epsilonpred075version-sdxl',3 unmodified lines'John6666/noobaiiter-xl-vpred-v075-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-v40-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-ntrmix35-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-v777-sdxl','John6666/ntr-mix-illustrious-xl-noob-xl-v777forlora-sdxl','John6666/haruki-mix-illustrious-v10-sdxl','John6666/noobreal-v10-sdxl','John6666/complicated-noobai-merge-vprediction-sdxl','Laxhar/noobai-XL-Vpred-0.65s','Laxhar/noobai-XL-Vpred-0.65','Laxhar/noobai-XL-Vpred-0.6','John6666/noobai-xl-nai-xl-vpred05version-sdxl','John6666/noobai-fusion2-vpred-itercomp-v1-sdxl',7 unmodified lines'John6666/wai-nsfw-illustrious-v70-sdxl','John6666/illustrious-pony-mix-v3-sdxl','John6666/nova-anime-xl-illustriousv10-sdxl','John6666/nova-orange-xl-v30-sdxl','John6666/silvermoon-mix03-illustrious-v10-sdxl','eienmojiki/Anything-XL','eienmojiki/Starry-XL-v5.2',20 unmodified lines'John6666/prefect-pony-xl-v4-sdxl','John6666/mala-anime-mix-nsfw-pony-xl-v5-sdxl','John6666/wai-ani-nsfw-ponyxl-v10-sdxl','John6666/wai-real-mix-v11-sdxl','John6666/wai-shuffle-pdxl-v2-sdxl','John6666/wai-c-v6-sdxl','John6666/iniverse-mix-xl-sfwnsfw-pony-guofeng-v43-sdxl','John6666/sifw-annihilation-xl-v2-sdxl',23 unmodified lines'digiplay/DarkSushi2.5D_v1','digiplay/darkphoenix3D_v1.1','digiplay/BeenYouLiteL11_diffusers','GraydientPlatformAPI/rev-animated2','youknownothing/cyberrealistic_v50','youknownothing/deliberate-v6','GraydientPlatformAPI/deliberate-cyber3',21 unmodified lines'https://huggingface.co/datasets/Nerfgun3/bad_prompt/blob/main/bad_prompt_version2.pt',# 'https://huggingface.co/embed/negative/resolve/main/EasyNegativeV2.safetensors',# 'https://huggingface.co/embed/negative/resolve/main/bad-hands-5.pt',]CIVITAI_API_KEY = os.environ.get("CIVITAI_API_KEY")HF_TOKEN = os.environ.get("HF_READ_TOKEN")6 unmodified linesCACHE_HF = "/home/user/.cache/huggingface/hub/"STORAGE_ROOT = "/home/user/"TASK_STABLEPY = {'txt2img': 'txt2img','img2img': 'img2img',50 unmodified linesUPSCALER_KEYS = list(UPSCALER_DICT_GUI.keys())DIFFUSERS_CONTROLNET_MODEL = ["Automatic","xinsir/controlnet-union-sdxl-1.0","xinsir/anime-painter","Eugeoter/noob-sdxl-controlnet-canny","Eugeoter/noob-sdxl-controlnet-lineart_anime","Eugeoter/noob-sdxl-controlnet-depth","Eugeoter/noob-sdxl-controlnet-normal","Eugeoter/noob-sdxl-controlnet-softedge_hed","Eugeoter/noob-sdxl-controlnet-scribble_pidinet","Eugeoter/noob-sdxl-controlnet-scribble_hed","Eugeoter/noob-sdxl-controlnet-manga_line","Eugeoter/noob-sdxl-controlnet-lineart_realistic","Eugeoter/noob-sdxl-controlnet-depth_midas-v1-1","dimitribarbot/controlnet-openpose-sdxl-1.0-safetensors","r3gm/controlnet-openpose-sdxl-1.0-fp16","r3gm/controlnet-canny-scribble-integrated-sdxl-v2-fp16","r3gm/controlnet-union-sdxl-1.0-fp16","r3gm/controlnet-lineart-anime-sdxl-fp16","r3gm/control_v1p_sdxl_qrcode_monster_fp16","r3gm/controlnet-tile-sdxl-1.0-fp16","r3gm/controlnet-recolor-sdxl-fp16","r3gm/controlnet-openpose-twins-sdxl-1.0-fp16","r3gm/controlnet-qr-pattern-sdxl-fp16","brad-twinkl/controlnet-union-sdxl-1.0-promax","Yakonrus/SDXL_Controlnet_Tile_Realistic_v2","TheMistoAI/MistoLine","briaai/BRIA-2.3-ControlNet-Recoloring","briaai/BRIA-2.3-ControlNet-Canny","lllyasviel/control_v11p_sd15_openpose","lllyasviel/control_v11p_sd15_canny","lllyasviel/control_v11p_sd15_mlsd","lllyasviel/control_v11p_sd15_scribble","lllyasviel/control_v11p_sd15_softedge","lllyasviel/control_v11p_sd15_seg","lllyasviel/control_v11f1p_sd15_depth","lllyasviel/control_v11p_sd15_normalbae","lllyasviel/control_v11p_sd15_lineart","lllyasviel/control_v11p_sd15s2_lineart_anime","lllyasviel/control_v11e_sd15_shuffle","lllyasviel/control_v11e_sd15_ip2p","lllyasviel/control_v11p_sd15_inpaint","monster-labs/control_v1p_sd15_qrcode_monster","lllyasviel/control_v11f1e_sd15_tile","latentcat/control_v1p_sd15_brightness","yuanqiuye/qrcode_controlnet_v3","Shakker-Labs/FLUX.1-dev-ControlNet-Union-Pro",# "Shakker-Labs/FLUX.1-dev-ControlNet-Pose",# "Shakker-Labs/FLUX.1-dev-ControlNet-Depth",# "jasperai/Flux.1-dev-Controlnet-Upscaler",# "jasperai/Flux.1-dev-Controlnet-Depth",# "jasperai/Flux.1-dev-Controlnet-Surface-Normals",# "XLabs-AI/flux-controlnet-canny-diffusers",# "XLabs-AI/flux-controlnet-hed-diffusers",# "XLabs-AI/flux-controlnet-depth-diffusers",# "InstantX/FLUX.1-dev-Controlnet-Union",# "InstantX/FLUX.1-dev-Controlnet-Canny",]PROMPT_W_OPTIONS = [("Compel format: (word)weight", "Compel"),("Classic format: (word:weight)", "Classic"),("Classic-original format: (word:weight)", "Classic-original"),("Classic-no_norm format: (word:weight)", "Classic-no_norm"),("Classic-sd_embed format: (word:weight)", "Classic-sd_embed"),("Classic-ignore", "Classic-ignore"),("None", "None"),]76 unmodified lines1.0, # cn scale0.0, # cn start1.0, # cn end"Classic-no_norm","Nearest",45,False,6 unmodified lines-1,"None",0.33,"FlowMatch Euler",1152,896,"black-forest-labs/FLUX.1-dev",17 unmodified lines-1,"None",0.33,"DPM++ 2M SDE Ef",1024,1024,"John6666/epicrealism-xl-v10kiss2-sdxl",76 unmodified lines1.0, # cn scale0.0, # cn start0.9, # cn end"Classic-original","Latent (antialiased)",46,False,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import spacesimport gradio as grfrom stablepy import Preprocessor
PREPROCESSOR_TASKS_LIST = [ "Canny", "Openpose", "DPT", "Midas", "ZoeDepth", "DepthAnything", "HED", "PidiNet", "TEED", "Lineart", "LineartAnime", "Anyline", "Lineart standard", "SegFormer", "UPerNet", "ContentShuffle", "Recolor", "Blur", "MLSD", "NormalBae",]
preprocessor = Preprocessor()
def process_inputs( image, name, resolution, precessor_resolution, low_threshold, high_threshold, value_threshod, distance_threshold, recolor_mode, recolor_gamma_correction, blur_k_size, pre_openpose_extra, hed_scribble, pre_pidinet_safe, pre_lineart_coarse, use_cuda,): if not image: raise ValueError("To use this, simply upload an image.")
preprocessor.load(name, False)
params = dict( image_resolution=resolution, detect_resolution=precessor_resolution, low_threshold=low_threshold, high_threshold=high_threshold, thr_v=value_threshod, thr_d=distance_threshold, mode=recolor_mode, gamma_correction=recolor_gamma_correction, blur_sigma=blur_k_size, hand_and_face=pre_openpose_extra, scribble=hed_scribble, safe=pre_pidinet_safe, coarse=pre_lineart_coarse, )
if use_cuda: @spaces.GPU(duration=15) def wrapped_func(): preprocessor.to("cuda") return preprocessor(image, **params) return wrapped_func()
return preprocessor(image, **params)
def preprocessor_tab(): with gr.Row(): with gr.Column(): pre_image = gr.Image(label="Image", type="pil", sources=["upload"]) pre_options = gr.Dropdown(label="Preprocessor", choices=PREPROCESSOR_TASKS_LIST, value=PREPROCESSOR_TASKS_LIST[0]) pre_img_resolution = gr.Slider( minimum=64, maximum=4096, step=64, value=1024, label="Image Resolution", info="The maximum proportional size of the generated image based on the uploaded image." ) pre_start = gr.Button(value="PROCESS IMAGE", variant="primary") with gr.Accordion("Advanced Settings", open=False): with gr.Column(): pre_processor_resolution = gr.Slider(minimum=64, maximum=2048, step=64, value=512, label="Preprocessor Resolution") pre_low_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=100, label="'CANNY' low threshold") pre_high_threshold = gr.Slider(minimum=1, maximum=255, step=1, value=200, label="'CANNY' high threshold") pre_value_threshold = gr.Slider(minimum=1, maximum=2.0, step=0.01, value=0.1, label="'MLSD' Hough value threshold") pre_distance_threshold = gr.Slider(minimum=1, maximum=20.0, step=0.01, value=0.1, label="'MLSD' Hough distance threshold") pre_recolor_mode = gr.Dropdown(label="'RECOLOR' mode", choices=["luminance", "intensity"], value="luminance") pre_recolor_gamma_correction = gr.Number(minimum=0., maximum=25., value=1., step=0.001, label="'RECOLOR' gamma correction") pre_blur_k_size = gr.Number(minimum=0, maximum=100, value=9, step=1, label="'BLUR' sigma") pre_openpose_extra = gr.Checkbox(value=True, label="'OPENPOSE' face and hand") pre_hed_scribble = gr.Checkbox(value=False, label="'HED' scribble") pre_pidinet_safe = gr.Checkbox(value=False, label="'PIDINET' safe") pre_lineart_coarse = gr.Checkbox(value=False, label="'LINEART' coarse") pre_use_cuda = gr.Checkbox(value=False, label="Use CUDA")
with gr.Column(): pre_result = gr.Image(label="Result", type="pil", interactive=False, format="png")
pre_start.click( fn=process_inputs, inputs=[ pre_image, pre_options, pre_img_resolution, pre_processor_resolution, pre_low_threshold, pre_high_threshold, pre_value_threshold, pre_distance_threshold, pre_recolor_mode, pre_recolor_gamma_correction, pre_blur_k_size, pre_openpose_extra, pre_hed_scribble, pre_pidinet_safe, pre_lineart_coarse, pre_use_cuda, ], outputs=[pre_result], )301 unmodified lines302303304305306307258 unmodified lines56656756856957057157211 unmodified lines58458558658758858959059159259359459594 unmodified lines6906916926936946956966 unmodified lines70370470570670770870971071133 unmodified lines74574674774874975075175275375475575675775875976076176276376476576676776876910 unmodified lines78078178278378478578678778878979079179279379479579679779879980080180280380480580680780880954 unmodified lines86486586686786886987087187287387487587618 unmodified lines8958968978988999006 unmodified lines90790890991091191291312 unmodified lines92692792892993093193210 unmodified lines94394494594694794826 unmodified lines97597697797897998098198298398498598638 unmodified lines102510261027102810291030301 unmodified linesreturn outputdef save_images(images: list[Image.Image], metadatas: list[str]):from PIL import PngImagePluginimport uuid258 unmodified linesdef get_civitai_info(path):global civitai_not_exists_listif path in set(civitai_not_exists_list): return ["", "", "", "", ""]if not Path(path).exists(): return Noneuser_agent = get_user_agent()headers = {'User-Agent': user_agent, 'content-type': 'application/json'}11 unmodified linesr = session.get(url, params=params, headers=headers, stream=True, timeout=(3.0, 15))except Exception as e:print(e)return ["", "", "", "", ""]if not r.ok: return Nonejson = r.json()if not 'baseModel' in json:civitai_not_exists_list.append(path)return ["", "", "", "", ""]items = []items.append(" / ".join(json['trainedWords']))items.append(json['baseModel'])94 unmodified linesreturn Nonedef download_my_lora(dl_urls: str, lora1: str, lora2: str, lora3: str, lora4: str, lora5: str):path = download_lora(dl_urls)if path:if not lora1 or lora1 == "None":6 unmodified lineslora4 = pathelif not lora5 or lora5 == "None":lora5 = pathchoices = get_all_lora_tupled_list()return gr.update(value=lora1, choices=choices), gr.update(value=lora2, choices=choices), gr.update(value=lora3, choices=choices),\gr.update(value=lora4, choices=choices), gr.update(value=lora5, choices=choices)def get_valid_lora_name(query: str, model_name: str):33 unmodified linesreturn wtdef set_prompt_loras(prompt, prompt_syntax, model_name, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt):if not "Classic" in str(prompt_syntax): return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wtlora1 = get_valid_lora_name(lora1, model_name)lora2 = get_valid_lora_name(lora2, model_name)lora3 = get_valid_lora_name(lora3, model_name)lora4 = get_valid_lora_name(lora4, model_name)lora5 = get_valid_lora_name(lora5, model_name)if not "<lora" in prompt: return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wtlora1_wt = get_valid_lora_wt(prompt, lora1, lora1_wt)lora2_wt = get_valid_lora_wt(prompt, lora2, lora2_wt)lora3_wt = get_valid_lora_wt(prompt, lora3, lora3_wt)lora4_wt = get_valid_lora_wt(prompt, lora4, lora4_wt)lora5_wt = get_valid_lora_wt(prompt, lora5, lora5_wt)on1, label1, tag1, md1 = get_lora_info(lora1)on2, label2, tag2, md2 = get_lora_info(lora2)on3, label3, tag3, md3 = get_lora_info(lora3)on4, label4, tag4, md4 = get_lora_info(lora4)on5, label5, tag5, md5 = get_lora_info(lora5)lora_paths = [lora1, lora2, lora3, lora4, lora5]prompts = prompt.split(",") if prompt else []for p in prompts:p = str(p).strip()10 unmodified linescontinueelif not on1:lora1 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5]lora1_wt = safe_float(wt)on1 = Trueelif not on2:lora2 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5]lora2_wt = safe_float(wt)on2 = Trueelif not on3:lora3 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5]lora3_wt = safe_float(wt)on3 = Trueelif not on4:lora4 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5]lora4_wt = safe_float(wt)on4 = Trueelif not on5:lora5 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5]lora5_wt = safe_float(wt)on5 = Truereturn lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wtdef get_lora_info(lora_path: str):54 unmodified linesreturn gr.update(value=prompt)def update_loras(prompt, prompt_syntax, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt):on1, label1, tag1, md1 = get_lora_info(lora1)on2, label2, tag2, md2 = get_lora_info(lora2)on3, label3, tag3, md3 = get_lora_info(lora3)on4, label4, tag4, md4 = get_lora_info(lora4)on5, label5, tag5, md5 = get_lora_info(lora5)lora_paths = [lora1, lora2, lora3, lora4, lora5]output_prompt = promptif "Classic" in str(prompt_syntax):18 unmodified linesif on3: lora_prompts.append(f"<lora:{to_lora_key(lora3)}:{lora3_wt:.2f}>")if on4: lora_prompts.append(f"<lora:{to_lora_key(lora4)}:{lora4_wt:.2f}>")if on5: lora_prompts.append(f"<lora:{to_lora_key(lora5)}:{lora5_wt:.2f}>")output_prompt = ", ".join(list_uniq(output_prompts + lora_prompts + [""]))choices = get_all_lora_tupled_list()6 unmodified linesgr.update(value=lora4, choices=choices), gr.update(value=lora4_wt),\gr.update(value=tag4, label=label4, visible=on4), gr.update(visible=on4), gr.update(value=md4, visible=on4),\gr.update(value=lora5, choices=choices), gr.update(value=lora5_wt),\gr.update(value=tag5, label=label5, visible=on5), gr.update(visible=on5), gr.update(value=md5, visible=on5)def get_my_lora(link_url, romanize):12 unmodified linespath.resolve().rename(new_path.resolve())update_lora_dict(str(new_path))l_path = str(new_path)new_lora_model_list = get_lora_model_list()new_lora_tupled_list = get_all_lora_tupled_list()msg_lora = "Downloaded"if l_name:10 unmodified lineschoices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(value=msg_lora)26 unmodified lineschoices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list)CIVITAI_SORT = ["Highest Rated", "Most Downloaded", "Newest"]CIVITAI_PERIOD = ["AllTime", "Year", "Month", "Week", "Day"]CIVITAI_BASEMODEL = ["Pony", "Illustrious", "SDXL 1.0", "SD 1.5", "Flux.1 D", "Flux.1 S"]def get_civitai_info(path):38 unmodified linessort: str = "Highest Rated", period: str = "AllTime", tag: str = "", user: str = "", page: int = 1):user_agent = get_user_agent()headers = {'User-Agent': user_agent, 'content-type': 'application/json'}base_url = 'https://civitai.com/api/v1/models'params = {'types': ['LORA'], 'sort': sort, 'period': period, 'limit': limit, 'page': int(page), 'nsfw': 'true'}if query: params["query"] = query301 unmodified lines302303304305306307308309310311258 unmodified lines57057157257357457557657711 unmodified lines58959059159259359459559659759859960094 unmodified lines6956966976986997007016 unmodified lines70870971071171271371471571671771871972033 unmodified lines75475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378410 unmodified lines79579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383454 unmodified lines88989089189289389489589689789889990090190290318 unmodified lines9229239249259269279289296 unmodified lines93693793893994094194294394494594612 unmodified lines95996096196296396410 unmodified lines97597697797897998098198298398426 unmodified lines101110121013101410151016101710181019102010211022102310241025102610271028102938 unmodified lines1068106910701071107210731074301 unmodified linesreturn outputdef valid_model_name(model_name: str):return model_name.split(" ")[0]def save_images(images: list[Image.Image], metadatas: list[str]):from PIL import PngImagePluginimport uuid258 unmodified linesdef get_civitai_info(path):global civitai_not_exists_listdefault = ["", "", "", "", ""]if path in set(civitai_not_exists_list): return defaultif not Path(path).exists(): return Noneuser_agent = get_user_agent()headers = {'User-Agent': user_agent, 'content-type': 'application/json'}11 unmodified linesr = session.get(url, params=params, headers=headers, stream=True, timeout=(3.0, 15))except Exception as e:print(e)return defaultif not r.ok: return Nonejson = r.json()if not 'baseModel' in json:civitai_not_exists_list.append(path)return defaultitems = []items.append(" / ".join(json['trainedWords']))items.append(json['baseModel'])94 unmodified linesreturn Nonedef download_my_lora(dl_urls: str, lora1: str, lora2: str, lora3: str, lora4: str, lora5: str, lora6: str, lora7: str):path = download_lora(dl_urls)if path:if not lora1 or lora1 == "None":6 unmodified lineslora4 = pathelif not lora5 or lora5 == "None":lora5 = path#elif not lora6 or lora6 == "None":# lora6 = path#elif not lora7 or lora7 == "None":# lora7 = pathchoices = get_all_lora_tupled_list()return gr.update(value=lora1, choices=choices), gr.update(value=lora2, choices=choices), gr.update(value=lora3, choices=choices),\gr.update(value=lora4, choices=choices), gr.update(value=lora5, choices=choices), gr.update(value=lora6, choices=choices), gr.update(value=lora7, choices=choices)def get_valid_lora_name(query: str, model_name: str):33 unmodified linesreturn wtdef set_prompt_loras(prompt, prompt_syntax, model_name, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt, lora6, lora6_wt, lora7, lora7_wt):if not "Classic" in str(prompt_syntax): return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt, lora6, lora6_wt, lora7, lora7_wtlora1 = get_valid_lora_name(lora1, model_name)lora2 = get_valid_lora_name(lora2, model_name)lora3 = get_valid_lora_name(lora3, model_name)lora4 = get_valid_lora_name(lora4, model_name)lora5 = get_valid_lora_name(lora5, model_name)#lora6 = get_valid_lora_name(lora6, model_name)#lora7 = get_valid_lora_name(lora7, model_name)if not "<lora" in prompt: return lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt, lora6, lora6_wt, lora7, lora7_wtlora1_wt = get_valid_lora_wt(prompt, lora1, lora1_wt)lora2_wt = get_valid_lora_wt(prompt, lora2, lora2_wt)lora3_wt = get_valid_lora_wt(prompt, lora3, lora3_wt)lora4_wt = get_valid_lora_wt(prompt, lora4, lora4_wt)lora5_wt = get_valid_lora_wt(prompt, lora5, lora5_wt)#lora6_wt = get_valid_lora_wt(prompt, lora6, lora5_wt)#lora7_wt = get_valid_lora_wt(prompt, lora7, lora5_wt)on1, label1, tag1, md1 = get_lora_info(lora1)on2, label2, tag2, md2 = get_lora_info(lora2)on3, label3, tag3, md3 = get_lora_info(lora3)on4, label4, tag4, md4 = get_lora_info(lora4)on5, label5, tag5, md5 = get_lora_info(lora5)#on6, label6, tag6, md6 = get_lora_info(lora6)#on7, label7, tag7, md7 = get_lora_info(lora7)lora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]prompts = prompt.split(",") if prompt else []for p in prompts:p = str(p).strip()10 unmodified linescontinueelif not on1:lora1 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]lora1_wt = safe_float(wt)on1 = Trueelif not on2:lora2 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]lora2_wt = safe_float(wt)on2 = Trueelif not on3:lora3 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]lora3_wt = safe_float(wt)on3 = Trueelif not on4:lora4 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]lora4_wt = safe_float(wt)on4 = Trueelif not on5:lora5 = pathlora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]lora5_wt = safe_float(wt)on5 = True#elif not on6:# lora6 = path# lora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]# lora6_wt = safe_float(wt)# on6 = True#elif not on7:# lora7 = path# lora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]# lora7_wt = safe_float(wt)# on7 = Truereturn lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt, lora6, lora6_wt, lora7, lora7_wtdef get_lora_info(lora_path: str):54 unmodified linesreturn gr.update(value=prompt)def update_loras(prompt, prompt_syntax, lora1, lora1_wt, lora2, lora2_wt, lora3, lora3_wt, lora4, lora4_wt, lora5, lora5_wt, lora6, lora6_wt, lora7, lora7_wt):on1, label1, tag1, md1 = get_lora_info(lora1)on2, label2, tag2, md2 = get_lora_info(lora2)on3, label3, tag3, md3 = get_lora_info(lora3)on4, label4, tag4, md4 = get_lora_info(lora4)on5, label5, tag5, md5 = get_lora_info(lora5)on6, label6, tag6, md6 = get_lora_info(lora6)on7, label7, tag7, md7 = get_lora_info(lora7)lora_paths = [lora1, lora2, lora3, lora4, lora5, lora6, lora7]output_prompt = promptif "Classic" in str(prompt_syntax):18 unmodified linesif on3: lora_prompts.append(f"<lora:{to_lora_key(lora3)}:{lora3_wt:.2f}>")if on4: lora_prompts.append(f"<lora:{to_lora_key(lora4)}:{lora4_wt:.2f}>")if on5: lora_prompts.append(f"<lora:{to_lora_key(lora5)}:{lora5_wt:.2f}>")#if on6: lora_prompts.append(f"<lora:{to_lora_key(lora6)}:{lora6_wt:.2f}>")#if on7: lora_prompts.append(f"<lora:{to_lora_key(lora7)}:{lora7_wt:.2f}>")output_prompt = ", ".join(list_uniq(output_prompts + lora_prompts + [""]))choices = get_all_lora_tupled_list()6 unmodified linesgr.update(value=lora4, choices=choices), gr.update(value=lora4_wt),\gr.update(value=tag4, label=label4, visible=on4), gr.update(visible=on4), gr.update(value=md4, visible=on4),\gr.update(value=lora5, choices=choices), gr.update(value=lora5_wt),\gr.update(value=tag5, label=label5, visible=on5), gr.update(visible=on5), gr.update(value=md5, visible=on5),\gr.update(value=lora6, choices=choices), gr.update(value=lora6_wt),\gr.update(value=tag6, label=label6, visible=on6), gr.update(visible=on6), gr.update(value=md6, visible=on6),\gr.update(value=lora7, choices=choices), gr.update(value=lora7_wt),\gr.update(value=tag7, label=label7, visible=on7), gr.update(visible=on7), gr.update(value=md7, visible=on7)def get_my_lora(link_url, romanize):12 unmodified linespath.resolve().rename(new_path.resolve())update_lora_dict(str(new_path))l_path = str(new_path)new_lora_tupled_list = get_all_lora_tupled_list()msg_lora = "Downloaded"if l_name:10 unmodified lineschoices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(value=msg_lora)26 unmodified lineschoices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list), gr.update(choices=new_lora_tupled_list)CIVITAI_SORT = ["Highest Rated", "Most Downloaded", "Most Liked", "Most Discussed", "Most Collected", "Most Buzz", "Newest"]CIVITAI_PERIOD = ["AllTime", "Year", "Month", "Week", "Day"]CIVITAI_BASEMODEL = ["Pony", "Illustrious", "SDXL 1.0", "SD 1.5", "Flux.1 D", "Flux.1 S"] # , "SD 3.5"CIVITAI_TYPE = ["Checkpoint", "TextualInversion", "Hypernetwork", "AestheticGradient", "LORA", "LoCon", "DoRA","Controlnet", "Upscaler", "MotionModule", "VAE", "Poses", "Wildcards", "Workflows", "Other"]CIVITAI_FILETYPE = ["Model", "VAE", "Config", "Training Data"]def get_civitai_info(path):38 unmodified linessort: str = "Highest Rated", period: str = "AllTime", tag: str = "", user: str = "", page: int = 1):user_agent = get_user_agent()headers = {'User-Agent': user_agent, 'content-type': 'application/json'}if CIVITAI_API_KEY: headers['Authorization'] = f'Bearer {{{CIVITAI_API_KEY}}}'base_url = 'https://civitai.com/api/v1/models'params = {'types': ['LORA'], 'sort': sort, 'period': period, 'limit': limit, 'page': int(page), 'nsfw': 'true'}if query: params["query"] = query
1234git+https://github.com/R3gm/stablepy.git@8edabb0 # -b refactor_sampler_fixtorch==2.2.0numpy<2gdown1234git+https://github.com/R3gm/stablepy.git@a9fe2dc # -b refactor_sampler_fixtorch==2.2.0numpy<2gdown
273 unmodified lines274275276277278279273 unmodified lineschoices=new_lora_model_list), gr.update(choices=new_lora_model_list), gr.update(value=msg_lora)273 unmodified lines274275276277278279280281282283273 unmodified lineschoices=new_lora_model_list), gr.update(choices=new_lora_model_list), gr.update(choices=new_lora_model_list), gr.update(choices=new_lora_model_list), gr.update(value=msg_lora)
app.py+252-167
constants.py+77-82
image_processor.pyAdded+130
modutils.py+65-21
requirements.txt+1-1
utils.py+4