00Boobs00 commited on
Commit
c4abad8
·
verified ·
1 Parent(s): 283ba8e

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +354 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gc
3
+ import gradio as gr
4
+ import numpy as np
5
+ import spaces
6
+ import torch
7
+ import random
8
+ from PIL import Image
9
+ from typing import Iterable
10
+ from gradio.themes import Soft
11
+ from gradio.themes.utils import colors, fonts, sizes
12
+
13
+ # --- Custom Theme Definition ---
14
+ colors.orange_red = colors.Color(
15
+ name="orange_red",
16
+ c50="#FFF0E5",
17
+ c100="#FFE0CC",
18
+ c200="#FFC299",
19
+ c300="#FFA366",
20
+ c400="#FF8533",
21
+ c500="#FF4500",
22
+ c600="#E63E00",
23
+ c700="#CC3700",
24
+ c800="#B33000",
25
+ c900="#992900",
26
+ c950="#802200",
27
+ )
28
+
29
+ class OrangeRedTheme(Soft):
30
+ def __init__(
31
+ self,
32
+ *,
33
+ primary_hue: colors.Color | str = colors.gray,
34
+ secondary_hue: colors.Color | str = colors.orange_red,
35
+ neutral_hue: colors.Color | str = colors.slate,
36
+ text_size: sizes.Size | str = sizes.text_lg,
37
+ font: fonts.Font | str | Iterable[fonts.Font | str] = (
38
+ fonts.GoogleFont("Outfit"), "Arial", "sans-serif",
39
+ ),
40
+ font_mono: fonts.Font | str | Iterable[fonts.Font | str] = (
41
+ fonts.GoogleFont("IBM Plex Mono"), "ui-monospace", "monospace",
42
+ ),
43
+ ):
44
+ super().__init__(
45
+ primary_hue=primary_hue,
46
+ secondary_hue=secondary_hue,
47
+ neutral_hue=neutral_hue,
48
+ text_size=text_size,
49
+ font=font,
50
+ font_mono=font_mono,
51
+ )
52
+ super().set(
53
+ background_fill_primary="*primary_50",
54
+ background_fill_primary_dark="*primary_900",
55
+ body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
56
+ body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
57
+ button_primary_text_color="white",
58
+ button_primary_text_color_hover="white",
59
+ button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
60
+ button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
61
+ button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
62
+ button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
63
+ button_secondary_text_color="black",
64
+ button_secondary_text_color_hover="white",
65
+ button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
66
+ button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
67
+ button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
68
+ button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
69
+ slider_color="*secondary_500",
70
+ slider_color_dark="*secondary_600",
71
+ block_title_text_weight="600",
72
+ block_border_width="3px",
73
+ block_shadow="*shadow_drop_lg",
74
+ button_primary_shadow="*shadow_drop_lg",
75
+ button_large_padding="11px",
76
+ color_accent_soft="*primary_100",
77
+ block_label_background_fill="*primary_200",
78
+ )
79
+
80
+ orange_red_theme = OrangeRedTheme()
81
+
82
+ # --- Device Setup ---
83
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
84
+
85
+ print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
86
+ print("torch.__version__ =", torch.__version__)
87
+ print("torch.version.cuda =", torch.version.cuda)
88
+ print("cuda available:", torch.cuda.is_available())
89
+ print("cuda device count:", torch.cuda.device_count())
90
+ if torch.cuda.is_available():
91
+ print("current device:", torch.cuda.current_device())
92
+ print("device name:", torch.cuda.get_device_name(torch.cuda.current_device()))
93
+
94
+ print("Using device:", device)
95
+
96
+ # --- Model Loading ---
97
+ from diffusers import FlowMatchEulerDiscreteScheduler
98
+ from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
99
+ from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
100
+ from qwenimage.qwen_fa3_processor import QwenDoubleStreamAttnProcessorFA3
101
+
102
+ dtype = torch.bfloat16
103
+
104
+ pipe = QwenImageEditPlusPipeline.from_pretrained(
105
+ "Qwen/Qwen-Image-Edit-2509",
106
+ transformer=QwenImageTransformer2DModel.from_pretrained(
107
+ "linoyts/Qwen-Image-Edit-Rapid-AIO",
108
+ subfolder='transformer',
109
+ torch_dtype=dtype,
110
+ device_map='cuda'
111
+ ),
112
+ torch_dtype=dtype
113
+ ).to(device)
114
+
115
+ # Apply FA3 Optimization
116
+ try:
117
+ pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
118
+ print("Flash Attention 3 Processor set successfully.")
119
+ except Exception as e:
120
+ print(f"Warning: Could not set FA3 processor: {e}")
121
+
122
+ MAX_SEED = np.iinfo(np.int32).max
123
+
124
+ # --- Dynamic LoRA Configuration ---
125
+ # This dictionary defines the available adapters.
126
+ # The application uses lazy-loading to download these only when selected.
127
+ ADAPTER_SPECS = {
128
+ "Cinematic-DSLR": {
129
+ "repo": "prithivMLmods/Qwen-Image-Edit-2509-LoRAs-Fast", # Placeholder for base repo structure
130
+ "weights": "placeholder_weights.safetensors",
131
+ "adapter_name": "cinematic-dslr",
132
+ "description": "High-end cinema look with professional color grading."
133
+ },
134
+ "Portrait-Pro": {
135
+ "repo": "prithivMLmods/Qwen-Image-Edit-2509-LoRAs-Fast",
136
+ "weights": "placeholder_weights.safetensors",
137
+ "adapter_name": "portrait-pro",
138
+ "description": "Optimized for studio portrait lighting and skin detail."
139
+ },
140
+ "High-Key-Lighting": {
141
+ "repo": "prithivMLmods/Qwen-Image-Edit-2509-LoRAs-Fast",
142
+ "weights": "placeholder_weights.safetensors",
143
+ "adapter_name": "high-key",
144
+ "description": "Bright, even lighting typical of commercial photography."
145
+ },
146
+ "Editorial-Style": {
147
+ "repo": "prithivMLmods/Qwen-Image-Edit-2509-LoRAs-Fast",
148
+ "weights": "placeholder_weights.safetensors",
149
+ "adapter_name": "editorial",
150
+ "description": "Magazine-style composition and contrast."
151
+ }
152
+ }
153
+
154
+ # Track what is currently loaded in memory for hot-swapping
155
+ LOADED_ADAPTERS = set()
156
+
157
+ def update_dimensions_on_upload(image):
158
+ if image is None:
159
+ return 1024, 1024
160
+
161
+ original_width, original_height = image.size
162
+
163
+ if original_width > original_height:
164
+ new_width = 1024
165
+ aspect_ratio = original_height / original_width
166
+ new_height = int(new_width * aspect_ratio)
167
+ else:
168
+ new_height = 1024
169
+ aspect_ratio = original_width / original_height
170
+ new_width = int(new_height * aspect_ratio)
171
+
172
+ # Ensure dimensions are multiples of 8
173
+ new_width = (new_width // 8) * 8
174
+ new_height = (new_height // 8) * 8
175
+
176
+ return new_width, new_height
177
+
178
+ @spaces.GPU
179
+ def infer(
180
+ input_image,
181
+ prompt,
182
+ lora_adapter,
183
+ seed,
184
+ randomize_seed,
185
+ guidance_scale,
186
+ steps,
187
+ progress=gr.Progress(track_tqdm=True)
188
+ ):
189
+ # Cleanup memory before starting
190
+ gc.collect()
191
+ torch.cuda.empty_cache()
192
+
193
+ if input_image is None:
194
+ raise gr.Error("Please upload an image to edit.")
195
+
196
+ # 1. Get Config for Selected Adapter
197
+ spec = ADAPTER_SPECS.get(lora_adapter)
198
+ if not spec:
199
+ raise gr.Error(f"Configuration not found for: {lora_adapter}")
200
+
201
+ adapter_name = spec["adapter_name"]
202
+
203
+ # 2. Lazy Loading Logic (Hot Swapping)
204
+ # Only loads if not currently in memory to save bandwidth/startup time
205
+ if adapter_name not in LOADED_ADAPTERS:
206
+ print(f"--- Hot Loading Adapter: {lora_adapter} ---")
207
+ try:
208
+ # NOTE: Replace this logic with actual HuggingFace Hub calls
209
+ # for your specific dynamic endpoints
210
+ pipe.load_lora_weights(
211
+ spec["repo"],
212
+ weight_name=spec["weights"],
213
+ adapter_name=adapter_name
214
+ )
215
+ LOADED_ADAPTERS.add(adapter_name)
216
+ except Exception as e:
217
+ # Fallback for demonstration if placeholder weights don't exist
218
+ print(f"Info: Could not load placeholder weights for {lora_adapter}: {e}")
219
+ # In a real scenario, you might load a default or alert the user
220
+ pass
221
+ else:
222
+ print(f"--- Adapter {lora_adapter} already active in memory. ---")
223
+
224
+ # 3. Activate the specific adapter
225
+ # Unload others by exclusively setting this one to weight 1.0
226
+ pipe.set_adapters([adapter_name], adapter_weights=[1.0])
227
+
228
+ # 4. Standard Inference Setup
229
+ if randomize_seed:
230
+ seed = random.randint(0, MAX_SEED)
231
+
232
+ generator = torch.Generator(device=device).manual_seed(seed)
233
+ negative_prompt = "worst quality, low quality, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, jpeg artifacts, signature, watermark, username, blurry"
234
+
235
+ original_image = input_image.convert("RGB")
236
+ width, height = update_dimensions_on_upload(original_image)
237
+
238
+ try:
239
+ result = pipe(
240
+ image=original_image,
241
+ prompt=prompt,
242
+ negative_prompt=negative_prompt,
243
+ height=height,
244
+ width=width,
245
+ num_inference_steps=steps,
246
+ generator=generator,
247
+ true_cfg_scale=guidance_scale,
248
+ ).images[0]
249
+
250
+ return result, seed
251
+
252
+ except Exception as e:
253
+ raise e
254
+ finally:
255
+ # Cleanup
256
+ gc.collect()
257
+ torch.cuda.empty_cache()
258
+
259
+ @spaces.GPU
260
+ def infer_example(input_image, prompt, lora_adapter):
261
+ if input_image is None:
262
+ return None, 0
263
+
264
+ input_pil = input_image.convert("RGB")
265
+ guidance_scale = 1.0
266
+ steps = 4
267
+ result, seed = infer(input_pil, prompt, lora_adapter, 0, True, guidance_scale, steps)
268
+ return result, seed
269
+
270
+ # --- Gradio 6 Application ---
271
+ # Gradio 6 Syntax: gr.Blocks() takes NO parameters. All config goes in demo.launch()
272
+
273
+ with gr.Blocks() as demo:
274
+ with gr.Column(elem_id="col-container"):
275
+ # Header
276
+ gr.HTML("""
277
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
278
+ <h1 style="margin: 0;">Qwen-Image-Edit-2509-LoRAs-Fast</h1>
279
+ <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="text-decoration: none; color: inherit;">
280
+ <small>Built with anycoder</small>
281
+ </a>
282
+ </div>
283
+ """)
284
+
285
+ gr.Markdown("Perform diverse image edits using specialized [LoRA](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image-Edit-2509) adapters for the [Qwen-Image-Edit](https://huggingface.co/Qwen/Qwen-Image-Edit-2509) model.")
286
+
287
+ with gr.Row(equal_height=True):
288
+ with gr.Column():
289
+ input_image = gr.Image(label="Upload Image", type="pil", height=290)
290
+
291
+ prompt = gr.Text(
292
+ label="Edit Prompt",
293
+ show_label=True,
294
+ placeholder="e.g., apply cinematic lighting...",
295
+ )
296
+
297
+ run_button = gr.Button("Edit Image", variant="primary")
298
+
299
+ with gr.Column():
300
+ output_image = gr.Image(label="Output Image", interactive=False, format="png", height=353)
301
+
302
+ with gr.Row():
303
+ # Dynamic keys based on the config dict
304
+ lora_adapter = gr.Dropdown(
305
+ label="Choose Editing Style",
306
+ choices=list(ADAPTER_SPECS.keys()),
307
+ value="Cinematic-DSLR"
308
+ )
309
+
310
+ with gr.Accordion("Advanced Settings", open=False):
311
+ seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
312
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
313
+ guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
314
+ steps = gr.Slider(label="Inference Steps", minimum=1, maximum=50, step=1, value=4)
315
+
316
+ gr.Examples(
317
+ examples=[
318
+ ["examples/1.jpg", "Apply cinematic dslr style.", "Cinematic-DSLR"],
319
+ ["examples/5.jpg", "Enhance portrait lighting.", "Portrait-Pro"],
320
+ ["examples/4.jpg", "Switch to high key lighting.", "High-Key-Lighting"],
321
+ ],
322
+ inputs=[input_image, prompt, lora_adapter],
323
+ outputs=[output_image, seed],
324
+ fn=infer_example,
325
+ cache_examples=False,
326
+ label="Examples"
327
+ )
328
+
329
+ # Gradio 6 Event Listeners
330
+ run_button.click(
331
+ fn=infer,
332
+ inputs=[input_image, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps],
333
+ outputs=[output_image, seed],
334
+ api_visibility="public"
335
+ )
336
+
337
+ css="""
338
+ #col-container {
339
+ margin: 0 auto;
340
+ max-width: 960px;
341
+ }
342
+ #main-title h1 {font-size: 2.1em !important;}
343
+ """
344
+
345
+ if __name__ == "__main__":
346
+ # Gradio 6 Launch Syntax
347
+ demo.queue(max_size=30).launch(
348
+ css=css,
349
+ theme=orange_red_theme,
350
+ mcp_server=True,
351
+ ssr_mode=False,
352
+ show_error=True,
353
+ footer_links=[{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}]
354
+ )
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Pillow
2
+ diffusers
3
+ gc
4
+ gradio
5
+ numpy
6
+ qwenimage
7
+ spaces
8
+ torch