naykun commited on
Commit
0ac5b5e
·
1 Parent(s): ac2fc18

init update

Browse files
Files changed (2) hide show
  1. app.py +325 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import random
4
+ import torch
5
+ import spaces
6
+
7
+ from PIL import Image
8
+ from diffusers import QwenImageEditPlusPipeline
9
+
10
+ import os
11
+ import base64
12
+ import json
13
+
14
+ SYSTEM_PROMPT = '''
15
+ # Edit Prompt Enhancer
16
+ You are a professional edit prompt enhancer. Your task is to generate a direct and specific edit prompt based on the user-provided instruction and the image input conditions.
17
+
18
+ Please strictly follow the enhancing rules below:
19
+
20
+ ## 1. General Principles
21
+ - Keep the enhanced prompt **direct and specific**.
22
+ - If the instruction is contradictory, vague, or unachievable, prioritize reasonable inference and correction, and supplement details when necessary.
23
+ - Keep the core intention of the original instruction unchanged, only enhancing its clarity, rationality, and visual feasibility.
24
+ - All added objects or modifications must align with the logic and style of the edited input image’s overall scene.
25
+
26
+ ## 2. Task-Type Handling Rules
27
+ ### 1. Add, Delete, Replace Tasks
28
+ - If the instruction is clear (already includes task type, target entity, position, quantity, attributes), preserve the original intent and only refine the grammar.
29
+ - If the description is vague, supplement with minimal but sufficient details (category, color, size, orientation, position, etc.). For example:
30
+ > Original: "Add an animal"
31
+ > Rewritten: "Add a light-gray cat in the bottom-right corner, sitting and facing the camera"
32
+ - Remove meaningless instructions: e.g., "Add 0 objects" should be ignored or flagged as invalid.
33
+ - For replacement tasks, specify "Replace Y with X" and briefly describe the key visual features of X.
34
+
35
+ ### 2. Text Editing Tasks
36
+ - All text content must be enclosed in English double quotes `" "`. Keep the original language of the text, and keep the capitalization.
37
+ - Both adding new text and replacing existing text are text replacement tasks, For example:
38
+ - Replace "xx" to "yy"
39
+ - Replace the mask / bounding box to "yy"
40
+ - Replace the visual object to "yy"
41
+ - Specify text position, color, and layout only if user has required.
42
+ - If font is specified, keep the original language of the font.
43
+
44
+ ### 3. Human (ID) Editing Tasks
45
+ - Emphasize maintaining the person’s core visual consistency (ethnicity, gender, age, hairstyle, expression, outfit, etc.).
46
+ - If modifying appearance (e.g., clothes, hairstyle), ensure the new element is consistent with the original style.
47
+ - **For expression changes / beauty / make up changes, they must be natural and subtle, never exaggerated.**
48
+ - Example:
49
+ > Original: "Change the person’s hat"
50
+ > Rewritten: "Replace the man’s hat with a dark brown beret; keep smile, short hair, and gray jacket unchanged"
51
+
52
+ ### 4. Style Conversion or Enhancement Tasks
53
+ - If a style is specified, describe it concisely using key visual features. For example:
54
+ > Original: "Disco style"
55
+ > Rewritten: "1970s disco style: flashing lights, disco ball, mirrored walls, colorful tones"
56
+ - For style reference, analyze the original image and extract key characteristics (color, composition, texture, lighting, artistic style, etc.), integrating them into the instruction.
57
+ - **Colorization tasks (including old photo restoration) must use the fixed template:**
58
+ "Restore and colorize the photo."
59
+ - Clearly specify the object to be modified. For example:
60
+ > Original: Modify the subject in Picture 1 to match the style of Picture 2.
61
+ > Rewritten: Change the girl in Picture 1 to the ink-wash style of Picture 2 — rendered in black-and-white watercolor with soft color transitions.
62
+
63
+ - If there are other changes, place the style description at the end.
64
+
65
+ ### 5. Content Filling Tasks
66
+ - For inpainting tasks, always use the fixed template: "Perform inpainting on this image. The original caption is: ".
67
+ - For outpainting tasks, always use the fixed template: ""Extend the image beyond its boundaries using outpainting. The original caption is: ".
68
+
69
+ ### 6. Multi-Image Tasks
70
+ - Rewritten prompts must clearly point out which image’s element is being modified. For example:
71
+ > Original: "Replace the subject of picture 1 with the subject of picture 2"
72
+ > Rewritten: "Replace the girl of picture 1 with the boy of picture 2, keeping picture 2’s background unchanged"
73
+ - For stylization tasks, describe the reference image’s style in the rewritten prompt, while preserving the visual content of the source image.
74
+
75
+ ## 3. Rationale and Logic Checks
76
+ - Resolve contradictory instructions: e.g., "Remove all trees but keep all trees" should be logically corrected.
77
+ - Add missing key information: e.g., if position is unspecified, choose a reasonable area based on composition (near subject, empty space, center/edge, etc.).
78
+
79
+ # Output Format Example
80
+ ```json
81
+ {
82
+ "Rewritten": "..."
83
+ }
84
+ '''
85
+
86
+ def polish_prompt(prompt, img):
87
+ prompt = f"{SYSTEM_PROMPT}\n\nUser Input: {prompt}\n\nRewritten Prompt:"
88
+ success=False
89
+ while not success:
90
+ try:
91
+ result = api(prompt, [img])
92
+ # print(f"Result: {result}")
93
+ # print(f"Polished Prompt: {polished_prompt}")
94
+ if isinstance(result, str):
95
+ result = result.replace('```json','')
96
+ result = result.replace('```','')
97
+ result = json.loads(result)
98
+ else:
99
+ result = json.loads(result)
100
+
101
+ polished_prompt = result['Rewritten']
102
+ polished_prompt = polished_prompt.strip()
103
+ polished_prompt = polished_prompt.replace("\n", " ")
104
+ success = True
105
+ except Exception as e:
106
+ print(f"[Warning] Error during API call: {e}")
107
+ return polished_prompt
108
+
109
+
110
+ def encode_image(pil_image):
111
+ import io
112
+ buffered = io.BytesIO()
113
+ pil_image.save(buffered, format="PNG")
114
+ return base64.b64encode(buffered.getvalue()).decode("utf-8")
115
+
116
+
117
+
118
+
119
+ def api(prompt, img_list, model="qwen-vl-max-latest", kwargs={}):
120
+ import dashscope
121
+ api_key = os.environ.get('DASH_API_KEY')
122
+ if not api_key:
123
+ raise EnvironmentError("DASH_API_KEY is not set")
124
+ assert model in ["qwen-vl-max-latest"], f"Not implemented model {model}"
125
+ sys_promot = "you are a helpful assistant, you should provide useful answers to users."
126
+ messages = [
127
+ {"role": "system", "content": sys_promot},
128
+ {"role": "user", "content": []}]
129
+ for img in img_list:
130
+ messages[1]["content"].append(
131
+ {"image": f"data:image/png;base64,{encode_image(img)}"})
132
+ messages[1]["content"].append({"text": f"{prompt}"})
133
+
134
+ response_format = kwargs.get('response_format', None)
135
+
136
+ response = dashscope.MultiModalConversation.call(
137
+ api_key=api_key,
138
+ model=model, # For example, use qwen-plus here. You can change the model name as needed. Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
139
+ messages=messages,
140
+ result_format='message',
141
+ response_format=response_format,
142
+ )
143
+
144
+ if response.status_code == 200:
145
+ return response.output.choices[0].message.content[0]['text']
146
+ else:
147
+ raise Exception(f'Failed to post: {response}')
148
+
149
+ # --- Model Loading ---
150
+ dtype = torch.bfloat16
151
+ device = "cuda" if torch.cuda.is_available() else "cpu"
152
+
153
+ # Load the model pipeline
154
+ pipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2511", torch_dtype=dtype).to(device)
155
+
156
+ # --- UI Constants and Helpers ---
157
+ MAX_SEED = np.iinfo(np.int32).max
158
+
159
+ # --- Main Inference Function (with hardcoded negative prompt) ---
160
+ @spaces.GPU(duration=180)
161
+ def infer(
162
+ images,
163
+ prompt,
164
+ seed=42,
165
+ randomize_seed=False,
166
+ true_guidance_scale=1.0,
167
+ num_inference_steps=50,
168
+ height=None,
169
+ width=None,
170
+ rewrite_prompt=True,
171
+ num_images_per_prompt=1,
172
+ progress=gr.Progress(track_tqdm=True),
173
+ ):
174
+ """
175
+ Generates an image using the local Qwen-Image diffusers pipeline.
176
+ """
177
+ # Hardcode the negative prompt as requested
178
+ negative_prompt = " "
179
+
180
+ if randomize_seed:
181
+ seed = random.randint(0, MAX_SEED)
182
+
183
+ # Set up the generator for reproducibility
184
+ generator = torch.Generator(device=device).manual_seed(seed)
185
+
186
+ # Load input images into PIL Images
187
+ pil_images = []
188
+ if images is not None:
189
+ for item in images:
190
+ try:
191
+ if isinstance(item[0], Image.Image):
192
+ pil_images.append(item[0].convert("RGB"))
193
+ elif isinstance(item[0], str):
194
+ pil_images.append(Image.open(item[0]).convert("RGB"))
195
+ elif hasattr(item, "name"):
196
+ pil_images.append(Image.open(item.name).convert("RGB"))
197
+ except Exception:
198
+ continue
199
+
200
+ if height==256 and width==256:
201
+ height, width = None, None
202
+ print(f"Calling pipeline with prompt: '{prompt}'")
203
+ print(f"Negative Prompt: '{negative_prompt}'")
204
+ print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}, Size: {width}x{height}")
205
+ if rewrite_prompt and len(pil_images) > 0:
206
+ prompt = polish_prompt(prompt, pil_images[0])
207
+ print(f"Rewritten Prompt: {prompt}")
208
+
209
+
210
+ # Generate the image
211
+ image = pipe(
212
+ image=pil_images if len(pil_images) > 0 else None,
213
+ prompt=prompt,
214
+ height=height,
215
+ width=width,
216
+ negative_prompt=negative_prompt,
217
+ num_inference_steps=num_inference_steps,
218
+ generator=generator,
219
+ true_cfg_scale=true_guidance_scale,
220
+ num_images_per_prompt=num_images_per_prompt,
221
+ ).images
222
+
223
+ return image, seed
224
+
225
+ # --- Examples and UI Layout ---
226
+ examples = []
227
+
228
+ css = """
229
+ #col-container {
230
+ margin: 0 auto;
231
+ max-width: 1024px;
232
+ }
233
+ #edit_text{margin-top: -62px !important}
234
+ """
235
+
236
+ with gr.Blocks(css=css) as demo:
237
+ with gr.Column(elem_id="col-container"):
238
+ gr.HTML('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/qwen_image_edit_logo.png" alt="Qwen-Image Logo" width="400" style="display: block; margin: 0 auto;">')
239
+ gr.Markdown("[Learn more](https://github.com/QwenLM/Qwen-Image) about the Qwen-Image series. Try on [Qwen Chat](https://chat.qwen.ai/), or [download model](https://huggingface.co/Qwen/Qwen-Image-Edit) to run locally with ComfyUI or diffusers.")
240
+ with gr.Row():
241
+ with gr.Column():
242
+ input_images = gr.Gallery(label="Input Images", show_label=False, type="pil", interactive=True)
243
+
244
+ # result = gr.Image(label="Result", show_label=False, type="pil")
245
+ result = gr.Gallery(label="Result", show_label=False, type="pil")
246
+ with gr.Row():
247
+ prompt = gr.Text(
248
+ label="Prompt",
249
+ show_label=False,
250
+ placeholder="describe the edit instruction",
251
+ container=False,
252
+ )
253
+ run_button = gr.Button("Edit!", variant="primary")
254
+
255
+ with gr.Accordion("Advanced Settings", open=False):
256
+ # Negative prompt UI element is removed here
257
+
258
+ seed = gr.Slider(
259
+ label="Seed",
260
+ minimum=0,
261
+ maximum=MAX_SEED,
262
+ step=1,
263
+ value=0,
264
+ )
265
+
266
+ randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
267
+
268
+ with gr.Row():
269
+
270
+ true_guidance_scale = gr.Slider(
271
+ label="True guidance scale",
272
+ minimum=1.0,
273
+ maximum=10.0,
274
+ step=0.1,
275
+ value=4.0
276
+ )
277
+
278
+ num_inference_steps = gr.Slider(
279
+ label="Number of inference steps",
280
+ minimum=1,
281
+ maximum=50,
282
+ step=1,
283
+ value=40,
284
+ )
285
+
286
+ height = gr.Slider(
287
+ label="Height",
288
+ minimum=256,
289
+ maximum=2048,
290
+ step=8,
291
+ value=None,
292
+ )
293
+
294
+ width = gr.Slider(
295
+ label="Width",
296
+ minimum=256,
297
+ maximum=2048,
298
+ step=8,
299
+ value=None,
300
+ )
301
+
302
+
303
+ rewrite_prompt = gr.Checkbox(label="Rewrite prompt", value=True)
304
+
305
+ # gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)
306
+
307
+ gr.on(
308
+ triggers=[run_button.click, prompt.submit],
309
+ fn=infer,
310
+ inputs=[
311
+ input_images,
312
+ prompt,
313
+ seed,
314
+ randomize_seed,
315
+ true_guidance_scale,
316
+ num_inference_steps,
317
+ height,
318
+ width,
319
+ rewrite_prompt,
320
+ ],
321
+ outputs=[result, seed],
322
+ )
323
+
324
+ if __name__ == "__main__":
325
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ git+https://github.com/huggingface/diffusers.git
2
+ transformers
3
+ accelerate
4
+ safetensors
5
+ sentencepiece
6
+ dashscope
7
+ kernels
8
+ torchvision