LPX55 commited on
Commit
94c44d0
·
verified ·
1 Parent(s): 546faf6

Create app_local.py

Browse files
Files changed (1) hide show
  1. app_local.py +321 -0
app_local.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import random
4
+ import torch
5
+ import spaces
6
+ from PIL import Image
7
+ from diffusers import QwenImageEditPipeline
8
+ from diffusers.utils import is_xformers_available
9
+ import os
10
+ import re
11
+ import gc
12
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
13
+
14
+ #############################
15
+ os.environ.setdefault('GRADIO_ANALYTICS_ENABLED', 'False')
16
+ os.environ.setdefault('HF_HUB_DISABLE_TELEMETRY', '1')
17
+
18
+ # Model configuration
19
+ REWRITER_MODEL = "Qwen/Qwen1.5-1.8B-Chat"
20
+ rewriter_tokenizer = None
21
+ rewriter_model = None
22
+ dtype = torch.bfloat16
23
+ device = "cuda" if torch.cuda.is_available() else "cpu"
24
+
25
+ # Quantization configuration
26
+ bnb_config = BitsAndBytesConfig(
27
+ load_in_4bit=True,
28
+ bnb_4bit_compute_dtype=torch.bfloat16,
29
+ bnb_4bit_quant_type="nf4",
30
+ bnb_4bit_use_double_quant=True
31
+ )
32
+
33
+ def load_rewriter():
34
+ """Lazily load the prompt enhancement model"""
35
+ global rewriter_tokenizer, rewriter_model
36
+ if rewriter_tokenizer is None or rewriter_model is None:
37
+ print("🔄 Loading enhancement model...")
38
+ rewriter_tokenizer = AutoTokenizer.from_pretrained(REWRITER_MODEL)
39
+ rewriter_model = AutoModelForCausalLM.from_pretrained(
40
+ REWRITER_MODEL,
41
+ torch_dtype=dtype,
42
+ device_map="auto",
43
+ quantization_config=bnb_config
44
+ )
45
+ print("✅ Enhancement model loaded")
46
+
47
+ SYSTEM_PROMPT_EDIT = '''
48
+ # Edit Instruction Rewriter
49
+ You are a professional edit instruction rewriter. Your task is to generate a precise, concise, and visually achievable instruction based on the user's intent and the input image.
50
+ ## 1. General Principles
51
+ - Keep the rewritten instruction **concise** and clear.
52
+ - Avoid contradictions, vagueness, or unachievable instructions.
53
+ - Maintain the core logic of the original instruction; only enhance clarity and feasibility.
54
+ - Ensure new added elements or modifications align with the image's original context and art style.
55
+ ## 2. Task Types
56
+ ### Add, Delete, Replace:
57
+ - When the input is detailed, only refine grammar and clarity.
58
+ - For vague instructions, infer minimal but sufficient details.
59
+ - For replacement, use the format: `"Replace X with Y"`.
60
+ ### Text Editing (e.g., text replacement):
61
+ - Enclose text content in quotes, e.g., `Replace "abc" with "xyz"`.
62
+ - Preserving the original structure and language—**do not translate** or alter style.
63
+ ### Human Editing (e.g., change a person’s face/hair):
64
+ - Preserve core visual identity (gender, ethnic features).
65
+ - Describe expressions in subtle and natural terms.
66
+ - Maintain key clothing or styling details unless explicitly replaced.
67
+ ### Style Transformation:
68
+ - If a style is specified, e.g., `Disco style`, rewrite it to encapsulate the essential visual traits.
69
+ - Use a fixed template for **coloring/restoration**:
70
+ `"Restore old photograph, remove scratches, reduce noise, enhance details, high resolution, realistic, natural skin tones, clear facial features, no distortion, vintage photo restoration"`
71
+ if applicable.
72
+ ## 4. Output Format
73
+ Please provide the rewritten instruction in a clean `json` format as:
74
+ {
75
+ "Rewritten": "..."
76
+ }
77
+ '''
78
+
79
+ def polish_prompt(original_prompt: str) -> str:
80
+ """Enhanced prompt rewriting using Qwen1.5-1.8B"""
81
+ load_rewriter()
82
+
83
+ # Format as Qwen chat with system prompt
84
+ messages = [
85
+ {"role": "system", "content": SYSTEM_PROMPT_EDIT},
86
+ {"role": "user", "content": original_prompt}
87
+ ]
88
+
89
+ # Generate enhanced prompt
90
+ text = rewriter_tokenizer.apply_chat_template(
91
+ messages,
92
+ tokenize=False,
93
+ add_generation_prompt=True
94
+ )
95
+
96
+ model_inputs = rewriter_tokenizer(text, return_tensors="pt").to(device)
97
+
98
+ with torch.no_grad():
99
+ generated_ids = rewriter_model.generate(
100
+ **model_inputs,
101
+ max_new_tokens=120,
102
+ do_sample=True,
103
+ temperature=0.7,
104
+ top_p=0.95,
105
+ no_repeat_ngram_size=2
106
+ )
107
+
108
+ # Extract and clean response
109
+ enhanced = rewriter_tokenizer.decode(
110
+ generated_ids[0][model_inputs.input_ids.shape[1]:],
111
+ skip_special_tokens=True
112
+ )
113
+
114
+ # Clean possible artifacts
115
+ enhanced = enhanced.strip()
116
+ if enhanced.lower().startswith(("rewritten instruction:", "enhanced:", "output:")):
117
+ enhanced = re.split(r':', enhanced, 1)[-1].strip()
118
+
119
+ # Remove any quotes around the prompt if present
120
+ if enhanced.startswith('"') and enhanced.endswith('"'):
121
+ enhanced = enhanced[1:-1]
122
+
123
+ return enhanced
124
+
125
+ # Load main image editing pipeline
126
+ pipe = QwenImageEditPipeline.from_pretrained(
127
+ "Qwen/Qwen-Image-Edit",
128
+ torch_dtype=dtype
129
+ ).to(device)
130
+
131
+ # Load LoRA weights for acceleration
132
+ pipe.load_lora_weights(
133
+ "lightx2v/Qwen-Image-Lightning",
134
+ weight_name="Qwen-Image-Lightning-8steps-V1.1.safetensors"
135
+ )
136
+ pipe.fuse_lora()
137
+
138
+ if is_xformers_available():
139
+ pipe.enable_xformers_memory_efficient_attention()
140
+ else:
141
+ print("xformers not available")
142
+
143
+ def unload_rewriter():
144
+ """Clear enhancement model from memory"""
145
+ global rewriter_tokenizer, rewriter_model
146
+ if rewriter_model:
147
+ del rewriter_tokenizer, rewriter_model
148
+ rewriter_tokenizer = None
149
+ rewriter_model = None
150
+ torch.cuda.empty_cache()
151
+ gc.collect()
152
+
153
+ @spaces.GPU(duration=60)
154
+ def infer(
155
+ image,
156
+ prompt,
157
+ seed=42,
158
+ randomize_seed=False,
159
+ true_guidance_scale=4.0,
160
+ num_inference_steps=8,
161
+ rewrite_prompt=False,
162
+ num_images_per_prompt=1,
163
+ ):
164
+ """Image editing endpoint with optimized prompt handling"""
165
+ original_prompt = prompt
166
+ prompt_info = ""
167
+
168
+ # Handle prompt rewriting
169
+ if rewrite_prompt:
170
+ try:
171
+ enhanced_instruction = polish_prompt(original_prompt)
172
+ prompt_info = (
173
+ f"<div style='margin:10px; padding:10px; border-radius:8px; border-left:4px solid #4CAF50; background: #f5f9fe'>"
174
+ f"<h4 style='margin-top: 0;'>🚀 Prompt Enhancement</h4>"
175
+ f"<p><strong>Original:</strong> {original_prompt}</p>"
176
+ f"<p><strong>Enhanced:</strong> {enhanced_instruction}</p>"
177
+ f"</div>"
178
+ )
179
+ prompt = enhanced_instruction
180
+ except Exception as e:
181
+ gr.Warning(f"Prompt enhancement failed: {str(e)}")
182
+ prompt_info = (
183
+ f"<div style='margin:10px; padding:10px; border-radius:8px; border-left:4px solid #FF5252; background: #fef5f5'>"
184
+ f"<h4 style='margin-top: 0;'>⚠️ Enhancement Not Applied</h4>"
185
+ f"<p>Using original prompt. Error: {str(e)}</p>"
186
+ f"</div>"
187
+ )
188
+ else:
189
+ prompt_info = (
190
+ f"<div style='margin:10px; padding:10px; border-radius:8px; background: #f8f9fa'>"
191
+ f"<h4 style='margin-top: 0;'>📝 Original Prompt</h4>"
192
+ f"<p>{original_prompt}</p>"
193
+ f"</div>"
194
+ )
195
+
196
+ # Free VRAM after enhancement
197
+ unload_rewriter()
198
+
199
+ # Set seed for reproducibility
200
+ seed_val = seed
201
+ if randomize_seed:
202
+ seed_val = random.randint(0, 2**32 - 1)
203
+ generator = torch.Generator(device=device).manual_seed(seed_val)
204
+
205
+ try:
206
+ # Generate images
207
+ edited_images = pipe(
208
+ image=image,
209
+ prompt=prompt,
210
+ negative_prompt=" ",
211
+ num_inference_steps=num_inference_steps,
212
+ generator=generator,
213
+ true_cfg_scale=true_guidance_scale,
214
+ num_images_per_prompt=num_images_per_prompt
215
+ ).images
216
+ except Exception as e:
217
+ gr.Error(f"Image generation failed: {str(e)}")
218
+ prompt_info = (
219
+ f"<div style='margin:10px; padding:10px; border-radius:8px; border-left:4px solid #dd2c00; background: #fef5f5'>"
220
+ f"<h4 style='margin-top: 0;'><strong>⚠️ Error:</strong> {str(e)}</h4>"
221
+ f"</div>"
222
+ )
223
+ return [], seed_val, prompt_info
224
+
225
+ return edited_images, seed_val, prompt_info
226
+
227
+ MAX_SEED = np.iinfo(np.int32).max
228
+ examples = [
229
+ "Replace the cat with a friendly golden retriever. Make it look happier, and add more background details.",
230
+ "Add text 'Qwen - AI for image editing' in Chinese at the bottom center with a small shadow.",
231
+ "Change the style to 1970s vintage, add old photo effect, restore any scratches on the wall or window.",
232
+ "Remove the blue sky and replace it with a dark night cityscape.",
233
+ """Replace "Qwen" with "通义" in the Image. Ensure Chinese font is used and position it at top left."""
234
+ ]
235
+
236
+ with gr.Blocks(title="Qwen Image Editor", theme=gr.themes.Soft()) as demo:
237
+ gr.Markdown("""
238
+ <div style="text-align: center;">
239
+ <h1>⚡️ Qwen-Image-Edit Lightning</h1>
240
+ <p>8-step image editing with local prompt enhancement | Powered by NVIDIA H200</p>
241
+ </div>
242
+ """)
243
+
244
+ with gr.Row():
245
+ # Input Column
246
+ with gr.Column():
247
+ input_image = gr.Image(label="Input Image", type="pil")
248
+ prompt = gr.Textbox(label="Edit Instruction", placeholder="e.g. Add a dog to the right side", lines=2)
249
+
250
+ with gr.Accordion("Advanced Settings", open=False):
251
+ gr.Markdown("### Generation Parameters")
252
+ with gr.Row():
253
+ seed = gr.Slider(label="Seed", min=0, max=MAX_SEED, step=1, value=42)
254
+ randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
255
+ with gr.Row():
256
+ true_guidance_scale = gr.Slider(
257
+ label="Guidance Scale", min=1.0, max=5.0, step=0.1, value=4.0
258
+ )
259
+ num_inference_steps = gr.Slider(
260
+ label="Inference Steps", min=4, max=16, step=1, value=8
261
+ )
262
+ num_images_per_prompt = gr.Slider(
263
+ label="Output Images", min=1, max=4, step=1, value=1
264
+ )
265
+
266
+ rewrite_toggle = gr.Checkbox(
267
+ label="Enable AI Prompt Enhancement",
268
+ value=True,
269
+ info="Uses local Qwen1.5-1.8B model to improve your instructions"
270
+ )
271
+
272
+ run_button = gr.Button("Generate Edits", variant="primary")
273
+
274
+ # Output Column
275
+ with gr.Column():
276
+ result = gr.Gallery(
277
+ label="Output Images",
278
+ columns=lambda x: 2 if x > 1 else 1,
279
+ object_fit="contain",
280
+ height="auto"
281
+ )
282
+ prompt_info = gr.HTML(
283
+ "<div style='margin-top:20px; padding:15px; border-radius:8px; background:#f8f9fa'>"
284
+ "<p>Prompt details will appear here after generation</p></div>"
285
+ )
286
+
287
+ gr.Examples(
288
+ examples=examples,
289
+ inputs=[prompt],
290
+ label="Try These Examples",
291
+ cache_examples=True
292
+ )
293
+
294
+ # Main processing handler
295
+ inputs = [
296
+ input_image,
297
+ prompt,
298
+ seed,
299
+ randomize_seed,
300
+ true_guidance_scale,
301
+ num_inference_steps,
302
+ rewrite_toggle,
303
+ num_images_per_prompt
304
+ ]
305
+
306
+ outputs = [result, seed, prompt_info]
307
+
308
+ run_button.click(
309
+ fn=infer,
310
+ inputs=inputs,
311
+ outputs=outputs
312
+ )
313
+
314
+ prompt.submit(
315
+ fn=infer,
316
+ inputs=inputs,
317
+ outputs=outputs
318
+ )
319
+
320
+ if __name__ == "__main__":
321
+ demo.launch()