VectorV17 commited on
Commit
5d459b6
·
verified ·
1 Parent(s): 172c6e6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -106
app.py CHANGED
@@ -5,143 +5,110 @@ import random
5
  import gradio as gr
6
  from PIL import Image
7
  from diffusers import Flux2KleinKVPipeline
8
- from transformers import T5EncoderModel, BitsAndBytesConfig
9
 
10
- # --- MODEL INITIALIZATION ---
11
- # Using the non-gated community mirror to avoid 401 GatedRepoError
12
- model_id = "sayakpaul/FLUX.2-klein-9b-kv"
13
 
14
- def load_pipeline():
15
- print("⏳ Loading Pipeline from non-gated mirror...")
16
- # Loading in bfloat16 is essential for T4/A100 efficiency
17
- pipe = Flux2KleinKVPipeline.from_pretrained(
18
- model_id,
19
- torch_dtype=torch.bfloat16
20
- )
21
-
22
- # This ensures the model stays off the GPU until the actual 'generate' call
23
- pipe.enable_model_cpu_offload()
24
- return pipe
25
-
26
- # Initialize the pipeline globally
27
- try:
28
- pipe = load_pipeline()
29
- except Exception as e:
30
- print(f"Error loading pipeline: {e}")
31
- pipe = None
32
-
33
- # --- COLOR & SIZE OPTIONS ---
34
- COLOR_OPTIONS = ["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"]
35
- SIZE_OPTIONS = ["Small", "Medium", "Large", "Free-size"]
36
-
37
- # --- CORE LOGIC ---
38
  @spaces.GPU(duration=180)
39
- def process_batch(input_files, base_prompt, selected_colors, selected_sizes, num_variations, strength, steps):
40
  if not input_files or not selected_colors or not selected_sizes:
41
- return None, "Select at least 1 image, color, and size."
42
-
43
- if pipe is None:
44
- return None, "Pipe not initialized."
45
 
46
- # Validate that enough unique combinations are possible
47
- possible_combinations = [(c, s) for c in selected_colors for s in selected_sizes]
48
- total_combinations = len(possible_combinations)
49
- if num_variations > total_combinations:
50
- num_variations = total_combinations
51
- message = f"Only {total_combinations} unique combinations are possible; generating those."
52
- else:
53
- message = f"Successfully generated {num_variations} variations."
 
54
 
55
- # Randomly select unique combinations
56
- unique_variations_set = random.sample(possible_combinations, num_variations)
57
 
58
- pipe.to("cuda")
59
- individual_vars = []
 
 
 
 
60
 
61
- # Process the variations
62
- for color, size in unique_variations_set:
63
- # Randomly pick source image from the pool to mix inputs
64
- source_file = random.choice(input_files)
65
-
66
- # Build prompt with your specific logic including trend keywords
67
- # The prompt implements the "market trend reject" by guiding style
68
- final_prompt = f"{base_prompt}, apparel tech pack design, color: {color}, fit: {size} size, technical drawing, market-ready standard presentation, industry consumer trend style"
69
-
70
- init_image = Image.open(source_file).convert("RGB").resize((768, 768))
71
 
72
- # Using KV-Cache variant with steps distilled Klein means rapid generation
73
  output = pipe(
74
- prompt=final_prompt,
75
  image=init_image,
76
  strength=strength,
77
- num_inference_steps=steps, # Standard Klein peak steps
78
  guidance_scale=3.5,
79
  width=768,
80
  height=768,
81
  ).images[0]
82
 
83
- individual_vars.append(output)
84
 
85
- # --- IMAGE COMBINATION LOGIC ---
86
- # Combine individual 768x768 outputs into a single image in a 2-column grid
87
- combined_width = 1024 # Standard composite width
88
- composite_image = Image.new("RGB", (combined_width, 1024), (255, 255, 255))
 
 
89
 
