prithivMLmods commited on
Commit
c8cf5ad
·
verified ·
1 Parent(s): 5cf1e0f

update app

Browse files
Files changed (1) hide show
  1. app.py +116 -53
app.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  import gradio as gr
3
  import numpy as np
4
  import spaces
@@ -7,12 +8,10 @@ import random
7
  from PIL import Image
8
  from typing import Iterable
9
 
10
- # Pipeline for FLUX.2 Klein
11
  from diffusers import Flux2KleinPipeline
12
  from diffusers.utils import load_image
13
  from huggingface_hub import hf_hub_download
14
 
15
- # --- Hardware and Theme Setup ---
16
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
 
18
  from gradio.themes import Soft
@@ -62,71 +61,128 @@ class OrangeRedTheme(Soft):
62
  orange_red_theme = OrangeRedTheme()
63
  MAX_SEED = np.iinfo(np.int32).max
64
 
65
- # --- Model Loading ---
66
- print("Loading FLUX.2 Klein 9B model...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  pipe = Flux2KleinPipeline.from_pretrained(
68
  "black-forest-labs/FLUX.2-klein-9B",
69
  torch_dtype=torch.bfloat16
70
  ).to(device)
71
- print("Model loaded successfully.")
72
-
73
- # --- LoRA Loading (Updated) ---
74
- print("Loading new LoRA adapters...")
75
- pipe.load_lora_weights(
76
- "markury/flux2k9b-simpletuner-lora-loona",
77
- weight_name="pytorch_lora_weights.safetensors",
78
- adapter_name="simple-tuner"
79
- )
80
- pipe.load_lora_weights(
81
- "linoyts/Flux2-Klein-Delight-LoRA",
82
- weight_name="pytorch_lora_weights.safetensors",
83
- adapter_name="klein-delight"
84
- )
85
- print("All LoRA adapters loaded.")
86
 
87
- # Updated map for the new adapters
88
- ADAPTER_MAP = {
89
- "Simple-Tuner": "simple-tuner",
90
- "Klein-Delight-Style": "klein-delight",
91
- }
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  @spaces.GPU
94
- def infer(input_image, prompt, lora_adapter, seed=42, randomize_seed=True, guidance_scale=4.0, steps=4, progress=gr.Progress(track_tqdm=True)):
95
- # Input image is required for image-to-image tasks
 
 
 
 
 
 
 
 
 
 
 
96
  if not input_image:
97
  raise gr.Error("Please upload an image to apply a style to.")
98
 
99
- # Dynamically set the adapter based on the dropdown choice
100
- adapter_name = ADAPTER_MAP.get(lora_adapter)
101
- if adapter_name:
102
- print(f"Activating LoRA: {lora_adapter} ({adapter_name})")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  pipe.set_adapters([adapter_name], adapter_weights=[1.0])
104
  else:
105
- # If "None" is selected (or an invalid choice), disable LoRAs
106
- print("No LoRA selected. Disabling adapters.")
107
  pipe.disable_lora()
108
-
109
  if randomize_seed:
110
  seed = random.randint(0, MAX_SEED)
111
 
112
- original_image = input_image.copy().convert("RGB")
 
113
 
114
- image = pipe(
115
- image=original_image,
116
- prompt=prompt,
117
- guidance_scale=guidance_scale,
118
- width=original_image.size[0],
119
- height=original_image.size[1],
120
- num_inference_steps=steps,
121
- generator=torch.Generator(device=device).manual_seed(seed),
122
- ).images[0]
 
 
 
 
123
 
124
- return image, seed
 
 
 
 
125
 
126
  @spaces.GPU
127
  def infer_example(input_image, prompt, lora_adapter):
128
  # Use a fixed seed for reproducible examples
129
- image, seed = infer(input_image, prompt, lora_adapter, seed=12345, randomize_seed=False)
 
 
 
 
 
 
 
 
 
 
 
130
  return image, seed
131
 
132
  # --- UI Layout ---
@@ -140,18 +196,26 @@ with gr.Blocks() as demo:
140
  gr.Markdown("# **FLUX.2 Klein LoRA Stylizer**", elem_id="main-title")
141
  gr.Markdown(
142
  "Apply creative styles to your images using **FLUX.2-klein-9B** and specialized LoRA adapters. "
143
- "Upload an image, select a style, and write a prompt to guide the transformation."
144
  )
