Commit Β·
b7ddbd8
1
Parent(s): f98185b
Upload app.py
Browse filesChanged image handling, added edit functions for uploaded images (e.g. crop), and made custom loaded loras user specific instead of a global dict
4 unmodified lines567889101112212 unmodified lines22522622722822923023123223323422822923523623223723823423924024124223824324424024524624224324724824925025125224824925325425525625715 unmodified lines2732742752712722732742752762772782792802812822832842852862872882892902772782792802812822912922932942832952852962972872982993002893013023033043053063073083092913103113123133143153163173182942952962973193203213223233242993253263013273283293043053063073083093103113123303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623163633643653662 unmodified lines369370371325372373374375121 unmodified lines4974984994535005015025035043 unmodified lines5085095105115125135147 unmodified lines5225235244764775255265274795285295305313 unmodified lines5355365374894905385395405415422 unmodified lines54554654749954854955055123 unmodified lines5755765775785795805812 unmodified lines58458558653758758853958959059159254359359459559672 unmodified lines6696706716226236726736746756766776786796806256816826276836846856865 unmodified lines69269369463964064164264364469569669769869970070170270370470564764870670770870971071171265465565671371471571665871771871972055 unmodified lines7767777787207797807817821 unmodified line78478578678778878979012 unmodified lines803804805746747748749750751752753754755756757758759760761762763806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839765766767768769770771772773840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893776777778779780781782783784785786787788789790791792793794795796797894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928800801802803804805806807808809810811812813814815816929930931932817818819820821822823824825826827828829933831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968871872873874875876877878879880969970971972973974975976977978882883884979980981982983984888889890891985986987988989990991992993994995996997998896999100010011002100310049029031005100610071008100916 unmodified lines1026102710289261029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010614 unmodified linesimport spacesimport torchimport randomimport uuidfrom PIL import Imagefrom PIL import Image, ImageOpsfrom typing import Iterableimport timeimport threading212 unmodified lines }, ]
# LOADED_ADAPTERS is the only piece of LoRA state that's legitimately global:# it just tracks which adapter names have been loaded onto the shared `pipe`# at least once, so we don't re-download/re-attach weights on every call.# It is NOT used to decide what a user can select β that comes from each# session's own `dynamic_loras_state` (a gr.State dict), so one user's custom# HuggingFace LoRA never shows up in another user's checklist.LOADED_ADAPTERS = set()DYNAMIC_LORAS = {}DYNAMIC_LORA_COUNTER = 0
def get_all_styles():def get_all_styles(dynamic_loras): all_styles = list(LORA_STYLES) for dynamic_lora in DYNAMIC_LORAS.values(): for dynamic_lora in (dynamic_loras or {}).values(): all_styles.append(dynamic_lora) return all_styles
def get_selectable_styles():def get_selectable_styles(dynamic_loras): """Return all styles except 'None' for the checkbox selector.""" return [s for s in get_all_styles() if s["adapter_name"] is not None] return [s for s in get_all_styles(dynamic_loras) if s["adapter_name"] is not None]
def get_style_by_title(title): for style in get_all_styles():def get_style_by_title(title, dynamic_loras): for style in get_all_styles(dynamic_loras): if style["title"] == title: return style return None
def get_style_by_adapter_name(adapter_name): for style in get_all_styles():def get_style_by_adapter_name(adapter_name, dynamic_loras): for style in get_all_styles(dynamic_loras): if style["adapter_name"] == adapter_name: return style return None15 unmodified lines# Keep old name as alias so nothing inside infer breaks if called directlyupdate_dimensions_on_upload = compute_base_dimensions
def on_gallery_change(images): """Update image count info and size display when gallery changes.""" count_info = get_image_count_info(images) if not images: return count_info, "*No image uploaded yet*"def fix_orientation(img): """Correct EXIF orientation in-place (returns a new image). Browsers/OS viewers respect the EXIF orientation tag, but PIL does not apply it by default β so an image can *look* correctly oriented everywhere you view it while the actual pixel data fed to the model is rotated 90/180/270Β°. This normalises the pixels to match what you see.""" if img is None: return None return ImageOps.exif_transpose(img)
def on_base_image_change(img): """Update the size/dimension preview when the base image changes.""" if img is None: return "*No base image uploaded yet*" try: first = images[0] path = first[0] if isinstance(first, (tuple, list)) else first img = Image.open(path if isinstance(path, str) else path.name) orig_w, orig_h = img.size base_w, base_h = compute_base_dimensions(img) size_text = f"Input: **{orig_w} Γ {orig_h}** px β Output (pre-upscale): **{base_w} Γ {base_h}** px" pil_img = img if isinstance(img, Image.Image) else Image.open(img) orig_w, orig_h = pil_img.size base_w, base_h = compute_base_dimensions(pil_img) return f"Input: **{orig_w} Γ {orig_h}** px β Output (pre-upscale): **{base_w} Γ {base_h}** px" return count_info, size_text except Exception as e: return count_info, f"*Could not read dimensions: {e}*" return f"*Could not read dimensions: {e}*"
def process_gallery_images(images):def on_reference_change(images): """Update the reference image count info when the gallery changes.""" if not images: return [] return "π· No reference images" count = len(images) return f"π· {count} reference image{'s' if count != 1 else ''} uploaded"
def process_images(base_image, reference_images): """Build the ordered list of PIL images sent to the pipeline: [base_image] + reference_images. EXIF orientation is corrected on every image, regardless of whether it came in via direct upload or the editor.""" pil_images = [] for item in images: if base_image is not None: try: img = base_image if isinstance(base_image, Image.Image) else Image.open(base_image) pil_images.append(fix_orientation(img).convert("RGB")) except Exception as e: print(f"Skipping invalid base image: {e}") for item in (reference_images or []): try: path_or_img = item[0] if isinstance(item, (tuple, list)) else item if isinstance(path_or_img, str): pil_images.append(Image.open(path_or_img).convert("RGB")) elif isinstance(path_or_img, Image.Image): pil_images.append(path_or_img.convert("RGB")) if isinstance(path_or_img, Image.Image): img = path_or_img elif isinstance(path_or_img, str): img = Image.open(path_or_img) else: img = Image.open(path_or_img.name) pil_images.append(Image.open(path_or_img.name).convert("RGB")) pil_images.append(fix_orientation(img).convert("RGB")) except Exception as e: print(f"Skipping invalid image: {e}") print(f"Skipping invalid reference image: {e}") return pil_images
def get_image_count_info(images): if not images: return "π· No images uploaded" count = len(images) if count == 1: return "π· 1 image uploaded (Picture 1 - Base)" elif count == 2: return "π· 2 images uploaded (Picture 1 - Base, Picture 2 - Face Source)" return f"π· {count} images uploaded"def fix_editor_orientation(editor_value): """Runs on upload into the Image Editor β corrects EXIF orientation on the background layer before the user starts cropping, so what they see in the crop box matches the actual pixel data.""" if not editor_value or editor_value.get("background") is None: return editor_value bg = editor_value["background"] if isinstance(bg, Image.Image): editor_value["background"] = fix_orientation(bg) return editor_value
def _editor_composite(editor_value): if not editor_value or editor_value.get("composite") is None: raise gr.Error("Upload and crop an image in the editor first.") composite = editor_value["composite"] if isinstance(composite, np.ndarray): composite = Image.fromarray(composite) return composite.convert("RGB")
def send_editor_to_base(editor_value): composite = _editor_composite(editor_value) gr.Info("Sent to Base Image") return composite
def send_editor_to_reference(editor_value, current_gallery): composite = _editor_composite(editor_value) current = list(current_gallery or []) current.append(composite) gr.Info("Added to Reference Images") return current
# ββ LoRA selection β update weight sliders + LoRA prompt display ββββββββββββββ
def update_weight_sliders(selected_titles):def update_weight_sliders(selected_titles, dynamic_loras): """ Given a list of selected LoRA titles, return updated visibility/label/value for each of the MAX_LORA_SLOTS pre-rendered sliders, plus an update for the2 unmodified lines The user's own prompt is never touched here β LoRA prompts are shown separately and appended at inference time. """ selected_styles = [get_style_by_title(t) for t in (selected_titles or []) if get_style_by_title(t)] selected_styles = [get_style_by_title(t, dynamic_loras) for t in (selected_titles or []) if get_style_by_title(t, dynamic_loras)] slider_updates = [] for i in range(MAX_LORA_SLOTS): if i < len(selected_styles):121 unmodified lines
def infer( input_images, base_image, reference_images, prompt, lora_prompt_text, custom_prompt_text,3 unmodified lines guidance_scale, steps, upscale_factor, dynamic_loras, *slider_values, progress=gr.Progress(track_tqdm=True)):7 unmodified lines if not isinstance(upscale_factor, str) or upscale_factor not in UPSCALE_MODELS: upscale_factor = "None"
if not input_images: raise gr.Error("Please upload at least one image.") if base_image is None: raise gr.Error("Please upload a base image.")
pil_images = process_gallery_images(input_images) pil_images = process_images(base_image, reference_images) if not pil_images: raise gr.Error("Could not process uploaded images.")
3 unmodified lines seed = random.randint(0, MAX_SEED)
# Collect LoRA metadata for logging before entering GPU active_styles = [get_style_by_title(t) for t in selected_titles if get_style_by_title(t) and get_style_by_title(t)["adapter_name"] is not None] active_styles = [get_style_by_title(t, dynamic_loras) for t in selected_titles if get_style_by_title(t, dynamic_loras) and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None] log_lora_titles = [s["title"] for s in active_styles] log_lora_weights = [float(w) for w in slider_values[:len(active_styles)]] log_lora_prompt = (lora_prompt_text or "").strip()2 unmodified lines try: image, seed, width, height = _infer_gpu( pil_images, prompt, lora_prompt_text, custom_prompt_text, selected_titles, seed, guidance_scale, steps, upscale_factor, seed, guidance_scale, steps, upscale_factor, dynamic_loras, *slider_values, progress=progress ) duration = time.perf_counter() - t023 unmodified lines guidance_scale, steps, upscale_factor, dynamic_loras, *slider_values, progress=gr.Progress(track_tqdm=True)):2 unmodified lines # Face-swap validation if "Best-Face-Swap" in selected_titles: if len(pil_images) < 2: raise gr.Error("Face Swap requires 2 images: Picture 1 (base) and Picture 2 (face source).") raise gr.Error("Face Swap requires 2 images: a Base image and one Reference image (used as the face source).") if len(pil_images) > 2: gr.Warning("Face Swap uses only the first 2 images.") gr.Warning("Face Swap uses only the Base image and the first Reference image.") pil_images = pil_images[:2]
# Build active adapter list (skip None) active_styles = [get_style_by_title(t) for t in selected_titles if get_style_by_title(t) and get_style_by_title(t)["adapter_name"] is not None] active_styles = [get_style_by_title(t, dynamic_loras) for t in selected_titles if get_style_by_title(t, dynamic_loras) and get_style_by_title(t, dynamic_loras)["adapter_name"] is not None] weights = list(slider_values[:len(active_styles)])
if not active_styles:72 unmodified lines
# ββ Dynamic LoRA loader βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def add_custom_lora(repo_id, weight_name, adapter_name): global DYNAMIC_LORA_COUNTERdef add_custom_lora(repo_id, weight_name, adapter_name, dynamic_loras_state): """ Adds a custom LoRA to *this session's* state only β other users never see it in their selector. The adapter_name attached to the shared pipe is still made globally unique (via a short random suffix) since the pipe object itself is one shared resource across all sessions. """ dynamic_loras = dict(dynamic_loras_state or {}) if not repo_id or not repo_id.strip(): return "Please enter a valid HuggingFace repo ID.", gr.update(), gr.update() return "Please enter a valid HuggingFace repo ID.", gr.update(), dynamic_loras repo_id = repo_id.strip() adapter_name = adapter_name.strip() if adapter_name and adapter_name.strip() else None requested_name = adapter_name.strip() if adapter_name and adapter_name.strip() else None try: from huggingface_hub import model_info info = model_info(repo_id)5 unmodified lines break if not actual_weight: available = [f.filename for f in info.siblings if f.filename.endswith(('.safetensors', '.bin'))] return f"No weight found. Available: {', '.join(available) or 'None'}", gr.update(), gr.update() if not adapter_name: DYNAMIC_LORA_COUNTER += 1 adapter_name = f"custom_{DYNAMIC_LORA_COUNTER}" else: adapter_name = "".join(c if c.isalnum() or c in "-_" else "_" for c in adapter_name) return f"No weight found. Available: {', '.join(available) or 'None'}", gr.update(), dynamic_loras
base_name = "".join(c if c.isalnum() or c in "-_" else "_" for c in requested_name) if requested_name else "custom"
static_names = {s["adapter_name"] for s in LORA_STYLES if s["adapter_name"]} final_adapter_name = f"{base_name}_{uuid.uuid4().hex[:6]}" while final_adapter_name in static_names or final_adapter_name in LOADED_ADAPTERS: final_adapter_name = f"{base_name}_{uuid.uuid4().hex[:6]}"
custom_style = { "image": "https://huggingface.co/spaces/prithivMLmods/FLUX.2-Klein-LoRA-Studio/resolve/main/examples/image.webp", "title": f"Custom: {adapter_name}", "adapter_name": adapter_name, "title": f"Custom: {base_name}", "adapter_name": final_adapter_name, "repo": repo_id, "weights": actual_weight, "default_prompt": None, "default_weight": 1.0, } DYNAMIC_LORAS[adapter_name] = custom_style new_choices = [s["title"] for s in get_selectable_styles()] return f"β
Added: {adapter_name} from {repo_id}", gr.update(choices=new_choices), gr.update(choices=new_choices) dynamic_loras[final_adapter_name] = custom_style new_choices = [s["title"] for s in get_selectable_styles(dynamic_loras)] return f"β
Added: {base_name} from {repo_id}", gr.update(choices=new_choices), dynamic_loras except Exception as e: return f"β Failed: {str(e)}", gr.update(), gr.update() return f"β Failed: {str(e)}", gr.update(), dynamic_loras
# ββ Custom Prompt manager βββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββββββββββ
55 unmodified linescss = """#col-container { margin: 0 auto; max-width: 980px; }#main-title h1 { font-size: 2.4em !important; }#input_gallery .grid-wrap { min-height: 200px }#reference_gallery .grid-wrap { min-height: 120px }.lora-weight-row { background: var(--block-background-fill); border-radius: 8px; padding: 4px 12px; margin-bottom: 4px; }"""
1 unmodified line # Per-session state β each user gets their own isolated copy, never shared across sessions custom_prompts_state = gr.State({}) custom_prompt_counter_state = gr.State(0) dynamic_loras_state = gr.State({}) # this session's custom HF LoRAs β never shared with other users
with gr.Column(elem_id="col-container"): _logging_on = os.environ.get("ENABLE_LOGGING", "No").strip().lower() == "yes"12 unmodified lines "stored data is automatically deleted. " "Always comply with HF and model Terms of Service.*" ) with gr.Row(equal_height=False): # ββ Left column ββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(scale=1): input_images = gr.Gallery( label="Upload Image(s)", type="filepath", columns=2, rows=1, height=260, allow_preview=True, elem_id="input_gallery", ) image_info = gr.Markdown("π· No images uploaded") size_info = gr.Markdown("*No image uploaded yet*")
prompt = gr.Text( label="Prompt", max_lines=3, placeholder="Describe the edit, or leave blank for style-only LoRAs", )
with gr.Tabs() as main_tabs: # ββ Generate tab ββββββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Tab("π¨ Generate", id="tab_generate"): with gr.Row(equal_height=False): # ββ Left column ββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(scale=1): base_image = gr.Image( label="Base Image", type="pil", sources=["upload", "clipboard"], height=260, elem_id="base_image", ) size_info = gr.Markdown("*No image uploaded yet*")
reference_images = gr.Gallery( label="Reference Image(s) β optional", type="filepath", columns=2, rows=1, height=140, allow_preview=True, elem_id="reference_gallery", ) reference_info = gr.Markdown("π· No reference images") gr.Markdown( "*For Face Swap, the first Reference image is used as the face source.*" )
prompt = gr.Text( label="Prompt", max_lines=3, placeholder="Describe the edit, or leave blank for style-only LoRAs", )
# Read-only display for LoRA default prompts β shown when any # selected LoRA has a default prompt. Combined with user prompt # at inference time; never overwrites what the user typed. lora_prompt_display = gr.Textbox( label="LoRA Default Prompts (auto-appended)", info="These prompts come from your selected LoRAs and are appended to your prompt above during generation.", interactive=False, visible=False, lines=3, # Read-only display for LoRA default prompts β shown when any # selected LoRA has a default prompt. Combined with user prompt # at inference time; never overwrites what the user typed. lora_prompt_display = gr.Textbox( label="LoRA Default Prompts (auto-appended)", info="These prompts come from your selected LoRAs and are appended to your prompt above during generation.", interactive=False, visible=False, lines=3, )
# Read-only display for active custom prompts β shown when any # saved custom prompt is ticked in the Custom Prompts accordion. custom_prompt_display = gr.Textbox( label="Custom Prompts (auto-appended)", info="These are your selected saved prompts, appended alongside LoRA prompts during generation.", interactive=False, visible=False, lines=3, )
run_button = gr.Button("βΆ Generate", variant="primary", size="lg")
with gr.Accordion("βοΈ Advanced Settings", open=False): seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.1, value=1.0, visible=MODEL_VARIANT != "9B-KV") steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=4, step=1) upscale_factor = gr.Dropdown( label="Upscale model", info="Applied after generation. UltraSharp / Remacri are sharper than RealESRGAN for clean photo inputs.", choices=list(UPSCALE_MODELS.keys()), value="None", )
# ββ Right column βββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(scale=1): output_image = gr.Image(label="Output", interactive=False, format="png", height=320) used_seed = gr.Textbox( label="π± Seed used", info="Re-enter this seed in Advanced Settings to reproduce the result exactly.", interactive=False, visible=True, max_lines=1, )
# ββ LoRA selector βββββββββββββββββββββββββββββββββββββββββββββββββ gr.Markdown("### π¨ Select LoRA(s)") lora_selector = gr.CheckboxGroup( choices=[s["title"] for s in get_selectable_styles({})], value=[], label="Active LoRAs β tick one or more", )
# Read-only display for active custom prompts β shown when any # saved custom prompt is ticked in the Custom Prompts accordion. custom_prompt_display = gr.Textbox( label="Custom Prompts (auto-appended)", info="These are your selected saved prompts, appended alongside LoRA prompts during generation.", interactive=False, visible=False, lines=3, )
run_button = gr.Button("βΆ Generate", variant="primary", size="lg")
with gr.Accordion("βοΈ Advanced Settings", open=False): seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0) randomize_seed = gr.Checkbox(label="Randomize seed", value=True) guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.1, value=1.0, visible=MODEL_VARIANT != "9B-KV") steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=4, step=1) upscale_factor = gr.Dropdown( label="Upscale model", info="Applied after generation. UltraSharp / Remacri are sharper than RealESRGAN for clean photo inputs.", choices=list(UPSCALE_MODELS.keys()), value="None", # ββ Weight sliders (pre-rendered, shown/hidden dynamically) βββββββ gr.Markdown("#### Weights for selected LoRAs") weight_sliders = [] with gr.Group(): for i in range(MAX_LORA_SLOTS): with gr.Row(elem_classes="lora-weight-row"): s = gr.Slider( minimum=0.0, maximum=2.0, step=0.05, value=1.0, label=f"LoRA slot {i+1}", visible=False, interactive=True, ) weight_sliders.append(s)
# ββ Dynamic HuggingFace loader βββββββββββββββββββββββββββββββββββββ with gr.Accordion("β Load Custom LoRA from HuggingFace", open=False): gr.Markdown("Add any FLUX.2-Klein-compatible LoRA from [HuggingFace Hub](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.2-klein-9B). " "*Added LoRAs are only visible in your own session β other visitors won't see them.*") with gr.Row(): lora_repo_id = gr.Textbox(label="Repo ID", placeholder="username/repo-name") with gr.Row(): lora_weight_name = gr.Textbox(label="Weight filename (optional)", placeholder="pytorch_lora_weights.safetensors") lora_adapter_name = gr.Textbox(label="Adapter name (optional)", placeholder="my-lora") with gr.Row(): add_lora_btn = gr.Button("Add LoRA", variant="primary") lora_status = gr.Textbox(label="Status", interactive=False)
# ββ Custom Prompt library ββββββββββββββββββββββββββββββββββββββββββ with gr.Accordion("π Custom Prompts", open=False): gr.Markdown( "Save reusable prompt snippets for this session. " "Tick any saved prompt below and it will be appended to your generation alongside any LoRA prompts. " "*Prompts are stored in memory β they reset when the Space restarts or the worker recycles.*" )
# ββ Right column βββββββββββββββββββββββββββββββββββββββββββββββββ with gr.Column(scale=1): output_image = gr.Image(label="Output", interactive=False, format="png", height=320) used_seed = gr.Textbox( label="π± Seed used", info="Re-enter this seed in Advanced Settings to reproduce the result exactly.", interactive=False, visible=True, max_lines=1, )
# ββ LoRA selector βββββββββββββββββββββββββββββββββββββββββββββββββββββ gr.Markdown("### π¨ Select LoRA(s)") lora_selector = gr.CheckboxGroup( choices=[s["title"] for s in get_selectable_styles()], value=[], label="Active LoRAs β tick one or more", custom_prompt_selector = gr.CheckboxGroup( choices=[], value=[], label="Saved prompts β tick to append to generation", )
# ββ Weight sliders (pre-rendered, shown/hidden dynamically) βββββββββββ gr.Markdown("#### Weights for selected LoRAs") weight_sliders = [] with gr.Group(): for i in range(MAX_LORA_SLOTS): with gr.Row(elem_classes="lora-weight-row"): s = gr.Slider( minimum=0.0, maximum=2.0, step=0.05, value=1.0, label=f"LoRA slot {i+1}", visible=False, interactive=True, ) weight_sliders.append(s)
# ββ Dynamic HuggingFace loader ββββββββββββββββββββββββββββββββββββββββ with gr.Accordion("β Load Custom LoRA from HuggingFace", open=False): gr.Markdown("Add any FLUX.2-Klein-compatible LoRA from [HuggingFace Hub](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.2-klein-9B)") with gr.Row(): lora_repo_id = gr.Textbox(label="Repo ID", placeholder="username/repo-name") with gr.Row(): lora_weight_name = gr.Textbox(label="Weight filename (optional)", placeholder="pytorch_lora_weights.safetensors") lora_adapter_name = gr.Textbox(label="Adapter name (optional)", placeholder="my-lora") with gr.Row(): add_lora_btn = gr.Button("Add LoRA", variant="primary") lora_status = gr.Textbox(label="Status", interactive=False)
# ββ Custom Prompt library βββββββββββββββββββββββββββββββββββββββββββββ with gr.Accordion("π Custom Prompts", open=False): gr.Markdown( "Save reusable prompt snippets for this session. " "Tick any saved prompt below and it will be appended to your generation alongside any LoRA prompts. " "*Prompts are stored in memory β they reset when the Space restarts or the worker recycles.*" )
custom_prompt_selector = gr.CheckboxGroup( choices=[], value=[], label="Saved prompts β tick to append to generation", )
with gr.Row(): prompt_name_input = gr.Textbox( label="Name", placeholder="e.g. Skin detail enhancer", scale=1, ) with gr.Row(): prompt_text_input = gr.Textbox( label="Prompt text", placeholder="Enter the prompt snippet you want to save and reuseβ¦", lines=4,
with gr.Row(): prompt_name_input = gr.Textbox( label="Name", placeholder="e.g. Skin detail enhancer", scale=1, ) with gr.Row(): prompt_text_input = gr.Textbox( label="Prompt text", placeholder="Enter the prompt snippet you want to save and reuseβ¦", lines=4, ) with gr.Row(): add_prompt_btn = gr.Button("πΎ Save Prompt", variant="primary") prompt_status = gr.Textbox(label="Status", interactive=False, scale=2) with gr.Row(): delete_prompt_name = gr.Dropdown( label="Delete a saved prompt", choices=[], value=None, interactive=True, scale=2, ) delete_prompt_btn = gr.Button("ποΈ Delete", variant="secondary", scale=1)
gr.Markdown("*Experimental space β results may vary when combining multiple LoRAs.*")
# ββ Crop / Fix Image tab βββββββββββββββββββββββββββββββββββββββββββββ with gr.Tab("βοΈ Crop / Fix Image", id="tab_editor"): gr.Markdown( "Upload an image to crop it, then send the result to the Base Image or add it as a " "Reference image on the Generate tab. EXIF orientation (the most common cause of " "images coming out sideways) is corrected automatically as soon as you upload here." ) with gr.Row(): add_prompt_btn = gr.Button("πΎ Save Prompt", variant="primary") prompt_status = gr.Textbox(label="Status", interactive=False, scale=2) with gr.Row(): delete_prompt_name = gr.Dropdown( label="Delete a saved prompt", choices=[], value=None, interactive=True, scale=2, editor = gr.ImageEditor( label="Editor", type="pil", transforms=["crop"], brush=False, eraser=False, layers=False, sources=["upload", "clipboard"], height=420, ) delete_prompt_btn = gr.Button("ποΈ Delete", variant="secondary", scale=1)
gr.Markdown("*Experimental space β results may vary when combining multiple LoRAs.*") with gr.Row(): send_to_base_btn = gr.Button("β Send to Base Image", variant="primary") send_to_ref_btn = gr.Button("β Add to Reference Images")
# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
input_images.change( fn=on_gallery_change, inputs=[input_images], outputs=[image_info, size_info], base_image.change( fn=on_base_image_change, inputs=[base_image], outputs=[size_info], )
reference_images.change( fn=on_reference_change, inputs=[reference_images], outputs=[reference_info], )
lora_selector.change( fn=update_weight_sliders, inputs=[lora_selector], inputs=[lora_selector, dynamic_loras_state], outputs=weight_sliders + [lora_prompt_display], )
add_lora_btn.click( fn=add_custom_lora, inputs=[lora_repo_id, lora_weight_name, lora_adapter_name], outputs=[lora_status, lora_selector, lora_selector], inputs=[lora_repo_id, lora_weight_name, lora_adapter_name, dynamic_loras_state], outputs=[lora_status, lora_selector, dynamic_loras_state], )
add_prompt_btn.click(16 unmodified lines
run_button.click( fn=infer, inputs=[input_images, prompt, lora_prompt_display, custom_prompt_display, lora_selector, seed, randomize_seed, guidance_scale, steps, upscale_factor] + weight_sliders, inputs=[base_image, reference_images, prompt, lora_prompt_display, custom_prompt_display, lora_selector, seed, randomize_seed, guidance_scale, steps, upscale_factor, dynamic_loras_state] + weight_sliders, outputs=[output_image, used_seed], )
# ββ Image Editor tab wiring βββββββββββββββββββββββββββββββββββββββββββββ editor.upload( fn=fix_editor_orientation, inputs=[editor], outputs=[editor], )
send_to_base_btn.click( fn=send_editor_to_base, inputs=[editor], outputs=[base_image], ).then( fn=on_base_image_change, inputs=[base_image], outputs=[size_info], ).then( fn=lambda: gr.Tabs(selected="tab_generate"), outputs=[main_tabs], )
send_to_ref_btn.click( fn=send_editor_to_reference, inputs=[editor, reference_images], outputs=[reference_images], ).then( fn=on_reference_change, inputs=[reference_images], outputs=[reference_info], ).then( fn=lambda: gr.Tabs(selected="tab_generate"), outputs=[main_tabs], )
if __name__ == "__main__": demo.queue().launch(css=css, theme=orange_red_theme, mcp_server=True, ssr_mode=False, show_error=True)app.py+340-210