90
- grid_w, grid_h = 2, (num_variations // 2 + num_variations % 2)
91
- composite_image = Image.new("RGB", (combined_width, grid_h * 512), (255, 255, 255))
92
 
93
- for i, img in enumerate(individual_vars):
94
- img_resized = img.resize((512, 512)) # Resizing for clean grid
95
- composite_image.paste(img_resized, ((i % grid_w) * 512, (i // grid_w) * 512))
96
-
97
- # Moving back to CPU to free up memory
98
- pipe.enable_model_cpu_offload()
99
 
100
- return composite_image, message
101
 
102
- # --- GRADIO UI (RECREATING IMAGE STRUCTURE) ---
103
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
104
- gr.Markdown("# 👗 FLUX.2 Klein: Technical Tech-Pack Randomizer")
105
- gr.Markdown("Upload your input sketches, describe the base style, and select the colors/sizes to generate random variations combined into a single downloadable image.")
106
 
107
  with gr.Row():
108
  with gr.Column():
109
- # Main prompt box as shown in the image
110
- prompt_box = gr.Textbox(label="Text Prompt", value="high quality tech pack images")
111
-
112
- # Input image(s) gallery component
113
- input_imgs = gr.File(label="Upload Source Images (up to 40)", file_count="multiple", type="filepath")
114
 
115
- # Colors and Sizes input using check boxes
116
- colors = gr.CheckboxGroup(
117
- choices=COLOR_OPTIONS,
118
- value=["Blue", "Red"], label="Colors to Permute (VIBGYOR)"
119
- )
120
- sizes = gr.CheckboxGroup(
121
- choices=SIZE_OPTIONS,
122
- value=["Medium", "Free-size"], label="Sizes to Permute"
123
- )
124
 
125
- # The Number of Variations requirement provision (5-8)
126
- num_var = gr.Slider(5, 8, value=5, step=1, label="Number of Variations required (5-8)")
127
 
128
  with gr.Accordion("Advanced Settings", open=False):
129
- with gr.Row():
130
- strength = gr.Slider(0.1, 1.0, value=0.6, label="Redesign Strength")
131
- steps = gr.Slider(1, 10, value=4, step=1, label="Steps (4 is best)")
132
- # (You can add Seed/Width/Height sliders here if needed, but they aren't used for the composite size)
133
-
134
- btn = gr.Button("🚀 Generate Batch Tech Packs", variant="primary")
135
 
136
  with gr.Column():
137
- # Output Gallery for final combined result as shown in the image
138
- final_output = gr.Image(label="Combined Variations", type="pil")
139
- log_box = gr.Textbox(label="Status Logs")
140
 
141
- btn.click(
142
- fn=process_batch,
143
- inputs=[input_imgs, prompt_box, colors, sizes, num_var, strength, steps],
144
- outputs=[final_output, log_box]
145
  )
146
 
147
- demo.queue().launch()
 
5
  import gradio as gr
6
  from PIL import Image
7
  from diffusers import Flux2KleinKVPipeline
 
8
 
9
+ # --- CONFIGURATION ---
10
+ # Using the optimized Klein model
11
+ MODEL_ID = "black-forest-labs/FLUX.2-klein-9b-kv"
12
 
13
+ # --- CORE GENERATION LOGIC ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  @spaces.GPU(duration=180)
15
+ def generate_batch(input_files, base_prompt, selected_colors, selected_sizes, num_variations, strength, steps):
16
  if not input_files or not selected_colors or not selected_sizes:
17
+ return None, "Please upload images and select at least one color and size."
 
 
 
18
 
19
+ # 1. Initialize Pipeline INSIDE the GPU function to avoid CPU RAM limits
20
+ # This prevents the "Pipe not initialized" error
21
+ try:
22
+ pipe = Flux2KleinKVPipeline.from_pretrained(
23
+ MODEL_ID,
24
+ torch_dtype=torch.bfloat16
25
+ ).to("cuda")
26
+ except Exception as e:
27
+ return None, f"Model loading failed: {e}. Ensure you have accepted the license on the model card."
28
 
29
+ # 2. Permutation & Logic
30
+ possible_combinations = [(c, s) for c in selected_colors for s in selected_sizes]
31
 
32
+ # Selection logic: Picking the best combinations based on the requested count
33
+ # We prioritize variety in colors first
34
+ random.shuffle(possible_combinations)
35
+ final_selections = possible_combinations[:num_variations]
36
+
37
+ individual_images = []
38
 
39
+ for color, size in final_selections:
40
+ # Pick a random image from the uploaded batch
41
+ source_img_path = random.choice(input_files)
42
+ init_image = Image.open(source_img_path).convert("RGB").resize((768, 768))
43
+
44
+ # Construct trend-aware prompt
45
+ full_prompt = f"{base_prompt}, tech pack drawing, color: {color}, size: {size}, professional apparel industry standard, flat lay mockup"
 
 
 
46
 
47
+ # Generate variation
48
  output = pipe(
49
+ prompt=full_prompt,
50
  image=init_image,
51
  strength=strength,
52
+ num_inference_steps=steps,
53
  guidance_scale=3.5,
54
  width=768,
55
  height=768,
56
  ).images[0]
57
 
58
+ individual_images.append(output)
59
 
60
+ # 3. Create Single Composite Image (Grid Layout)
61
+ # We create a canvas that fits 5-8 images (4 columns x 2 rows max)
62
+ cols = 4
63
+ rows = (num_variations + cols - 1) // cols
64
+ canvas_w = 2048
65
+ canvas_h = rows * 512
66
 
67
+ composite_image = Image.new("RGB", (canvas_w, canvas_h), (255, 255, 255))
 
68
 
69
+ for i, img in enumerate(individual_images):
70
+ img_res = img.resize((512, 512))
71
+ x = (i % cols) * 512
72
+ y = (i // cols) * 512
73
+ composite_image.paste(img_res, (x, y))
 
74
 
75
+ return composite_image, f"Generated {num_variations} variations using market-standard combinations."
76
 
77
+ # --- GRADIO INTERFACE ---
78
+ with gr.Blocks(theme=gr.themes.Default()) as demo:
79
+ gr.Markdown("# 👗 Automated Tech-Pack Batch Generator")
 
80
 
81
  with gr.Row():
82
  with gr.Column():
83
+ prompt = gr.Textbox(label="Text Prompt", value="high quality tech pack images")
84
+ input_imgs = gr.File(label="Input Images (Upload up to 40)", file_count="multiple", type="filepath")
 
 
 
85
 
86
+ with gr.Row():
87
+ colors = gr.CheckboxGroup(
88
+ choices=["Violet", "Indigo", "Blue", "Green", "Yellow", "Orange", "Red"],
89
+ value=["Blue", "Green", "Red"], label="Colors (VIBGYOR)"
90
+ )
91
+ sizes = gr.CheckboxGroup(
92
+ choices=["Small", "Medium", "Large", "Free-size"],
93
+ value=["Medium", "Free-size"], label="Sizes"
94
+ )
95
 
96
+ num_var = gr.Slider(5, 8, value=5, step=1, label="Number of Variations Required")
 
97
 
98
  with gr.Accordion("Advanced Settings", open=False):
99
+ strength = gr.Slider(0.1, 1.0, value=0.6, label="Redesign Strength")
100
+ steps = gr.Slider(1, 10, value=4, step=1, label="Inference Steps")
101
+
102
+ run_btn = gr.Button("🚀 Generate Batch", variant="primary")
 
 
103
 
104
  with gr.Column():
105
+ output_img = gr.Image(label="Combined Tech-Pack Variations", type="pil")
106
+ status_log = gr.Textbox(label="Status Logs")
 
107
 
108
+ run_btn.click(
109
+ fn=generate_batch,
110
+ inputs=[input_imgs, prompt, colors, sizes, num_var, strength, steps],
111
+ outputs=[output_img, status_log]
112
  )
113
 
114
+ demo.launch()