145
 
146
  with gr.Row(equal_height=True):
147
  with gr.Column():
148
- input_image = gr.Image(label="Upload Image", type="pil", height=290, sources=["upload", "webcam", "clipboard"])
149
- prompt = gr.Text(label="Guiding Prompt", show_label=True, placeholder="e.g., a man with a red superhero mask")
 
 
 
 
 
 
 
 
 
150
 
151
  lora_adapter = gr.Dropdown(
152
  label="Choose a Creative Style",
153
- # Updated choices for the new adapters
154
- choices=["Simple-Tuner", "Klein-Delight-Style"],
155
  value="Klein-Delight-Style"
156
  )
157
 
@@ -160,18 +224,17 @@ with gr.Blocks() as demo:
160
  with gr.Accordion("Advanced Settings", open=False):
161
  seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
162
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
163
- # Updated defaults suitable for FLUX.2 Klein
164
- guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.1, value=4.0)
165
  steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=4, step=1)
166
 
167
  with gr.Column():
168
  output_image = gr.Image(label="Stylized Image", interactive=False, format="png", height=450)
169
  used_seed = gr.Textbox(label="Used Seed", interactive=False)
170
 
171
- # Updated examples for the new LoRAs
172
  gr.Examples(
173
  examples=[
174
  ["examples/animal.jpg", "a cute red panda, charming and delightful illustration, soft lighting", "Klein-Delight-Style"],
 
175
  ],
176
  inputs=[input_image, prompt, lora_adapter],
177
  outputs=[output_image, used_seed],
 
1
  import os
2
+ import gc
3
  import gradio as gr
4
  import numpy as np
5
  import spaces
 
8
  from PIL import Image
9
  from typing import Iterable
10
 
 
11
  from diffusers import Flux2KleinPipeline
12
  from diffusers.utils import load_image
13
  from huggingface_hub import hf_hub_download
14
 
 
15
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
 
17
  from gradio.themes import Soft
 
61
  orange_red_theme = OrangeRedTheme()
62
  MAX_SEED = np.iinfo(np.int32).max
63
 
64
+ ADAPTER_SPECS = {
65
+ "Simple-Tuner": {
66
+ "repo": "markury/flux2k9b-simpletuner-lora-loona",
67
+ "weights": "pytorch_lora_weights.safetensors",
68
+ "adapter_name": "simple-tuner"
69
+ },
70
+ "Klein-Delight-Style": {
71
+ "repo": "linoyts/Flux2-Klein-Delight-LoRA",
72
+ "weights": "pytorch_lora_weights.safetensors",
73
+ "adapter_name": "klein-delight"
74
+ }
75
+ }
76
+
77
+ LOADED_ADAPTERS = set()
78
+
79
+ print("Loading FLUX.2 Klein 9B model base...")
80
  pipe = Flux2KleinPipeline.from_pretrained(
81
  "black-forest-labs/FLUX.2-klein-9B",
82
  torch_dtype=torch.bfloat16
83
  ).to(device)
84
+ print("Base Model loaded successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ def update_dimensions_on_upload(image):
87
+ """Resizes image to be divisible by 16 to avoid tensor mismatch errors in FLUX."""
88
+ if image is None:
89
+ return 1024, 1024
90
+
91
+ original_width, original_height = image.size
92
+
93
+ # Simple logic to keep aspect ratio but snap to multiples of 16
94
+ # You can adjust the max size (e.g., 1024) as needed
95
+ scale = min(1024 / original_width, 1024 / original_height)
96
+ new_width = int(original_width * scale)
97
+ new_height = int(original_height * scale)
98
+
99
+ new_width = (new_width // 16) * 16
100
+ new_height = (new_height // 16) * 16
101
+
102
+ return new_width, new_height
103
 
104
  @spaces.GPU
105
+ def infer(
106
+ input_image,
107
+ prompt,
108
+ lora_adapter,
109
+ seed=42,
110
+ randomize_seed=True,
111
+ guidance_scale=1.0,
112
+ steps=4,
113
+ progress=gr.Progress(track_tqdm=True)
114
+ ):
115
+ gc.collect()
116
+ torch.cuda.empty_cache()
117
+
118
  if not input_image:
119
  raise gr.Error("Please upload an image to apply a style to.")
120
 
121
+ spec = ADAPTER_SPECS.get(lora_adapter)
122
+ if spec:
123
+ adapter_name = spec["adapter_name"]
124
+
125
+ if adapter_name not in LOADED_ADAPTERS:
126
+ print(f"--- Downloading and Loading Adapter: {lora_adapter} ---")
127
+ try:
128
+ pipe.load_lora_weights(
129
+ spec["repo"],
130
+ weight_name=spec["weights"],
131
+ adapter_name=adapter_name
132
+ )
133
+ LOADED_ADAPTERS.add(adapter_name)
134
+ except Exception as e:
135
+ raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}")
136
+ else:
137
+ print(f"--- Adapter {lora_adapter} is already loaded. ---")
138
+
139
+ print(f"Activating LoRA: {adapter_name}")
140
  pipe.set_adapters([adapter_name], adapter_weights=[1.0])
141
  else:
142
+ print("No valid LoRA selected or found. Disabling adapters.")
 
143
  pipe.disable_lora()
144
+
145
  if randomize_seed:
146
  seed = random.randint(0, MAX_SEED)
147
 
148
+ width, height = update_dimensions_on_upload(input_image)
149
+ processed_input = input_image.resize((width, height), Image.LANCZOS).convert("RGB")
150
 
151
+ # 4. Inference
152
+ try:
153
+ image = pipe(
154
+ image=processed_input,
155
+ prompt=prompt,
156
+ guidance_scale=guidance_scale,
157
+ width=width,
158
+ height=height,
159
+ num_inference_steps=steps,
160
+ generator=torch.Generator(device=device).manual_seed(seed),
161
+ ).images[0]
162
+
163
+ return image, seed
164
 
165
+ except Exception as e:
166
+ raise gr.Error(f"Inference failed: {e}")
167
+ finally:
168
+ gc.collect()
169
+ torch.cuda.empty_cache()
170
 
171
  @spaces.GPU
172
  def infer_example(input_image, prompt, lora_adapter):
173
  # Use a fixed seed for reproducible examples
174
+ if input_image is None:
175
+ return None, 0
176
+
177
+ image, seed = infer(
178
+ input_image=input_image,
179
+ prompt=prompt,
180
+ lora_adapter=lora_adapter,
181
+ seed=12345,
182
+ randomize_seed=False,
183
+ guidance_scale=4.0,
184
+ steps=4
185
+ )
186
  return image, seed
187
 
188
  # --- UI Layout ---
 
196
  gr.Markdown("# **FLUX.2 Klein LoRA Stylizer**", elem_id="main-title")
197
  gr.Markdown(
198
  "Apply creative styles to your images using **FLUX.2-klein-9B** and specialized LoRA adapters. "
199
+ "Adapters are loaded lazily (on-demand) to save resources."
200
  )
201
 
202
  with gr.Row(equal_height=True):
203
  with gr.Column():
204
+ input_image = gr.Image(
205
+ label="Upload Image",
206
+ type="pil",
207
+ height=290,
208
+ sources=["upload", "webcam", "clipboard"]
209
+ )
210
+ prompt = gr.Text(
211
+ label="Guiding Prompt",
212
+ show_label=True,
213
+ placeholder="e.g., a man with a red superhero mask"
214
+ )
215
 
216
  lora_adapter = gr.Dropdown(
217
  label="Choose a Creative Style",
218
+ choices=list(ADAPTER_SPECS.keys()),
 
219
  value="Klein-Delight-Style"
220
  )
221
 
 
224
  with gr.Accordion("Advanced Settings", open=False):
225
  seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
226
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
227
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=0.0, maximum=10.0, step=0.1, value=1.0)
 
228
  steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=4, step=1)
229
 
230
  with gr.Column():
231
  output_image = gr.Image(label="Stylized Image", interactive=False, format="png", height=450)
232
  used_seed = gr.Textbox(label="Used Seed", interactive=False)
233
 
 
234
  gr.Examples(
235
  examples=[
236
  ["examples/animal.jpg", "a cute red panda, charming and delightful illustration, soft lighting", "Klein-Delight-Style"],
237
+ ["examples/portrait.jpg", "cinematic lighting, high contrast", "Simple-Tuner"],
238
  ],
239
  inputs=[input_image, prompt, lora_adapter],
240
  outputs=[output_image, used_seed],