zhoudewei.666 commited on
Commit
12c29f6
·
1 Parent(s): b05a72d
Files changed (2) hide show
  1. app.py +890 -133
  2. requirements.txt +8 -5
app.py CHANGED
@@ -1,154 +1,911 @@
1
- import gradio as gr
2
- import numpy as np
3
- import random
4
-
5
- # import spaces #[uncomment to use ZeroGPU]
6
- from diffusers import DiffusionPipeline
7
- import torch
8
-
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- model_repo_id = "stabilityai/sdxl-turbo" # Replace to the model you would like to use
11
-
12
- if torch.cuda.is_available():
13
- torch_dtype = torch.float16
14
- else:
15
- torch_dtype = torch.float32
16
-
17
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
18
- pipe = pipe.to(device)
19
-
20
- MAX_SEED = np.iinfo(np.int32).max
21
- MAX_IMAGE_SIZE = 1024
22
-
23
-
24
- # @spaces.GPU #[uncomment to use ZeroGPU]
25
- def infer(
26
- prompt,
27
- negative_prompt,
28
- seed,
29
- randomize_seed,
30
- width,
31
- height,
32
- guidance_scale,
33
- num_inference_steps,
34
- progress=gr.Progress(track_tqdm=True),
35
- ):
36
- if randomize_seed:
37
- seed = random.randint(0, MAX_SEED)
38
-
39
- generator = torch.Generator().manual_seed(seed)
40
-
41
- image = pipe(
42
- prompt=prompt,
43
- negative_prompt=negative_prompt,
44
- guidance_scale=guidance_scale,
45
- num_inference_steps=num_inference_steps,
46
- width=width,
47
- height=height,
48
- generator=generator,
49
- ).images[0]
50
-
51
- return image, seed
52
-
53
-
54
- examples = [
55
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
56
- "An astronaut riding a green horse",
57
- "A delicious ceviche cheesecake slice",
58
- ]
59
-
60
- css = """
61
- #col-container {
62
- margin: 0 auto;
63
- max-width: 640px;
64
- }
65
- """
66
-
67
- with gr.Blocks(css=css) as demo:
68
- with gr.Column(elem_id="col-container"):
69
- gr.Markdown(" # Text-to-Image Gradio Template")
70
-
71
- with gr.Row():
72
- prompt = gr.Text(
73
- label="Prompt",
74
- show_label=False,
75
- max_lines=1,
76
- placeholder="Enter your prompt",
77
- container=False,
78
- )
79
 
80
- run_button = gr.Button("Run", scale=0, variant="primary")
 
 
 
 
 
81
 
82
- result = gr.Image(label="Result", show_label=False)
83
 
84
- with gr.Accordion("Advanced Settings", open=False):
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
  )
 
 
 
 
99
 
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
 
 
 
 
101
 
102
- with gr.Row():
103
- width = gr.Slider(
104
- label="Width",
105
- minimum=256,
106
- maximum=MAX_IMAGE_SIZE,
107
- step=32,
108
- value=1024, # Replace with defaults that work for your model
109
- )
110
 
111
- height = gr.Slider(
112
- label="Height",
113
- minimum=256,
114
- maximum=MAX_IMAGE_SIZE,
115
- step=32,
116
- value=1024, # Replace with defaults that work for your model
117
- )
118
 
119
- with gr.Row():
120
- guidance_scale = gr.Slider(
121
- label="Guidance scale",
122
- minimum=0.0,
123
- maximum=10.0,
124
- step=0.1,
125
- value=0.0, # Replace with defaults that work for your model
126
- )
127
 
