hitoshifreak commited on
Commit
a0a57dd
·
verified ·
1 Parent(s): 78dfb49

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -246
app.py CHANGED
@@ -48,42 +48,11 @@ class OrangeRedTheme(Soft):
48
  font=font,
49
  font_mono=font_mono,
50
  )
51
- super().set(
52
- background_fill_primary="*primary_50",
53
- background_fill_primary_dark="*primary_900",
54
- body_background_fill="linear-gradient(135deg, *primary_200, *primary_100)",
55
- body_background_fill_dark="linear-gradient(135deg, *primary_900, *primary_800)",
56
- button_primary_text_color="white",
57
- button_primary_text_color_hover="white",
58
- button_primary_background_fill="linear-gradient(90deg, *secondary_500, *secondary_600)",
59
- button_primary_background_fill_hover="linear-gradient(90deg, *secondary_600, *secondary_700)",
60
- button_primary_background_fill_dark="linear-gradient(90deg, *secondary_600, *secondary_700)",
61
- button_primary_background_fill_hover_dark="linear-gradient(90deg, *secondary_500, *secondary_600)",
62
- button_secondary_text_color="black",
63
- button_secondary_text_color_hover="white",
64
- button_secondary_background_fill="linear-gradient(90deg, *primary_300, *primary_300)",
65
- button_secondary_background_fill_hover="linear-gradient(90deg, *primary_400, *primary_400)",
66
- button_secondary_background_fill_dark="linear-gradient(90deg, *primary_500, *primary_600)",
67
- button_secondary_background_fill_hover_dark="linear-gradient(90deg, *primary_500, *primary_500)",
68
- slider_color="*secondary_500",
69
- slider_color_dark="*secondary_600",
70
- block_title_text_weight="600",
71
- block_border_width="3px",
72
- block_shadow="*shadow_drop_lg",
73
- button_primary_shadow="*shadow_drop_lg",
74
- button_large_padding="11px",
75
- color_accent_soft="*primary_100",
76
- block_label_background_fill="*primary_200",
77
- )
78
 
79
  orange_red_theme = OrangeRedTheme()
80
 
81
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
82
 
83
- print("CUDA_VISIBLE_DEVICES=", os.environ.get("CUDA_VISIBLE_DEVICES"))
84
- print("torch.__version__ =", torch.__version__)
85
- print("Using device:", device)
86
-
87
  from diffusers import FlowMatchEulerDiscreteScheduler
88
  from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
89
  from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
@@ -96,14 +65,13 @@ pipe = QwenImageEditPlusPipeline.from_pretrained(
96
  transformer=QwenImageTransformer2DModel.from_pretrained(
97
  "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19",
98
  torch_dtype=dtype,
99
- device_map='cuda'
100
  ),
101
  torch_dtype=dtype
102
  ).to(device)
103
 
104
  try:
105
  pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
106
- print("Flash Attention 3 Processor set successfully.")
107
  except Exception as e:
108
  print(f"Warning: Could not set FA3 processor: {e}")
109
 
@@ -150,61 +118,6 @@ ADAPTER_SPECS = {
150
  "weights": "anything2real_2601.safetensors",
151
  "adapter_name": "anything2real"
152
  },
