File size: 22,548 Bytes
4c4a3dc 11f6d56 4c4a3dc 76c1a5e 43a9297 e3bdb7e 4c4a3dc 76c1a5e 43a9297 76c1a5e c8f8e23 4c4a3dc 0e5aeb3 e3bdb7e 95207fd b320ea8 e3bdb7e 0e5aeb3 e3bdb7e b320ea8 e3bdb7e c8cf5ad 0e5aeb3 43a6736 0e5aeb3 90e450f 1b27151 8405b64 f913f65 8405b64 1b27151 14caa87 c8cf5ad 71e7589 c8cf5ad 76c1a5e 0fa25d5 76c1a5e c8cf5ad 76c1a5e c8cf5ad 4c4a3dc 6dd3fd8 44ace3b 71e7589 f5d20f9 71e7589 44ace3b f5d20f9 e3bdb7e 44ace3b 71e7589 0e5aeb3 44ace3b f5d20f9 44ace3b 0e5aeb3 95207fd 76c1a5e c8cf5ad 6dd3fd8 c8cf5ad 44ace3b c8cf5ad 6dd3fd8 2095b98 44ace3b e3bdb7e 0e5aeb3 e3bdb7e d950e96 368eb22 e3bdb7e 90e450f e3bdb7e c8cf5ad d950e96 43a9297 6dd3fd8 43a9297 c8cf5ad 6dd3fd8 c8cf5ad 6dd3fd8 c8cf5ad d950e96 c8cf5ad 76c1a5e f5d20f9 6dd3fd8 44ace3b 6dd3fd8 44ace3b c8cf5ad 6dd3fd8 c8cf5ad 44ace3b be17096 c8cf5ad 43a9297 4c4a3dc 6dd3fd8 2095b98 a263337 6dd3fd8 4c4a3dc 9fbd325 4c4a3dc 843f194 0429449 43a9297 44ace3b e3bdb7e 2095b98 6dd3fd8 e013dd2 6dd3fd8 2095b98 0e5aeb3 2095b98 b3de007 e013dd2 2095b98 c213a7d b3de007 2095b98 e3bdb7e 76c1a5e 2095b98 f5d20f9 2095b98 90e450f b320ea8 90e450f 71e7589 e3bdb7e 71e7589 e3bdb7e 90878b9 e3bdb7e 95207fd 71e7589 0e5aeb3 14caa87 44ace3b 33b15ae 44ace3b a364fd1 44ace3b 1b27151 14caa87 f5d20f9 14caa87 6dd3fd8 14caa87 2095b98 0e5aeb3 e3bdb7e 44ace3b f5d20f9 44ace3b f5d20f9 44ace3b f5d20f9 e3bdb7e 4c4a3dc f5d20f9 76c1a5e 4c4a3dc 246b4a7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 | import os
import gc
import gradio as gr
import numpy as np
import spaces
import torch
import random
from PIL import Image
from typing import Iterable
from diffusers import Flux2KleinPipeline
from diffusers.utils import load_image
from huggingface_hub import hf_hub_download
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
from gradio.themes import Soft
from gradio.themes.utils import colors, fonts, sizes
colors.orange_red = colors.Color(
name="orange_red", c50="#FFF0E5", c100="#FFE0CC", c200="#FFC299", c300="#FFA366",
c400="#FF8533", c500="#FF4500", c600="#E63E00", c700="#CC3700", c800="#B33000",
c900="#992900", c950="#802200",
)
class OrangeRedTheme(Soft):
def __init__(
self, *, primary_hue: colors.Color | str = colors.gray,
secondary_hue: colors.Color | str = colors.orange_red,
neutral_hue: colors.Color | str = colors.slate, text_size: sizes.Size | str = sizes.text_lg,
font: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
),
font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
),
):
super().__init__(
primary_hue=primary_hue, secondary_hue=secondary_hue, neutral_hue=neutral_hue,
text_size=text_size, font=font, font_mono=font_mono,
)
super().set(
background_fill_primary="*primary_50",
background_fill_primary_dark="*primary_900",
body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
button_primary_text_color="white",
button_primary_text_color_hover="white",
button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
slider_color="*secondary_500",
slider_color_dark="*secondary_600",
block_title_text_weight="600", block_border_width="3px",
block_shadow="*shadow_drop_lg", button_primary_shadow="*shadow_drop_lg",
button_large_padding="11px", color_accent_soft="*primary_100",
block_label_background_fill="*primary_200",
)
orange_red_theme = OrangeRedTheme()
MAX_SEED = np.iinfo(np.int32).max
# Face Swap Prompt Template
FACE_SWAP_PROMPT = """head_swap: start with Picture 1 as the base image, keeping its lighting, environment, and background. Remove the head from Picture 1 completely and replace it with the head from Picture 2.
FROM PICTURE 1 (strictly preserve):
- Scene: lighting conditions, shadows, highlights, color temperature, environment, background
- Head positioning: exact rotation angle, tilt, direction the head is facing
- Expression: facial expression, micro-expressions, eye gaze direction, mouth position, emotion
FROM PICTURE 2 (strictly preserve identity):
- Facial structure: face shape, bone structure, jawline, chin
- All facial features: eye color, eye shape, nose structure, lip shape and fullness, eyebrows
- Hair: color, style, texture, hairline
- Skin: texture, tone, complexion
The replaced head must seamlessly match Picture 1's lighting and expression while maintaining the complete identity from Picture 2. High quality, photorealistic, sharp details, 4k."""
LORA_STYLES = [
{
"image": "https://huggingface.co/spaces/prithivMLmods/FLUX.2-Klein-LoRA-Studio/resolve/main/examples/image.webp",
"title": "None",
"adapter_name": None,
"repo": None,
"weights": None,
"default_prompt": None
},
{
"image": "https://huggingface.co/linoyts/Flux2-Klein-Delight-LoRA/resolve/main/image_3.png",
"title": "Klein-Delight-Style",
"adapter_name": "klein-delight",
"repo": "linoyts/Flux2-Klein-Delight-LoRA",
"weights": "pytorch_lora_weights.safetensors",
"default_prompt": None
},
{
"image": "https://huggingface.co/spaces/prithivMLmods/FLUX.2-Klein-LoRA-Studio/resolve/main/examples/face-swap.jpg",
"title": "Best-Face-Swap",
"adapter_name": "face-swap",
"repo": "Alissonerdx/BFS-Best-Face-Swap",
"weights": "bfs_head_v1_flux-klein_9b_step3750_rank64.safetensors",
"default_prompt": FACE_SWAP_PROMPT
},
{
"image": "https://huggingface.co/datasets/malcolmrey/samples/resolve/main/thumbnails/emmawatson.jpg",
"title": "Emmma Watson",
"adapter_name": "fk9_emmawatson_v1.safetensors",
"repo": "malcolmrey/klein9",
"weights": "fk9_emmawatson_v1.safetensors",
"default_prompt": "emmawatson"
},
]
LOADED_ADAPTERS = set()
# Dynamic LoRA storage for user-added adapters
DYNAMIC_LORAS = {}
DYNAMIC_LORA_COUNTER = 0
def get_all_styles():
"""Combine predefined styles with dynamically added LoRAs."""
all_styles = list(LORA_STYLES)
for dynamic_lora in DYNAMIC_LORAS.values():
all_styles.append(dynamic_lora)
return all_styles
def add_custom_lora(repo_id, weight_name, adapter_name):
"""Add a custom LoRA adapter from HuggingFace Hub."""
global DYNAMIC_LORA_COUNTER
if not repo_id or not repo_id.strip():
return "Please enter a valid HuggingFace repo ID.", None, False, gr.update()
repo_id = repo_id.strip()
adapter_name = adapter_name.strip() if adapter_name and adapter_name.strip() else None
# Check if already loaded
existing_check = f"custom_{adapter_name}" if adapter_name else None
if existing_check and existing_check in LOADED_ADAPTERS:
return f"Adapter '{adapter_name}' is already loaded.", None, True, gr.update()
try:
# Validate the repo exists by attempting to download
from huggingface_hub import model_info
info = model_info(repo_id)
# Get the weight file to use
actual_weight = weight_name.strip() if weight_name and weight_name.strip() else None
# If no weight specified, try to find common LoRA filenames
if not actual_weight:
common_names = [
"pytorch_lora_weights.safetensors",
"pytorch_lora_weights.bin",
"lora.safetensors",
"lora.bin",
"adapter_model.safetensors",
"adapter_model.bin",
]
for name in common_names:
if any(f.filename == name for f in info.siblings):
actual_weight = name
break
if not actual_weight:
# List available files for user reference
available = [f.filename for f in info.siblings if f.filename.endswith(('.safetensors', '.bin', '.pt', '.pth'))]
return f"No common LoRA weight found. Available files: {', '.join(available) if available else 'None'}", None, False, gr.update()
# Generate adapter name if not provided
if not adapter_name:
DYNAMIC_LORA_COUNTER += 1
adapter_name = f"custom_{DYNAMIC_LORA_COUNTER}"
else:
# Sanitize for safe use
adapter_name = "".join(c if c.isalnum() or c in "-_" else "_" for c in adapter_name)
# Create the style entry
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
}
# Store in dynamic LoRAs
DYNAMIC_LORAS[adapter_name] = custom_style
# Update gallery with new style
new_gallery = get_all_styles()
new_gallery_data = [(item["image"], item["title"]) for item in new_gallery]
return f"Successfully added LoRA: {adapter_name} from {repo_id}", custom_style, True, new_gallery_data
except Exception as e:
return f"Failed to add LoRA: {str(e)}", None, False, gr.update()
def remove_custom_lora(adapter_name):
"""Remove a dynamically added LoRA."""
if adapter_name in DYNAMIC_LORAS:
del DYNAMIC_LORAS[adapter_name]
if adapter_name in LOADED_ADAPTERS:
LOADED_ADAPTERS.remove(adapter_name)
return True
return False
print("Loading FLUX.2 Klein 9B model base...")
pipe = Flux2KleinPipeline.from_pretrained(
"black-forest-labs/FLUX.2-klein-9B",
torch_dtype=torch.bfloat16,
).to(device)
print("Base Model loaded successfully.")
def update_dimensions_on_upload(image):
"""Resizes image to be divisible by 16 to avoid tensor mismatch errors in FLUX."""
if image is None:
return 1024, 1024
original_width, original_height = image.size
scale = min(1024 / original_width, 1024 / original_height)
new_width = int(original_width * scale)
new_height = int(original_height * scale)
new_width = (new_width // 16) * 16
new_height = (new_height // 16) * 16
return new_width, new_height
def process_gallery_images(images):
"""Process images from gallery input and return list of PIL images."""
if not images:
return []
pil_images = []
for item in images:
try:
if isinstance(item, tuple) or isinstance(item, list):
path_or_img = item[0]
else:
path_or_img = 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"))
else:
pil_images.append(Image.open(path_or_img.name).convert("RGB"))
except Exception as e:
print(f"Skipping invalid image item: {e}")
continue
return pil_images
def get_style_by_name(name):
"""Retrieve the style dictionary by its title (checks both predefined and dynamic LoRAs)."""
for style in LORA_STYLES:
if style["title"] == name:
return style
# Also check dynamic LoRAs
for style in DYNAMIC_LORAS.values():
if style["title"] == name:
return style
return LORA_STYLES[0] # Default to None
def update_style_selection(evt: gr.SelectData):
"""Update selected style based on gallery click."""
all_styles = get_all_styles()
if evt.index >= len(all_styles):
return LORA_STYLES[0]["title"], gr.update()
selected_style = all_styles[evt.index]
default_prompt = selected_style.get("default_prompt", None)
# Return the title string and optional prompt update
return selected_style["title"], default_prompt if default_prompt else gr.update()
def update_style_info(style_name):
"""Update the info text based on the selected style name."""
return f"### Selected: {style_name} ✅"
def get_image_count_info(images):
"""Return info about uploaded 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)"
else:
return f"📷 {count} images uploaded"
@spaces.GPU
def infer(
input_images,
prompt,
style_name,
seed=42,
randomize_seed=True,
guidance_scale=1.0,
steps=4,
progress=gr.Progress(track_tqdm=True)
):
gc.collect()
torch.cuda.empty_cache()
if not input_images:
raise gr.Error("Please upload at least one image to apply a style to.")
# Process gallery images
pil_images = process_gallery_images(input_images)
if not pil_images:
raise gr.Error("Could not process uploaded images.")
# Find the selected style configuration
selected_style = get_style_by_name(style_name)
# Check if Face Swap is selected and validate image count
if selected_style["adapter_name"] == "face-swap":
if len(pil_images) < 2:
raise gr.Error("Face Swap requires exactly 2 images: Picture 1 (base/body) and Picture 2 (face source). Please upload 2 images.")
elif len(pil_images) > 2:
gr.Warning("Face Swap uses only the first 2 images. Additional images will be ignored.")
pil_images = pil_images[:2]
if selected_style["adapter_name"] is None:
print("Selection is None. Disabling LoRA adapters.")
pipe.disable_lora()
else:
adapter_name = selected_style["adapter_name"]
if adapter_name not in LOADED_ADAPTERS:
print(f"--- Downloading and Loading Adapter: {selected_style['title']} ---")
try:
pipe.load_lora_weights(
selected_style["repo"],
weight_name=selected_style["weights"],
adapter_name=adapter_name
)
LOADED_ADAPTERS.add(adapter_name)
except Exception as e:
raise gr.Error(f"Failed to load adapter {selected_style['title']}: {e}")
else:
print(f"--- Adapter {selected_style['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)
# Get dimensions from first image
width, height = update_dimensions_on_upload(pil_images[0])
# Process all images to the same dimensions
processed_images = [
img.resize((width, height), Image.LANCZOS).convert("RGB")
for img in pil_images
]
try:
# Pass single image or list based on count
image_input = processed_images if len(processed_images) > 1 else processed_images[0]
image = pipe(
image=image_input,
prompt=prompt,
guidance_scale=guidance_scale,
width=width,
height=height,
num_inference_steps=steps,
generator=torch.Generator(device=device).manual_seed(seed),
).images[0]
return image, seed
except Exception as e:
raise gr.Error(f"Inference failed: {e}")
finally:
gc.collect()
torch.cuda.empty_cache()
@spaces.GPU
def infer_example(input_images, prompt, style_name):
if not input_images:
return None, 0
# Handle examples where inputs might be paths
if isinstance(input_images, str):
input_images = [input_images]
image, seed = infer(
input_images=input_images,
prompt=prompt,
style_name=style_name,
seed=0,
randomize_seed=True,
guidance_scale=1.0,
steps=4
)
return image, seed
css = """
#col-container { margin: 0 auto; max-width: 960px; }
#main-title h1 { font-size: 2.4em !important; }
#style_gallery .grid-wrap { height: 10vh }
#input_gallery .grid-wrap { min-height: 200px }
"""
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.")
selected_style_name = gr.Textbox(value="None", visible=False, label="Selected Style Name")
with gr.Row(equal_height=True):
with gr.Column():
input_images = gr.Gallery(
label="Upload Images",
type="filepath",
columns=2,
rows=1,
height=290,
allow_preview=True,
elem_id="input_gallery"
)
with gr.Row():
prompt = gr.Text(
label="Edit Prompt",
max_lines=1,
show_label=True,
placeholder="e.g., a man with a red superhero mask"
)
run_button = gr.Button("Apply Style", variant="primary")
with gr.Accordion("Advanced Settings", open=False, visible=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)
steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=4, step=1)
with 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)
selected_style_info = gr.Markdown("### Selected: None (FLUX.2-klein-9B) ✅")
# Dynamic LoRA Loading Section
with gr.Accordion("➕ Load Custom LoRA from HuggingFace", open=False):
gr.Markdown("Load any FLUX-compatible LoRA adapter 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="HuggingFace Repo ID",
placeholder="e.g., user/my-flux-lora",
info="The repository ID on HuggingFace (e.g., 'user/my-lora' or full path)"
)
with gr.Row():
lora_weight_name = gr.Textbox(
label="Weight File Name (Optional)",
placeholder="e.g., pytorch_lora_weights.safetensors",
info="Leave empty to auto-detect common LoRA filenames"
)
lora_adapter_name = gr.Textbox(
label="Adapter Name (Optional)",
placeholder="e.g., my-custom-lora",
info="Custom name for this adapter (auto-generated if empty)"
)
with gr.Row():
add_lora_btn = gr.Button("Add LoRA", variant="primary")
lora_status = gr.Textbox(label="Status", interactive=False, lines=1)
style_gallery = gr.Gallery(
[(item["image"], item["title"]) for item in get_all_styles()],
label="Edit Style Gallery",
allow_preview=False,
columns=3,
elem_id="style_gallery",
)
def on_add_lora_click(repo_id, weight_name, adapter_name):
"""Handle the Add LoRA button click."""
msg, style, success, new_gallery = add_custom_lora(repo_id, weight_name, adapter_name)
if new_gallery:
return msg, new_gallery
return msg, [(item["image"], item["title"]) for item in get_all_styles()]
add_lora_btn.click(
fn=on_add_lora_click,
inputs=[lora_repo_id, lora_weight_name, lora_adapter_name],
outputs=[lora_status, style_gallery]
)
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", "examples/2.jpg"],
FACE_SWAP_PROMPT,
"Best-Face-Swap"
],
[
["examples/1.jpg"],
"cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed by prithivMLmods preserving realistic texture and details",
"None"
],
[
["examples/cloth.jpg"],
"3Dghostmannequin",
"Ghost-Mannequin"
],
],
inputs=[input_images, prompt, selected_style_name],
outputs=[output_image, used_seed],
fn=infer_example,
cache_examples=False,
label="Examples"
)
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.")
input_images.change(
fn=get_image_count_info,
inputs=[input_images],
)
style_gallery.select(
fn=update_style_selection,
outputs=[selected_style_name, prompt]
)
selected_style_name.change(
fn=update_style_info,
inputs=[selected_style_name],
outputs=[selected_style_info]
)
run_button.click(
fn=infer,
inputs=[input_images, prompt, selected_style_name, seed, randomize_seed, guidance_scale, steps],
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) |