VectorV17 commited on
Commit
855fccb
·
verified ·
1 Parent(s): 96f388b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -55
app.py CHANGED
@@ -6,67 +6,64 @@ import gradio as gr
6
  from PIL import Image
7
  from diffusers import Flux2KleinKVPipeline
8
 
9
- # --- AUTHENTICATION & MODEL ---
10
- # This pulls the secret you just added to your Space Settings
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
- print("❌ ERROR: HF_TOKEN not found in Space Secrets!")
17
 
18
- print("⏳ Authenticating and Loading Pipeline...")
19
- # Passing the token here bypasses the 401 Gated Error
20
- pipe = Flux2KleinKVPipeline.from_pretrained(
21
- model_id,
22
- torch_dtype=torch.bfloat16,
23
- token=hf_token
24
- )
25
- pipe.enable_model_cpu_offload()
26
- return pipe
 
 
27
 
 
28
  try:
29
  pipe = load_pipeline()
 
30
  except Exception as e:
31
- print(f"Failed to load: {e}")
32
  pipe = None
 
33
 
34
- # --- OPTIONS ---
35
  VIBGYOR = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
36
  SIZES = ["Small", "Medium", "Large", "Free-size"]
37
 
38
- @spaces.GPU(duration=200)
39
- def generate_composite_techpack(input_files, base_prompt, selected_colors, selected_sizes, num_var, strength, steps):
 
 
40
  if not input_files or not selected_colors or not selected_sizes:
41
- return None, "Please upload images and select at least one color and size."
42
-
43
- if pipe is None:
44
- return None, "Model failed to load. Check your HF_TOKEN in Settings."
45
 
46
- # 1. Permutation and Selection Logic
47
- # Filter selections to ensure we only use what the user checked
48
- combinations = [(c, s) for c in selected_colors if c in VIBGYOR for s in selected_sizes if s in SIZES]
49
-
50
- if not combinations:
51
- return None, "No valid color/size combinations selected."
52
-
53
- # Randomly pick the requested number (5-8)
54
- num_to_gen = min(len(combinations), int(num_var))
55
- chosen_combos = random.sample(combinations, num_to_gen)
56
 
57
  pipe.to("cuda")
58
- images = []
59
 
60
  # 2. Sequential Generation
61
  for color, size in chosen_combos:
62
  source_img = random.choice(input_files)
63
- # Construct trend-aware prompt
64
- full_prompt = f"{base_prompt}, apparel tech pack, color: {color}, size: {size}, professional flat lay, industrial standard drawing"
65
 
66
  init_image = Image.open(source_img).convert("RGB").resize((768, 768))
67
 
