Spaces:
Runtime error
Runtime error
Delete prompt_augment.py
Browse files- prompt_augment.py +0 -237
prompt_augment.py
DELETED
|
@@ -1,237 +0,0 @@
|
|
| 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-instruct"
|
| 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 |
-
try:
|
| 216 |
-
raw_text = response.output.choices[0].message.content[0]['text']
|
| 217 |
-
print(f"Raw API response: {repr(raw_text[:500])}")
|
| 218 |
-
|
| 219 |
-
# The thinking model may wrap JSON in markdown or include <think> tags
|
| 220 |
-
# Try to extract JSON from the response
|
| 221 |
-
json_match = re.search(r'\{[^{}]*"Rewritten"\s*:\s*"[^"]*"[^{}]*\}', raw_text, re.DOTALL)
|
| 222 |
-
if json_match:
|
| 223 |
-
polished_prompt = json.loads(json_match.group())['Rewritten']
|
| 224 |
-
else:
|
| 225 |
-
# More flexible: find any JSON block (possibly in ```json ... ```)
|
| 226 |
-
json_block = re.search(r'```json\s*(\{.*?\})\s*```', raw_text, re.DOTALL)
|
| 227 |
-
if json_block:
|
| 228 |
-
polished_prompt = json.loads(json_block.group(1))['Rewritten']
|
| 229 |
-
else:
|
| 230 |
-
print("Could not extract JSON from response, using original prompt")
|
| 231 |
-
polished_prompt = original_prompt
|
| 232 |
-
except Exception as e:
|
| 233 |
-
print(f"Prompt rewrite failed: {e}, using original prompt")
|
| 234 |
-
polished_prompt = original_prompt
|
| 235 |
-
|
| 236 |
-
return polished_prompt # + magic_prompt
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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