128
- num_inference_steps = gr.Slider(
129
- label="Number of inference steps",
130
- minimum=1,
131
- maximum=50,
132
- step=1,
133
- value=2, # Replace with defaults that work for your model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- gr.Examples(examples=examples, inputs=[prompt])
137
- gr.on(
138
- triggers=[run_button.click, prompt.submit],
139
- fn=infer,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  inputs=[
 
 
141
  prompt,
142
- negative_prompt,
 
 
 
 
143
  seed,
144
- randomize_seed,
145
- width,
146
- height,
147
  guidance_scale,
148
- num_inference_steps,
 
 
 
 
 
 
 
 
 
149
  ],
150
- outputs=[result, seed],
 
151
  )
 
 
 
 
 
 
 
152
 
153
  if __name__ == "__main__":
154
- demo.launch()
 
1
+ import math
2
+ import os
3
+ import threading
4
+ import time
5
+
6
+ try:
7
+ import spaces
8
+ _HAS_SPACES = True
9
+ except ImportError:
10
+ _HAS_SPACES = False
11
+
12
+
13
+ def setup_debug():
14
+ import debugpy
15
+ rank = int(os.environ.get("RANK", 0))
16
+ if rank == 0:
17
+ debugpy.listen(5679)
18
+ print("wait for debug")
19
+ debugpy.wait_for_client()
20
+
21
+ def calculate_dimensions(target_area: int, ratio: float):
22
+ width = math.sqrt(target_area * ratio)
23
+ height = width / ratio
24
+ width = round(width / 32) * 32
25
+ height = round(height / 32) * 32
26
+ return int(width), int(height), None
27
+
28
+
29
+ def vit_resize_dims(src_w: int, src_h: int, vit_resize_size: int = 384) -> tuple[int, int]:
30
+ ratio = float(src_w) / float(src_h) if src_h else 1.0
31
+ new_w, new_h, _ = calculate_dimensions(vit_resize_size * vit_resize_size, ratio)
32
+ return new_w, new_h
33
+
34
+
35
+ def scale_bbox_xyxy(
36
+ bbox_xyxy: tuple[int, int, int, int],
37
+ src_w: int,
38
+ src_h: int,
39
+ dst_w: int,
40
+ dst_h: int,
41
+ ) -> tuple[int, int, int, int]:
42
+ sx = float(dst_w) / float(src_w) if src_w else 1.0
43
+ sy = float(dst_h) / float(src_h) if src_h else 1.0
44
+ x1, y1, x2, y2 = bbox_xyxy
45
+ return (
46
+ int(round(x1 * sx)),
47
+ int(round(y1 * sy)),
48
+ int(round(x2 * sx)),
49
+ int(round(y2 * sy)),
50
+ )
51
+
52
+
53
+ def format_bbox_xyxy(bbox_xyxy: tuple[int, int, int, int]) -> str:
54
+ x1, y1, x2, y2 = bbox_xyxy
55
+ return f"[{x1}, {y1}, {x2}, {y2}]"
56
+
57
+
58
+ def draw_bbox_on_image(image, bbox_xyxy: tuple[int, int, int, int]):
59
+ from PIL import ImageDraw
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
+ x1, y1, x2, y2 = bbox_xyxy
62
+ vis = image.copy()
63
+ draw = ImageDraw.Draw(vis)
64
+ w = max(2, int(round(min(vis.size) * 0.006)))
65
+ draw.rectangle((x1, y1, x2, y2), outline=(255, 64, 64), width=w)
66
+ return vis
67
 
 
68
 
69
+ def draw_points_on_image(image, points: list[tuple[int, int]], *, connect: bool = False):
70
+ from PIL import ImageDraw
71
+
72
+ vis = image.copy()
73
+ draw = ImageDraw.Draw(vis)
74
+ w, h = vis.size
75
+ r = max(2, int(round(min(w, h) * 0.004)))
76
+ if connect and len(points) >= 2:
77
+ draw.line(points + [points[0]], fill=(255, 64, 64), width=max(1, r // 2))
78
+ for x, y in points:
79
+ draw.ellipse((x - r, y - r, x + r, y + r), fill=(64, 255, 64), outline=(0, 0, 0))
80
+ return vis
81
+
82
+
83
+ _HF_LORA_REPO = "limuloo1999/RefineAnything"
84
+ _HF_LORA_FILENAME = "Qwen-Image-Edit-2511-RefineAny.safetensors"
85
+ _HF_LORA_ADAPTER = "refine_anything"
86
+
87
+ _PIPELINE = None
88
+ _PIPELINE_KEY = None
89
+ _LORA_LOADED = False
90
+ _LIGHTNING_LOADED = False
91
+ _PIPELINE_LOCK = threading.Lock()
92
+
93
+
94
+ def _ensure_hf_lora() -> str:
95
+ """Download the LoRA weights from HuggingFace Hub and return the local path."""
96
+ from huggingface_hub import hf_hub_download
97
+
98
+ return hf_hub_download(repo_id=_HF_LORA_REPO, filename=_HF_LORA_FILENAME)
99
+
100
+
101
+ def _get_pipeline(model_dir: str, device: str, load_lightning_lora: bool):
102
+ global _PIPELINE, _PIPELINE_KEY, _LORA_LOADED, _LIGHTNING_LOADED
103
+ base_key = (model_dir, device)
104
+
105
+ with _PIPELINE_LOCK:
106
+ if _PIPELINE is None or _PIPELINE_KEY != base_key:
107
+ import torch
108
+ from diffusers import FlowMatchEulerDiscreteScheduler, QwenImageEditPlusPipeline
109
+
110
+ scheduler_config = {
111
+ "base_image_seq_len": 256,
112
+ "base_shift": math.log(3),
113
+ "invert_sigmas": False,
114
+ "max_image_seq_len": 8192,
115
+ "max_shift": math.log(3),
116
+ "num_train_timesteps": 1000,
117
+ "shift": 1.0,
118
+ "shift_terminal": None,
119
+ "stochastic_sampling": False,
120
+ "time_shift_type": "exponential",
121
+ "use_beta_sigmas": False,
122
+ "use_dynamic_shifting": True,
123
+ "use_exponential_sigmas": False,
124
+ "use_karras_sigmas": False,
125
+ }
126
+ scheduler = FlowMatchEulerDiscreteScheduler.from_config(scheduler_config)
127
+ pipe = QwenImageEditPlusPipeline.from_pretrained(
128
+ model_dir,
129
+ torch_dtype=torch.bfloat16,
130
+ scheduler=scheduler,
131
  )
132
+ pipe.to(device)
133
+ pipe.set_progress_bar_config(disable=None)
134
+
135
+ _PIPELINE = pipe
136
+ _PIPELINE_KEY = base_key
137
+ _LORA_LOADED = False
138
+ _LIGHTNING_LOADED = False
139
+
140
+ if not _LORA_LOADED:
141
+ local_path = _ensure_hf_lora()
142
+ lora_dir = os.path.dirname(local_path)
143
+ weight_name = os.path.basename(local_path)
144
+ _PIPELINE.load_lora_weights(lora_dir, weight_name=weight_name, adapter_name=_HF_LORA_ADAPTER)
145
+ _LORA_LOADED = True
146
+
147
+ if load_lightning_lora and not _LIGHTNING_LOADED:
148
+ from huggingface_hub import hf_hub_download
149
 
150
+ lightning_path = hf_hub_download(
151
+ repo_id="lightx2v/Qwen-Image-Edit-2511-Lightning",
152
+ filename="Qwen-Image-Edit-2511-Lightning-8steps-V1.0-bf16.safetensors",
 
 
 
153
  )
154
+ lightning_dir = os.path.dirname(lightning_path)
155
+ lightning_weight = os.path.basename(lightning_path)
156
+ _PIPELINE.load_lora_weights(lightning_dir, weight_name=lightning_weight, adapter_name="lightning")
157
+ _LIGHTNING_LOADED = True
158
 
159
+ adapter_names: list[str] = [_HF_LORA_ADAPTER]
160
+ adapter_weights: list[float] = [1.0]
161
+ if _LIGHTNING_LOADED:
162
+ adapter_names.append("lightning")
163
+ adapter_weights.append(1.0 if load_lightning_lora else 0.0)
164
 
165
+ if hasattr(_PIPELINE, "set_adapters"):
166
+ try:
167
+ _PIPELINE.set_adapters(adapter_names, adapter_weights=adapter_weights)
168
+ except TypeError:
169
+ _PIPELINE.set_adapters(adapter_names, adapter_weights=[1.0] * len(adapter_names))
 
 
 
170
 
171
+ return _PIPELINE
 
 
 
 
 
 
172
 
 
 
 
 
 
 
 
 
173
 
174
+ def build_app(
175
+ *,
176
+ default_model_dir: str,
177
+ default_device: str,
178
+ ):
179
+ import base64
180
+ import gradio as gr
181
+ import inspect
182
+ import io
183
+ import numpy as np
184
+ import random
185
+ import re
186
+ from PIL import Image
187
+
188
+ def _to_float01_rgb(img: Image.Image) -> np.ndarray:
189
+ arr = np.asarray(img.convert("RGB")).astype(np.float32) / 255.0
190
+ return arr
191
+
192
+ def _to_float01_mask(mask_img: Image.Image) -> np.ndarray:
193
+ arr = np.asarray(mask_img.convert("L")).astype(np.float32) / 255.0
194
+ return arr
195
+
196
+ def composite_masked(
197
+ *,
198
+ destination: Image.Image,
199
+ source: Image.Image,
200
+ mask: Image.Image,
201
+ resize_source: bool = True,
202
+ ) -> Image.Image:
203
+ dst = destination.convert("RGB")
204
+ if resize_source and getattr(source, "size", None) != dst.size:
205
+ src = source.convert("RGB").resize(dst.size, resample=Image.BICUBIC)
206
+ else:
207
+ src = source.convert("RGB")
208
+
209
+ m = mask.convert("L")
210
+ if getattr(m, "size", None) != dst.size:
211
+ m = m.resize(dst.size, resample=Image.BILINEAR)
212
+
213
+ dst_f = _to_float01_rgb(dst)
214
+ src_f = _to_float01_rgb(src)
215
+ m_f = _to_float01_mask(m)[:, :, None]
216
+ out = src_f * m_f + dst_f * (1.0 - m_f)
217
+ out = np.clip(out * 255.0 + 0.5, 0, 255).astype(np.uint8)
218
+ return Image.fromarray(out, mode="RGB")
219
+
220
+ def prepare_paste_mask(
221
+ mask_l: Image.Image,
222
+ *,
223
+ mask_grow: int = 0,
224
+ blend_kernel: int = 0,
225
+ ) -> Image.Image:
226
+ from PIL import ImageFilter
227
+
228
+ m = mask_l.convert("L")
229
+ if mask_grow and int(mask_grow) > 0:
230
+ k = 2 * int(mask_grow) + 1
231
+ m = m.filter(ImageFilter.MaxFilter(size=k))
232
+ if blend_kernel and int(blend_kernel) > 0:
233
+ m = m.filter(ImageFilter.GaussianBlur(radius=float(blend_kernel)))
234
+ return m
235
+
236
+ def make_bbox_mask(
237
+ *,
238
+ size: tuple[int, int],
239
+ bbox_xyxy: tuple[int, int, int, int],
240
+ mask_grow: int = 0,
241
+ blend_kernel: int = 0,
242
+ ) -> Image.Image:
243
+ from PIL import ImageDraw, ImageFilter
244
+
245
+ w, h = size
246
+ x1, y1, x2, y2 = bbox_xyxy
247
+ x1 = max(0, min(w - 1, int(x1)))
248
+ y1 = max(0, min(h - 1, int(y1)))
249
+ x2 = max(1, min(w, int(x2)))
250
+ y2 = max(1, min(h, int(y2)))
251
+
252
+ m = Image.new("L", (w, h), 0)
253
+ draw = ImageDraw.Draw(m)
254
+ draw.rectangle((x1, y1, max(x1, x2 - 1), max(y1, y2 - 1)), fill=255)
255
+
256
+ if mask_grow and int(mask_grow) > 0:
257
+ k = 2 * int(mask_grow) + 1
258
+ m = m.filter(ImageFilter.MaxFilter(size=k))
259
+
260
+ if blend_kernel and int(blend_kernel) > 0:
261
+ m = m.filter(ImageFilter.GaussianBlur(radius=float(blend_kernel)))
262
+
263
+ return m
264
+
265
+ def compute_crop_box_xyxy(
266
+ *,
267
+ image_size: tuple[int, int],
268
+ bbox_xyxy: tuple[int, int, int, int],
269
+ margin: int,
270
+ ) -> tuple[int, int, int, int]:
271
+ w, h = image_size
272
+ x1, y1, x2, y2 = bbox_xyxy
273
+ m = max(0, int(margin))
274
+ cx1 = max(0, min(w - 1, int(x1) - m))
275
+ cy1 = max(0, min(h - 1, int(y1) - m))
276
+ cx2 = max(1, min(w, int(x2) + m))
277
+ cy2 = max(1, min(h, int(y2) + m))
278
+ if cx2 <= cx1:
279
+ cx2 = min(w, cx1 + 1)
280
+ if cy2 <= cy1:
281
+ cy2 = min(h, cy1 + 1)
282
+ return (cx1, cy1, cx2, cy2)
283
+
284
+ def crop_box_from_1024_area_margin(
285
+ *,
286
+ image_size: tuple[int, int],
287
+ bbox_xyxy: tuple[int, int, int, int],
288
+ margin: int,
289
+ ) -> tuple[int, int, int, int]:
290
+ iw, ih = image_size
291
+ if iw <= 0 or ih <= 0:
292
+ return compute_crop_box_xyxy(image_size=image_size, bbox_xyxy=bbox_xyxy, margin=margin)
293
+ s = math.sqrt(1024 * 1024 / float(iw * ih))
294
+ vw, vh = float(iw) * s, float(ih) * s
295
+ x1, y1, x2, y2 = bbox_xyxy
296
+ vx1 = max(0.0, min(vw - 1.0, float(x1) * s - float(margin)))
297
+ vy1 = max(0.0, min(vh - 1.0, float(y1) * s - float(margin)))
298
+ vx2 = max(1.0, min(vw, float(x2) * s + float(margin)))
299
+ vy2 = max(1.0, min(vh, float(y2) * s + float(margin)))
300
+ if vx2 <= vx1:
301
+ vx2 = min(vw, vx1 + 1.0)
302
+ if vy2 <= vy1:
303
+ vy2 = min(vh, vy1 + 1.0)
304
+ cx1 = max(0, min(iw - 1, int(math.floor(vx1 / s))))
305
+ cy1 = max(0, min(ih - 1, int(math.floor(vy1 / s))))
306
+ cx2 = max(1, min(iw, int(math.ceil(vx2 / s))))
307
+ cy2 = max(1, min(ih, int(math.ceil(vy2 / s))))
308
+ if cx2 <= cx1:
309
+ cx2 = min(iw, cx1 + 1)
310
+ if cy2 <= cy1:
311
+ cy2 = min(ih, cy1 + 1)
312
+ return (cx1, cy1, cx2, cy2)
313
+
314
+ def offset_bbox_xyxy(bbox_xyxy: tuple[int, int, int, int], dx: int, dy: int) -> tuple[int, int, int, int]:
315
+ x1, y1, x2, y2 = bbox_xyxy
316
+ return (int(x1) - int(dx), int(y1) - int(dy), int(x2) - int(dx), int(y2) - int(dy))
317
+
318
+ def _decode_data_url(x):
319
+ if not isinstance(x, str):
320
+ return None
321
+ s = x
322
+ if s.startswith("data:") and "," in s:
323
+ s = s.split(",", 1)[1]
324
+ try:
325
+ data = base64.b64decode(s)
326
+ except Exception:
327
+ return None
328
+ try:
329
+ return Image.open(io.BytesIO(data))
330
+ except Exception:
331
+ return None
332
+
333
+ def _to_rgb_pil(x, *, label: str):
334
+ if x is None:
335
+ return None
336
+ if isinstance(x, str):
337
+ x2 = _decode_data_url(x)
338
+ if x2 is None:
339
+ raise gr.Error(f"{label} 数���格式不支持")
340
+ x = x2
341
+ if isinstance(x, np.ndarray):
342
+ x = Image.fromarray(x.astype(np.uint8))
343
+ if not hasattr(x, "convert"):
344
+ raise gr.Error(f"{label} 数据格式不支持")
345
+ try:
346
+ return x.convert("RGB")
347
+ except Exception as e:
348
+ raise gr.Error(f"{label} 转换 RGB 失败: {type(e).__name__}: {e}")
349
+
350
+ def mask_to_points_sample_list(mask_img: Image.Image, *, num_points: int = 64, seed: int = 0) -> tuple[str, list[tuple[int, int]]]:
351
+ arr = np.array(mask_img.convert("L"), dtype=np.uint8)
352
+ if arr.max() <= 1:
353
+ mask = arr.astype(bool)
354
+ else:
355
+ mask = arr > 0
356
+ ys, xs = np.where(mask)
357
+ if xs.size == 0:
358
+ raise gr.Error("mask 为空,无法从中采样点")
359
+ rng = random.Random(int(seed))
360
+ idxs = list(range(int(xs.size)))
361
+ rng.shuffle(idxs)
362
+ idxs = idxs[: int(num_points)]
363
+ pts = [(int(xs[i]), int(ys[i])) for i in idxs]
364
+ s = "[" + ", ".join(f"({int(x)},{int(y)})" for (x, y) in pts) + "]"
365
+ return s, pts
366
+
367
+ def strip_special_region(prompt: str) -> str:
368
+ p = (prompt or "").replace("<SPECIAL_REGION>", " ")
369
+ p = p.replace("\n", " ")
370
+ p = re.sub(r"\s{2,}", " ", p).strip()
371
+ return p
372
+
373
+ def strip_location_text(prompt: str) -> str:
374
+ p = strip_special_region(prompt)
375
+ p = re.sub(r"\[\s*\d+\s*,\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\]", "", p)
376
+ p = re.sub(r"\s{2,}", " ", p).strip()
377
+ return p
378
+
379
+ def mask_has_foreground(mask_l: Image.Image) -> bool:
380
+ arr = np.array(mask_l.convert("L"), dtype=np.uint8)
381
+ return bool(arr.max() > 0)
382
+
383
+ def mask_bbox_xyxy(mask_img_l: Image.Image) -> tuple[int, int, int, int] | None:
384
+ arr = np.array(mask_img_l.convert("L"), dtype=np.uint8)
385
+ ys, xs = np.where(arr > 0)
386
+ if xs.size == 0 or ys.size == 0:
387
+ return None
388
+ x1 = int(xs.min())
389
+ x2 = int(xs.max()) + 1
390
+ y1 = int(ys.min())
391
+ y2 = int(ys.max()) + 1
392
+ w, h = mask_img_l.size
393
+ x1 = max(0, min(w - 1, x1))
394
+ y1 = max(0, min(h - 1, y1))
395
+ x2 = max(1, min(w, x2))
396
+ y2 = max(1, min(h, y2))
397
+ if x2 <= x1 or y2 <= y1:
398
+ return None
399
+ return (x1, y1, x2, y2)
400
+
401
+ def render_spatial_prompt(mask_img_l: Image.Image, *, source: str, bbox_margin: int = 0) -> Image.Image | None:
402
+ src = (source or "mask").strip().lower()
403
+ if src == "bbox":
404
+ bbox = mask_bbox_xyxy(mask_img_l)
405
+ if bbox is None:
406
+ return None
407
+ w, h = mask_img_l.size
408
+ out = Image.new("L", (w, h), 0)
409
+ x1, y1, x2, y2 = bbox
410
+ m = max(0, int(bbox_margin))
411
+ x1 = max(0, x1 - m)
412
+ y1 = max(0, y1 - m)
413
+ x2 = min(w, x2 + m)
414
+ y2 = min(h, y2 + m)
415
+ from PIL import ImageDraw
416
+
417
+ draw = ImageDraw.Draw(out)
418
+ draw.rectangle((x1, y1, max(x1, x2 - 1), max(y1, y2 - 1)), fill=255)
419
+ return out
420
+ arr = np.array(mask_img_l.convert("L"), dtype=np.uint8)
421
+ arr = np.where(arr > 0, 255, 0).astype(np.uint8)
422
+ return Image.fromarray(arr, mode="L")
423
+
424
+ def overlay_mask_on_image(image_rgb: Image.Image, mask_l: Image.Image) -> Image.Image:
425
+ base = image_rgb.convert("RGB")
426
+ m = mask_l.convert("L")
427
+ if getattr(m, "size", None) != base.size:
428
+ m = m.resize(base.size, resample=Image.NEAREST)
429
+ base_f = np.asarray(base).astype(np.float32)
430
+ mf = (np.asarray(m).astype(np.float32) > 0)[:, :, None].astype(np.float32)
431
+ color = np.array([64.0, 255.0, 64.0], dtype=np.float32)[None, None, :]
432
+ alpha = 0.35
433
+ out = base_f * (1.0 - alpha * mf) + color * (alpha * mf)
434
+ out = np.clip(out + 0.5, 0, 255).astype(np.uint8)
435
+ return Image.fromarray(out, mode="RGB")
436
+
437
+ def extract_bbox_from_image1(image1_value):
438
+ if image1_value is None:
439
+ raise gr.Error("image1 必须上传")
440
+ if not isinstance(image1_value, dict):
441
+ raise gr.Error("image1 数据格式不支持")
442
+
443
+ if "image" in image1_value and "mask" in image1_value:
444
+ img = image1_value["image"]
445
+ mask = image1_value["mask"]
446
+ if img is None:
447
+ raise gr.Error("image1 必须上传")
448
+ elif "background" in image1_value and "layers" in image1_value:
449
+ img = image1_value.get("background") or image1_value.get("composite")
450
+ layers = image1_value.get("layers") or []
451
+ if img is None:
452
+ raise gr.Error("image1 数据缺少 background/composite")
453
+ mask = layers if layers else None
454
+ else:
455
+ raise gr.Error("请在 image1 上涂抹选择区域")
456
+
457
+ if isinstance(img, str):
458
+ img2 = _decode_data_url(img)
459
+ if img2 is None:
460
+ raise gr.Error("image1 数据格式不支持��image)")
461
+ img = img2
462
+ if isinstance(mask, str):
463
+ mask2 = _decode_data_url(mask)
464
+ if mask2 is None:
465
+ raise gr.Error("image1 数据格式不支持(mask)")
466
+ mask = mask2
467
+
468
+ if isinstance(img, np.ndarray):
469
+ img_pil = Image.fromarray(img.astype(np.uint8))
470
+ else:
471
+ img_pil = img
472
+
473
+ if hasattr(img_pil, "convert"):
474
+ img_pil = img_pil.convert("RGB")
475
+
476
+ iw, ih = img_pil.size
477
+ vit_w, vit_h = vit_resize_dims(iw, ih, vit_resize_size=384)
478
+
479
+ if mask is None:
480
+ return img_pil, None, None, None, (vit_w, vit_h)
481
+
482
+ if isinstance(mask, list):
483
+ mask_arr = np.zeros((img_pil.size[1], img_pil.size[0]), dtype=np.uint8)
484
+ for layer in mask:
485
+ if isinstance(layer, str):
486
+ layer2 = _decode_data_url(layer)
487
+ if layer2 is None:
488
+ continue
489
+ layer = layer2
490
+ if isinstance(layer, np.ndarray):
491
+ layer_pil = Image.fromarray(layer.astype(np.uint8))
492
+ else:
493
+ layer_pil = layer
494
+ if layer_pil is None:
495
+ continue
496
+ if getattr(layer_pil, "size", None) != img_pil.size:
497
+ layer_pil = layer_pil.resize(img_pil.size)
498
+ layer_arr = np.array(layer_pil, dtype=np.uint8)
499
+ if layer_arr.ndim == 3 and layer_arr.shape[2] >= 4:
500
+ layer_mask = layer_arr[:, :, 3]
501
+ elif layer_arr.ndim == 3:
502
+ layer_mask = layer_arr.max(axis=2)
503
+ else:
504
+ layer_mask = layer_arr
505
+ mask_arr = np.maximum(mask_arr, layer_mask.astype(np.uint8))
506
+ elif isinstance(mask, np.ndarray):
507
+ mask_arr = mask.astype(np.uint8)
508
+ if mask_arr.ndim == 3:
509
+ mask_arr = mask_arr.max(axis=2)
510
+ mask_pil_l = Image.fromarray(mask_arr, mode="L")
511
+ if getattr(mask_pil_l, "size", None) != img_pil.size:
512
+ mask_pil_l = mask_pil_l.resize(img_pil.size, resample=Image.NEAREST)
513
+ mask_arr = np.array(mask_pil_l, dtype=np.uint8)
514
+ else:
515
+ mask_pil_l = mask.convert("L")
516
+ if getattr(mask_pil_l, "size", None) != img_pil.size:
517
+ mask_pil_l = mask_pil_l.resize(img_pil.size, resample=Image.NEAREST)
518
+ mask_arr = np.array(mask_pil_l, dtype=np.uint8)
519
+ if isinstance(mask, list):
520
+ mask_pil_l = Image.fromarray(mask_arr, mode="L")
521
+
522
+ ys, xs = np.where(mask_arr > 0)
523
+ if xs.size == 0 or ys.size == 0:
524
+ return img_pil, None, None, None, (vit_w, vit_h)
525
+
526
+ x1 = int(xs.min())
527
+ x2 = int(xs.max()) + 1
528
+ y1 = int(ys.min())
529
+ y2 = int(ys.max()) + 1
530
+
531
+ x1 = max(0, min(iw - 1, x1))
532
+ y1 = max(0, min(ih - 1, y1))
533
+ x2 = max(1, min(iw, x2))
534
+ y2 = max(1, min(ih, y2))
535
+
536
+ bbox_raw = (x1, y1, x2, y2)
537
+ bbox_vit = scale_bbox_xyxy(bbox_raw, iw, ih, vit_w, vit_h)
538
+ return img_pil, mask_pil_l, bbox_raw, bbox_vit, (vit_w, vit_h)
539
+
540
+ def extract_ref_from_image2(image2_value):
541
+ """Return (ref_pil_rgb | None, crop_info_str | None).
542
+
543
+ If the user painted on image2, crop to the brush bounding-box and
544
+ return only that region. Otherwise return the full image.
545
+ """
546
+ if image2_value is None:
547
+ return None, None
548
+
549
+ if not isinstance(image2_value, dict):
550
+ return _to_rgb_pil(image2_value, label="image2"), None
551
+
552
+ if "image" in image2_value and "mask" in image2_value:
553
+ img = image2_value["image"]
554
+ mask = image2_value["mask"]
555
+ elif "background" in image2_value and "layers" in image2_value:
556
+ img = image2_value.get("background") or image2_value.get("composite")
557
+ layers = image2_value.get("layers") or []
558
+ mask = layers if layers else None
559
+ else:
560
+ img = image2_value
561
+ mask = None
562
+
563
+ if img is None:
564
+ return None, None
565
+
566
+ if isinstance(img, str):
567
+ img2 = _decode_data_url(img)
568
+ if img2 is None:
569
+ return None, None
570
+ img = img2
571
+ if isinstance(img, np.ndarray):
572
+ img_pil = Image.fromarray(img.astype(np.uint8))
573
+ else:
574
+ img_pil = img
575
+ img_pil = img_pil.convert("RGB")
576
+
577
+ if mask is None:
578
+ return img_pil, None
579
+
580
+ if isinstance(mask, list):
581
+ mask_arr = np.zeros((img_pil.size[1], img_pil.size[0]), dtype=np.uint8)
582
+ for layer in mask:
583
+ if isinstance(layer, str):
584
+ layer2 = _decode_data_url(layer)
585
+ if layer2 is None:
586
+ continue
587
+ layer = layer2
588
+ if isinstance(layer, np.ndarray):
589
+ layer_pil = Image.fromarray(layer.astype(np.uint8))
590
+ else:
591
+ layer_pil = layer
592
+ if layer_pil is None:
593
+ continue
594
+ if getattr(layer_pil, "size", None) != img_pil.size:
595
+ layer_pil = layer_pil.resize(img_pil.size)
596
+ layer_arr = np.array(layer_pil, dtype=np.uint8)
597
+ if layer_arr.ndim == 3 and layer_arr.shape[2] >= 4:
598
+ layer_mask = layer_arr[:, :, 3]
599
+ elif layer_arr.ndim == 3:
600
+ layer_mask = layer_arr.max(axis=2)
601
+ else:
602
+ layer_mask = layer_arr
603
+ mask_arr = np.maximum(mask_arr, layer_mask.astype(np.uint8))
604
+ elif isinstance(mask, np.ndarray):
605
+ mask_arr = mask.astype(np.uint8)
606
+ if mask_arr.ndim == 3:
607
+ mask_arr = mask_arr.max(axis=2)
608
+ tmp = Image.fromarray(mask_arr, mode="L")
609
+ if getattr(tmp, "size", None) != img_pil.size:
610
+ tmp = tmp.resize(img_pil.size, resample=Image.NEAREST)
611
+ mask_arr = np.array(tmp, dtype=np.uint8)
612
+ else:
613
+ tmp = mask.convert("L")
614
+ if getattr(tmp, "size", None) != img_pil.size:
615
+ tmp = tmp.resize(img_pil.size, resample=Image.NEAREST)
616
+ mask_arr = np.array(tmp, dtype=np.uint8)
617
+
618
+ ys, xs = np.where(mask_arr > 0)
619
+ if xs.size == 0 or ys.size == 0:
620
+ return img_pil, None
621
+
622
+ iw, ih = img_pil.size
623
+ x1 = max(0, min(iw - 1, int(xs.min())))
624
+ y1 = max(0, min(ih - 1, int(ys.min())))
625
+ x2 = max(1, min(iw, int(xs.max()) + 1))
626
+ y2 = max(1, min(ih, int(ys.max()) + 1))
627
+
628
+ cropped = img_pil.crop((x1, y1, x2, y2))
629
+ crop_info = f"ref_crop=[{x1},{y1},{x2},{y2}] ({x2 - x1}x{y2 - y1})"
630
+ return cropped, crop_info
631
+
632
+ def _predict_impl(
633
+ image1_value,
634
+ image2,
635
+ prompt,
636
+ mode,
637
+ spatial_source,
638
+ spatial_bbox_margin,
639
+ model_dir,
640
+ device,
641
+ seed,
642
+ steps,
643
+ true_cfg_scale,
644
+ guidance_scale,
645
+ negative_prompt,
646
+ output_path,
647
+ load_lightning_lora,
648
+ paste_back_bbox,
649
+ paste_back_mode,
650
+ focus_crop_for_bbox,
651
+ focus_crop_margin,
652
+ paste_mask_grow,
653
+ paste_blend_kernel,
654
+ not_use_spatial_vae,
655
+ ):
656
+ import torch
657
+
658
+ prompt = (prompt or "").strip()
659
+ if not prompt:
660
+ raise gr.Error("prompt 为空")
661
+
662
+ img_pil, mask_pil_l, bbox_raw, bbox_vit, (vit_w, vit_h) = extract_bbox_from_image1(image1_value)
663
+ img_pil = _to_rgb_pil(img_pil, label="image1")
664
+ image2, ref_crop_info = extract_ref_from_image2(image2)
665
+
666
+ has_mask = (mask_pil_l is not None) and mask_has_foreground(mask_pil_l)
667
+ has_bbox = bbox_raw is not None
668
+
669
+ use_focus_crop = bool(paste_back_bbox) and bool(focus_crop_for_bbox) and has_bbox
670
+ crop_xyxy = None
671
+ bbox_for_model_raw = bbox_raw
672
+ img_for_model = img_pil
673
+ image2_for_model = image2
674
+ mask_for_model_l = mask_pil_l if has_mask else None
675
+ vit_wh_for_prompt = (vit_w, vit_h)
676
+
677
+ if use_focus_crop:
678
+ iw, ih = img_pil.size
679
+ margin = int(focus_crop_margin) if focus_crop_margin is not None and str(focus_crop_margin).strip() else 0
680
+ crop_xyxy = crop_box_from_1024_area_margin(image_size=(iw, ih), bbox_xyxy=bbox_raw, margin=margin)
681
+ cx1, cy1, cx2, cy2 = crop_xyxy
682
+ img_for_model = img_pil.crop((cx1, cy1, cx2, cy2))
683
+ bbox_for_model_raw = offset_bbox_xyxy(bbox_raw, cx1, cy1)
684
+ if has_mask and mask_pil_l is not None:
685
+ mask_for_model_l = mask_pil_l.crop((cx1, cy1, cx2, cy2))
686
+ vit_w2, vit_h2 = vit_resize_dims(img_for_model.size[0], img_for_model.size[1], vit_resize_size=384)
687
+ vit_wh_for_prompt = (vit_w2, vit_h2)
688
+ bbox_vit = scale_bbox_xyxy(bbox_for_model_raw, img_for_model.size[0], img_for_model.size[1], vit_w2, vit_h2)
689
+
690
+ prompt_for_model = strip_location_text(prompt)
691
+
692
+ spatial_source = (spatial_source or "mask").strip().lower()
693
+ spatial_bbox_margin = int(spatial_bbox_margin) if spatial_bbox_margin is not None and str(spatial_bbox_margin).strip() else 0
694
+ spatial_mask_l = None
695
+ if mask_for_model_l is not None and mask_has_foreground(mask_for_model_l):
696
+ spatial_mask_l = render_spatial_prompt(mask_for_model_l, source=spatial_source, bbox_margin=spatial_bbox_margin)
697
+
698
+ info = ""
699
+ if has_bbox:
700
+ info = f"BBox(raw)={format_bbox_xyxy(bbox_raw)}"
701
+ else:
702
+ info = "未检测到涂抹区域"
703
+ if has_bbox:
704
+ info += f" -> QwenVit(384-area)={format_bbox_xyxy(bbox_vit)} vit_wh=({vit_wh_for_prompt[0]},{vit_wh_for_prompt[1]})"
705
+ if ref_crop_info:
706
+ info += f" {ref_crop_info}"
707
+ if spatial_mask_l is not None:
708
+ info += f" spatial={spatial_source}"
709
+ if crop_xyxy is not None:
710
+ info += f" crop={format_bbox_xyxy(crop_xyxy)} bbox_in_crop={format_bbox_xyxy(bbox_for_model_raw)}"
711
+
712
+ vis_base = img_for_model.resize(vit_wh_for_prompt, resample=Image.BICUBIC)
713
+ if spatial_mask_l is not None:
714
+ spatial_vis = spatial_mask_l.resize(vit_wh_for_prompt, resample=Image.NEAREST)
715
+ vis = overlay_mask_on_image(vis_base, spatial_vis)
716
+ elif has_bbox:
717
+ vis = draw_bbox_on_image(vis_base, bbox_vit)
718
+ else:
719
+ vis = vis_base
720
+
721
+ if mode == "仅生成prompt":
722
+ return (img_pil, img_pil), prompt_for_model, info, vis, "完成"
723
+
724
+ model_dir = (model_dir or "").strip()
725
+ if not model_dir:
726
+ raise gr.Error("model_dir 不能为空")
727
+ if os.path.exists(model_dir) and not os.path.isdir(model_dir):
728
+ raise gr.Error(f"model_dir 不是目录: {model_dir}")
729
+
730
+ device = (device or "").strip() or "cuda"
731
+
732
+ seed = int(seed) if seed is not None and str(seed).strip() else 0
733
+ steps = int(steps) if steps is not None and str(steps).strip() else 8
734
+ true_cfg_scale = float(true_cfg_scale) if true_cfg_scale is not None and str(true_cfg_scale).strip() else 4.0
735
+ guidance_scale = float(guidance_scale) if guidance_scale is not None and str(guidance_scale).strip() else 1.0
736
+ negative_prompt = negative_prompt if negative_prompt is not None else " "
737
+
738
+ pipe = _get_pipeline(
739
+ model_dir=model_dir,
740
+ device=device,
741
+ load_lightning_lora=bool(load_lightning_lora),
742
+ )
743
+
744
+ img = img_for_model if image2_for_model is None else [img_for_model, image2_for_model]
745
+ if spatial_mask_l is not None:
746
+ spatial_rgb = spatial_mask_l.convert("RGB")
747
+ if isinstance(img, list):
748
+ img = img + [spatial_rgb]
749
+ else:
750
+ img = [img, spatial_rgb]
751
+ gen = torch.Generator(device=device)
752
+ gen.manual_seed(seed)
753
+
754
+ t0 = time.time()
755
+ with torch.inference_mode():
756
+ try:
757
+ out = pipe(
758
+ image=img,
759
+ prompt=prompt_for_model,
760
+ generator=gen,
761
+ true_cfg_scale=true_cfg_scale,
762
+ negative_prompt=negative_prompt,
763
+ num_inference_steps=steps,
764
+ guidance_scale=guidance_scale,
765
+ num_images_per_prompt=1,
766
+ not_use_spatial_vae=bool(not_use_spatial_vae),
767
  )
768
+ # img[0].save('input0.png')
769
+ # img[1].save('input1.png')
770
+ # print(img[0].size, img[1].size, out.images[0].size)
771
+ # out.images[0].save('./zdw_debug.png')
772
+ except Exception as e:
773
+ raise gr.Error(f"推理失败: {type(e).__name__}: {e}")
774
+ dt = time.time() - t0
775
+ out_img = out.images[0]
776
+
777
+ if paste_back_bbox:
778
+ paste_back_mode = (paste_back_mode or "bbox").strip().lower()
779
+ mg = int(paste_mask_grow) if paste_mask_grow is not None and str(paste_mask_grow).strip() else 0
780
+ bk = int(paste_blend_kernel) if paste_blend_kernel is not None and str(paste_blend_kernel).strip() else 0
781
+ paste_mask = None
782
+ if paste_back_mode.startswith("mask") and mask_for_model_l is not None and mask_has_foreground(mask_for_model_l):
783
+ paste_mask = prepare_paste_mask(mask_for_model_l, mask_grow=mg, blend_kernel=bk)
784
+ elif bbox_for_model_raw is not None:
785
+ paste_mask = make_bbox_mask(size=img_for_model.size, bbox_xyxy=bbox_for_model_raw, mask_grow=mg, blend_kernel=bk)
786
+
787
+ if paste_mask is not None:
788
+ out_img_crop = composite_masked(destination=img_for_model, source=out_img, mask=paste_mask, resize_source=True)
789
+ if crop_xyxy is not None:
790
+ cx1, cy1, cx2, cy2 = crop_xyxy
791
+ out_full = img_pil.copy()
792
+ out_full.paste(out_img_crop, (cx1, cy1))
793
+ out_img = out_full
794
+ else:
795
+ out_img = out_img_crop
796
+
797
+ output_path = (output_path or "").strip()
798
+ saved = ""
799
+ if output_path:
800
+ if os.path.isdir(output_path):
801
+ raise gr.Error(f"output_path 不能是目录: {output_path}")
802
+ parent = os.path.dirname(os.path.abspath(output_path)) or "."
803
+ if not os.path.isdir(parent):
804
+ raise gr.Error(f"output_path 的父目录不存在: {parent}")
805
+ out_img.save(output_path)
806
+ saved = os.path.abspath(output_path)
807
+ base, ext = os.path.splitext(saved)
808
+ img_pil.save(base + "_input" + ext)
809
+ if image2 is not None:
810
+ image2.save(base + "_ref" + ext)
811
+ if mask_pil_l is not None:
812
+ mask_pil_l.save(base + "_mask.png")
813
 
814
+ status = f"完成 ({dt:.2f}s)"
815
+ if saved:
816
+ status += f" 已保存: {saved}"
817
+ return (img_pil, out_img), prompt_for_model, info, vis, status
818
+
819
+ if _HAS_SPACES:
820
+ predict = spaces.GPU(duration=180)(_predict_impl)
821
+ else:
822
+ predict = _predict_impl
823
+
824
+ if hasattr(gr, "ImageMask"):
825
+ image1 = gr.ImageMask(label="image1(必选,涂抹选择区域)", type="pil")
826
+ else:
827
+ tool_supported = "tool" in inspect.signature(gr.Image.__init__).parameters
828
+ if tool_supported:
829
+ image1 = gr.Image(label="image1(必选,使用画笔圈选区域)", type="pil", tool="sketch")
830
+ else:
831
+ image1 = gr.Image(label="image1(必选)", type="pil")
832
+ if hasattr(gr, "ImageMask"):
833
+ image2 = gr.ImageMask(label="image2(可选,可涂抹选取局部参考区域获取更精确的参考,不涂抹则参考整张图)", type="pil")
834
+ else:
835
+ tool_supported = "tool" in inspect.signature(gr.Image.__init__).parameters
836
+ if tool_supported:
837
+ image2 = gr.Image(label="image2(可选,可涂抹选取局部参考区域获取更精确的参考,不涂抹则参考整张图)", type="pil", tool="sketch")
838
+ else:
839
+ image2 = gr.Image(label="image2(可选)", type="pil")
840
+ prompt = gr.Textbox(label="prompt", lines=4, value='优化文字 "宽重阴游欢想"')
841
+
842
+ mode = gr.Radio(["仅生成prompt", "运行推理"], value="运行推理", label="模式")
843
+
844
+ spatial_source = gr.Radio(["mask", "bbox"], value="mask", label="空间提示来源(作为 mask 输入模型)")
845
+ spatial_bbox_margin = gr.Number(label="spatial_bbox_margin", value=0, precision=0)
846
+
847
+ model_dir = gr.Textbox(label="model_dir", value=default_model_dir)
848
+ device = gr.Textbox(label="device", value=default_device)
849
+ seed = gr.Number(label="seed", value=0, precision=0)
850
+ steps = gr.Number(label="num_inference_steps", value=8, precision=0)
851
+ true_cfg_scale = gr.Number(label="true_cfg_scale", value=4.0)
852
+ guidance_scale = gr.Number(label="guidance_scale", value=1.0)
853
+ negative_prompt = gr.Textbox(label="negative_prompt", value=" ")
854
+ output_path = gr.Textbox(label="output_path(可空)", value="")
855
+
856
+ load_lightning_lora = gr.Checkbox(label="加载加速 LoRA(Lightning)", value=False)
857
+
858
+ paste_back_bbox = gr.Checkbox(label="仅回贴局部区域(composite)", value=True)
859
+ paste_back_mode = gr.Radio(["bbox", "mask(涂抹)"], value="bbox", label="回贴方式")
860
+ focus_crop_for_bbox = gr.Checkbox(label="聚焦编辑区域(裁剪输入)", value=True)
861
+ focus_crop_margin = gr.Number(label="聚焦裁剪扩张像素", value=64, precision=0)
862
+ paste_mask_grow = gr.Number(label="回贴 mask_grow", value=3, precision=0)
863
+ paste_blend_kernel = gr.Number(label="回贴 blend_kernel", value=5, precision=0)
864
+
865
+ not_use_spatial_vae = gr.Checkbox(label="不使用 spatial VAE(not_use_spatial_vae)", value=False)
866
+
867
+ out_image = gr.ImageSlider(label="对比:原图 vs 输出", show_label=True)
868
+ replaced_prompt = gr.Textbox(label="实际使用的 prompt", lines=4)
869
+ bbox_info = gr.Textbox(label="区域信息", lines=2)
870
+ image1_vis = gr.Image(label="model_input(vit384) + 区域可视化", type="pil")
871
+ status = gr.Textbox(label="状态", lines=1)
872
+
873
+ demo = gr.Interface(
874
+ fn=predict,
875
  inputs=[
876
+ image1,
877
+ image2,
878
  prompt,
879
+ mode,
880
+ spatial_source,
881
+ spatial_bbox_margin,
882
+ model_dir,
883
+ device,
884
  seed,
885
+ steps,
886
+ true_cfg_scale,
 
887
  guidance_scale,
888
+ negative_prompt,
889
+ output_path,
890
+ load_lightning_lora,
891
+ paste_back_bbox,
892
+ paste_back_mode,
893
+ focus_crop_for_bbox,
894
+ focus_crop_margin,
895
+ paste_mask_grow,
896
+ paste_blend_kernel,
897
+ not_use_spatial_vae,
898
  ],
899
+ outputs=[out_image, replaced_prompt, bbox_info, image1_vis, status],
900
+ title="Qwen-Image-Edit GUI Tester",
901
  )
902
+ return demo
903
+
904
+
905
+ demo = build_app(
906
+ default_model_dir=os.environ.get("MODEL_DIR", "Qwen/Qwen-Image-Edit-2511"),
907
+ default_device="cuda",
908
+ )
909
 
910
  if __name__ == "__main__":
911
+ demo.launch(show_error=True)
requirements.txt CHANGED
@@ -1,6 +1,9 @@
1
- accelerate
2
- diffusers
3
- invisible_watermark
 
 
 
4
  torch
5
- transformers
6
- xformers
 
1
+ huggingface-hub>=0.34.3
2
+ transformers>=4.55.0
3
+ peft>=0.17.0
4
+ attrs
5
+ gradio_imageslider
6
+ git+https://github.com/huggingface/diffusers
7
  torch
8
+ accelerate
9
+ safetensors