Matteoooo46 commited on
Commit
75952e4
·
verified ·
1 Parent(s): 6a4d7e5

Add ReCoEdit Gradio application

Browse files
Files changed (1) hide show
  1. app.py +318 -0
app.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import glob
4
+ import os
5
+ import re
6
+ import time
7
+ from pathlib import Path
8
+
9
+ import gradio as gr
10
+ import spaces
11
+ import torch
12
+ from diffsynth.pipelines.qwen_image import ModelConfig, QwenImagePipeline
13
+ from huggingface_hub import snapshot_download
14
+ from peft import PeftModel
15
+ from PIL import Image, ImageOps
16
+ from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
17
+
18
+ from apg_guidance import patch_pipeline_for_apg
19
+
20
+
21
+ BASE_MODEL_ID = os.getenv("BASE_MODEL_ID", "Qwen/Qwen-Image-Edit-2511")
22
+ IMAGE_LORA_ID = os.getenv("IMAGE_LORA_ID", "Matteoooo46/ReCoEdit-RL")
23
+ REWRITER_BASE_ID = os.getenv("REWRITER_BASE_ID", "Qwen/Qwen3-VL-8B-Instruct")
24
+ REWRITER_LORA_ID = os.getenv("REWRITER_LORA_ID", "Matteoooo46/ReCoEdit-rewriter")
25
+ HF_TOKEN = os.getenv("HF_TOKEN")
26
+ VRAM_LIMIT_GB = float(os.getenv("VRAM_LIMIT_GB", "72"))
27
+
28
+ NO_TEXT_SUFFIX = (
29
+ ",画面中不要出现任何多余的文字、字幕、水印、签名、乱码或无关logo,"
30
+ "仅保留商品原本的品牌文字且保持清晰一致。"
31
+ )
32
+ NEGATIVE_PROMPT = (
33
+ "text, watermark, signature, letters, writing, words, typography, "
34
+ "logo, brand name, garbled characters, subtitles"
35
+ )
36
+
37
+ PROMPT_REWRITE_SYSTEM = """
38
+ 你是一个电商商品图像编辑 prompt 改写助手。你的任务是根据商品参考图和 original prompt,生成一段更清晰、更具体、更适合图像编辑模型执行的中文 prompt。
39
+
40
+ 请遵守以下原则:
41
+ 1. 以 original prompt 的编辑意图为主。保留并扩写场景、背景、光线、氛围、构图、人物、动作、道具和风格要求,不要改变原始编辑目标。
42
+ 2. 适度补充商品本体的类别、形状、颜色、材质、logo、文字、图案和关键结构细节,以帮助模型保持商品一致性。
43
+ 3. 参考图只用于识别商品本体。不要描述参考图的原始背景、摆放方式、手、模特或装饰物,除非 original prompt 明确要求保留。
44
+ 4. 最终 prompt 中,编辑目标约占 50%,商品细节约占 40%,质量约束约占 10%;总长度控制在 120~150 个中文字符,不要列小标题或分点。
45
+ 5. 保持商品颜色、形状、logo、文字、图案和材质与参考图一致;不要新增无关文字、水印、乱码;不要让商品变形、镜像、错色或丢失关键标识。只描述单帧静态画面。
46
+
47
+ 只输出一条最终 prompt,格式如下:
48
+ i2v描述:<优化后的 prompt>
49
+ """.strip()
50
+
51
+
52
+ def _download(repo_id: str) -> str:
53
+ return snapshot_download(repo_id, token=HF_TOKEN)
54
+
55
+
56
+ def _weight_files(root: str, subfolder: str) -> list[str]:
57
+ folder = Path(root) / subfolder
58
+ files = sorted(str(path) for path in folder.glob("*.safetensors"))
59
+ if not files:
60
+ raise FileNotFoundError(f"在 {folder} 中没有找到 safetensors 权重。")
61
+ return files
62
+
63
+
64
+ def _adapter_file(root: str) -> str:
65
+ preferred = Path(root) / "adapter_model.safetensors"
66
+ if preferred.exists():
67
+ return str(preferred)
68
+ files = sorted(glob.glob(str(Path(root) / "**" / "*.safetensors"), recursive=True))
69
+ if len(files) != 1:
70
+ raise FileNotFoundError(f"无法在 {root} 中唯一确定图像 LoRA 权重。")
71
+ return files[0]
72
+
73
+
74
+ print("正在下载并加载 ReCoEdit 模型……")
75
+ base_dir = _download(BASE_MODEL_ID)
76
+ image_lora_dir = _download(IMAGE_LORA_ID)
77
+
78
+ vram_config = {
79
+ "offload_dtype": "disk",
80
+ "offload_device": "disk",
81
+ "onload_dtype": torch.float8_e4m3fn,
82
+ "onload_device": "cpu",
83
+ "preparing_dtype": torch.float8_e4m3fn,
84
+ "preparing_device": "cuda",
85
+ "computation_dtype": torch.bfloat16,
86
+ "computation_device": "cuda",
87
+ }
88
+
89
+ image_pipe = QwenImagePipeline.from_pretrained(
90
+ torch_dtype=torch.bfloat16,
91
+ device="cuda",
92
+ model_configs=[
93
+ ModelConfig(path=_weight_files(base_dir, "transformer"), **vram_config),
94
+ ModelConfig(path=_weight_files(base_dir, "text_encoder"), **vram_config),
95
+ ModelConfig(
96
+ path=str(Path(base_dir) / "vae" / "diffusion_pytorch_model.safetensors"),
97
+ **vram_config,
98
+ ),
99
+ ],
100
+ tokenizer_config=None,
101
+ processor_config=ModelConfig(path=str(Path(base_dir) / "processor")),
102
+ vram_limit=VRAM_LIMIT_GB,
103
+ )
104
+ image_pipe.load_lora(image_pipe.dit, _adapter_file(image_lora_dir))
105
+ patch_pipeline_for_apg(image_pipe, eta=0.0, beta=-0.5, norm_threshold=None)
106
+
107
+ rewriter = Qwen3VLForConditionalGeneration.from_pretrained(
108
+ REWRITER_BASE_ID,
109
+ torch_dtype=torch.bfloat16,
110
+ device_map="cuda:0",
111
+ token=HF_TOKEN,
112
+ trust_remote_code=True,
113
+ )
114
+ rewriter = PeftModel.from_pretrained(rewriter, REWRITER_LORA_ID, token=HF_TOKEN)
115
+ rewriter.eval()
116
+ rewriter_processor = AutoProcessor.from_pretrained(
117
+ REWRITER_BASE_ID,
118
+ token=HF_TOKEN,
119
+ trust_remote_code=True,
120
+ )
121
+ print("ReCoEdit 模型加载完成。")
122
+
123
+
124
+ def _clean_rewritten_prompt(text: str) -> str:
125
+ match = re.search(r"i2v描述\s*[::]\s*(.+)", text or "", flags=re.DOTALL)
126
+ value = match.group(1) if match else (text or "")
127
+ return re.sub(r"\s+", " ", value.strip().strip("`").strip())
128
+
129
+
130
+ def _load_reference_images(files) -> list[Image.Image]:
131
+ if not files:
132
+ raise gr.Error("请至少上传一张商品参考图。")
133
+ if len(files) > 4:
134
+ raise gr.Error("最多支持 4 张参考图。")
135
+
136
+ images = []
137
+ for file in files:
138
+ path = file if isinstance(file, str) else getattr(file, "path", None) or file.name
139
+ image = ImageOps.exif_transpose(Image.open(path)).convert("RGB")
140
+ image.thumbnail((1536, 1536), Image.Resampling.LANCZOS)
141
+ images.append(image)
142
+ return images
143
+
144
+
145
+ def rewrite_prompt(original_prompt: str, images: list[Image.Image]) -> tuple[str, str]:
146
+ content = [{"type": "image", "image": image.copy()} for image in images]
147
+ content.append(
148
+ {
149
+ "type": "text",
150
+ "text": PROMPT_REWRITE_SYSTEM + "\n\noriginal prompt:" + original_prompt,
151
+ }
152
+ )
153
+ messages = [{"role": "user", "content": content}]
154
+ chat_text = rewriter_processor.apply_chat_template(
155
+ messages,
156
+ tokenize=False,
157
+ add_generation_prompt=True,
158
+ )
159
+ inputs = rewriter_processor(
160
+ text=[chat_text],
161
+ images=images,
162
+ return_tensors="pt",
163
+ ).to(rewriter.device)
164
+
165
+ with torch.inference_mode():
166
+ generated_ids = rewriter.generate(
167
+ **inputs,
168
+ max_new_tokens=512,
169
+ do_sample=False,
170
+ )
171
+ output_ids = generated_ids[0][inputs["input_ids"].shape[1] :]
172
+ raw_answer = rewriter_processor.tokenizer.decode(
173
+ output_ids,
174
+ skip_special_tokens=True,
175
+ ).strip()
176
+ rewritten = _clean_rewritten_prompt(raw_answer) or original_prompt
177
+ return rewritten, raw_answer
178
+
179
+
180
+ def _parse_size(size: str) -> tuple[int, int]:
181
+ width, height = size.split("×")
182
+ return int(width), int(height)
183
+
184
+
185
+ def _gpu_duration(_files, _prompt, _size, steps, *_args):
186
+ return min(300, max(120, int(steps) * 5 + 45))
187
+
188
+
189
+ @spaces.GPU(size="xlarge", duration=_gpu_duration)
190
+ def generate(files, prompt, size, steps, cfg_scale, seed, progress=gr.Progress()):
191
+ prompt = (prompt or "").strip()
192
+ if not prompt:
193
+ raise gr.Error("请输入希望如何编辑商品图。")
194
+
195
+ images = _load_reference_images(files)
196
+ width, height = _parse_size(size)
197
+
198
+ started = time.time()
199
+ progress(0.08, desc="正在分析商品与编辑目标")
200
+ try:
201
+ rewritten, raw_answer = rewrite_prompt(prompt, images)
202
+ except Exception as exc:
203
+ print(f"Prompt 改写失败,回退到原始提示词:{exc}")
204
+ rewritten, raw_answer = prompt, "改写模型不可用,本次已使用原始提示词。"
205
+
206
+ progress(0.25, desc="提示词已优化,正在生成图片")
207
+ final_prompt = rewritten + NO_TEXT_SUFFIX
208
+ with torch.inference_mode():
209
+ result = image_pipe(
210
+ prompt=final_prompt,
211
+ negative_prompt=NEGATIVE_PROMPT,
212
+ edit_image=images,
213
+ seed=int(seed),
214
+ num_inference_steps=int(steps),
215
+ height=height,
216
+ width=width,
217
+ edit_image_auto_resize=True,
218
+ zero_cond_t=True,
219
+ cfg_scale=float(cfg_scale),
220
+ )
221
+
222
+ elapsed = time.time() - started
223
+ details = (
224
+ f"优化后的提示词:\n{rewritten}\n\n"
225
+ f"耗时:{elapsed:.1f} 秒|尺寸:{width}×{height}|"
226
+ f"步数:{int(steps)}|CFG:{float(cfg_scale):.1f}|Seed:{int(seed)}"
227
+ )
228
+ progress(1.0, desc="生成完成")
229
+ return details, result
230
+
231
+
232
+ CSS = """
233
+ .gradio-container {max-width: 1260px !important;}
234
+ .hero {padding: 12px 0 8px;}
235
+ .hero h1 {font-size: 2.2rem; margin-bottom: .3rem;}
236
+ .hero p {color: var(--body-text-color-subdued); font-size: 1.02rem;}
237
+ #generate-button {min-height: 48px; font-weight: 700;}
238
+ #result-image {min-height: 560px;}
239
+ .model-note {border-left: 4px solid #7c3aed; padding-left: 12px;}
240
+ """
241
+
242
+ with gr.Blocks(
243
+ theme=gr.themes.Soft(primary_hue="violet", secondary_hue="blue"),
244
+ css=CSS,
245
+ title="ReCoEdit — 商品图像编辑",
246
+ ) as demo:
247
+ gr.Markdown(
248
+ """
249
+ <div class="hero">
250
+ <h1>ReCoEdit 商品图像编辑</h1>
251
+ <p>上传商品参考图并描述目标画面。模型会先优化编辑提示词,再生成保持商品一致性的结果。</p>
252
+ </div>
253
+ """
254
+ )
255
+
256
+ with gr.Row(equal_height=False):
257
+ with gr.Column(scale=5):
258
+ reference_files = gr.File(
259
+ label="商品参考图(1–4 张)",
260
+ file_count="multiple",
261
+ file_types=["image"],
262
+ type="filepath",
263
+ )
264
+ prompt_input = gr.Textbox(
265
+ label="编辑指令",
266
+ placeholder="例如:把这款口红放在高级黑色梳妆台上,暖色侧光,商业广告摄影风格……",
267
+ lines=6,
268
+ )
269
+ with gr.Accordion("生成参数", open=False):
270
+ size_input = gr.Dropdown(
271
+ ["896×1152", "1024×1024", "1152×896"],
272
+ value="896×1152",
273
+ label="输出尺寸",
274
+ )
275
+ steps_input = gr.Slider(20, 50, value=40, step=1, label="推理步数")
276
+ cfg_input = gr.Slider(1.0, 7.5, value=4.0, step=0.5, label="APG / CFG 强度")
277
+ seed_input = gr.Number(value=1, precision=0, label="随机种子")
278
+ generate_button = gr.Button("开始生成", variant="primary", elem_id="generate-button")
279
+ gr.Markdown(
280
+ """
281
+ <div class="model-note">
282
+ 当前流程:Qwen3-VL Rewriter LoRA → Qwen-Image-Edit-2511 + ReCoEdit-RL LoRA → APG。
283
+ </div>
284
+ """
285
+ )
286
+
287
+ with gr.Column(scale=7):
288
+ image_output = gr.Image(
289
+ label="生成结果",
290
+ type="pil",
291
+ format="png",
292
+ interactive=False,
293
+ elem_id="result-image",
294
+ )
295
+ prompt_output = gr.Textbox(
296
+ label="提示词优化结果与参数",
297
+ lines=7,
298
+ interactive=False,
299
+ )
300
+
301
+ generate_button.click(
302
+ fn=generate,
303
+ inputs=[
304
+ reference_files,
305
+ prompt_input,
306
+ size_input,
307
+ steps_input,
308
+ cfg_input,
309
+ seed_input,
310
+ ],
311
+ outputs=[prompt_output, image_output],
312
+ api_name="generate",
313
+ )
314
+
315
+ demo.queue(default_concurrency_limit=1, max_size=12)
316
+
317
+ if __name__ == "__main__":
318
+ demo.launch()