153
- "Fal-Multiple-Angles": {
154
- "repo": "fal/Qwen-Image-Edit-2511-Multiple-Angles-LoRA",
155
- "weights": "qwen-image-edit-2511-multiple-angles-lora.safetensors",
156
- "adapter_name": "fal-multiple-angles"
157
- },
158
- "Polaroid-Photo": {
159
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Polaroid-Photo",
160
- "weights": "Qwen-Image-Edit-2511-Polaroid-Photo.safetensors",
161
- "adapter_name": "polaroid-photo"
162
- },
163
- "Unblur-Anything": {
164
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Unblur-Upscale",
165
- "weights": "Qwen-Image-Edit-Unblur-Upscale_15.safetensors",
166
- "adapter_name": "unblur-anything"
167
- },
168
- "Midnight-Noir-Eyes-Spotlight": {
169
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Midnight-Noir-Eyes-Spotlight",
170
- "weights": "Qwen-Image-Edit-2511-Midnight-Noir-Eyes-Spotlight.safetensors",
171
- "adapter_name": "midnight-noir-eyes-spotlight"
172
- },
173
- "Hyper-Realistic-Portrait": {
174
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Hyper-Realistic-Portrait",
175
- "weights": "HRP_20.safetensors",
176
- "adapter_name": "hyper-realistic-portrait"
177
- },
178
- "Ultra-Realistic-Portrait": {
179
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Ultra-Realistic-Portrait",
180
- "weights": "URP_20.safetensors",
181
- "adapter_name": "ultra-realistic-portrait"
182
- },
183
- "Pixar-Inspired-3D": {
184
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Pixar-Inspired-3D",
185
- "weights": "PI3_20.safetensors",
186
- "adapter_name": "pi3"
187
- },
188
- "Noir-Comic-Book": {
189
- "repo": "prithivMLmods/Qwen-Image-Edit-2511-Noir-Comic-Book-Panel",
190
- "weights": "Noir-Comic-Book-Panel_20.safetensors",
191
- "adapter_name": "ncb"
192
- },
193
- "Any-light": {
194
- "repo": "lilylilith/QIE-2511-MP-AnyLight",
195
- "weights": "QIE-2511-AnyLight_.safetensors",
196
- "adapter_name": "any-light"
197
- },
198
- "Studio-DeLight": {
199
- "repo": "prithivMLmods/QIE-2511-Studio-DeLight",
200
- "weights": "QIE-2511-Studio-DeLight-5000.safetensors",
201
- "adapter_name": "studio-delight"
202
- },
203
- "Cinematic-FlatLog": {
204
- "repo": "prithivMLmods/QIE-2511-Cinematic-FlatLog-Control",
205
- "weights": "QIE-2511-Cinematic-FlatLog-Control-3200.safetensors",
206
- "adapter_name": "flat-log"
207
- },
208
  }
209
 
210
  LOADED_ADAPTERS = set()
@@ -212,28 +125,26 @@ LOADED_ADAPTERS = set()
212
  def update_dimensions_on_upload(image):
213
  if image is None:
214
  return 1024, 1024
215
-
216
  original_width, original_height = image.size
217
-
218
  if original_width > original_height:
219
  new_width = 1024
220
- aspect_ratio = original_height / original_width
221
- new_height = int(new_width * aspect_ratio)
222
  else:
223
  new_height = 1024
