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 lines567891011212 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025125215 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183192 unmodified lines322323324325326327328121 unmodified lines4504514524534544554563 unmodified lines4604614624634644657 unmodified lines4734744754764774784794804814823 unmodified lines4864874884894904914924932 unmodified lines49649749849950050150223 unmodified lines5265275285295305312 unmodified lines53453553653753853954054154254354454554672 unmodified lines6196206216226236246256266276286296305 unmodified lines63663763863964064164264364464564664764864965065165265365465565665765865966066155 unmodified lines7177187197207217227231 unmodified line72572672772872973012 unmodified lines74374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590616 unmodified lines9239249259269279289299309314 unmodified linesimport spacesimport torchimport randomfrom PIL import Imagefrom typing import Iterableimport timeimport threading212 unmodified lines},]LOADED_ADAPTERS = set()DYNAMIC_LORAS = {}DYNAMIC_LORA_COUNTER = 0def get_all_styles():all_styles = list(LORA_STYLES)for dynamic_lora in DYNAMIC_LORAS.values():all_styles.append(dynamic_lora)return all_stylesdef get_selectable_styles():"""Return all styles except 'None' for the checkbox selector."""return [s for s in get_all_styles() if s["adapter_name"] is not None]def get_style_by_title(title):for style in get_all_styles():if style["title"] == title:return stylereturn Nonedef get_style_by_adapter_name(adapter_name):for style in get_all_styles():if style["adapter_name"] == adapter_name:return stylereturn None15 unmodified lines# Keep old name as alias so nothing inside infer breaks if called directlyupdate_dimensions_on_upload = compute_base_dimensionsdef 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*"try:first = images[0]path = first[0] if isinstance(first, (tuple, list)) else firstimg = Image.open(path if isinstance(path, str) else path.name)orig_w, orig_h = img.sizebase_w, base_h = compute_base_dimensions(img)size_text = f"Input: **{orig_w} Γ {orig_h}** px β Output (pre-upscale): **{base_w} Γ {base_h}** px"return count_info, size_textexcept Exception as e:return count_info, f"*Could not read dimensions: {e}*"def process_gallery_images(images):if not images:return []pil_images = []for item in images:try:path_or_img = item[0] if isinstance(item, (tuple, list)) else itemif 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"))else:pil_images.append(Image.open(path_or_img.name).convert("RGB"))except Exception as e:print(f"Skipping invalid image: {e}")return pil_imagesdef 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"# ββ LoRA selection β update weight sliders + LoRA prompt display ββββββββββββββdef update_weight_sliders(selected_titles):"""Given a list of selected LoRA titles, return updated visibility/label/valuefor each of the MAX_LORA_SLOTS pre-rendered sliders, plus an update for the2 unmodified linesThe user's own prompt is never touched here β LoRA prompts are shownseparately and appended at inference time."""selected_styles = [get_style_by_title(t) for t in (selected_titles or []) if get_style_by_title(t)]slider_updates = []for i in range(MAX_LORA_SLOTS):if i < len(selected_styles):121 unmodified linesdef infer(input_images,prompt,lora_prompt_text,custom_prompt_text,3 unmodified linesguidance_scale,steps,upscale_factor,*slider_values,progress=gr.Progress(track_tqdm=True)):7 unmodified linesif 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.")pil_images = process_gallery_images(input_images)if not pil_images:raise gr.Error("Could not process uploaded images.")3 unmodified linesseed = random.randint(0, MAX_SEED)# Collect LoRA metadata for logging before entering GPUactive_styles = [get_style_by_title(t) for t in selected_titlesif get_style_by_title(t) and get_style_by_title(t)["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 linestry:image, seed, width, height = _infer_gpu(pil_images, prompt, lora_prompt_text, custom_prompt_text, selected_titles,seed, guidance_scale, steps, upscale_factor,*slider_values, progress=progress)duration = time.perf_counter() - t023 unmodified linesguidance_scale,steps,upscale_factor,*slider_values,progress=gr.Progress(track_tqdm=True)):2 unmodified lines# Face-swap validationif "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).")if len(pil_images) > 2:gr.Warning("Face Swap uses only the first 2 images.")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]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_COUNTERif not repo_id or not repo_id.strip():return "Please enter a valid HuggingFace repo ID.", gr.update(), gr.update()repo_id = repo_id.strip()adapter_name = adapter_name.strip() if adapter_name and adapter_name.strip() else Nonetry:from huggingface_hub import model_infoinfo = model_info(repo_id)5 unmodified linesbreakif 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 += 1adapter_name = f"custom_{DYNAMIC_LORA_COUNTER}"else:adapter_name = "".join(c if c.isalnum() or c in "-_" else "_" for c in adapter_name)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,"repo": repo_id,"weights": actual_weight,"default_prompt": None,"default_weight": 1.0,}DYNAMIC_LORAS[adapter_name] = custom_stylenew_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)except Exception as e:return f"β Failed: {str(e)}", gr.update(), gr.update()# ββ 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 }.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 sessionscustom_prompts_state = gr.State({})custom_prompt_counter_state = gr.State(0)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",)# 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",)# ββ 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():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.*")# ββ Event wiring ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββinput_images.change(fn=on_gallery_change,inputs=[input_images],outputs=[image_info, size_info],)lora_selector.change(fn=update_weight_sliders,inputs=[lora_selector],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],)add_prompt_btn.click(16 unmodified linesrun_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,outputs=[output_image, used_seed],)if __name__ == "__main__":demo.queue().launch(css=css, theme=orange_red_theme, mcp_server=True, ssr_mode=False, show_error=True)4 unmodified lines56789101112212 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625715 unmodified lines2732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653662 unmodified lines369370371372373374375121 unmodified lines4974984995005015025035043 unmodified lines5085095105115125135147 unmodified lines5225235245255265275285295305313 unmodified lines5355365375385395405415422 unmodified lines54554654754854955055123 unmodified lines5755765775785795805812 unmodified lines58458558658758858959059159259359459559672 unmodified lines6696706716726736746756766776786796806816826836846856865 unmodified lines69269369469569669769869970070170270370470570670770870971071171271371471571671771871972055 unmodified lines7767777787797807817821 unmodified line78478578678778878979012 unmodified lines803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100916 unmodified lines1026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010614 unmodified linesimport spacesimport torchimport randomimport uuidfrom 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()def get_all_styles(dynamic_loras):all_styles = list(LORA_STYLES)for dynamic_lora in (dynamic_loras or {}).values():all_styles.append(dynamic_lora)return all_stylesdef get_selectable_styles(dynamic_loras):"""Return all styles except 'None' for the checkbox selector."""return [s for s in get_all_styles(dynamic_loras) if s["adapter_name"] is not None]def get_style_by_title(title, dynamic_loras):for style in get_all_styles(dynamic_loras):if style["title"] == title:return stylereturn Nonedef get_style_by_adapter_name(adapter_name, dynamic_loras):for style in get_all_styles(dynamic_loras):if style["adapter_name"] == adapter_name:return stylereturn None15 unmodified lines# Keep old name as alias so nothing inside infer breaks if called directlyupdate_dimensions_on_upload = compute_base_dimensionsdef fix_orientation(img):"""Correct EXIF orientation in-place (returns a new image).Browsers/OS viewers respect the EXIF orientation tag, but PIL does notapply it by default β so an image can *look* correctly orientedeverywhere you view it while the actual pixel data fed to the model isrotated 90/180/270Β°. This normalises the pixels to match what you see."""if img is None:return Nonereturn 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:pil_img = img if isinstance(img, Image.Image) else Image.open(img)orig_w, orig_h = pil_img.sizebase_w, base_h = compute_base_dimensions(pil_img)return f"Input: **{orig_w} Γ {orig_h}** px β Output (pre-upscale): **{base_w} Γ {base_h}** px"except Exception as e:return f"*Could not read dimensions: {e}*"def on_reference_change(images):"""Update the reference image count info when the gallery changes."""if not images: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 everyimage, regardless of whether it came in via direct upload or the editor."""pil_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 itemif isinstance(path_or_img, Image.Image):img = path_or_imgelif isinstance(path_or_img, str):img = Image.open(path_or_img)else:img = Image.open(path_or_img.name)pil_images.append(fix_orientation(img).convert("RGB"))except Exception as e:print(f"Skipping invalid reference image: {e}")return pil_imagesdef fix_editor_orientation(editor_value):"""Runs on upload into the Image Editor β corrects EXIF orientation onthe background layer before the user starts cropping, so what they seein the crop box matches the actual pixel data."""if not editor_value or editor_value.get("background") is None:return editor_valuebg = editor_value["background"]if isinstance(bg, Image.Image):editor_value["background"] = fix_orientation(bg)return editor_valuedef _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 compositedef 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, dynamic_loras):"""Given a list of selected LoRA titles, return updated visibility/label/valuefor each of the MAX_LORA_SLOTS pre-rendered sliders, plus an update for the2 unmodified linesThe user's own prompt is never touched here β LoRA prompts are shownseparately and appended at inference time."""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 linesdef infer(base_image,reference_images,prompt,lora_prompt_text,custom_prompt_text,3 unmodified linesguidance_scale,steps,upscale_factor,dynamic_loras,*slider_values,progress=gr.Progress(track_tqdm=True)):7 unmodified linesif not isinstance(upscale_factor, str) or upscale_factor not in UPSCALE_MODELS:upscale_factor = "None"if base_image is None:raise gr.Error("Please upload a base image.")pil_images = process_images(base_image, reference_images)if not pil_images:raise gr.Error("Could not process uploaded images.")3 unmodified linesseed = random.randint(0, MAX_SEED)# Collect LoRA metadata for logging before entering GPUactive_styles = [get_style_by_title(t, dynamic_loras) for t in selected_titlesif 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 linestry:image, seed, width, height = _infer_gpu(pil_images, prompt, lora_prompt_text, custom_prompt_text, selected_titles,seed, guidance_scale, steps, upscale_factor, dynamic_loras,*slider_values, progress=progress)duration = time.perf_counter() - t023 unmodified linesguidance_scale,steps,upscale_factor,dynamic_loras,*slider_values,progress=gr.Progress(track_tqdm=True)):2 unmodified lines# Face-swap validationif "Best-Face-Swap" in selected_titles:if len(pil_images) < 2: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 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, 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, dynamic_loras_state):"""Adds a custom LoRA to *this session's* state only β other users never seeit in their selector. The adapter_name attached to the shared pipe isstill made globally unique (via a short random suffix) since the pipeobject 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(), dynamic_lorasrepo_id = repo_id.strip()requested_name = adapter_name.strip() if adapter_name and adapter_name.strip() else Nonetry:from huggingface_hub import model_infoinfo = model_info(repo_id)5 unmodified linesbreakif 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(), dynamic_lorasbase_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: {base_name}","adapter_name": final_adapter_name,"repo": repo_id,"weights": actual_weight,"default_prompt": None,"default_weight": 1.0,}dynamic_loras[final_adapter_name] = custom_stylenew_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_lorasexcept Exception as e: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; }#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 sessionscustom_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 userswith 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.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 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",)# ββ 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.*")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():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.")editor = gr.ImageEditor(label="Editor",type="pil",transforms=["crop"],brush=False,eraser=False,layers=False,sources=["upload", "clipboard"],height=420,)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 ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ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, 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, dynamic_loras_state],outputs=[lora_status, lora_selector, dynamic_loras_state],)add_prompt_btn.click(16 unmodified linesrun_button.click(fn=infer,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