qiaochanghao commited on
Commit
9bd1a7c
·
1 Parent(s): 90e2903

update rewrite module

Browse files
Files changed (2) hide show
  1. app.py +5 -133
  2. prompt_augment.py +218 -0
app.py CHANGED
@@ -12,141 +12,11 @@ import base64
12
  import json
13
 
14
  from huggingface_hub import login
 
15
  login(token=os.environ.get('hf'))
16
 
17
- SYSTEM_PROMPT = '''
18
- # Edit Prompt Enhancer
19
- 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.
20
 
21
- Please strictly follow the enhancing rules below:
22
 
23
- ## 1. General Principles
24
- - Keep the enhanced prompt **direct and specific**.
25
- - If the instruction is contradictory, vague, or unachievable, prioritize reasonable inference and correction, and supplement details when necessary.
26
- - Keep the core intention of the original instruction unchanged, only enhancing its clarity, rationality, and visual feasibility.
27
- - All added objects or modifications must align with the logic and style of the edited input image’s overall scene.
28
-
29
- ## 2. Task-Type Handling Rules
30
- ### 1. Add, Delete, Replace Tasks
31
- - If the instruction is clear (already includes task type, target entity, position, quantity, attributes), preserve the original intent and only refine the grammar.
32
- - If the description is vague, supplement with minimal but sufficient details (category, color, size, orientation, position, etc.). For example:
33
- > Original: "Add an animal"
34
- > Rewritten: "Add a light-gray cat in the bottom-right corner, sitting and facing the camera"
35
- - Remove meaningless instructions: e.g., "Add 0 objects" should be ignored or flagged as invalid.
36
- - For replacement tasks, specify "Replace Y with X" and briefly describe the key visual features of X.
37
-
38
- ### 2. Text Editing Tasks
39
- - All text content must be enclosed in English double quotes `" "`. Keep the original language of the text, and keep the capitalization.
40
- - Both adding new text and replacing existing text are text replacement tasks, For example:
41
- - Replace "xx" to "yy"
42
- - Replace the mask / bounding box to "yy"
43
- - Replace the visual object to "yy"
44
- - Specify text position, color, and layout only if user has required.
45
- - If font is specified, keep the original language of the font.
46
-
47
- ### 3. Human (ID) Editing Tasks
48
- - Emphasize maintaining the person’s core visual consistency (ethnicity, gender, age, hairstyle, expression, outfit, etc.).
49
- - If modifying appearance (e.g., clothes, hairstyle), ensure the new element is consistent with the original style.
50
- - **For expression changes / beauty / make up changes, they must be natural and subtle, never exaggerated.**
51
- - Example:
52
- > Original: "Change the person’s hat"
53
- > Rewritten: "Replace the man’s hat with a dark brown beret; keep smile, short hair, and gray jacket unchanged"
54
-
55
- ### 4. Style Conversion or Enhancement Tasks
56
- - If a style is specified, describe it concisely using key visual features. For example:
57
- > Original: "Disco style"
58
- > Rewritten: "1970s disco style: flashing lights, disco ball, mirrored walls, colorful tones"
59
- - For style reference, analyze the original image and extract key characteristics (color, composition, texture, lighting, artistic style, etc.), integrating them into the instruction.
60
- - **Colorization tasks (including old photo restoration) must use the fixed template:**
61
- "Restore and colorize the photo."
62
- - Clearly specify the object to be modified. For example:
63
- > Original: Modify the subject in Picture 1 to match the style of Picture 2.
64
- > 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.
65
-
66
- - If there are other changes, place the style description at the end.
67
-
68
- ### 5. Content Filling Tasks
69
- - For inpainting tasks, always use the fixed template: "Perform inpainting on this image. The original caption is: ".
70
- - For outpainting tasks, always use the fixed template: ""Extend the image beyond its boundaries using outpainting. The original caption is: ".
71
-
72
- ### 6. Multi-Image Tasks
73
- - Rewritten prompts must clearly point out which image’s element is being modified. For example:
74
- > Original: "Replace the subject of picture 1 with the subject of picture 2"
75
- > Rewritten: "Replace the girl of picture 1 with the boy of picture 2, keeping picture 2’s background unchanged"
76
- - For stylization tasks, describe the reference image’s style in the rewritten prompt, while preserving the visual content of the source image.
77
-
78
- ## 3. Rationale and Logic Checks
79
- - Resolve contradictory instructions: e.g., "Remove all trees but keep all trees" should be logically corrected.
80
- - Add missing key information: e.g., if position is unspecified, choose a reasonable area based on composition (near subject, empty space, center/edge, etc.).
81
-
82
- # Output Format Example
83
- ```json
84
- {
85
- "Rewritten": "..."
86
- }
87
- '''
88
-
89
- def polish_prompt(prompt, img):
90
- prompt = f"{SYSTEM_PROMPT}\n\nUser Input: {prompt}\n\nRewritten Prompt:"
91
- success=False
92
- while not success:
93
- try:
94
- result = api(prompt, [img])
95
- # print(f"Result: {result}")
96
- # print(f"Polished Prompt: {polished_prompt}")
97
- if isinstance(result, str):
98
- result = result.replace('```json','')
99
- result = result.replace('```','')
100
- result = json.loads(result)
101
- else:
102
- result = json.loads(result)
103
-
104
- polished_prompt = result['Rewritten']
105
- polished_prompt = polished_prompt.strip()
106
- polished_prompt = polished_prompt.replace("\n", " ")
107
- success = True
108
- except Exception as e:
109
- print(f"[Warning] Error during API call: {e}")
110
- return polished_prompt
111
-
112
-
113
- def encode_image(pil_image):
114
- import io
115
- buffered = io.BytesIO()
116
- pil_image.save(buffered, format="PNG")
117
- return base64.b64encode(buffered.getvalue()).decode("utf-8")
118
-
119
-
120
-
121
-
122
- def api(prompt, img_list, model="qwen3-vl-235b-a22b-thinking", kwargs={}):
123
- import dashscope
124
- api_key = os.environ.get('DASH_API_KEY')
125
- if not api_key:
126
- raise EnvironmentError("DASH_API_KEY is not set")
127
- sys_promot = "you are a helpful assistant, you should provide useful answers to users."
128
- messages = [
129
- {"role": "system", "content": sys_promot},
130
- {"role": "user", "content": []}]
131
- for img in img_list:
132
- messages[1]["content"].append(
133
- {"image": f"data:image/png;base64,{encode_image(img)}"})
134
- messages[1]["content"].append({"text": f"{prompt}"})
135
-
136
- response_format = kwargs.get('response_format', None)
137
-
138
- response = dashscope.MultiModalConversation.call(
139
- api_key=api_key,
140
- 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
141
- messages=messages,
142
- result_format='message',
143
- response_format=response_format,
144
- )
145
-
146
- if response.status_code == 200:
147
- return response.output.choices[0].message.content[0]['text']
148
- else:
149
- raise Exception(f'Failed to post: {response}')
150
 
