Update app.py
Browse files60 unmodified lines6162636465666768697071727374757677787980818283848519 unmodified lines1051061071081091101111121131141151161171181196 unmodified lines12612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815921 unmodified lines1811821831841851861871881891901911921931941951 unmodified line19719819920020120220320420520620720820921021121225 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727860 unmodified linesorange_red_theme = OrangeRedTheme()MAX_SEED = np.iinfo(np.int32).max# Define LoRA configurations with images for the gallery# Index 0 is always Noneloras = [{"image": "examples/1.jpg", # Placeholder for None"title": "None","repo": None,"weights": None,"adapter_name": None},{"image": "examples/2.jpg", # Thumbnail for Klein-Delight"title": "Klein-Delight-Style","repo": "linoyts/Flux2-Klein-Delight-LoRA","weights": "pytorch_lora_weights.safetensors","adapter_name": "klein-delight"}]LOADED_ADAPTERS = set()print("Loading FLUX.2 Klein 9B model base...")19 unmodified linesreturn new_width, new_heightdef update_selection(evt: gr.SelectData):"""Updates the selected index based on gallery click."""return evt.index@spaces.GPUdef infer(input_image,prompt,selected_index,seed=42,randomize_seed=True,guidance_scale=1.0,6 unmodified linesif not input_image:raise gr.Error("Please upload an image to apply a style to.")# Get LoRA details from the list based on index# Default to 0 (None) if something goes wrongif selected_index is None:selected_index = 0current_lora = loras[selected_index]adapter_name = current_lora["adapter_name"]if adapter_name is None:print("Selection is None. Disabling LoRA adapters.")pipe.disable_lora()else:if adapter_name not in LOADED_ADAPTERS:print(f"--- Downloading and Loading Adapter: {current_lora['title']} ---")try:pipe.load_lora_weights(current_lora["repo"],weight_name=current_lora["weights"],adapter_name=adapter_name)LOADED_ADAPTERS.add(adapter_name)except Exception as e:raise gr.Error(f"Failed to load adapter {current_lora['title']}: {e}")else:print(f"--- Adapter {current_lora['title']} is already loaded. ---")print(f"Activating LoRA: {adapter_name}")pipe.set_adapters([adapter_name], adapter_weights=[1.0])if randomize_seed:seed = random.randint(0, MAX_SEED)21 unmodified linestorch.cuda.empty_cache()@spaces.GPUdef infer_example(input_image, prompt):# Example inference defaults to None (Index 0) for simplicity in this viewif input_image is None:return None, 0image, seed = infer(input_image=input_image,prompt=prompt,selected_index=0,seed=0,randomize_seed=True,guidance_scale=1.0,1 unmodified line)return image, seedcss="""#col-container { margin: 0 auto; max-width: 960px; }#main-title h1 { font-size: 2.2em !important; }#gallery { height: auto; }"""with gr.Blocks() as demo:# State to hold the selected LoRA index, default is 0 (None)selected_index = gr.State(0)with gr.Column(elem_id="col-container"):gr.Markdown("# **FLUX.2-Klein-LoRA-Studio**", elem_id="main-title")gr.Markdown("Perform diverse image edits using specialized [LoRAs](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.2-klein-9B) adapters for the [FLUX.2-Klein-Distilled](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) model.")25 unmodified lineswith gr.Column():output_image = gr.Image(label="Output Image", interactive=False, format="png", height=358)used_seed = gr.Textbox(label="Used Seed", interactive=False, visible=False)# Replaced Dropdown with Gallerygr.Markdown("### Choose Edit Style")gallery = gr.Gallery([(item["image"], item["title"]) for item in loras],label="Style Gallery",allow_preview=False,columns=2,elem_id="gallery",selected_index=0)gr.Examples(examples=[["examples/2.jpg", "Relight the image to remove all existing lighting conditions and replace them with neutral, uniform illumination. Apply soft, evenly distributed lighting with no directional shadows, no harsh highlights, and no dramatic contrast. Maintain the original identity of all subjects exactly—preserve facial structure, skin tone, proportions, expressions, hair, clothing, and textures. Do not alter pose, camera angle, background geometry, or image composition. Lighting should appear balanced, and studio-neutral, similar to diffuse overcast or a soft lightbox setup. Ensure consistent exposure across the entire image with realistic depth and subtle shading only where necessary for form."],["examples/1.jpg", "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed by prithivMLmods preserving realistic texture and details"],],inputs=[input_image, prompt],outputs=[output_image, used_seed],fn=infer_example,cache_examples=False,)gr.Markdown("[*](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B)This is still an experimental Space for FLUX.2-Klein-9B. More adapters will be added soon.")# Event Wiringgallery.select(fn=update_selection,inputs=None,outputs=selected_index)run_button.click(fn=infer,inputs=[input_image, prompt, selected_index, seed, randomize_seed, guidance_scale, steps],outputs=[output_image, used_seed])60 unmodified lines61626364656667686970717273747576777879808119 unmodified lines1011021031041051061071081091101116 unmodified lines11811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915021 unmodified lines1721731741751761771781791801811821831841851 unmodified line18718818919019119219319419519619719819920020120220325 unmodified lines22923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927060 unmodified linesorange_red_theme = OrangeRedTheme()MAX_SEED = np.iinfo(np.int32).maxADAPTER_SPECS = {"Klein-Delight-Style": {"repo": "linoyts/Flux2-Klein-Delight-LoRA","weights": "pytorch_lora_weights.safetensors","adapter_name": "klein-delight"},}GALLERY_ITEMS = [("examples/1.jpg", "None"),("examples/2.jpg", "Klein-Delight-Style")]GALLERY_KEYS = ["None", "Klein-Delight-Style"]LOADED_ADAPTERS = set()print("Loading FLUX.2 Klein 9B model base...")19 unmodified linesreturn new_width, new_height@spaces.GPUdef infer(input_image,prompt,lora_adapter,seed=42,randomize_seed=True,guidance_scale=1.0,6 unmodified linesif not input_image:raise gr.Error("Please upload an image to apply a style to.")if lora_adapter == "None" or lora_adapter is None:print("Selection is None. Disabling LoRA adapters.")pipe.disable_lora()else:spec = ADAPTER_SPECS.get(lora_adapter)if spec:adapter_name = spec["adapter_name"]if adapter_name not in LOADED_ADAPTERS:print(f"--- Downloading and Loading Adapter: {lora_adapter} ---")try:pipe.load_lora_weights(spec["repo"],weight_name=spec["weights"],adapter_name=adapter_name)LOADED_ADAPTERS.add(adapter_name)except Exception as e:raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}")else:print(f"--- Adapter {lora_adapter} is already loaded. ---")print(f"Activating LoRA: {adapter_name}")pipe.set_adapters([adapter_name], adapter_weights=[1.0])else:print("Adapter not found in specs. Disabling LoRA.")pipe.disable_lora()if randomize_seed:seed = random.randint(0, MAX_SEED)21 unmodified linestorch.cuda.empty_cache()@spaces.GPUdef infer_example(input_image, prompt, lora_adapter):if input_image is None:return None, 0image, seed = infer(input_image=input_image,prompt=prompt,lora_adapter=lora_adapter,seed=0,randomize_seed=True,guidance_scale=1.0,1 unmodified line)return image, seeddef update_gallery_selection(evt: gr.SelectData):if evt.index < len(GALLERY_KEYS):return GALLERY_KEYS[evt.index]return "None"css="""#col-container { margin: 0 auto; max-width: 960px; }#main-title h1 { font-size: 2.2em !important; }"""with gr.Blocks() as demo:with gr.Column(elem_id="col-container"):gr.Markdown("# **FLUX.2-Klein-LoRA-Studio**", elem_id="main-title")gr.Markdown("Perform diverse image edits using specialized [LoRAs](https://huggingface.co/models?other=base_model:adapter:black-forest-labs/FLUX.2-klein-9B) adapters for the [FLUX.2-Klein-Distilled](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B) model.")25 unmodified lineswith gr.Column():output_image = gr.Image(label="Output Image", interactive=False, format="png", height=358)used_seed = gr.Textbox(label="Used Seed", interactive=False, visible=False)gr.Markdown("### Edit Style Gallery")lora_gallery = gr.Gallery(label="Choose Editing Style",value=GALLERY_ITEMS,selected_index=0,allow_preview=False,columns=2,height=220)# Hidden textbox to store selection for the inference functionlora_adapter_state = gr.Textbox(value="None", visible=False)# Event: Update hidden state when gallery item is selectedlora_gallery.select(fn=update_gallery_selection,inputs=None,outputs=lora_adapter_state)gr.Examples(examples=[["examples/2.jpg", "Relight the image to remove all existing lighting conditions and replace them with neutral, uniform illumination. Apply soft, evenly distributed lighting with no directional shadows, no harsh highlights, and no dramatic contrast. Maintain the original identity of all subjects exactly—preserve facial structure, skin tone, proportions, expressions, hair, clothing, and textures. Do not alter pose, camera angle, background geometry, or image composition. Lighting should appear balanced, and studio-neutral, similar to diffuse overcast or a soft lightbox setup. Ensure consistent exposure across the entire image with realistic depth and subtle shading only where necessary for form.", "Klein-Delight-Style"],["examples/1.jpg", "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed by prithivMLmods preserving realistic texture and details", "None"],],inputs=[input_image, prompt, lora_adapter_state],outputs=[output_image, used_seed],fn=infer_example,cache_examples=False,)gr.Markdown("[*](https://huggingface.co/black-forest-labs/FLUX.2-klein-9B)This is still an experimental Space for FLUX.2-Klein-9B. More adapters will be added soon.")run_button.click(fn=infer,inputs=[input_image, prompt, lora_adapter_state, seed, randomize_seed, guidance_scale, steps],outputs=[output_image, used_seed])
app.py+61-69