224
- aspect_ratio = original_width / original_height
225
- new_width = int(new_height * aspect_ratio)
226
-
227
  new_width = (new_width // 8) * 8
228
  new_height = (new_height // 8) * 8
229
-
230
  return new_width, new_height
231
 
 
232
  @spaces.GPU
233
  def infer(
234
  images,
235
  prompt,
236
- lora_adapter,
237
  seed,
238
  randomize_seed,
239
  guidance_scale,
@@ -244,49 +155,40 @@ def infer(
244
  torch.cuda.empty_cache()
245
 
246
  if not images:
247
- raise gr.Error("Please upload at least one image to edit.")
248
 
249
  pil_images = []
250
- if images is not None:
251
- for item in images:
252
- try:
253
- if isinstance(item, tuple) or isinstance(item, list):
254
- path_or_img = item[0]
255
- else:
256
- path_or_img = item
257
-
258
- if isinstance(path_or_img, str):
259
- pil_images.append(Image.open(path_or_img).convert("RGB"))
260
- elif isinstance(path_or_img, Image.Image):
261
- pil_images.append(path_or_img.convert("RGB"))
262
- else:
263
- pil_images.append(Image.open(path_or_img.name).convert("RGB"))
264
- except Exception as e:
265
- print(f"Skipping invalid image item: {e}")
266
- continue
267
 
268
- if not pil_images:
269
- raise gr.Error("Could not process uploaded images.")
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
- spec = ADAPTER_SPECS.get(lora_adapter)
272
- if not spec:
273
- raise gr.Error(f"Configuration not found for: {lora_adapter}")
274
 
 
 
275
  adapter_name = spec["adapter_name"]
276
 
277
  if adapter_name not in LOADED_ADAPTERS:
278
- print(f"--- Downloading and Loading Adapter: {lora_adapter} ---")
279
- try:
280
- pipe.load_lora_weights(
281
- spec["repo"],
282
- weight_name=spec["weights"],
283
- adapter_name=adapter_name
284
- )
285
- LOADED_ADAPTERS.add(adapter_name)
286
- except Exception as e:
287
- raise gr.Error(f"Failed to load adapter {lora_adapter}: {e}")
288
- else:
289
- print(f"--- Adapter {lora_adapter} is already loaded. ---")
290
 
291
  pipe.set_adapters([adapter_name], adapter_weights=[1.0])
292
 
@@ -294,136 +196,87 @@ def infer(
294
  seed = random.randint(0, MAX_SEED)
295
 
296
  generator = torch.Generator(device=device).manual_seed(seed)
297
- 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"
298
 
299
  width, height = update_dimensions_on_upload(pil_images[0])
300
 
301
- try:
302
- result_image = pipe(
303
- image=pil_images,
304
- prompt=prompt,
305
- negative_prompt=negative_prompt,
306
- height=height,
307
- width=width,
308
- num_inference_steps=steps,
309
- generator=generator,
310
- true_cfg_scale=guidance_scale,
311
- ).images[0]
312
-
313
- return result_image, seed
314
-
315
- except Exception as e:
316
- raise e
317
- finally:
318
- gc.collect()
319
- torch.cuda.empty_cache()
320
-
321
- @spaces.GPU
322
- def infer_example(images, prompt, lora_adapter):
323
- if not images:
324
- return None, 0
325
-
326
- if isinstance(images, str):
327
- images_list = [images]
328
- else:
329
- images_list = images
330
-
331
- result, seed = infer(
332
- images=images_list,
333
  prompt=prompt,
334
- lora_adapter=lora_adapter,
335
- seed=0,
336
- randomize_seed=True,
337
- guidance_scale=1.0,
338
- steps=4
339
- )
340
- return result, seed
 
 
 
 
 
341
 
342
- css="""
 
343
  #col-container {
344
  margin: 0 auto;
345
- max-width: 1000px;
 
 
 
 
346
  }
347
- #main-title h1 {font-size: 2.4em !important;}
348
  """
349
 
350
- with gr.Blocks() as demo:
351
  with gr.Column(elem_id="col-container"):
352
- gr.Markdown("# **Qwen-Image-Edit-2511-LoRAs-Fast**", elem_id="main-title")
353
- gr.Markdown("Perform diverse image edits using specialized [LoRA](https://huggingface.co/models?other=base_model:adapter:Qwen/Qwen-Image-Edit-2511) adapters. Open on [GitHub](https://github.com/PRITHIVSAKTHIUR/Qwen-Image-Edit-2511-LoRAs-Fast-Lazy-Load).")
354
-
355
- with gr.Row(equal_height=True):
356
- with gr.Column():
357
- images = gr.Gallery(
358
- label="Upload Images",
359
- type="filepath",
360
- columns=2,
361
- rows=1,
362
- height=300,
363
- allow_preview=True
364
- )
365
-
366
- prompt = gr.Text(
367
- label="Edit Prompt",
368
- #max_lines=1,
369
- show_label=True,
370
- placeholder="e.g., transform into anime..",
371
- )
372
-
373
- run_button = gr.Button("Edit Image", variant="primary")
374
-
375
- with gr.Column():
376
- output_image = gr.Image(label="Output Image", interactive=False, format="png", height=365)
377
-
378
- with gr.Row():
379
- lora_adapter = gr.Dropdown(
380
- label="Choose Editing Style",
381
- choices=list(ADAPTER_SPECS.keys()),
382
- value="Photo-to-Anime"
383
- )
384
-
385
- with gr.Accordion("Advanced Settings", open=False, visible=False):
386
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
387
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
388
- guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=10.0, step=0.1, value=1.0)
389
- steps = gr.Slider(label="Inference Steps", minimum=1, maximum=50, step=1, value=4)
390
-
391
- gr.Examples(
392
- examples=[
393
- [["examples/B.jpg"], "Transform into anime.", "Photo-to-Anime"],
394
- [["examples/HRP.jpg"], "Transform into a hyper-realistic face portrait.", "Hyper-Realistic-Portrait"],
395
- [["examples/A.jpeg"], "Rotate the camera 45 degrees to the right.", "Multiple-Angles"],
396
- [["examples/U.jpg"], "Upscale this picture to 4K resolution.", "Upscaler"],
397
- [["examples/L1.jpg", "examples/L2.jpg"], "Apply the lighting from image 2 to image 1.", "Any-light"],
398
- [["examples/PP1.jpg"], "cinematic polaroid with soft grain subtle vignette gentle lighting white frame handwritten photographed by hf‪‪‬ preserving realistic texture and details", "Polaroid-Photo"],
399
- [["examples/Z1.jpg"], "Front-right quarter view.", "Fal-Multiple-Angles"],
400
- [["examples/URP.jpg"], "Transform into a cinematic flat log.", "Cinematic-FlatLog"],
401
- [["examples/SL.jpg"], "Neutral uniform lighting Preserve identity and composition.", "Studio-DeLight"],
402
- [["examples/PI.jpg"], "Transform it into Pixar-inspired 3D.", "Pixar-Inspired-3D"],
403
- [["examples/MT.jpg"], "Paint with manga tone.", "Manga-Tone"],
404
- [["examples/NCB.jpg"], "Transform into a noir comic book style.", "Noir-Comic-Book"],
405
- [["examples/URP.jpg"], "ultra-realistic portrait.", "Ultra-Realistic-Portrait"],
406
- [["examples/MN.jpg"], "Transform into Midnight Noir Eyes Spotlight.", "Midnight-Noir-Eyes-Spotlight"],
407
- [["examples/ST1.jpg", "examples/ST2.jpg"], "Convert Image 1 to the style of Image 2.", "Style-Transfer"],
408
- [["examples/R1.jpg"], "Change the picture to realistic photograph.", "Anything2Real"],
409
- [["examples/UA.jpeg"], "Unblur and upscale.", "Unblur-Anything"],
410
- [["examples/L1.jpg", "examples/L2.jpg"], "Refer to the color tone, remove the original lighting from Image 1, and relight Image 1 based on the lighting and color tone of Image 2.", "Light-Migration"],
411
- [["examples/P1.jpg"], "Transform into anime (while preserving the background and remaining elements maintaining realism and original details.)", "Anime-V2"],
412
- ],
413
- inputs=[images, prompt, lora_adapter],
414
- outputs=[output_image, seed],
415
- fn=infer_example,
416
- cache_examples=False,
417
- label="Examples"
418
  )
419
-
420
- gr.Markdown("[*](https://huggingface.co/spaces/prithivMLmods/Qwen-Image-Edit-2511-LoRAs-Fast)This is still an experimental Space for Qwen-Image-Edit-2511.")
 
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
  run_button.click(
423
  fn=infer,
424
- inputs=[images, prompt, lora_adapter, seed, randomize_seed, guidance_scale, steps],
 
 
 
 
 
 
 
425
  outputs=[output_image, seed]
426
  )
427
 
428
  if __name__ == "__main__":
429
- demo.queue(max_size=30).launch(css=css, theme=orange_red_theme, mcp_server=True, ssr_mode=False, show_error=True)
 
 
 
 
 
48
  font=font,
49
  font_mono=font_mono,
50
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  orange_red_theme = OrangeRedTheme()
53
 
54
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
55
 
 
 
 
 
56
  from diffusers import FlowMatchEulerDiscreteScheduler
57
  from qwenimage.pipeline_qwenimage_edit_plus import QwenImageEditPlusPipeline
58
  from qwenimage.transformer_qwenimage import QwenImageTransformer2DModel
 
65
  transformer=QwenImageTransformer2DModel.from_pretrained(
66
  "prithivMLmods/Qwen-Image-Edit-Rapid-AIO-V19",
67
  torch_dtype=dtype,
68
+ device_map="cuda"
69
  ),
70
  torch_dtype=dtype
71
  ).to(device)
72
 
73
  try:
74
  pipe.transformer.set_attn_processor(QwenDoubleStreamAttnProcessorFA3())
 
75
  except Exception as e:
76
  print(f"Warning: Could not set FA3 processor: {e}")
77
 
 
118
  "weights": "anything2real_2601.safetensors",
119
  "adapter_name": "anything2real"
120
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  }
122
 
123
  LOADED_ADAPTERS = set()
 
125
  def update_dimensions_on_upload(image):
126
  if image is None:
127
  return 1024, 1024
128
+
129
  original_width, original_height = image.size
130
+
131
  if original_width > original_height:
132
  new_width = 1024
133
+ new_height = int(new_width * (original_height / original_width))
 
134
  else:
135
  new_height = 1024
136
+ new_width = int(new_height * (original_width / original_height))
137
+
 
138
  new_width = (new_width // 8) * 8
139
  new_height = (new_height // 8) * 8
140
+
141
  return new_width, new_height
142
 
143
+
144
  @spaces.GPU
145
  def infer(
146
  images,
147
  prompt,
 
148
  seed,
149
  randomize_seed,
150
  guidance_scale,
 
155
  torch.cuda.empty_cache()
156
 
157
  if not images:
158
+ raise gr.Error("Please upload an image.")
159
 
160
  pil_images = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
 
162
+ for item in images:
163
+ try:
164
+ if isinstance(item, tuple) or isinstance(item, list):
165
+ path_or_img = item[0]
166
+ else:
167
+ path_or_img = item
168
+
169
+ if isinstance(path_or_img, str):
170
+ pil_images.append(Image.open(path_or_img).convert("RGB"))
171
+ elif isinstance(path_or_img, Image.Image):
172
+ pil_images.append(path_or_img.convert("RGB"))
173
+ else:
174
+ pil_images.append(Image.open(path_or_img.name).convert("RGB"))
175
+ except Exception:
176
+ continue
177
 
178
+ if not pil_images:
179
+ raise gr.Error("Could not process uploaded image.")
 
180
 
181
+ # LOCKED STYLE
182
+ spec = ADAPTER_SPECS["Anything2Real"]
183
  adapter_name = spec["adapter_name"]
184
 
185
  if adapter_name not in LOADED_ADAPTERS:
186
+ pipe.load_lora_weights(
187
+ spec["repo"],
188
+ weight_name=spec["weights"],
189
+ adapter_name=adapter_name
190
+ )
191
+ LOADED_ADAPTERS.add(adapter_name)
 
 
 
 
 
 
192
 
193
  pipe.set_adapters([adapter_name], adapter_weights=[1.0])
194
 
 
196
  seed = random.randint(0, MAX_SEED)
197
 
198
  generator = torch.Generator(device=device).manual_seed(seed)
 
199
 
200
  width, height = update_dimensions_on_upload(pil_images[0])
201
 
202
+ result_image = pipe(
203
+ image=pil_images,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  prompt=prompt,
205
+ negative_prompt="worst quality, blurry, watermark",
206
+ height=height,
207
+ width=width,
208
+ num_inference_steps=steps,
209
+ generator=generator,
210
+ true_cfg_scale=guidance_scale,
211
+ ).images[0]
212
+
213
+ gc.collect()
214
+ torch.cuda.empty_cache()
215
+
216
+ return result_image, seed
217
 
218
+
219
+ css = """
220
  #col-container {
221
  margin: 0 auto;
222
+ max-width: 850px;
223
+ }
224
+ #main-title h1 {
225
+ font-size: 2.4em !important;
226
+ text-align: center;
227
  }
 
228
  """
229
 
230
+ with gr.Blocks(theme=orange_red_theme, css=css) as demo:
231
  with gr.Column(elem_id="col-container"):
232
+ gr.Markdown("# **Image Nsfw Editor**", elem_id="main-title")
233
+ gr.Markdown("Upload an image and transform it into NSFW.")
234
+
235
+ input_image = gr.Gallery(
236
+ label="Upload Image",
237
+ type="filepath",
238
+ columns=1,
239
+ rows=1,
240
+ height=350,
241
+ allow_preview=True
242
+ )
243
+
244
+ prompt = gr.Textbox(
245
+ label="Prompt",
246
+ placeholder="Describe the realistic transformation..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
247
  )
248
+
249
+ run_button = gr.Button("Generate", variant="primary")
250
+
251
+ output_image = gr.Image(
252
+ label="Output",
253
+ interactive=False,
254
+ format="png",
255
+ height=500
256
+ )
257
+
258
+ # hidden backend essentials
259
+ seed = gr.State(0)
260
+ randomize_seed = gr.State(True)
261
+ guidance_scale = gr.State(1.0)
262
+ steps = gr.State(4)
263
 
264
  run_button.click(
265
  fn=infer,
266
+ inputs=[
267
+ input_image,
268
+ prompt,
269
+ seed,
270
+ randomize_seed,
271
+ guidance_scale,
272
+ steps
273
+ ],
274
  outputs=[output_image, seed]
275
  )
276
 
277
  if __name__ == "__main__":
278
+ demo.queue(max_size=30).launch(
279
+ mcp_server=True,
280
+ ssr_mode=False,
281
+ show_error=True
282
+ )