68
  output = pipe(
69
- prompt=full_prompt,
70
  image=init_image,
71
  strength=strength,
72
  num_inference_steps=int(steps),
@@ -75,52 +72,49 @@ def generate_composite_techpack(input_files, base_prompt, selected_colors, selec
75
  height=768
76
  ).images[0]
77
 
78
- images.append(output)
79
 
80
- # 3. Create "Single Image" Composite (Grid)
81
- # We create a 2-column grid to match industry standards
82
  cols = 2
83
- rows = (len(images) + 1) // 2
84
- canvas_w = 1024
85
- canvas_h = rows * 512
86
-
87
- composite = Image.new("RGB", (canvas_w, canvas_h), (255, 255, 255))
88
 
89
- for i, img in enumerate(images):
90
  img_resized = img.resize((512, 512))
91
  x = (i % cols) * 512
92
  y = (i // cols) * 512
93
  composite.paste(img_resized, (x, y))
94
 
95
- return composite, f"Generated {len(images)} variations successfully."
96
 
97
- # --- UI LAYOUT ---
98
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
99
- gr.Markdown("# 👗 FLUX.2 Klein: Professional Tech-Pack Generator")
100
 
101
  with gr.Row():
102
  with gr.Column():
103
- prompt = gr.Textbox(label="Base Design Prompt", value="High quality tech pack images")
104
- files = gr.File(label="Upload Sketches", file_count="multiple", type="filepath")
105
 
106
  with gr.Row():
107
- colors = gr.CheckboxGroup(choices=VIBGYOR, value=["Blue", "Red"], label="Colors")
108
  sizes = gr.CheckboxGroup(choices=SIZES, value=["Medium", "Free-size"], label="Sizes")
109
 
110
- num_var = gr.Slider(5, 8, value=5, step=1, label="Number of Variations (5-8)")
111
 
112
- with gr.Accordion("Advanced", open=False):
113
  strength = gr.Slider(0.1, 1.0, value=0.6, label="Strength")
114
  steps = gr.Slider(1, 10, value=4, step=1, label="Steps")
115
 
116
- btn = gr.Button("🚀 Generate Batch", variant="primary")
117
 
118
  with gr.Column():
119
- output_img = gr.Image(label="Final Combined Tech-Pack", type="pil")
120
- status = gr.Textbox(label="Logs")
121
 
122
  btn.click(
123
- fn=generate_composite_techpack,
124
  inputs=[files, prompt, colors, sizes, num_var, strength, steps],
125
  outputs=[output_img, status]
126
  )
 
6
  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. Please add it to your Space Secrets in Settings.")
17
 
18
+ print(f"⏳ Loading {model_id}...")
19
+ try:
20
+ pipe = Flux2KleinKVPipeline.from_pretrained(
21
+ model_id,
22
+ torch_dtype=torch.bfloat16,
23
+ token=hf_token
24
+ )
25
+ pipe.enable_model_cpu_offload()
26
+ return pipe
27
+ except Exception as e:
28
+ raise RuntimeError(f"Could not load model. Ensure you accepted the license at {model_id}. Error: {e}")
29
 
30
+ # Global initialization with error catching
31
  try:
32
  pipe = load_pipeline()
33
+ init_error = None
34
  except Exception as e:
 
35
  pipe = None
36
+ init_error = str(e)
37
 
38
+ # --- CONFIG ---
39
  VIBGYOR = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
40
  SIZES = ["Small", "Medium", "Large", "Free-size"]
41
 
42
+ @spaces.GPU(duration=250)
43
+ def generate_batch(input_files, base_prompt, selected_colors, selected_sizes, num_var, strength, steps):
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 at least one color and size."
 
 
 
48
 
49
+ # 1. Permutation Logic: Create unique combos
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
+ generated_images = []
56
 
57
  # 2. Sequential Generation
58
  for color, size in chosen_combos:
59
  source_img = random.choice(input_files)
60
+ # Construct trend-optimized prompt
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
 
65
  output = pipe(
66
+ prompt=final_prompt,
67
  image=init_image,
68
  strength=strength,
69
  num_inference_steps=int(steps),
 
72
  height=768
73
  ).images[0]
74
 
75
+ generated_images.append(output)
76
 
77
+ # 3. Composite Creation (Single Downloadable Image)
78
+ # We create a grid: 2 columns wide
79
  cols = 2
80
+ rows = (len(generated_images) + 1) // 2
81
+ composite = Image.new("RGB", (1024, rows * 512), (255, 255, 255))
 
 
 
82
 
83
+ for i, img in enumerate(generated_images):
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
+ return composite, f"✅ Successfully generated {len(generated_images)} variations."
90
 
91
+ # --- UI ---
92
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
93
+ gr.Markdown("# 👔 FLUX.2 Klein: Multi-Variation Tech-Pack Generator")
94
 
95
  with gr.Row():
96
  with gr.Column():
97
+ prompt = gr.Textbox(label="Base Design Prompt", value="A high-quality technical apparel tech pack")
98
+ files = gr.File(label="Upload Sketches (Max 40)", file_count="multiple", type="filepath")
99
 
100
  with gr.Row():
101
+ colors = gr.CheckboxGroup(choices=VIBGYOR, value=["Blue", "Indigo"], label="VIBGYOR Colors")
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 Settings", open=False):
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="Final Composite Image", type="pil")
114
+ status = gr.Textbox(label="Status Logs")
115
 
116
  btn.click(
117
+ fn=generate_batch,
118
  inputs=[files, prompt, colors, sizes, num_var, strength, steps],
119
  outputs=[output_img, status]
120
  )