Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,6 +8,127 @@ from PIL import Image
|
|
| 8 |
from diffusers import QwenImageEditPipeline
|
| 9 |
|
| 10 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# --- Model Loading ---
|
| 13 |
dtype = torch.bfloat16
|
|
@@ -20,22 +141,23 @@ pipe = QwenImageEditPipeline.from_pretrained("Qwen/Qwen-Image-Edit", torch_dtype
|
|
| 20 |
MAX_SEED = np.iinfo(np.int32).max
|
| 21 |
|
| 22 |
# --- Main Inference Function (with hardcoded negative prompt) ---
|
| 23 |
-
@spaces.GPU(duration=
|
| 24 |
def infer(
|
| 25 |
image,
|
| 26 |
prompt,
|
| 27 |
seed=42,
|
| 28 |
randomize_seed=False,
|
| 29 |
-
guidance_scale=4.0,
|
| 30 |
true_guidance_scale=1.0,
|
| 31 |
num_inference_steps=50,
|
|
|
|
|
|
|
| 32 |
progress=gr.Progress(track_tqdm=True),
|
| 33 |
):
|
| 34 |
"""
|
| 35 |
Generates an image using the local Qwen-Image diffusers pipeline.
|
| 36 |
"""
|
| 37 |
# Hardcode the negative prompt as requested
|
| 38 |
-
negative_prompt = "
|
| 39 |
|
| 40 |
if randomize_seed:
|
| 41 |
seed = random.randint(0, MAX_SEED)
|
|
@@ -45,7 +167,10 @@ def infer(
|
|
| 45 |
|
| 46 |
print(f"Calling pipeline with prompt: '{prompt}'")
|
| 47 |
print(f"Negative Prompt: '{negative_prompt}'")
|
| 48 |
-
print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
# Generate the image
|
| 51 |
image = pipe(
|
|
@@ -55,8 +180,8 @@ def infer(
|
|
| 55 |
num_inference_steps=num_inference_steps,
|
| 56 |
generator=generator,
|
| 57 |
true_cfg_scale=true_guidance_scale,
|
| 58 |
-
|
| 59 |
-
).images
|
| 60 |
|
| 61 |
return image, seed
|
| 62 |
|
|
@@ -73,21 +198,22 @@ css = """
|
|
| 73 |
|
| 74 |
with gr.Blocks(css=css) as demo:
|
| 75 |
with gr.Column(elem_id="col-container"):
|
| 76 |
-
gr.HTML('<img src="https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-Image/
|
| 77 |
-
gr.HTML('<h1 style="text-align: center;margin-left: 80px;color: #5b47d1;font-style: italic;">Edit</h1>', elem_id="edit_text")
|
| 78 |
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.")
|
| 79 |
with gr.Row():
|
| 80 |
with gr.Column():
|
| 81 |
input_image = gr.Image(label="Input Image", show_label=False, type="pil")
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
label="Prompt",
|
| 84 |
show_label=False,
|
| 85 |
placeholder="describe the edit instruction",
|
| 86 |
container=False,
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
result = gr.Image(label="Result", show_label=False, type="pil")
|
| 91 |
|
| 92 |
with gr.Accordion("Advanced Settings", open=False):
|
| 93 |
# Negative prompt UI element is removed here
|
|
@@ -103,20 +229,13 @@ with gr.Blocks(css=css) as demo:
|
|
| 103 |
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 104 |
|
| 105 |
with gr.Row():
|
| 106 |
-
guidance_scale = gr.Slider(
|
| 107 |
-
label="Distilled guidance scale",
|
| 108 |
-
minimum=0.0,
|
| 109 |
-
maximum=10.0,
|
| 110 |
-
step=0.1,
|
| 111 |
-
value=4.0,
|
| 112 |
-
)
|
| 113 |
|
| 114 |
true_guidance_scale = gr.Slider(
|
| 115 |
label="True guidance scale",
|
| 116 |
minimum=1.0,
|
| 117 |
maximum=10.0,
|
| 118 |
step=0.1,
|
| 119 |
-
value=
|
| 120 |
)
|
| 121 |
|
| 122 |
num_inference_steps = gr.Slider(
|
|
@@ -126,6 +245,16 @@ with gr.Blocks(css=css) as demo:
|
|
| 126 |
step=1,
|
| 127 |
value=50,
|
| 128 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
# gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)
|
| 131 |
|
|
@@ -137,9 +266,10 @@ with gr.Blocks(css=css) as demo:
|
|
| 137 |
prompt,
|
| 138 |
seed,
|
| 139 |
randomize_seed,
|
| 140 |
-
guidance_scale,
|
| 141 |
true_guidance_scale,
|
| 142 |
num_inference_steps,
|
|
|
|
|
|
|
| 143 |
],
|
| 144 |
outputs=[result, seed],
|
| 145 |
)
|
|
|
|
| 8 |
from diffusers import QwenImageEditPipeline
|
| 9 |
|
| 10 |
import os
|
| 11 |
+
import base64
|
| 12 |
+
import json
|
| 13 |
+
|
| 14 |
+
SYSTEM_PROMPT = '''
|
| 15 |
+
# Edit Instruction Rewriter
|
| 16 |
+
You are a professional edit instruction rewriter. Your task is to generate a precise, concise, and visually achievable professional-level edit instruction based on the user-provided instruction and the image to be edited.
|
| 17 |
+
|
| 18 |
+
Please strictly follow the rewriting rules below:
|
| 19 |
+
|
| 20 |
+
## 1. General Principles
|
| 21 |
+
- Keep the rewritten prompt **concise**. Avoid overly long sentences and reduce unnecessary descriptive language.
|
| 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 `" "`. Do not translate or alter the original language of the text.
|
| 37 |
+
- **For text replacement tasks, always use the fixed template:** `Replace "xx" to "yy"`. Do not improvise beyond this format.
|
| 38 |
+
- If the user does not specify text content, infer and add concise text based on the instruction and the input image’s context. For example:
|
| 39 |
+
> Original: "Add a line of text" (poster)
|
| 40 |
+
> Rewritten: "Add text \"LIMITED EDITION\" at the top center, bold white font with slight shadow"
|
| 41 |
+
- Specify text position, font style (can be inferred), color, and layout in a concise way.
|
| 42 |
+
|
| 43 |
+
### 3. Human Editing Tasks
|
| 44 |
+
- Maintain the person’s core visual consistency (ethnicity, gender, age, hairstyle, expression, outfit, etc.).
|
| 45 |
+
- If modifying appearance (e.g., clothes, hairstyle), ensure the new element is consistent with the original style.
|
| 46 |
+
- **For expression changes, they must be natural and subtle, never exaggerated.**
|
| 47 |
+
- Example:
|
| 48 |
+
> Original: "Change the person’s hat"
|
| 49 |
+
> Rewritten: "Replace the man’s hat with a dark brown beret; keep smile, short hair, and gray jacket unchanged"
|
| 50 |
+
|
| 51 |
+
### 4. Style Transformation or Enhancement Tasks
|
| 52 |
+
- If a style is specified, describe it concisely with key visual traits. For example:
|
| 53 |
+
> Original: "Disco style"
|
| 54 |
+
> Rewritten: "1970s disco: flashing lights, disco ball, mirrored walls, colorful tones"
|
| 55 |
+
- If the instruction says "use reference style" or "keep current style," analyze the input image, extract main features (color, composition, texture, lighting, art style), and integrate them concisely.
|
| 56 |
+
- **For coloring tasks, do not preserve the original tones.** Example:
|
| 57 |
+
> "Restore old photograph, remove scratches, reduce noise, enhance details, high resolution, realistic, natural skin tones, clear facial features, no distortion, vintage photo restoration"
|
| 58 |
+
|
| 59 |
+
## 3. Rationality and Logic Checks
|
| 60 |
+
- Resolve contradictory instructions: e.g., "Remove all trees but keep all trees" should be logically corrected.
|
| 61 |
+
- Add missing key information: if position is unspecified, choose a reasonable area based on composition (near subject, empty space, center/edges).
|
| 62 |
+
|
| 63 |
+
# Output Format Example
|
| 64 |
+
```json
|
| 65 |
+
{
|
| 66 |
+
"Rewritten": "..."
|
| 67 |
+
}
|
| 68 |
+
'''
|
| 69 |
+
|
| 70 |
+
def polish_prompt(prompt, img):
|
| 71 |
+
prompt = f"{SYSTEM_PROMPT}\n\nUser Input: {prompt}\n\nRewritten Prompt:"
|
| 72 |
+
success=False
|
| 73 |
+
while not success:
|
| 74 |
+
try:
|
| 75 |
+
result = api(prompt, [img])
|
| 76 |
+
# print(f"Result: {result}")
|
| 77 |
+
# print(f"Polished Prompt: {polished_prompt}")
|
| 78 |
+
if isinstance(result, str):
|
| 79 |
+
result = result.replace('```json','')
|
| 80 |
+
result = result.replace('```','')
|
| 81 |
+
result = json.loads(result)
|
| 82 |
+
else:
|
| 83 |
+
result = json.loads(result)
|
| 84 |
+
|
| 85 |
+
polished_prompt = result['Rewritten']
|
| 86 |
+
polished_prompt = polished_prompt.strip()
|
| 87 |
+
polished_prompt = polished_prompt.replace("\n", " ")
|
| 88 |
+
success = True
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"[Warning] Error during API call: {e}")
|
| 91 |
+
return polished_prompt
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def encode_image(pil_image):
|
| 95 |
+
import io
|
| 96 |
+
buffered = io.BytesIO()
|
| 97 |
+
pil_image.save(buffered, format="PNG")
|
| 98 |
+
return base64.b64encode(buffered.getvalue()).decode("utf-8")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def api(prompt, img_list, model="qwen-vl-max-latest", kwargs={}):
|
| 104 |
+
import dashscope
|
| 105 |
+
api_key = os.environ.get('DASH_API_KEY')
|
| 106 |
+
if not api_key:
|
| 107 |
+
raise EnvironmentError("DASH_API_KEY is not set")
|
| 108 |
+
assert model in ["qwen-vl-max-latest"], f"Not implemented model {model}"
|
| 109 |
+
sys_promot = "you are a helpful assistant, you should provide useful answers to users."
|
| 110 |
+
messages = [
|
| 111 |
+
{"role": "system", "content": sys_promot},
|
| 112 |
+
{"role": "user", "content": []}]
|
| 113 |
+
for img in img_list:
|
| 114 |
+
messages[1]["content"].append(
|
| 115 |
+
{"image": f"data:image/png;base64,{encode_image(img)}"})
|
| 116 |
+
messages[1]["content"].append({"text": f"{prompt}"})
|
| 117 |
+
|
| 118 |
+
response_format = kwargs.get('response_format', None)
|
| 119 |
+
|
| 120 |
+
response = dashscope.MultiModalConversation.call(
|
| 121 |
+
api_key=api_key,
|
| 122 |
+
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
|
| 123 |
+
messages=messages,
|
| 124 |
+
result_format='message',
|
| 125 |
+
response_format=response_format,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
if response.status_code == 200:
|
| 129 |
+
return response.output.choices[0].message.content[0]['text']
|
| 130 |
+
else:
|
| 131 |
+
raise Exception(f'Failed to post: {response}')
|
| 132 |
|
| 133 |
# --- Model Loading ---
|
| 134 |
dtype = torch.bfloat16
|
|
|
|
| 141 |
MAX_SEED = np.iinfo(np.int32).max
|
| 142 |
|
| 143 |
# --- Main Inference Function (with hardcoded negative prompt) ---
|
| 144 |
+
@spaces.GPU(duration=300)
|
| 145 |
def infer(
|
| 146 |
image,
|
| 147 |
prompt,
|
| 148 |
seed=42,
|
| 149 |
randomize_seed=False,
|
|
|
|
| 150 |
true_guidance_scale=1.0,
|
| 151 |
num_inference_steps=50,
|
| 152 |
+
rewrite_prompt=True,
|
| 153 |
+
num_images_per_prompt=1,
|
| 154 |
progress=gr.Progress(track_tqdm=True),
|
| 155 |
):
|
| 156 |
"""
|
| 157 |
Generates an image using the local Qwen-Image diffusers pipeline.
|
| 158 |
"""
|
| 159 |
# Hardcode the negative prompt as requested
|
| 160 |
+
negative_prompt = " "
|
| 161 |
|
| 162 |
if randomize_seed:
|
| 163 |
seed = random.randint(0, MAX_SEED)
|
|
|
|
| 167 |
|
| 168 |
print(f"Calling pipeline with prompt: '{prompt}'")
|
| 169 |
print(f"Negative Prompt: '{negative_prompt}'")
|
| 170 |
+
print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}")
|
| 171 |
+
if rewrite_prompt:
|
| 172 |
+
prompt = polish_prompt(prompt, image)
|
| 173 |
+
print(f"Rewritten Prompt: {prompt}")
|
| 174 |
|
| 175 |
# Generate the image
|
| 176 |
image = pipe(
|
|
|
|
| 180 |
num_inference_steps=num_inference_steps,
|
| 181 |
generator=generator,
|
| 182 |
true_cfg_scale=true_guidance_scale,
|
| 183 |
+
num_images_per_prompt=num_images_per_prompt
|
| 184 |
+
).images
|
| 185 |
|
| 186 |
return image, seed
|
| 187 |
|
|
|
|
| 198 |
|
| 199 |
with gr.Blocks(css=css) as demo:
|
| 200 |
with gr.Column(elem_id="col-container"):
|
| 201 |
+
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;">')
|
|
|
|
| 202 |
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.")
|
| 203 |
with gr.Row():
|
| 204 |
with gr.Column():
|
| 205 |
input_image = gr.Image(label="Input Image", show_label=False, type="pil")
|
| 206 |
+
|
| 207 |
+
# result = gr.Image(label="Result", show_label=False, type="pil")
|
| 208 |
+
result = gr.Gallery(label="Result", show_label=False, type="pil")
|
| 209 |
+
with gr.Row():
|
| 210 |
+
prompt = gr.Text(
|
| 211 |
label="Prompt",
|
| 212 |
show_label=False,
|
| 213 |
placeholder="describe the edit instruction",
|
| 214 |
container=False,
|
| 215 |
+
)
|
| 216 |
+
run_button = gr.Button("Edit!", variant="primary")
|
|
|
|
|
|
|
| 217 |
|
| 218 |
with gr.Accordion("Advanced Settings", open=False):
|
| 219 |
# Negative prompt UI element is removed here
|
|
|
|
| 229 |
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
|
| 230 |
|
| 231 |
with gr.Row():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
|
| 233 |
true_guidance_scale = gr.Slider(
|
| 234 |
label="True guidance scale",
|
| 235 |
minimum=1.0,
|
| 236 |
maximum=10.0,
|
| 237 |
step=0.1,
|
| 238 |
+
value=4.0
|
| 239 |
)
|
| 240 |
|
| 241 |
num_inference_steps = gr.Slider(
|
|
|
|
| 245 |
step=1,
|
| 246 |
value=50,
|
| 247 |
)
|
| 248 |
+
|
| 249 |
+
num_images_per_prompt = gr.Slider(
|
| 250 |
+
label="Number of images per prompt",
|
| 251 |
+
minimum=1,
|
| 252 |
+
maximum=4,
|
| 253 |
+
step=1,
|
| 254 |
+
value=1,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
rewrite_prompt = gr.Checkbox(label="Rewrite prompt", value=True)
|
| 258 |
|
| 259 |
# gr.Examples(examples=examples, inputs=[prompt], outputs=[result, seed], fn=infer, cache_examples=False)
|
| 260 |
|
|
|
|
| 266 |
prompt,
|
| 267 |
seed,
|
| 268 |
randomize_seed,
|
|
|
|
| 269 |
true_guidance_scale,
|
| 270 |
num_inference_steps,
|
| 271 |
+
rewrite_prompt,
|
| 272 |
+
num_images_per_prompt,
|
| 273 |
],
|
| 274 |
outputs=[result, seed],
|
| 275 |
)
|