Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files1234123456779101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475768910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817978798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237297298299300301302239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293303295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325304305306307308309310328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363311312313314315316317366367318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363370371372373374375376364365366367368369370371379380381382383384385386387388389390391392393394395396397398399372import osimport randomimport uuidfrom typing import Tupleimport gradio as grimport torchfrom diffusers import FluxFillPipelinefrom diffusers.utils import load_imagefrom PIL import Image, ImageDrawimport numpy as npfrom PIL import Imageimport spacesimport torchfrom diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
title = """<h1>SDXL LoRA DLC 🤩</h1>"""
# Ensure assets directory exists if needed for predefined imagesif not os.path.exists("assets"): print("Warning: 'assets' directory not found. Predefined gallery might be empty.") # Optionally create it: os.makedirs("assets")
def save_image(img): # Ensure an 'outputs' directory exists to save generated images (optional, good practice) output_dir = "outputs" if not os.path.exists(output_dir): os.makedirs(output_dir) unique_name = os.path.join(output_dir, str(uuid.uuid4()) + ".png") img.save(unique_name) return unique_name
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed
MAX_SEED = np.iinfo(np.int32).maxpipe = None # Initialize pipe to None
if not torch.cuda.is_available(): DESCRIPTIONz += "\n<p>⚠️Running on CPU, This may not work on CPU. If it runs for an extended time or if you encounter errors, try running it on a GPU by duplicating the space using @spaces.GPU(). +import spaces.📍</p>" # Optionally, you could add a placeholder or disable functionality hereelse: USE_TORCH_COMPILE = False # Set to False as 0 is not standard boolean ENABLE_CPU_OFFLOAD = False # Set to False as 0 is not standard boolean
# Moved pipe initialization inside the CUDA check pipe = StableDiffusionXLPipeline.from_pretrained( "SG161222/RealVisXL_V4.0_Lightning", # [or] SG161222/RealVisXL_V5.0_Lightning torch_dtype=torch.float16, use_safetensors=True, ) pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
LORA_OPTIONS = { "Realism (face/character)👦🏻": ("prithivMLmods/Canopus-Realism-LoRA", "Canopus-Realism-LoRA.safetensors", "rlms"), "Pixar (art/toons)🙀": ("prithivMLmods/Canopus-Pixar-Art", "Canopus-Pixar-Art.safetensors", "pixar"), "Photoshoot (camera/film)📸": ("prithivMLmods/Canopus-Photo-Shoot-Mini-LoRA", "Canopus-Photo-Shoot-Mini-LoRA.safetensors", "photo"), "Clothing (hoodies/pant/shirts)👔": ("prithivMLmods/Canopus-Clothing-Adp-LoRA", "Canopus-Dress-Clothing-LoRA.safetensors", "clth"), "Interior Architecture (house/hotel)🏠": ("prithivMLmods/Canopus-Interior-Architecture-0.1", "Canopus-Interior-Architecture-0.1δ.safetensors", "arch"), "Fashion Product (wearing/usable)👜": ("prithivMLmods/Canopus-Fashion-Product-Dilation", "Canopus-Fashion-Product-Dilation.safetensors", "fashion"), "Minimalistic Image (minimal/detailed)🏞️": ("prithivMLmods/Pegasi-Minimalist-Image-Style", "Pegasi-Minimalist-Image-Style.safetensors", "minimalist"), "Modern Clothing (trend/new)👕": ("prithivMLmods/Canopus-Modern-Clothing-Design", "Canopus-Modern-Clothing-Design.safetensors", "mdrnclth"), "Animaliea (farm/wild)🫎": ("prithivMLmods/Canopus-Animaliea-Artism", "Canopus-Animaliea-Artism.safetensors", "Animaliea"), "Liquid Wallpaper (minimal/illustration)🖼️": ("prithivMLmods/Canopus-Liquid-Wallpaper-Art", "Canopus-Liquid-Wallpaper-Minimalize-LoRA.safetensors", "liquid"), "Canes Cars (realistic/futurecars)🚘": ("prithivMLmods/Canes-Cars-Model-LoRA", "Canes-Cars-Model-LoRA.safetensors", "car"), "Pencil Art (characteristic/creative)✏️": ("prithivMLmods/Canopus-Pencil-Art-LoRA", "Canopus-Pencil-Art-LoRA.safetensors", "Pencil Art"), "Art Minimalistic (paint/semireal)🎨": ("prithivMLmods/Canopus-Art-Medium-LoRA", "Canopus-Art-Medium-LoRA.safetensors", "mdm"), }
# Load LoRAs only if pipe is initialized if pipe: for model_name, weight_name, adapter_name in LORA_OPTIONS.values(): try: pipe.load_lora_weights(model_name, weight_name=weight_name, adapter_name=adapter_name) print(f"Loaded LoRA: {adapter_name}") except Exception as e: print(f"Warning: Could not load LoRA {adapter_name} from {model_name}. Error: {e}") pipe.to("cuda") print("Pipeline and LoRAs loaded to CUDA.")from huggingface_hub import hf_hub_download
pipe = FluxFillPipeline.from_pretrained( "black-forest-labs/FLUX.1-Fill-dev", torch_dtype=torch.bfloat16).to("cuda")
def can_expand(source_width, source_height, target_width, target_height, alignment): if alignment in ("Left", "Right") and source_width >= target_width: return False if alignment in ("Top", "Bottom") and source_height >= target_height: return False return True
def prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom): target_size = (width, height)
scale_factor = min(target_size[0] / image.width, target_size[1] / image.height) new_width = int(image.width * scale_factor) new_height = int(image.height * scale_factor) source = image.resize((new_width, new_height), Image.LANCZOS)
if resize_option == "Full": resize_percentage = 100 elif resize_option == "75%": resize_percentage = 75 elif resize_option == "50%": resize_percentage = 50 elif resize_option == "33%": resize_percentage = 33 elif resize_option == "25%": resize_percentage = 25 else: # Custom resize_percentage = custom_resize_percentage
# Calculate new dimensions based on percentage resize_factor = resize_percentage / 100 new_width = int(source.width * resize_factor) new_height = int(source.height * resize_factor)
# Ensure minimum size of 64 pixels new_width = max(new_width, 64) new_height = max(new_height, 64)
# Resize the image source = source.resize((new_width, new_height), Image.LANCZOS)
# Calculate the overlap in pixels based on the percentage overlap_x = int(new_width * (overlap_percentage / 100)) overlap_y = int(new_height * (overlap_percentage / 100))
# Ensure minimum overlap of 1 pixel overlap_x = max(overlap_x, 1) overlap_y = max(overlap_y, 1)
# Calculate margins based on alignment if alignment == "Middle": margin_x = (target_size[0] - new_width) // 2 margin_y = (target_size[1] - new_height) // 2 elif alignment == "Left": margin_x = 0 margin_y = (target_size[1] - new_height) // 2 elif alignment == "Right": margin_x = target_size[0] - new_width margin_y = (target_size[1] - new_height) // 2 elif alignment == "Top": margin_x = (target_size[0] - new_width) // 2 margin_y = 0 elif alignment == "Bottom": margin_x = (target_size[0] - new_width) // 2 margin_y = target_size[1] - new_height
# Adjust margins to eliminate gaps margin_x = max(0, min(margin_x, target_size[0] - new_width)) margin_y = max(0, min(margin_y, target_size[1] - new_height))
# Create a new background image and paste the resized source image background = Image.new('RGB', target_size, (255, 255, 255)) background.paste(source, (margin_x, margin_y))
# Create the mask mask = Image.new('L', target_size, 255) mask_draw = ImageDraw.Draw(mask)
# Calculate overlap areas white_gaps_patch = 2
left_overlap = margin_x + overlap_x if overlap_left else margin_x + white_gaps_patch right_overlap = margin_x + new_width - overlap_x if overlap_right else margin_x + new_width - white_gaps_patch top_overlap = margin_y + overlap_y if overlap_top else margin_y + white_gaps_patch bottom_overlap = margin_y + new_height - overlap_y if overlap_bottom else margin_y + new_height - white_gaps_patch if alignment == "Left": left_overlap = margin_x + overlap_x if overlap_left else margin_x elif alignment == "Right": right_overlap = margin_x + new_width - overlap_x if overlap_right else margin_x + new_width elif alignment == "Top": top_overlap = margin_y + overlap_y if overlap_top else margin_y elif alignment == "Bottom": bottom_overlap = margin_y + new_height - overlap_y if overlap_bottom else margin_y + new_height
# Draw the mask mask_draw.rectangle([ (left_overlap, top_overlap), (right_overlap, bottom_overlap) ], fill=0)
return background, mask
@spaces.GPUdef inpaint(image, width, height, overlap_percentage, num_inference_steps, resize_option, custom_resize_percentage, prompt_input, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom, progress=gr.Progress(track_tqdm=True)): background, mask = prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom) if not can_expand(background.width, background.height, width, height, alignment): alignment = "Middle"
cnet_image = background.copy() cnet_image.paste(0, (0, 0), mask)
final_prompt = prompt_input
#generator = torch.Generator(device="cuda").manual_seed(42)
result = pipe( prompt=final_prompt, height=height, width=width, image=cnet_image, mask_image=mask, num_inference_steps=num_inference_steps, guidance_scale=30, ).images[0] result = result.convert("RGBA") cnet_image.paste(result, (0, 0), mask)
return cnet_image, background
def preview_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom): background, mask = prepare_image_and_mask(image, width, height, overlap_percentage, resize_option, custom_resize_percentage, alignment, overlap_left, overlap_right, overlap_top, overlap_bottom) preview = background.copy().convert('RGBA') red_overlay = Image.new('RGBA', background.size, (255, 0, 0, 64)) red_mask = Image.new('RGBA', background.size, (0, 0, 0, 0)) red_mask.paste(red_overlay, (0, 0), mask) preview = Image.alpha_composite(preview, red_mask) return preview
def clear_result(): return gr.update(value=None)
def preload_presets(target_ratio, ui_width, ui_height): if target_ratio == "9:16": return 720, 1280, gr.update() elif target_ratio == "16:9": return 1280, 720, gr.update() elif target_ratio == "1:1": return 1024, 1024, gr.update() elif target_ratio == "Custom": return ui_width, ui_height, gr.update(open=True)
def select_the_right_preset(user_width, user_height): if user_width == 720 and user_height == 1280: return "9:16" elif user_width == 1280 and user_height == 720: return "16:9" elif user_width == 1024 and user_height == 1024: return "1:1" else: print("Pipeline not initialized (likely no CUDA available).")
style_list = [ { "name": "3840 x 2160", "prompt": "hyper-realistic 8K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly", }, { "name": "2560 x 1440", "prompt": "hyper-realistic 4K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly", }, { "name": "HD+", "prompt": "hyper-realistic 2K image of {prompt}. ultra-detailed, lifelike, high-resolution, sharp, vibrant colors, photorealistic", "negative_prompt": "cartoonish, low resolution, blurry, simplistic, abstract, deformed, ugly", }, { "name": "Style Zero", "prompt": "{prompt}", "negative_prompt": "", },]
styles = {k["name"]: (k["prompt"], k["negative_prompt"]) for k in style_list}
DEFAULT_STYLE_NAME = "3840 x 2160"STYLE_NAMES = list(styles.keys())
def apply_style(style_name: str, positive: str, negative: str = "") -> Tuple[str, str]: p, n = styles.get(style_name, styles[DEFAULT_STYLE_NAME]) # Use .get for safety
if not negative: negative = "" return p.replace("{prompt}", positive), n + " " + negative # Add space for clarity
@spaces.GPU(duration=180, enable_queue=True)def generate( prompt: str, negative_prompt: str = "", use_negative_prompt: bool = False, seed: int = 0, width: int = 1024, height: int = 1024, guidance_scale: float = 3, randomize_seed: bool = False, style_name: str = DEFAULT_STYLE_NAME, lora_model: str = "Realism (face/character)👦🏻", progress=gr.Progress(track_tqdm=True),): if pipe is None: raise gr.Error("Pipeline not initialized. Check if CUDA is available and drivers are installed.") return "Custom"
def toggle_custom_resize_slider(resize_option): return gr.update(visible=(resize_option == "Custom"))
def update_history(new_image, history): if history is None: history = [] history.insert(0, new_image) return history
css = """.gradio-container { max-width: 1250px !important;}"""
title = """<h1 align="center">Flux Outpaint Dev 🤩</h1>"""
with gr.Blocks(css=css) as demo: with gr.Column(): gr.HTML(title)
with gr.Row(): with gr.Column(): input_image = gr.Image( type="pil", label="Input Image" )
with gr.Row(): with gr.Column(scale=2): prompt_input = gr.Textbox(label="Prompt (Optional)") with gr.Column(scale=1): run_button = gr.Button("Generate")
with gr.Row(): target_ratio = gr.Radio( label="Image Ratio", choices=["9:16", "16:9", "1:1", "Custom"], value="9:16", scale=3 ) alignment_dropdown = gr.Dropdown( choices=["Middle", "Left", "Right", "Top", "Bottom"], value="Middle", label="Alignment", ) resize_option = gr.Radio( label="Resize input image", choices=["Full", "75%", "50%", "33%", "25%", "Custom"], value="75%" ) custom_resize_percentage = gr.Slider( label="Custom resize (%)", minimum=1, maximum=100, step=1, value=50, visible=False ) with gr.Accordion(label="Advanced settings", open=False) as settings_panel: with gr.Column(): with gr.Row(): width_slider = gr.Slider( label="Target Width", minimum=720, maximum=1536, step=8, value=720, ) height_slider = gr.Slider( label="Target Height", minimum=720, maximum=1536, step=8, value=1280, ) num_inference_steps = gr.Slider(label="Steps", minimum=2, maximum=50, step=1, value=28) with gr.Group(): overlap_percentage = gr.Slider( label="Mask overlap (%)", minimum=1, maximum=50, value=10, step=1 ) with gr.Row(): overlap_top = gr.Checkbox(label="Overlap Top", value=True) overlap_right = gr.Checkbox(label="Overlap Right", value=True) with gr.Row(): overlap_left = gr.Checkbox(label="Overlap Left", value=True) overlap_bottom = gr.Checkbox(label="Overlap Bottom", value=True) with gr.Column(): preview_button = gr.Button("Preview alignment and mask") with gr.Column(): result = gr.Image( interactive=False, label="Generated Image", ) use_as_input_button = gr.Button("Use as Input Image", visible=False) with gr.Accordion("History and Mask", open=False): history_gallery = gr.Gallery(label="History", columns=6, object_fit="contain", interactive=False) preview_image = gr.Image(label="Mask preview")
def use_output_as_input(output_image): return output_image
use_as_input_button.click( fn=use_output_as_input, inputs=[result], outputs=[input_image] ) seed = int(randomize_seed_fn(seed, randomize_seed))
# Apply style first positive_prompt, base_negative_prompt = apply_style(style_name, prompt, negative_prompt if use_negative_prompt else "")
# If user explicitly provided a negative prompt and wants to use it, append it # (apply_style already incorporates the style's negative prompt) # This logic might need adjustment depending on desired behavior: replace or append? # Current: Style neg prompt + user neg prompt effective_negative_prompt = base_negative_prompt if use_negative_prompt and negative_prompt: # Check if the negative prompt from apply_style is already there to avoid duplication if not negative_prompt in effective_negative_prompt: effective_negative_prompt = (effective_negative_prompt + " " + negative_prompt).strip()
# Ensure LoRA selection is valid if lora_model not in LORA_OPTIONS: print(f"Warning: Invalid LoRA selection '{lora_model}'. Using default or first available.") # Fallback logic could be added here, e.g., use the first key lora_model = next(iter(LORA_OPTIONS)) # Get the first key as a fallback
model_name, weight_name, adapter_name = LORA_OPTIONS[lora_model]
try: print(f"Setting adapter: {adapter_name}") pipe.set_adapters(adapter_name) # Optional: Add LoRA scale if needed, often done via cross_attention_kwargs # Example: cross_attention_kwargs={"scale": lora_scale} # Note: RealVisXL Lightning might not need explicit scale adjustments like older models. # Using 0.65 as hardcoded before. Keeping it. lora_scale = 0.65
print(f"Generating with prompt: '{positive_prompt}'") print(f"Negative prompt: '{effective_negative_prompt}'") print(f"Seed: {seed}, W: {width}, H: {height}, Scale: {guidance_scale}, Steps: 20")
images = pipe( prompt=positive_prompt, negative_prompt=effective_negative_prompt, width=width, height=height, guidance_scale=guidance_scale, num_inference_steps=20, # Lightning models use fewer steps num_images_per_prompt=1, generator=torch.Generator("cuda").manual_seed(seed), # Ensure reproducibility cross_attention_kwargs={"scale": lora_scale}, # Apply LoRA scale if needed output_type="pil", ).images image_paths = [save_image(img) for img in images] print(f"Generated {len(image_paths)} image(s).") return image_paths, seed
except Exception as e: print(f"Error during generation: {e}") # Raise a Gradio error to display it in the UI import traceback traceback.print_exc() raise gr.Error(f"Generation failed: {e}")
examples = [ ["Realism: Man in the style of dark beige and brown, uhd image, youthful protagonists, nonrepresentational"], ["Pixar: A young man with light brown wavy hair and light brown eyes sitting in an armchair and looking directly at the camera, pixar style, disney pixar, office background, ultra detailed, 1 man"], ["Hoodie: Front view, capture a urban style, Superman Hoodie, technical materials, fabric small point label on text Blue theory, the design is minimal, with a raised collar, fabric is a Light yellow, low angle to capture the Hoodies form and detailing, f/5.6 to focus on the hoodies craftsmanship, solid grey background, studio light setting, with batman logo in the chest region of the t-shirt"],]
css = '''.gradio-container{max-width: 680px !important; margin: auto;}h1{text-align:center}#gallery { min-height: 400px; }footer { display: none !important; visibility: hidden !important; }'''
def load_predefined_images(): predefined_images = [] asset_dir = "assets" if os.path.exists(asset_dir): valid_extensions = {".png", ".jpg", ".jpeg", ".webp"} try: for i in range(1, 10): # Try loading 1.png to 9.png for ext in valid_extensions: img_path = os.path.join(asset_dir, f"{i}{ext}") if os.path.exists(img_path): predefined_images.append(img_path) break # Found image for this number, move to next except Exception as e: print(f"Error loading predefined images: {e}") if not predefined_images: print("No predefined images found in assets folder (e.g., assets/1.png, assets/2.jpg).") return predefined_images
# --- Gradio UI Definition ---with gr.Blocks(css=css, theme="Yntec/HaleyCH_Theme_craiyon_alt") as demo: gr.HTML(title)
# Define the output gallery component first result_gallery = gr.Gallery( label="Generated Images", show_label=False, elem_id="gallery", # For CSS styling columns=1, # Adjust as needed height="auto" target_ratio.change( fn=preload_presets, inputs=[target_ratio, width_slider, height_slider], outputs=[width_slider, height_slider, settings_panel], queue=False ) # Define the output seed component output_seed = gr.State(value=0) # Use gr.State for non-displayed outputs or values needing persistence
with gr.Row(): prompt = gr.Textbox( label="Prompt", show_label=False, max_lines=2, placeholder="Enter your prompt here...", container=False, scale=7 # Give more space to prompt ) run_button = gr.Button("Generate", scale=1, variant="primary")
with gr.Row(): model_choice = gr.Dropdown( label="LoRA Selection", choices=list(LORA_OPTIONS.keys()), value="Realism (face/character)👦🏻", # Default selection scale=3 ) style_selection = gr.Radio( show_label=False, # Label provided by Row context or Accordion container=True, interactive=True, choices=STYLE_NAMES, value=DEFAULT_STYLE_NAME, label="Quality Style", scale=2 )
with gr.Accordion("Advanced options", open=False): with gr.Row(): use_negative_prompt = gr.Checkbox(label="Use Negative Prompt", value=True, scale=1) randomize_seed = gr.Checkbox(label="Randomize Seed", value=True, scale=1) seed = gr.Slider( label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0, # Initial value visible=True, # Controlled by randomize_seed logic later if needed scale=3 )
negative_prompt = gr.Textbox( label="Negative Prompt", lines=2, max_lines=4, value="(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation", placeholder="Enter things to avoid...", visible=True, # Controlled by use_negative_prompt checkbox )
with gr.Row(): width = gr.Slider( label="Width", minimum=512, maximum=1536, # Adjusted max for typical SDXL usage step=64, # Step by 64 for common resolutions value=1024, ) height = gr.Slider( label="Height", minimum=512, maximum=1536, # Adjusted max step=64, # Step by 64 value=1024, ) guidance_scale = gr.Slider( label="Guidance Scale (CFG)", minimum=1.0, # Usually start CFG from 1 maximum=10.0, # Lightning models often use low CFG step=0.1, value=3.0, )
# --- Event Listeners ---
# Toggle negative prompt visibility use_negative_prompt.change( fn=lambda x: gr.update(visible=x), inputs=use_negative_prompt, outputs=negative_prompt, api_name=False, width_slider.change( fn=select_the_right_preset, inputs=[width_slider, height_slider], outputs=[target_ratio], queue=False )
# Toggle seed slider visibility based on randomize checkbox # def toggle_seed_visibility(randomize): # return gr.update(interactive=not randomize) # randomize_seed.change( # fn=toggle_seed_visibility, # inputs=randomize_seed, # outputs=seed, # api_name=False # )
# --- Image Generation Trigger --- inputs = [ prompt, negative_prompt, use_negative_prompt, seed, width, height, guidance_scale, randomize_seed, style_selection, model_choice, ] # Define outputs using the created components outputs = [ result_gallery, # The gallery to display images output_seed # The state to hold the used seed ]
# Connect the generate function to the button click and prompt submit gr.on( triggers=[run_button.click, prompt.submit], fn=generate, inputs=inputs, outputs=outputs, api_name="run" # Keep API name if needed height_slider.change( fn=select_the_right_preset, inputs=[width_slider, height_slider], outputs=[target_ratio], queue=False )
# Update the seed slider display when a new seed is generated and returned via output_seed output_seed.change(fn=lambda x: x, inputs=output_seed, outputs=seed, api_name=False) resize_option.change( fn=toggle_custom_resize_slider, inputs=[resize_option], outputs=[custom_resize_percentage], queue=False ) run_button.click( fn=clear_result, inputs=None, outputs=result, ).then( fn=inpaint, inputs=[input_image, width_slider, height_slider, overlap_percentage, num_inference_steps, resize_option, custom_resize_percentage, prompt_input, alignment_dropdown, overlap_left, overlap_right, overlap_top, overlap_bottom], outputs=[result, preview_image], ).then( fn=lambda x, history: update_history(x, history), inputs=[result, history_gallery], outputs=history_gallery, ).then( fn=lambda: gr.update(visible=True), inputs=None, outputs=use_as_input_button, )
prompt_input.submit( fn=clear_result, inputs=None, outputs=result, ).then( fn=inpaint, inputs=[input_image, width_slider, height_slider, overlap_percentage, num_inference_steps, resize_option, custom_resize_percentage, prompt_input, alignment_dropdown, overlap_left, overlap_right, overlap_top, overlap_bottom], outputs=[result, preview_image], ).then( fn=lambda x, history: update_history(x, history), inputs=[result, history_gallery], outputs=history_gallery, ).then( fn=lambda: gr.update(visible=True), inputs=None, outputs=use_as_input_button, )
# --- Examples --- gr.Examples( examples=examples, inputs=[prompt], # Only prompt needed for examples outputs=[result_gallery, output_seed], # Update example outputs as well fn=generate, # Function to run when example is clicked cache_examples=os.getenv("CACHE_EXAMPLES", "False").lower() == "true" # Cache examples in Spaces preview_button.click( fn=preview_image_and_mask, inputs=[input_image, width_slider, height_slider, overlap_percentage, resize_option, custom_resize_percentage, alignment_dropdown, overlap_left, overlap_right, overlap_top, overlap_bottom], outputs=preview_image, queue=False )
# --- Predefined Image Gallery (Static) --- with gr.Column(): # Use column for better layout control if needed gr.Markdown("### Example Gallery (Predefined)") try: predefined_gallery_images = load_predefined_images() if predefined_gallery_images: predefined_gallery = gr.Gallery( label="Predefined Images", value=predefined_gallery_images, columns=3, show_label=False ) else: gr.Markdown("_(No predefined images found in 'assets' folder)_") except Exception as e: gr.Markdown(f"_Error loading predefined gallery: {e}_")
# --- Launch the App ---if __name__ == "__main__": demo.queue(max_size=20).launch(ssr_mode=True, debug=True) # Add debug=True for more detailed logsdemo.queue(max_size=12).launch(share=False)app.py+357-384