Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,27 +7,34 @@ from PIL import Image
|
|
| 7 |
from diffusers import Flux2KleinKVPipeline
|
| 8 |
|
| 9 |
# --- AUTHENTICATION ---
|
| 10 |
-
# This looks for the secret you added in Step 2
|
| 11 |
hf_token = os.getenv("HF_TOKEN")
|
| 12 |
model_id = "black-forest-labs/FLUX.2-klein-9b-kv"
|
| 13 |
|
| 14 |
def load_pipeline():
|
| 15 |
if not hf_token:
|
| 16 |
-
raise ValueError("HF_TOKEN is missing
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
print(f"⏳ Loading {model_id}...")
|
| 19 |
try:
|
| 20 |
-
|
| 21 |
-
model_id,
|
| 22 |
-
torch_dtype=torch.bfloat16,
|
| 23 |
-
token=hf_token
|
| 24 |
-
)
|
| 25 |
pipe.enable_model_cpu_offload()
|
| 26 |
-
|
| 27 |
except Exception as e:
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
# Global initialization
|
| 31 |
try:
|
| 32 |
pipe = load_pipeline()
|
| 33 |
init_error = None
|
|
@@ -35,30 +42,29 @@ except Exception as e:
|
|
| 35 |
pipe = None
|
| 36 |
init_error = str(e)
|
| 37 |
|
| 38 |
-
# ---
|
| 39 |
VIBGYOR = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
|
| 40 |
SIZES = ["Small", "Medium", "Large", "Free-size"]
|
| 41 |
|
| 42 |
@spaces.GPU(duration=250)
|
| 43 |
-
def
|
| 44 |
if init_error:
|
| 45 |
return None, f"❌ Initialization Error: {init_error}"
|
| 46 |
if not input_files or not selected_colors or not selected_sizes:
|
| 47 |
-
return None, "⚠️ Please upload images and select
|
| 48 |
|
| 49 |
-
# 1.
|
| 50 |
combos = [(c, s) for c in selected_colors for s in selected_sizes]
|
| 51 |
num_to_gen = min(len(combos), int(num_var))
|
| 52 |
chosen_combos = random.sample(combos, num_to_gen)
|
| 53 |
|
|
|
|
| 54 |
pipe.to("cuda")
|
| 55 |
-
|
| 56 |
|
| 57 |
-
# 2. Sequential Generation
|
| 58 |
for color, size in chosen_combos:
|
| 59 |
source_img = random.choice(input_files)
|
| 60 |
-
|
| 61 |
-
final_prompt = f"{base_prompt}, tech pack format, color: {color}, size: {size}, professional apparel design, market trend standard"
|
| 62 |
|
| 63 |
init_image = Image.open(source_img).convert("RGB").resize((768, 768))
|
| 64 |
|
|
@@ -72,49 +78,50 @@ def generate_batch(input_files, base_prompt, selected_colors, selected_sizes, nu
|
|
| 72 |
height=768
|
| 73 |
).images[0]
|
| 74 |
|
| 75 |
-
|
| 76 |
|
| 77 |
-
# 3.
|
| 78 |
-
# We create a grid: 2 columns wide
|
| 79 |
cols = 2
|
| 80 |
-
rows = (len(
|
| 81 |
composite = Image.new("RGB", (1024, rows * 512), (255, 255, 255))
|
| 82 |
|
| 83 |
-
for i, img in enumerate(
|
| 84 |
img_resized = img.resize((512, 512))
|
| 85 |
x = (i % cols) * 512
|
| 86 |
y = (i // cols) * 512
|
| 87 |
composite.paste(img_resized, (x, y))
|
| 88 |
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
# --- UI ---
|
| 92 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 93 |
-
gr.Markdown("#
|
| 94 |
|
| 95 |
with gr.Row():
|
| 96 |
with gr.Column():
|
| 97 |
-
prompt = gr.Textbox(label="Base Design Prompt", value="
|
| 98 |
-
files = gr.File(label="Upload Sketches
|
| 99 |
|
| 100 |
with gr.Row():
|
| 101 |
-
colors = gr.CheckboxGroup(choices=VIBGYOR, value=["Blue", "
|
| 102 |
sizes = gr.CheckboxGroup(choices=SIZES, value=["Medium", "Free-size"], label="Sizes")
|
| 103 |
|
| 104 |
num_var = gr.Slider(5, 8, value=5, step=1, label="Variations to Generate (5-8)")
|
| 105 |
|
| 106 |
-
with gr.Accordion("Advanced
|
| 107 |
strength = gr.Slider(0.1, 1.0, value=0.6, label="Strength")
|
| 108 |
steps = gr.Slider(1, 10, value=4, step=1, label="Steps")
|
| 109 |
|
| 110 |
btn = gr.Button("🚀 Generate Combined Tech-Pack", variant="primary")
|
| 111 |
|
| 112 |
with gr.Column():
|
| 113 |
-
output_img = gr.Image(label="
|
| 114 |
-
status = gr.Textbox(label="
|
| 115 |
|
| 116 |
btn.click(
|
| 117 |
-
fn=
|
| 118 |
inputs=[files, prompt, colors, sizes, num_var, strength, steps],
|
| 119 |
outputs=[output_img, status]
|
| 120 |
)
|
|
|
|
| 7 |
from diffusers import Flux2KleinKVPipeline
|
| 8 |
|
| 9 |
# --- AUTHENTICATION ---
|
|
|
|
| 10 |
hf_token = os.getenv("HF_TOKEN")
|
| 11 |
model_id = "black-forest-labs/FLUX.2-klein-9b-kv"
|
| 12 |
|
| 13 |
def load_pipeline():
|
| 14 |
if not hf_token:
|
| 15 |
+
raise ValueError("HF_TOKEN is missing in Space Secrets.")
|
| 16 |
+
|
| 17 |
+
print(f"⏳ Attempting to load {model_id}...")
|
| 18 |
+
|
| 19 |
+
# Load the pipeline in bfloat16
|
| 20 |
+
pipe = Flux2KleinKVPipeline.from_pretrained(
|
| 21 |
+
model_id,
|
| 22 |
+
torch_dtype=torch.bfloat16,
|
| 23 |
+
token=hf_token
|
| 24 |
+
)
|
| 25 |
|
|
|
|
| 26 |
try:
|
| 27 |
+
# This is what was causing the error; it requires the 'accelerate' library
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
pipe.enable_model_cpu_offload()
|
| 29 |
+
print("✅ CPU Offload enabled successfully.")
|
| 30 |
except Exception as e:
|
| 31 |
+
print(f"⚠️ Warning: Accelerate not found, falling back to manual management. Error: {e}")
|
| 32 |
+
# Manual fallback if accelerate fails
|
| 33 |
+
pipe.to("cpu")
|
| 34 |
+
|
| 35 |
+
return pipe
|
| 36 |
|
| 37 |
+
# Global initialization
|
| 38 |
try:
|
| 39 |
pipe = load_pipeline()
|
| 40 |
init_error = None
|
|
|
|
| 42 |
pipe = None
|
| 43 |
init_error = str(e)
|
| 44 |
|
| 45 |
+
# --- OPTIONS ---
|
| 46 |
VIBGYOR = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
|
| 47 |
SIZES = ["Small", "Medium", "Large", "Free-size"]
|
| 48 |
|
| 49 |
@spaces.GPU(duration=250)
|
| 50 |
+
def generate_composite_techpack(input_files, base_prompt, selected_colors, selected_sizes, num_var, strength, steps):
|
| 51 |
if init_error:
|
| 52 |
return None, f"❌ Initialization Error: {init_error}"
|
| 53 |
if not input_files or not selected_colors or not selected_sizes:
|
| 54 |
+
return None, "⚠️ Please upload images and select colors/sizes."
|
| 55 |
|
| 56 |
+
# 1. Random Combination Logic
|
| 57 |
combos = [(c, s) for c in selected_colors for s in selected_sizes]
|
| 58 |
num_to_gen = min(len(combos), int(num_var))
|
| 59 |
chosen_combos = random.sample(combos, num_to_gen)
|
| 60 |
|
| 61 |
+
# 2. Move to GPU only during generation
|
| 62 |
pipe.to("cuda")
|
| 63 |
+
images = []
|
| 64 |
|
|
|
|
| 65 |
for color, size in chosen_combos:
|
| 66 |
source_img = random.choice(input_files)
|
| 67 |
+
final_prompt = f"{base_prompt}, tech pack layout, color: {color}, size: {size}, professional apparel design"
|
|
|
|
| 68 |
|
| 69 |
init_image = Image.open(source_img).convert("RGB").resize((768, 768))
|
| 70 |
|
|
|
|
| 78 |
height=768
|
| 79 |
).images[0]
|
| 80 |
|
| 81 |
+
images.append(output)
|
| 82 |
|
| 83 |
+
# 3. Create Single Composite Image (Grid)
|
|
|
|
| 84 |
cols = 2
|
| 85 |
+
rows = (len(images) + 1) // 2
|
| 86 |
composite = Image.new("RGB", (1024, rows * 512), (255, 255, 255))
|
| 87 |
|
| 88 |
+
for i, img in enumerate(images):
|
| 89 |
img_resized = img.resize((512, 512))
|
| 90 |
x = (i % cols) * 512
|
| 91 |
y = (i // cols) * 512
|
| 92 |
composite.paste(img_resized, (x, y))
|
| 93 |
|
| 94 |
+
# Move back to CPU to free GPU memory for others
|
| 95 |
+
pipe.to("cpu")
|
| 96 |
+
return composite, f"✅ Generated {len(images)} variations successfully."
|
| 97 |
|
| 98 |
# --- UI ---
|
| 99 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 100 |
+
gr.Markdown("# 👗 FLUX.2 Klein: Tech-Pack Variation Generator")
|
| 101 |
|
| 102 |
with gr.Row():
|
| 103 |
with gr.Column():
|
| 104 |
+
prompt = gr.Textbox(label="Base Design Prompt", value="High quality technical apparel tech pack")
|
| 105 |
+
files = gr.File(label="Upload Sketches", file_count="multiple", type="filepath")
|
| 106 |
|
| 107 |
with gr.Row():
|
| 108 |
+
colors = gr.CheckboxGroup(choices=VIBGYOR, value=["Blue", "Red"], label="Colors")
|
| 109 |
sizes = gr.CheckboxGroup(choices=SIZES, value=["Medium", "Free-size"], label="Sizes")
|
| 110 |
|
| 111 |
num_var = gr.Slider(5, 8, value=5, step=1, label="Variations to Generate (5-8)")
|
| 112 |
|
| 113 |
+
with gr.Accordion("Advanced", open=False):
|
| 114 |
strength = gr.Slider(0.1, 1.0, value=0.6, label="Strength")
|
| 115 |
steps = gr.Slider(1, 10, value=4, step=1, label="Steps")
|
| 116 |
|
| 117 |
btn = gr.Button("🚀 Generate Combined Tech-Pack", variant="primary")
|
| 118 |
|
| 119 |
with gr.Column():
|
| 120 |
+
output_img = gr.Image(label="Downloadable Tech-Pack Grid", type="pil")
|
| 121 |
+
status = gr.Textbox(label="Logs")
|
| 122 |
|
| 123 |
btn.click(
|
| 124 |
+
fn=generate_composite_techpack,
|
| 125 |
inputs=[files, prompt, colors, sizes, num_var, strength, steps],
|
| 126 |
outputs=[output_img, status]
|
| 127 |
)
|