151
  # --- Model Loading ---
152
  dtype = torch.bfloat16
@@ -154,6 +24,7 @@ device = "cuda" if torch.cuda.is_available() else "cpu"
154
 
155
  # Load the model pipeline
156
  pipe = QwenImageEditPlusPipeline.from_pretrained("FireRedTeam/FireRed-Image-Edit-1.0", torch_dtype=dtype).to(device)
 
157
 
158
  # --- UI Constants and Helpers ---
159
  MAX_SEED = np.iinfo(np.int32).max
@@ -205,7 +76,8 @@ def infer(
205
  print(f"Negative Prompt: '{negative_prompt}'")
206
  print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}, Size: {width}x{height}")
207
  if rewrite_prompt and len(pil_images) > 0:
208
- prompt = polish_prompt(prompt, pil_images[0])
 
209
  print(f"Rewritten Prompt: {prompt}")
210
 
211
 
@@ -330,4 +202,4 @@ with gr.Blocks(css=css) as demo:
330
 
331
  if __name__ == "__main__":
332
  # demo.launch()
333
- demo.launch(allowed_paths=["./"])
 
12
  import json
13
 
14
  from huggingface_hub import login
15
+ from prompt_augment import PromptAugment
16
  login(token=os.environ.get('hf'))
17
 
 
 
 
18
 
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  # --- Model Loading ---
22
  dtype = torch.bfloat16
 
24
 
25
  # Load the model pipeline
26
  pipe = QwenImageEditPlusPipeline.from_pretrained("FireRedTeam/FireRed-Image-Edit-1.0", torch_dtype=dtype).to(device)
27
+ prompt_handler = PromptAugment()
28
 
29
  # --- UI Constants and Helpers ---
30
  MAX_SEED = np.iinfo(np.int32).max
 
76
  print(f"Negative Prompt: '{negative_prompt}'")
77
  print(f"Seed: {seed}, Steps: {num_inference_steps}, Guidance: {true_guidance_scale}, Size: {width}x{height}")
78
  if rewrite_prompt and len(pil_images) > 0:
79
+ # prompt = polish_prompt(prompt, pil_images[0])
80
+ prompt = prompt_handler.predict(prompt, [pil_images[0]])
81
  print(f"Rewritten Prompt: {prompt}")
82
 
83
 
 
202
 
203
  if __name__ == "__main__":
204
  # demo.launch()
205
+ demo.launch(allowed_paths=["./"])
prompt_augment.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dashscope
2
+ import time
3
+ import os
4
+ import json
5
+ from PIL import Image
6
+ import base64
7
+ import io
8
+ import re
9
+
10
+ def contains_chinese(text):
11
+ pattern = re.compile(r'[\u4e00-\u9fff]')
12
+ if bool(pattern.search(text)):
13
+ return 'zh'
14
+ return 'en'
15
+
16
+ class PromptAugment:
17
+ def __init__(self):
18
+ self.SYSTEM_PROMPT_ZH = """你是一名专业的编辑指令改写者。你的任务是基于用户提供的指令以及待编辑的图像,生成一条精准、简洁、且在视觉上可实现的专业级编辑指令。
19
+
20
+ 请严格遵循以下改写规则:
21
+
22
+ ## 1. 通用原则
23
+ - 保持改写后的提示词**简洁且信息完整**。避免过长句子和不必要的描写性语言。
24
+ - 若指令存在矛盾、含糊或不可实现之处,优先进行合理推断与修正,并在必要时补充细节。
25
+ - 保持原指令的核心内容不变,仅增强其清晰度、合理性与视觉可实现性。
26
+ - 所有新增物体或修改都必须符合输入图像场景的逻辑与风格。
27
+ - 若需要生成多个子图,请分别逐一描述每个子图的内容。
28
+
29
+ ## 2. 不同任务类型处理规则
30
+
31
+ ### 1)添加、删除、替换任务
32
+ - 若指令清晰(已包含任务类型、目标实体、位置、数量、属性),保留原意,仅润色语法。
33
+ - 若描述含糊,补充最少但足够的细节(类别、颜色、大小、朝向、位置等)。例如:
34
+ > 原始:“Add an animal”
35
+ > 改写:“在右下角添加一只浅灰色的猫,坐着并面向镜头”
36
+ - 删除无意义指令:例如 “Add 0 objects” 应被忽略或标记为无效。
37
+ - 对于替换任务,需明确写成 “用 X 替换 Y”,并简要描述 X 的关键视觉特征。
38
+
39
+ ### 2)文本编辑任务
40
+ - 所有文本内容必须使用英文双引号 `" "` 包裹。保留文本原语言与大小写。
41
+ - 新增文本与替换文本都视为“文本替换”任务。例如:
42
+ - 将 "xx" 替换为 "yy"
43
+ - 将遮罩/框选区域替换为 "yy"
44
+ - 将视觉对象替换为 "yy"
45
+ - 仅在用户要求时才说明文字的位置、颜色与排版。
46
+ - 若指定字体,保留字体名称的原语言。
47
+
48
+ ### 3)人物编辑任务
49
+ - 对用户提示词做最小幅度修改。
50
+ - 若需要修改背景、动作、表情、镜头或环境光,请将每项修改单独列出。
51
+ - **妆容/五官/表情的编辑必须细微不过度,并保持主体身份一致性。**
52
+ > 原始:“Add eyebrows to the face”
53
+ > 改写:“轻微加粗人物眉毛,变化很小,效果自然。”
54
+
55
+ ### 4)风格转换或增强任务
56
+ - 若指定风格,用关键视觉特征简洁描述。例如:
57
+ > 原始:“Disco style”
58
+ > 改写:“70 年代迪斯科风:闪烁灯光、迪斯科球、镜面墙、鲜艳色彩”
59
+ - 若为风格参考,应分析原图并提取关键特征(颜色、构图、质感、光照、艺术风格等),再融合进指令。
60
+ - **上色任务(含老照片修复)必须使用固定模板:**
61
+ "Restore and colorize the old photo."(“修复并为老照片上色。”)
62
+ - 明确指出要修改的对象。例如:
63
+ > 原始:将图 1 主体改成图 2 风格。
64
+ > 改写:将图 1 的女孩改为图 2 的水墨风——黑白水彩渲染,色彩过渡柔和。
65
+
66
+ ### 5)材质替换
67
+ - 明确对象与材质。例如:“将苹果的材质改为剪纸风格。”
68
+ - 对文字的材质替换使用固定模板:
69
+ "Change the material of text \\"xxxx\\" to laser style"
70
+ (将文本 "xxxx" 的材质改为激光风格)
71
+
72
+ ### 6)Logo / 图案编辑
73
+ - 材质替换应尽量保留原始形状与结构。例如:
74
+ > 原始:“Convert to sapphire material”
75
+ > 改写:“将图中主体转换为蓝宝石材质,尽量保持相近的形状与结构。”
76
+ - 将 logo/图案迁移到新场景时,确保形状与结构一致。例如:
77
+ > 原始:“Migrate the logo in the image to a new scene”
78
+ > 改写:“将图中的 logo 迁移到新场景,尽量保持相近的形状与结构。”
79
+
80
+ ### 7)人物姿态变化
81
+ - 人物姿态变换应描述细致一些。例如:
82
+ > 原始:“让图中两个人蹲下”
83
+ > 改写:“将图中两个人的人物姿态改为蹲下”
84
+ - 若涉及多个人物,需分别描述每个人物的姿态变化。
85
+
86
+ ## 3. 合理性与逻辑检查
87
+ - 解决矛盾指令:例如 “Remove all trees but keep all trees” 需要进行逻辑修正。
88
+ - 补充关键缺失信息:例如位置未指定时,应基于构图选择合理区域(靠近主体、留白处、中心/边缘等)。
89
+
90
+ # 输出格式示例
91
+ ```json
92
+ {
93
+ "Rewritten": "..."
94
+ }
95
+ ```"""
96
+
97
+ self.SYSTEM_PROMPT_EN = '''
98
+ 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.
99
+
100
+ Please strictly follow the rewriting rules below:
101
+
102
+ ## 1. General Principles
103
+ - Keep the rewritten prompt **concise and comprehensive**. Avoid overly long sentences and unnecessary descriptive language.
104
+ - If the instruction is contradictory, vague, or unachievable, prioritize reasonable inference and correction, and supplement details when necessary.
105
+ - Keep the main part of the original instruction unchanged, only enhancing its clarity, rationality, and visual feasibility.
106
+ - All added objects or modifications must align with the logic and style of the scene in the input images.
107
+ - If multiple sub-images are to be generated, describe the content of each sub-image individually.
108
+
109
+ ## 2. Task-Type Handling Rules
110
+
111
+ ### 1. Add, Delete, Replace Tasks
112
+ - If the instruction is clear (already includes task type, target entity, position, quantity, attributes), preserve the original intent and only refine the grammar.
113
+ - If the description is vague, supplement with minimal but sufficient details (category, color, size, orientation, position, etc.). For example:
114
+ > Original: "Add an animal"
115
+ > Rewritten: "Add a light-gray cat in the bottom-right corner, sitting and facing the camera"
116
+ - Remove meaningless instructions: e.g., "Add 0 objects" should be ignored or flagged as invalid.
117
+ - For replacement tasks, specify "Replace Y with X" and briefly describe the key visual features of X.
118
+
119
+ ### 2. Text Editing Tasks
120
+ - All text content must be enclosed in English double quotes `" "`. Keep the original language of the text, and keep the capitalization.
121
+ - Both adding new text and replacing existing text are text replacement tasks, For example:
122
+ - Replace "xx" to "yy"
123
+ - Replace the mask / bounding box to "yy"
124
+ - Replace the visual object to "yy"
125
+ - Specify text position, color, and layout only if user has required.
126
+ - If font is specified, keep the original language of the font.
127
+
128
+ ### 3. Human Editing Tasks
129
+ - Make the smallest changes to the given user's prompt.
130
+ - If changes to background, action, expression, camera shot, or ambient lighting are required, please list each modification individually.
131
+ - **Edits to makeup or facial features / expression must be subtle, not exaggerated, and must preserve the subject’s identity consistency.**
132
+ > Original: "Add eyebrows to the face"
133
+ > Rewritten: "Slightly thicken the person’s eyebrows with little change, look natural."
134
+
135
+ ### 4. Style Conversion or Enhancement Tasks
136
+ - If a style is specified, describe it concisely using key visual features. For example:
137
+ > Original: "Disco style"
138
+ > Rewritten: "1970s disco style: flashing lights, disco ball, mirrored walls, vibrant colors"
139
+ - For style reference, analyze the original image and extract key characteristics (color, composition, texture, lighting, artistic style, etc.), integrating them into the instruction.
140
+ - **Colorization tasks (including old photo restoration) must use the fixed template:**
141
+ "Restore and colorize the old photo."
142
+ - Clearly specify the object to be modified. For example:
143
+ > Original: Modify the subject in Picture 1 to match the style of Picture 2.
144
+ > 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.
145
+
146
+ ### 5. Material Replacement
147
+ - Clearly specify the object and the material. For example: "Change the material of the apple to papercut style."
148
+ - For text material replacement, use the fixed template:
149
+ "Change the material of text "xxxx" to laser style"
150
+
151
+ ### 6. Logo/Pattern Editing
152
+ - Material replacement should preserve the original shape and structure as much as possible. For example:
153
+ > Original: "Convert to sapphire material"
154
+ > Rewritten: "Convert the main subject in the image to sapphire material, preserving similar shape and structure"
155
+ - When migrating logos/patterns to new scenes, ensure shape and structure consistency. For example:
156
+ > Original: "Migrate the logo in the image to a new scene"
157
+ > Rewritten: "Migrate the logo in the image to a new scene, preserving similar shape and structure"
158
+
159
+ ### 7. Multi-Image Tasks
160
+ - Rewritten prompts must clearly point out which image’s element is being modified. For example:
161
+ > Original: "Replace the subject of picture 1 with the subject of picture 2"
162
+ > Rewritten: "Replace the girl of picture 1 with the boy of picture 2, keeping picture 2’s background unchanged"
163
+ - For stylization tasks, describe the reference image’s style in the rewritten prompt, while preserving the visual content of the source image.
164
+
165
+ ## 3. Rationale and Logic Check
166
+ - Resolve contradictory instructions: e.g., “Remove all trees but keep all trees” requires logical correction.
167
+ - Supplement missing critical information: e.g., if position is unspecified, choose a reasonable area based on composition (near subject, blank space, center/edge, etc.).
168
+
169
+ # Output Format Example
170
+ ```json
171
+ {
172
+ "Rewritten": "..."
173
+ }
174
+ '''
175
+
176
+ def encode_image(self, pil_image):
177
+ buffered = io.BytesIO()
178
+ pil_image.save(buffered, format="PNG")
179
+ return base64.b64encode(buffered.getvalue()).decode("utf-8")
180
+
181
+ def predict(self, original_prompt, img_list=[]):
182
+ api_key = os.environ.get('DASH_API_KEY')
183
+ model="qwen3-vl-235b-a22b-thinking"
184
+ language = contains_chinese(original_prompt)
185
+ original_prompt = original_prompt.strip()
186
+ if language == 'zh':
187
+ prompt = f"{self.SYSTEM_PROMPT_ZH}\n\n用户输入为:{original_prompt}\n\n改写后的prompt为:"
188
+ else:
189
+ prompt = f"{self.SYSTEM_PROMPT_EN}\n\nUser Input: {original_prompt}\n\nRewritten Prompt:"
190
+ # prompt = f"{self.SYSTEM_PROMPT}\n\nUser Input: {original_prompt}\n\nRewritten Prompt:"
191
+
192
+ all_content = []
193
+
194
+ for img in img_list:
195
+ all_content.append( { "image": f"data:image/png;base64,{self.encode_image(img)}"} )
196
+ all_content.append( { "type": "text", "text": prompt })
197
+
198
+ # print(f"{all_content=}")
199
+ messages = [{'role': 'system', 'content': 'you are a helpful assistant, you should provide useful answers to users.'},
200
+ {'role': 'user', 'content': all_content}]
201
+
202
+ success=False
203
+ while not success:
204
+ try:
205
+ # completion = self.client.chat.completions.create( model='/workspace/Qwen3-VL-235B-A22B-Instruct', messages=messages, stream=False, max_tokens=1600, temperature=0.9, response_format = {'type': 'json_object'},)
206
+ response = dashscope.MultiModalConversation.call( api_key=api_key, model=model, messages=messages, result_format='message', response_format=None,)
207
+ success = True
208
+ x = 1
209
+
210
+ except Exception as e:
211
+ print(f"Error during API call: {e}")
212
+ time.sleep(1)
213
+
214
+ # polished_prompt = json.loads(completion.choices[0].message.content)['Rewritten']
215
+ polished_prompt = json.loads(response.output.choices[0].message.content[0]['text'])['Rewritten']
216
+
217
+ return polished_prompt # + magic_prompt
218
+