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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from typing import Any
|
| 7 |
+
import torch
|
| 8 |
+
import torchvision.transforms as T
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
|
| 11 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 12 |
+
os.environ["GRADIO_TEMP_DIR"] = "./tmp"
|
| 13 |
+
from jodi_pipeline import JodiPipeline
|
| 14 |
+
from model.postprocess import (
|
| 15 |
+
ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
|
| 16 |
+
NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
|
| 17 |
+
)
|
| 18 |
+
from transformers import (
|
| 19 |
+
Qwen2VLForConditionalGeneration,
|
| 20 |
+
Qwen2_5_VLForConditionalGeneration,
|
| 21 |
+
Qwen3VLForConditionalGeneration,
|
| 22 |
+
Qwen3VLMoeForConditionalGeneration
|
| 23 |
+
)
|
| 24 |
+
from transformers import AutoProcessor, Trainer
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
import itertools
|
| 27 |
+
import ast
|
| 28 |
+
import re
|
| 29 |
+
from PIL import Image
|
| 30 |
+
import json
|
| 31 |
+
import re
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def clean_eval_question(q: str) -> str:
|
| 35 |
+
"""
|
| 36 |
+
Clean VQA-style question text for evaluation.
|
| 37 |
+
- If lettered options (A–Z) exist, keep text up to the last option.
|
| 38 |
+
- Otherwise, keep text up to the first '?' (inclusive).
|
| 39 |
+
"""
|
| 40 |
+
if not isinstance(q, str):
|
| 41 |
+
q = str(q)
|
| 42 |
+
|
| 43 |
+
# 删除 <image> 占位符
|
| 44 |
+
q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
|
| 45 |
+
|
| 46 |
+
# 匹配所有选项(A–Z),兼容多种写法:A. / A) / (A) / A: / A - / A– ...
|
| 47 |
+
option_pattern = r"(?:\(?[A-Z]\)?[\.\:\-\)]\s)"
|
| 48 |
+
matches = list(re.finditer(option_pattern, q, flags=re.IGNORECASE))
|
| 49 |
+
|
| 50 |
+
if matches:
|
| 51 |
+
# 找到最后一个选项出现位置 → 保留到该选项行的结束处
|
| 52 |
+
last_match = matches[-1]
|
| 53 |
+
# 找到从最后一个选项开始到该段落结束(如选项内容的末尾)
|
| 54 |
+
tail = q[last_match.end():]
|
| 55 |
+
# 截断尾部任何额外提示("Please answer..." 等)
|
| 56 |
+
tail_cut = re.split(r"(please\s+answer|choose\s+the|select\s+the|answer\s+directly)", tail, flags=re.IGNORECASE)[0]
|
| 57 |
+
q = q[:last_match.end()] + tail_cut
|
| 58 |
+
else:
|
| 59 |
+
# 无选项 → 只保留问句(问号前的部分)
|
| 60 |
+
match_qmark = re.search(r"\?", q)
|
| 61 |
+
if match_qmark:
|
| 62 |
+
q = q[:match_qmark.end()]
|
| 63 |
+
else:
|
| 64 |
+
q = q.split("\n")[0] # fallback
|
| 65 |
+
|
| 66 |
+
# 清理多余换行与空格
|
| 67 |
+
q = re.sub(r"\n+", " ", q)
|
| 68 |
+
q = re.sub(r"\s+", " ", q).strip()
|
| 69 |
+
return q
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def clean_prompt_question(q: str) -> str:
|
| 73 |
+
"""Clean VQA-style question text, keeping only the question stem before '?'. """
|
| 74 |
+
if not isinstance(q, str):
|
| 75 |
+
q = str(q)
|
| 76 |
+
|
| 77 |
+
# 删除 <image> 占位符
|
| 78 |
+
q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
|
| 79 |
+
|
| 80 |
+
# 截取问号之前的部分(包括问号)
|
| 81 |
+
match = re.search(r"^(.*?\?)", q)
|
| 82 |
+
if match:
|
| 83 |
+
q = match.group(1)
|
| 84 |
+
else:
|
| 85 |
+
# 若无问号则保留首句
|
| 86 |
+
q = q.split("\n")[0]
|
| 87 |
+
|
| 88 |
+
# 去除多余空白与换行
|
| 89 |
+
q = re.sub(r"\s+", " ", q).strip()
|
| 90 |
+
return q
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def dump_image(image, save_root):
|
| 94 |
+
os.makedirs(save_root, exist_ok=True)
|
| 95 |
+
save_path = os.path.join(save_root, "input.jpg")
|
| 96 |
+
image.convert("RGB").save(save_path, format="JPEG", quality=95)
|
| 97 |
+
return save_path
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
|
| 101 |
+
""" 将多个图像拼接成一张大图并保存。
|
| 102 |
+
Args: image_paths: List[str] 图像路径列表
|
| 103 |
+
save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
|
| 104 |
+
image_format: 保存格式
|
| 105 |
+
"""
|
| 106 |
+
from PIL import Image
|
| 107 |
+
import io
|
| 108 |
+
# 读取图像
|
| 109 |
+
images = [Image.open(p).convert("RGB") for p in image_paths]
|
| 110 |
+
|
| 111 |
+
if images_per_row is None:
|
| 112 |
+
images_per_row = len(images)
|
| 113 |
+
|
| 114 |
+
# 调整尺寸(可选)
|
| 115 |
+
target_size = min(1024, images[0].size[0])
|
| 116 |
+
images = [img.resize((target_size, target_size)) for img in images]
|
| 117 |
+
|
| 118 |
+
# 拼接
|
| 119 |
+
widths, heights = zip(*(img.size for img in images))
|
| 120 |
+
max_width = max(widths)
|
| 121 |
+
rows = (len(images) + images_per_row - 1) // images_per_row
|
| 122 |
+
total_height = sum(heights[:images_per_row]) * rows
|
| 123 |
+
|
| 124 |
+
new_im = Image.new("RGB", (max_width * images_per_row, total_height))
|
| 125 |
+
y_offset = 0
|
| 126 |
+
for i in range(0, len(images), images_per_row):
|
| 127 |
+
row_imgs = images[i:i + images_per_row]
|
| 128 |
+
x_offset = 0
|
| 129 |
+
for img in row_imgs:
|
| 130 |
+
new_im.paste(img, (x_offset, y_offset))
|
| 131 |
+
x_offset += max_width
|
| 132 |
+
y_offset += heights[0]
|
| 133 |
+
|
| 134 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
| 135 |
+
new_im.save(save_path, format=image_format.upper())
|
| 136 |
+
print(f"🧩 Saved merged image → {save_path}")
|
| 137 |
+
return save_path
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def build_vqa_message(root, prompt, question):
|
| 141 |
+
"""
|
| 142 |
+
Build Qwen3-VL message for multimodal or single-image VQA.
|
| 143 |
+
Now explicitly tags each modality image before feeding into Qwen3-VL,
|
| 144 |
+
so that the model can distinguish RGB, edge, depth, normal, etc.
|
| 145 |
+
"""
|
| 146 |
+
|
| 147 |
+
root_path = Path(root)
|
| 148 |
+
|
| 149 |
+
# ---------- 单图像情况 ----------
|
| 150 |
+
if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
|
| 151 |
+
image_path = str(root)
|
| 152 |
+
messages = [
|
| 153 |
+
{
|
| 154 |
+
"role": "user",
|
| 155 |
+
"content": [
|
| 156 |
+
{"type": "image", "image": image_path},
|
| 157 |
+
{"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
|
| 158 |
+
],
|
| 159 |
+
}
|
| 160 |
+
]
|
| 161 |
+
return messages
|
| 162 |
+
|
| 163 |
+
# ---------- 多模态文件夹情况 ----------
|
| 164 |
+
modality_names = [
|
| 165 |
+
"image",
|
| 166 |
+
"annotation_lineart",
|
| 167 |
+
"annotation_edge",
|
| 168 |
+
"annotation_depth",
|
| 169 |
+
"annotation_normal",
|
| 170 |
+
"annotation_albedo",
|
| 171 |
+
"annotation_seg_12colors",
|
| 172 |
+
# "annotation_openpose",
|
| 173 |
+
]
|
| 174 |
+
|
| 175 |
+
# 检查存在的模态文件
|
| 176 |
+
available = []
|
| 177 |
+
for name in modality_names:
|
| 178 |
+
for ext in [".png", ".jpg", ".jpeg"]:
|
| 179 |
+
path = Path(root) / f"{name}{ext}"
|
| 180 |
+
if path.exists():
|
| 181 |
+
available.append((name, str(path)))
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
# 可读名称映射
|
| 185 |
+
readable_map = {
|
| 186 |
+
"image": "RGB image",
|
| 187 |
+
"annotation_lineart": "line drawing",
|
| 188 |
+
"annotation_edge": "edge map",
|
| 189 |
+
"annotation_depth": "depth map",
|
| 190 |
+
"annotation_normal": "normal map",
|
| 191 |
+
"annotation_albedo": "albedo map",
|
| 192 |
+
"annotation_seg_12colors": "segmentation map",
|
| 193 |
+
# "annotation_openpose": "human pose map",
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
present_modalities = [readable_map[n] for n, _ in available]
|
| 197 |
+
|
| 198 |
+
text_prompt = (
|
| 199 |
+
f"Answer the following question based on multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
|
| 200 |
+
f"The following caption describes the image in detail: '{prompt}'. "
|
| 201 |
+
f"Question:{question}"
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# ---------- 构建内容序列(模态锚定) ----------
|
| 205 |
+
content = []
|
| 206 |
+
print(f'available:{available}')
|
| 207 |
+
for name, path in available:
|
| 208 |
+
readable = readable_map.get(name, "visual input")
|
| 209 |
+
# 在每张图像前显式标注模态类型
|
| 210 |
+
content.append({"type": "text", "text": f"This is the {readable}."})
|
| 211 |
+
content.append({"type": "image", "image": path})
|
| 212 |
+
|
| 213 |
+
# 最后加入主指令
|
| 214 |
+
content.append({"type": "text", "text": text_prompt})
|
| 215 |
+
|
| 216 |
+
messages = [{"role": "user", "content": content}]
|
| 217 |
+
return messages
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
|
| 221 |
+
"""
|
| 222 |
+
Build Qwen3-VL message for multi-modal caption refinement.
|
| 223 |
+
Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
|
| 224 |
+
so Qwen3-VL can reason over them correctly and refine the caption faithfully.
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
modality_names = [
|
| 228 |
+
"image",
|
| 229 |
+
"annotation_lineart",
|
| 230 |
+
"annotation_edge",
|
| 231 |
+
"annotation_depth",
|
| 232 |
+
"annotation_normal",
|
| 233 |
+
"annotation_albedo",
|
| 234 |
+
"annotation_seg_12colors",
|
| 235 |
+
# "annotation_openpose",
|
| 236 |
+
]
|
| 237 |
+
|
| 238 |
+
# --- 检查存在的模态 ---
|
| 239 |
+
available = []
|
| 240 |
+
for name in modality_names:
|
| 241 |
+
for ext in [".png", ".jpg", ".jpeg"]:
|
| 242 |
+
path = Path(root) / f"{name}{ext}"
|
| 243 |
+
if path.exists():
|
| 244 |
+
available.append((name, str(path)))
|
| 245 |
+
break
|
| 246 |
+
|
| 247 |
+
# --- 构建模态说明 ---
|
| 248 |
+
readable_map = {
|
| 249 |
+
"image": "RGB image",
|
| 250 |
+
"annotation_lineart": "line drawing",
|
| 251 |
+
"annotation_edge": "edge map",
|
| 252 |
+
"annotation_depth": "depth map",
|
| 253 |
+
"annotation_normal": "normal map",
|
| 254 |
+
"annotation_albedo": "albedo map",
|
| 255 |
+
"annotation_seg_12colors": "segmentation map",
|
| 256 |
+
# "annotation_openpose": "human pose map",
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
present_modalities = [readable_map[n] for n, _ in available]
|
| 260 |
+
|
| 261 |
+
# --- 构造文本指令 ---
|
| 262 |
+
text_prompt = (
|
| 263 |
+
f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
|
| 264 |
+
f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
|
| 265 |
+
f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
|
| 266 |
+
f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
|
| 267 |
+
f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
|
| 268 |
+
f"while maintaining faithfulness to the original visual content. "
|
| 269 |
+
f"Do not include any additional commentary or evaluations. "
|
| 270 |
+
f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
|
| 271 |
+
f"Focus on describing the visual properties, including: "
|
| 272 |
+
f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
|
| 273 |
+
f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
|
| 274 |
+
f"Exclude any stylistic, environmental, emotional, or narrative information. "
|
| 275 |
+
f"Consider the following feedback when refining your description: '{feedback}'. "
|
| 276 |
+
f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
|
| 277 |
+
f"Coarse caption: '{coarse_caption}' "
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
# text_prompt0 = (
|
| 281 |
+
# f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
|
| 282 |
+
# f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
|
| 283 |
+
# f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
|
| 284 |
+
# f"### Your Task:\n"
|
| 285 |
+
# f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
|
| 286 |
+
# f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
|
| 287 |
+
# f"### Guidelines:\n"
|
| 288 |
+
# f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
|
| 289 |
+
# f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
|
| 290 |
+
# f"3. Do NOT invent or assume anything not visually supported.\n"
|
| 291 |
+
# f"4. Avoid including any additional commentary or evaluations.\n"
|
| 292 |
+
# f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
|
| 293 |
+
# f"### Coarse Caption:\n'{coarse_caption}'\n\n"
|
| 294 |
+
# f"### Feedback to Incorporate:\n'{feedback}'\n\n"
|
| 295 |
+
# f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
|
| 296 |
+
# )
|
| 297 |
+
|
| 298 |
+
# --- 构建消息内容:在每个图像前加模态标识 ---
|
| 299 |
+
content = []
|
| 300 |
+
for name, path in available:
|
| 301 |
+
readable = readable_map.get(name, "visual input")
|
| 302 |
+
content.append({
|
| 303 |
+
"type": "text",
|
| 304 |
+
"text": f"This is the {readable}, which provides {get_modality_description(name)}."
|
| 305 |
+
})
|
| 306 |
+
content.append({"type": "image", "image": path})
|
| 307 |
+
|
| 308 |
+
# 最后附上总任务说明
|
| 309 |
+
content.append({"type": "text", "text": text_prompt})
|
| 310 |
+
|
| 311 |
+
messages = [{"role": "user", "content": content}]
|
| 312 |
+
return messages
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def get_modality_description(name: str) -> str:
|
| 316 |
+
"""为每个模态生成一句说明,用于提示模型理解模态功能"""
|
| 317 |
+
desc_map = {
|
| 318 |
+
"image": "the main visual appearance of the scene, including color, texture, and lighting",
|
| 319 |
+
"annotation_lineart": "structural outlines, object contours, and fine geometry",
|
| 320 |
+
"annotation_edge": "strong boundaries and contrast edges between objects",
|
| 321 |
+
"annotation_depth": "distance and perspective information for spatial understanding",
|
| 322 |
+
"annotation_normal": "surface orientation and geometric curvature cues",
|
| 323 |
+
"annotation_albedo": "pure surface color without lighting or shading effects",
|
| 324 |
+
"annotation_seg_12colors": "semantic regions and object categories",
|
| 325 |
+
"annotation_openpose": "human body keypoints, joints, and orientation",
|
| 326 |
+
}
|
| 327 |
+
return desc_map.get(name, "complementary visual evidence")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
# ------------------------------
|
| 331 |
+
# Argument Parser
|
| 332 |
+
# ------------------------------
|
| 333 |
+
def get_parser():
|
| 334 |
+
parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
|
| 335 |
+
parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
|
| 336 |
+
help="Path to model checkpoint.")
|
| 337 |
+
parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
|
| 338 |
+
parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
|
| 339 |
+
help="Path to model checkpoint.")
|
| 340 |
+
parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
|
| 341 |
+
help="Path to model checkpoint.")
|
| 342 |
+
parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
|
| 343 |
+
help="Prompt text for generation.")
|
| 344 |
+
parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
|
| 345 |
+
help="Optional negative prompt.")
|
| 346 |
+
parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
|
| 347 |
+
help="Prompt text for generation.")
|
| 348 |
+
parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
|
| 349 |
+
parser.add_argument("--question", type=str, default="how many cars in this image?",
|
| 350 |
+
help="Optional negative prompt.")
|
| 351 |
+
parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
|
| 352 |
+
parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
|
| 353 |
+
parser.add_argument("--guidance_scale", type=float, default=4.5)
|
| 354 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 355 |
+
parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
|
| 356 |
+
return parser
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
# ------------------------------
|
| 360 |
+
# Main Inference Function
|
| 361 |
+
# ------------------------------
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
@torch.inference_mode()
|
| 365 |
+
def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
|
| 366 |
+
messages = [
|
| 367 |
+
{
|
| 368 |
+
"role": "user",
|
| 369 |
+
"content": [
|
| 370 |
+
{
|
| 371 |
+
"type": "image",
|
| 372 |
+
"image": image_path,
|
| 373 |
+
},
|
| 374 |
+
{"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
|
| 375 |
+
],
|
| 376 |
+
}
|
| 377 |
+
]
|
| 378 |
+
|
| 379 |
+
print(messages)
|
| 380 |
+
|
| 381 |
+
inputs = processor.apply_chat_template(
|
| 382 |
+
messages,
|
| 383 |
+
tokenize=True,
|
| 384 |
+
add_generation_prompt=True,
|
| 385 |
+
return_dict=True,
|
| 386 |
+
return_tensors="pt"
|
| 387 |
+
)
|
| 388 |
+
inputs = inputs.to(model.device)
|
| 389 |
+
|
| 390 |
+
# Inference: Generation of the output
|
| 391 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 392 |
+
generated_ids_trimmed = [
|
| 393 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 394 |
+
]
|
| 395 |
+
output_text = processor.batch_decode(
|
| 396 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 397 |
+
)
|
| 398 |
+
print(output_text)
|
| 399 |
+
|
| 400 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 401 |
+
save_dir = Path(args.output_dir) / str(vqa_id)
|
| 402 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 403 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 404 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 405 |
+
f.write(output_text[0].strip())
|
| 406 |
+
|
| 407 |
+
return output_text[0]
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@torch.inference_mode()
|
| 411 |
+
def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
|
| 412 |
+
messages = [
|
| 413 |
+
{
|
| 414 |
+
"role": "user",
|
| 415 |
+
"content": [
|
| 416 |
+
{
|
| 417 |
+
"type": "image",
|
| 418 |
+
"image": image_path,
|
| 419 |
+
},
|
| 420 |
+
{"type": "text", "text": f"Describe this image."},
|
| 421 |
+
],
|
| 422 |
+
}
|
| 423 |
+
]
|
| 424 |
+
|
| 425 |
+
inputs = processor.apply_chat_template(
|
| 426 |
+
messages,
|
| 427 |
+
tokenize=True,
|
| 428 |
+
add_generation_prompt=True, return_dict=True, return_tensors="pt"
|
| 429 |
+
)
|
| 430 |
+
inputs = inputs.to(model.device)
|
| 431 |
+
|
| 432 |
+
# Inference: Generation of the output
|
| 433 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 434 |
+
generated_ids_trimmed = [
|
| 435 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 436 |
+
]
|
| 437 |
+
output_text = processor.batch_decode(
|
| 438 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 439 |
+
)
|
| 440 |
+
print(output_text)
|
| 441 |
+
|
| 442 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 443 |
+
save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
|
| 444 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 445 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 446 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 447 |
+
f.write(output_text[0].strip())
|
| 448 |
+
|
| 449 |
+
return output_text[0]
|
| 450 |
+
|
| 451 |
+
@torch.inference_mode()
|
| 452 |
+
def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
|
| 453 |
+
# --- 构造 Qwen 输入 ---
|
| 454 |
+
question = clean_eval_question(question)
|
| 455 |
+
eval_prompt = f"""
|
| 456 |
+
You are a VQA answer evaluator.
|
| 457 |
+
Given an image, a question, and a proposed answer,
|
| 458 |
+
score how correct the answer is according to the image evidence.
|
| 459 |
+
Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
|
| 460 |
+
to make the answer more accurate or grounded in the image.
|
| 461 |
+
Return JSON strictly:
|
| 462 |
+
{{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
|
| 463 |
+
|
| 464 |
+
Question: "{question}"
|
| 465 |
+
Answer: "{answer}"
|
| 466 |
+
<image>
|
| 467 |
+
"""
|
| 468 |
+
|
| 469 |
+
messages = [
|
| 470 |
+
{
|
| 471 |
+
"role": "user",
|
| 472 |
+
"content": [
|
| 473 |
+
{"type": "image", "image": image_path},
|
| 474 |
+
{"type": "text", "text": eval_prompt},
|
| 475 |
+
],
|
| 476 |
+
}
|
| 477 |
+
]
|
| 478 |
+
|
| 479 |
+
# --- 推理 ---
|
| 480 |
+
inputs = processor.apply_chat_template(
|
| 481 |
+
messages,
|
| 482 |
+
tokenize=True,
|
| 483 |
+
add_generation_prompt=True,
|
| 484 |
+
return_dict=True,
|
| 485 |
+
return_tensors="pt"
|
| 486 |
+
).to(model.device)
|
| 487 |
+
|
| 488 |
+
out_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 489 |
+
out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
|
| 490 |
+
text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
|
| 491 |
+
|
| 492 |
+
# --- 解析输出 ---
|
| 493 |
+
try:
|
| 494 |
+
data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
|
| 495 |
+
score = float(data.get("AnswerScore", 0))
|
| 496 |
+
feedback = data.get("Feedback", "")
|
| 497 |
+
except Exception:
|
| 498 |
+
score, feedback = 0.0, text.strip()
|
| 499 |
+
|
| 500 |
+
print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
|
| 501 |
+
return score, feedback
|
| 502 |
+
|
| 503 |
+
@torch.inference_mode()
|
| 504 |
+
def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
|
| 505 |
+
"""
|
| 506 |
+
Evaluate VQA answer correctness using all available modalities (not just RGB).
|
| 507 |
+
This reduces model bias and improves visual grounding reliability.
|
| 508 |
+
"""
|
| 509 |
+
|
| 510 |
+
# 检查存在的模态文件
|
| 511 |
+
modality_names = [
|
| 512 |
+
"image", "annotation_lineart", "annotation_edge",
|
| 513 |
+
"annotation_depth", "annotation_normal", "annotation_albedo",
|
| 514 |
+
"annotation_seg_12colors", "annotation_openpose"
|
| 515 |
+
]
|
| 516 |
+
|
| 517 |
+
available = []
|
| 518 |
+
for name in modality_names:
|
| 519 |
+
for ext in [".png", ".jpg", ".jpeg"]:
|
| 520 |
+
path = Path(root) / f"{name}{ext}"
|
| 521 |
+
if path.exists():
|
| 522 |
+
available.append((name, str(path)))
|
| 523 |
+
break
|
| 524 |
+
|
| 525 |
+
# 可读映射
|
| 526 |
+
readable_map = {
|
| 527 |
+
"image": "RGB image",
|
| 528 |
+
"annotation_lineart": "line drawing",
|
| 529 |
+
"annotation_edge": "edge map",
|
| 530 |
+
"annotation_depth": "depth map",
|
| 531 |
+
"annotation_normal": "normal map",
|
| 532 |
+
"annotation_albedo": "albedo map",
|
| 533 |
+
"annotation_seg_12colors": "segmentation map",
|
| 534 |
+
"annotation_openpose": "human pose map",
|
| 535 |
+
}
|
| 536 |
+
|
| 537 |
+
present_modalities = [readable_map[n] for n, _ in available]
|
| 538 |
+
|
| 539 |
+
# 构造 prompt
|
| 540 |
+
eval_prompt = f"""
|
| 541 |
+
You are a multimodal visual reasoning evaluator.
|
| 542 |
+
|
| 543 |
+
You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
|
| 544 |
+
Your task is to judge **how correct and visually grounded** the given answer is for the question,
|
| 545 |
+
based purely on visual evidence from all modalities.
|
| 546 |
+
|
| 547 |
+
Follow this process:
|
| 548 |
+
1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
|
| 549 |
+
2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
|
| 550 |
+
3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
|
| 551 |
+
4. Otherwise, directly evaluate how accurate the free-form answer is.
|
| 552 |
+
5. Penalize any parts that contradict the image, or ignore modalities.
|
| 553 |
+
|
| 554 |
+
Return JSON strictly:
|
| 555 |
+
{{
|
| 556 |
+
"AnswerScore": <float between 0 and 1>,
|
| 557 |
+
"Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
|
| 558 |
+
}}
|
| 559 |
+
|
| 560 |
+
Question: "{question}"
|
| 561 |
+
Answer: "{answer}"
|
| 562 |
+
"""
|
| 563 |
+
|
| 564 |
+
# 构建内容序列(模态+图像)
|
| 565 |
+
content = []
|
| 566 |
+
for name, path in available:
|
| 567 |
+
readable = readable_map.get(name, "visual input")
|
| 568 |
+
content.append({"type": "text", "text": f"This is the {readable}."})
|
| 569 |
+
content.append({"type": "image", "image": path})
|
| 570 |
+
content.append({"type": "text", "text": eval_prompt})
|
| 571 |
+
|
| 572 |
+
messages = [{"role": "user", "content": content}]
|
| 573 |
+
|
| 574 |
+
# --- 推理 ---
|
| 575 |
+
inputs = processor.apply_chat_template(
|
| 576 |
+
messages, tokenize=True, add_generation_prompt=True,
|
| 577 |
+
return_dict=True, return_tensors="pt"
|
| 578 |
+
).to(model.device)
|
| 579 |
+
|
| 580 |
+
out_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 581 |
+
out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
|
| 582 |
+
text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
|
| 583 |
+
|
| 584 |
+
# --- 解析输出 ---
|
| 585 |
+
try:
|
| 586 |
+
data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
|
| 587 |
+
score = float(data.get("AnswerScore", 0))
|
| 588 |
+
feedback = data.get("Feedback", "")
|
| 589 |
+
except Exception:
|
| 590 |
+
score, feedback = 0.0, text.strip()
|
| 591 |
+
|
| 592 |
+
print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
|
| 593 |
+
return score, feedback
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
@torch.inference_mode()
|
| 598 |
+
def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
|
| 599 |
+
question = clean_prompt_question(question)
|
| 600 |
+
messages = build_multimodal_message(root, question, prompt, feedback)
|
| 601 |
+
inputs = processor.apply_chat_template(
|
| 602 |
+
messages,
|
| 603 |
+
tokenize=True,
|
| 604 |
+
add_generation_prompt=True,
|
| 605 |
+
return_dict=True,
|
| 606 |
+
return_tensors="pt"
|
| 607 |
+
)
|
| 608 |
+
inputs = inputs.to(model.device)
|
| 609 |
+
|
| 610 |
+
# Inference: Generation of the output
|
| 611 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 612 |
+
generated_ids_trimmed = [
|
| 613 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 614 |
+
]
|
| 615 |
+
output_text = processor.batch_decode(
|
| 616 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 617 |
+
)
|
| 618 |
+
print(output_text)
|
| 619 |
+
|
| 620 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 621 |
+
save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
|
| 622 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 623 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 624 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 625 |
+
f.write(output_text[0].strip())
|
| 626 |
+
return output_text[0]
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
@torch.inference_mode()
|
| 630 |
+
def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
|
| 631 |
+
messages = build_vqa_message(root, prompt, question)
|
| 632 |
+
print(messages)
|
| 633 |
+
inputs = processor.apply_chat_template(
|
| 634 |
+
messages,
|
| 635 |
+
tokenize=True,
|
| 636 |
+
add_generation_prompt=True,
|
| 637 |
+
return_dict=True,
|
| 638 |
+
return_tensors="pt"
|
| 639 |
+
)
|
| 640 |
+
inputs = inputs.to(model.device)
|
| 641 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 642 |
+
generated_ids_trimmed = [
|
| 643 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
|
| 644 |
+
output_text = processor.batch_decode(
|
| 645 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 646 |
+
)
|
| 647 |
+
print(output_text)
|
| 648 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 649 |
+
save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
|
| 650 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 651 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 652 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 653 |
+
f.write(output_text[0].strip())
|
| 654 |
+
return output_text[0]
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
@torch.inference_mode()
|
| 658 |
+
def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
|
| 659 |
+
# print(f"🚀 Generating with prompt: {prompt}")
|
| 660 |
+
outputs = pipe(
|
| 661 |
+
images=images,
|
| 662 |
+
role=role,
|
| 663 |
+
prompt=prompt,
|
| 664 |
+
negative_prompt=args.negative_prompt,
|
| 665 |
+
height=height,
|
| 666 |
+
width=width,
|
| 667 |
+
num_inference_steps=args.steps,
|
| 668 |
+
guidance_scale=args.guidance_scale,
|
| 669 |
+
num_images_per_prompt=1,
|
| 670 |
+
generator=generator,
|
| 671 |
+
task='t2i'
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
+
# Apply post-processing for each modality
|
| 675 |
+
results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
|
| 676 |
+
results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
|
| 677 |
+
results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
|
| 678 |
+
|
| 679 |
+
# --------------------------
|
| 680 |
+
# Save results
|
| 681 |
+
# --------------------------
|
| 682 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 683 |
+
save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
|
| 684 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 685 |
+
for idx, img in enumerate(results):
|
| 686 |
+
name = modality_names[idx]
|
| 687 |
+
save_path = save_dir / f"{name}.png"
|
| 688 |
+
img.save(save_path)
|
| 689 |
+
print(f"💾 Saved {name} → {save_path}")
|
| 690 |
+
|
| 691 |
+
merged_path = save_dir / f"merged_iteration_{iter_num}.png"
|
| 692 |
+
concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
|
| 693 |
+
print(f"\n✅ All results saved in: {save_dir}\n")
|
| 694 |
+
return save_dir
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
if __name__ == "__main__":
|
| 698 |
+
args = get_parser().parse_args()
|
| 699 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 700 |
+
print(f"✅ Using device: {device}")
|
| 701 |
+
|
| 702 |
+
processor = AutoProcessor.from_pretrained(
|
| 703 |
+
args.model_name_or_path,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
model = Qwen3VLForConditionalGeneration.from_pretrained(
|
| 707 |
+
args.text_model_path,
|
| 708 |
+
attn_implementation="flash_attention_2",
|
| 709 |
+
dtype=(torch.bfloat16),
|
| 710 |
+
).to(device)
|
| 711 |
+
|
| 712 |
+
pipe = JodiPipeline(args.config)
|
| 713 |
+
pipe.from_pretrained(args.model_path)
|
| 714 |
+
|
| 715 |
+
modality_names = [
|
| 716 |
+
"image",
|
| 717 |
+
"annotation_lineart",
|
| 718 |
+
"annotation_edge",
|
| 719 |
+
"annotation_depth",
|
| 720 |
+
"annotation_normal",
|
| 721 |
+
"annotation_albedo",
|
| 722 |
+
"annotation_seg_12colors",
|
| 723 |
+
"annotation_openpose",
|
| 724 |
+
]
|
| 725 |
+
|
| 726 |
+
# Build post-processors
|
| 727 |
+
post_processors: list[Any] = [ImagePostProcessor()]
|
| 728 |
+
for condition in pipe.config.conditions: # type: ignore
|
| 729 |
+
if condition == "lineart":
|
| 730 |
+
post_processors.append(LineartPostProcessor())
|
| 731 |
+
elif condition == "edge":
|
| 732 |
+
post_processors.append(EdgePostProcessor())
|
| 733 |
+
elif condition == "depth":
|
| 734 |
+
post_processors.append(DepthPostProcessor())
|
| 735 |
+
elif condition == "normal":
|
| 736 |
+
post_processors.append(NormalPostProcessor())
|
| 737 |
+
elif condition == "albedo":
|
| 738 |
+
post_processors.append(AlbedoPostProcessor())
|
| 739 |
+
elif condition == "segmentation":
|
| 740 |
+
post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
|
| 741 |
+
elif condition == "openpose":
|
| 742 |
+
post_processors.append(OpenposePostProcessor())
|
| 743 |
+
else:
|
| 744 |
+
print(f"⚠️ Warning: Unknown condition: {condition}")
|
| 745 |
+
post_processors.append(ImagePostProcessor())
|
| 746 |
+
|
| 747 |
+
torch.manual_seed(args.seed)
|
| 748 |
+
generator = torch.Generator(device=device).manual_seed(args.seed)
|
| 749 |
+
|
| 750 |
+
with open(args.json, "r", encoding="utf-8") as f:
|
| 751 |
+
annotations = json.load(f)
|
| 752 |
+
|
| 753 |
+
for sample in annotations[15:306]:
|
| 754 |
+
image_path = os.path.join(args.data_path, sample["image"])
|
| 755 |
+
image_id = sample["image"].split('.')[0]
|
| 756 |
+
image = Image.open(image_path)
|
| 757 |
+
question = sample["question"]
|
| 758 |
+
|
| 759 |
+
control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
|
| 760 |
+
|
| 761 |
+
role = [1] + [0] * pipe.num_conditions
|
| 762 |
+
print(role)
|
| 763 |
+
|
| 764 |
+
best_result, best_score = '', 0.0
|
| 765 |
+
max_length = 1024
|
| 766 |
+
|
| 767 |
+
# input_img = Image.open(image_path).convert("RGB")
|
| 768 |
+
width, height = image.size
|
| 769 |
+
print(f'ori width:{width}', f'ori height:{height}')
|
| 770 |
+
|
| 771 |
+
prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
|
| 772 |
+
result = vqa_i2t(model, processor, image_path, question, 100, max_length)
|
| 773 |
+
score, feedback = evaluate_consistency(image_path, model, processor, question, result)
|
| 774 |
+
|
| 775 |
+
if score >= best_score:
|
| 776 |
+
best_result, best_score = result, score
|
| 777 |
+
|
| 778 |
+
for step in range(1, args.iters):
|
| 779 |
+
save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
|
| 780 |
+
image_id)
|
| 781 |
+
max_length += 100
|
| 782 |
+
prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
|
| 783 |
+
result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
|
| 784 |
+
score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
|
| 785 |
+
|
| 786 |
+
if score >= best_score:
|
| 787 |
+
best_result, best_score = result, score
|
| 788 |
+
|
| 789 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 790 |
+
save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
|
| 791 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 792 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 793 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 794 |
+
f.write(best_result)
|
| 795 |
+
print(best_result)
|
| 796 |
+
|
test_t2i_geneval.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import argparse
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from typing import Any
|
| 7 |
+
import torch
|
| 8 |
+
import torchvision.transforms as T
|
| 9 |
+
import re
|
| 10 |
+
from shutil import copy
|
| 11 |
+
|
| 12 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 13 |
+
os.environ["GRADIO_TEMP_DIR"] = "./tmp"
|
| 14 |
+
|
| 15 |
+
from jodi_pipeline import JodiPipeline
|
| 16 |
+
from model.postprocess import (
|
| 17 |
+
ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
|
| 18 |
+
NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
|
| 19 |
+
)
|
| 20 |
+
from transformers import (
|
| 21 |
+
Qwen2VLForConditionalGeneration,
|
| 22 |
+
Qwen2_5_VLForConditionalGeneration,
|
| 23 |
+
Qwen3VLForConditionalGeneration,
|
| 24 |
+
Qwen3VLMoeForConditionalGeneration
|
| 25 |
+
)
|
| 26 |
+
from transformers import AutoProcessor, Trainer
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
import itertools
|
| 29 |
+
|
| 30 |
+
import nltk
|
| 31 |
+
nltk.download('averaged_perceptron_tagger_eng')
|
| 32 |
+
try:
|
| 33 |
+
nltk.data.find("tokenizers/punkt_tab")
|
| 34 |
+
except LookupError:
|
| 35 |
+
nltk.download("punkt_tab")
|
| 36 |
+
nltk.download("punkt")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
from nltk import word_tokenize, pos_tag
|
| 40 |
+
|
| 41 |
+
def extract_main_objects(prompt: str):
|
| 42 |
+
"""
|
| 43 |
+
提取主要对象名词:
|
| 44 |
+
- 优先匹配 'of', 'with', 'showing', 'featuring', 'containing' 后面的名词短语
|
| 45 |
+
- 过滤媒介词 (photo, picture, image, scene, view, shot, painting, drawing)
|
| 46 |
+
- 回退到通用名词提取
|
| 47 |
+
"""
|
| 48 |
+
if not isinstance(prompt, str):
|
| 49 |
+
return []
|
| 50 |
+
|
| 51 |
+
prompt = prompt.strip().lower()
|
| 52 |
+
|
| 53 |
+
# Step 1️⃣: 优先匹配介词后的核心名词短语
|
| 54 |
+
# 例如 "photo of a bottle and a refrigerator" → "bottle", "refrigerator"
|
| 55 |
+
pattern = r"(?:of|with|showing|featuring|containing)\s+([a-z\s,]+)"
|
| 56 |
+
match = re.search(pattern, prompt)
|
| 57 |
+
candidates = []
|
| 58 |
+
if match:
|
| 59 |
+
segment = match.group(1)
|
| 60 |
+
tokens = word_tokenize(segment)
|
| 61 |
+
tagged = pos_tag(tokens)
|
| 62 |
+
candidates = [w for w, pos in tagged if pos.startswith("NN")]
|
| 63 |
+
|
| 64 |
+
# Step 2️⃣: 如果未匹配,则通用名词提取
|
| 65 |
+
if not candidates:
|
| 66 |
+
tokens = word_tokenize(prompt)
|
| 67 |
+
tagged = pos_tag(tokens)
|
| 68 |
+
candidates = [w for w, pos in tagged if pos.startswith("NN")]
|
| 69 |
+
|
| 70 |
+
# Step 3️⃣: 过滤掉常见媒介词
|
| 71 |
+
filter_words = {
|
| 72 |
+
"photo", "picture", "image", "scene", "view",
|
| 73 |
+
"shot", "painting", "drawing", "sketch",
|
| 74 |
+
"illustration", "render", "frame", "snapshot"
|
| 75 |
+
}
|
| 76 |
+
filtered = [w for w in candidates if w not in filter_words]
|
| 77 |
+
|
| 78 |
+
# Step 4️⃣: 去重但保持顺序
|
| 79 |
+
main_objects = list(dict.fromkeys(filtered))
|
| 80 |
+
|
| 81 |
+
return main_objects
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
|
| 85 |
+
"""
|
| 86 |
+
将多个图像拼接成一张大图并保存。
|
| 87 |
+
Args:
|
| 88 |
+
image_paths: List[str] 图像路径列表
|
| 89 |
+
save_path: 保存路径(包括文件名)
|
| 90 |
+
images_per_row: 每行图像数量(默认为全部在一行)
|
| 91 |
+
image_format: 保存格式
|
| 92 |
+
"""
|
| 93 |
+
from PIL import Image
|
| 94 |
+
import io
|
| 95 |
+
|
| 96 |
+
# 读取图像
|
| 97 |
+
images = [Image.open(p).convert("RGB") for p in image_paths]
|
| 98 |
+
|
| 99 |
+
if images_per_row is None:
|
| 100 |
+
images_per_row = len(images)
|
| 101 |
+
|
| 102 |
+
# 调整尺寸(可选)
|
| 103 |
+
target_size = min(1024, images[0].size[0])
|
| 104 |
+
images = [img.resize((target_size, target_size)) for img in images]
|
| 105 |
+
|
| 106 |
+
# 拼接
|
| 107 |
+
widths, heights = zip(*(img.size for img in images))
|
| 108 |
+
max_width = max(widths)
|
| 109 |
+
rows = (len(images) + images_per_row - 1) // images_per_row
|
| 110 |
+
total_height = sum(heights[:images_per_row]) * rows
|
| 111 |
+
|
| 112 |
+
new_im = Image.new("RGB", (max_width * images_per_row, total_height))
|
| 113 |
+
y_offset = 0
|
| 114 |
+
for i in range(0, len(images), images_per_row):
|
| 115 |
+
row_imgs = images[i:i + images_per_row]
|
| 116 |
+
x_offset = 0
|
| 117 |
+
for img in row_imgs:
|
| 118 |
+
new_im.paste(img, (x_offset, y_offset))
|
| 119 |
+
x_offset += max_width
|
| 120 |
+
y_offset += heights[0]
|
| 121 |
+
|
| 122 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
| 123 |
+
new_im.save(save_path, format=image_format.upper())
|
| 124 |
+
print(f"🧩 Saved merged image → {save_path}")
|
| 125 |
+
return save_path
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def build_multimodal_message(root, prompt, feedback, coarse_caption="a generic scene"):
|
| 129 |
+
"""
|
| 130 |
+
Build Qwen3-VL message for multi-modal caption refinement.
|
| 131 |
+
Automatically detects available modalities under root.
|
| 132 |
+
"""
|
| 133 |
+
modality_names = [
|
| 134 |
+
"image",
|
| 135 |
+
"annotation_lineart",
|
| 136 |
+
"annotation_edge",
|
| 137 |
+
"annotation_depth",
|
| 138 |
+
"annotation_normal",
|
| 139 |
+
"annotation_albedo",
|
| 140 |
+
"annotation_seg_12colors",
|
| 141 |
+
"annotation_openpose",
|
| 142 |
+
]
|
| 143 |
+
|
| 144 |
+
# --- 检查存在的模态 ---
|
| 145 |
+
available = []
|
| 146 |
+
for name in modality_names:
|
| 147 |
+
for ext in [".png", ".jpg", ".jpeg"]:
|
| 148 |
+
path = Path(root) / f"{name}{ext}"
|
| 149 |
+
if path.exists():
|
| 150 |
+
available.append((name, str(path)))
|
| 151 |
+
break
|
| 152 |
+
|
| 153 |
+
# --- 构建模态说明 ---
|
| 154 |
+
readable_map = {
|
| 155 |
+
"image": "RGB image",
|
| 156 |
+
"annotation_lineart": "line drawing",
|
| 157 |
+
"annotation_edge": "edge map",
|
| 158 |
+
"annotation_depth": "depth map",
|
| 159 |
+
"annotation_normal": "normal map",
|
| 160 |
+
"annotation_albedo": "albedo map",
|
| 161 |
+
"annotation_seg_12colors": "segmentation map",
|
| 162 |
+
"annotation_openpose": "human pose map",
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
present_modalities = [readable_map[n] for n, _ in available]
|
| 166 |
+
|
| 167 |
+
# --- 构造文本指令 ---
|
| 168 |
+
text_prompt = (
|
| 169 |
+
f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
|
| 170 |
+
f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
|
| 171 |
+
f"Generate an enhanced prompt that provides detailed and precise visual descriptions suitable for image generation. "
|
| 172 |
+
f"Your task is based on all visual modalities to improve the description for the coarse caption while strictly following its original intent: '{prompt}'. "
|
| 173 |
+
f"Do not include any additional commentary or evaluations. "
|
| 174 |
+
f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
|
| 175 |
+
f"Focus on describing the visual properties, including: "
|
| 176 |
+
f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
|
| 177 |
+
f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
|
| 178 |
+
f"Exclude any stylistic, environmental, emotional, or narrative information. "
|
| 179 |
+
f"Consider the following feedback when refining your description: '{feedback}'. "
|
| 180 |
+
f"Preserve the same object category as in the coarse caption and describe its fine details in a realistic, objective tone. "
|
| 181 |
+
f"Coarse caption: '{coarse_caption}' "
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# --- 构建消息内容:在每个图像前加模态标识 ---
|
| 185 |
+
content = []
|
| 186 |
+
for name, path in available:
|
| 187 |
+
readable = readable_map.get(name, "visual input")
|
| 188 |
+
content.append({
|
| 189 |
+
"type": "text",
|
| 190 |
+
"text": f"This is the {readable}, which provides {get_modality_description(name)}."
|
| 191 |
+
})
|
| 192 |
+
content.append({"type": "image", "image": path})
|
| 193 |
+
|
| 194 |
+
# 最后附上总任务说明
|
| 195 |
+
content.append({"type": "text", "text": text_prompt})
|
| 196 |
+
|
| 197 |
+
messages = [{"role": "user", "content": content}]
|
| 198 |
+
return messages
|
| 199 |
+
|
| 200 |
+
def get_modality_description(name: str) -> str:
|
| 201 |
+
"""为每个模态生成一句说明,用于提示模型理解模态功能"""
|
| 202 |
+
desc_map = {
|
| 203 |
+
"image": "the main visual appearance of the scene, including color, texture, and lighting",
|
| 204 |
+
"annotation_lineart": "structural outlines, object contours, and fine geometry",
|
| 205 |
+
"annotation_edge": "strong boundaries and contrast edges between objects",
|
| 206 |
+
"annotation_depth": "distance and perspective information for spatial understanding",
|
| 207 |
+
"annotation_normal": "surface orientation and geometric curvature cues",
|
| 208 |
+
"annotation_albedo": "pure surface color without lighting or shading effects",
|
| 209 |
+
"annotation_seg_12colors": "semantic regions and object categories",
|
| 210 |
+
"annotation_openpose": "human body keypoints, joints, and orientation",
|
| 211 |
+
}
|
| 212 |
+
return desc_map.get(name, "complementary visual evidence")
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
# ------------------------------
|
| 216 |
+
# Argument Parser
|
| 217 |
+
# ------------------------------
|
| 218 |
+
def get_parser():
|
| 219 |
+
parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
|
| 220 |
+
parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
|
| 221 |
+
help="Path to model checkpoint.")
|
| 222 |
+
parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
|
| 223 |
+
parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
|
| 224 |
+
help="Path to model checkpoint.")
|
| 225 |
+
parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
|
| 226 |
+
help="Path to model checkpoint.")
|
| 227 |
+
parser.add_argument("--prompt", type=str, default="cat.", help="Prompt text for generation.")
|
| 228 |
+
parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
|
| 229 |
+
parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
|
| 230 |
+
parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
|
| 231 |
+
parser.add_argument("--guidance_scale", type=float, default=4.5)
|
| 232 |
+
parser.add_argument("--height", type=int, default=1024)
|
| 233 |
+
parser.add_argument("--width", type=int, default=1024)
|
| 234 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 235 |
+
parser.add_argument("--output_dir", type=str, default="./geneval_outputs", help="Directory to save results.")
|
| 236 |
+
return parser
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# ------------------------------
|
| 240 |
+
# Main Inference Function
|
| 241 |
+
# ------------------------------
|
| 242 |
+
@torch.inference_mode()
|
| 243 |
+
def init_t2i(args, prompt, pipe, iter_num, post_processors, modality_names, generator, index, num):
|
| 244 |
+
# --------------------------
|
| 245 |
+
# Inference
|
| 246 |
+
# --------------------------
|
| 247 |
+
|
| 248 |
+
print(f"🚀 Generating with prompt: {prompt}")
|
| 249 |
+
outputs = pipe(
|
| 250 |
+
images=[None] * (1 + pipe.num_conditions),
|
| 251 |
+
role=[0] * (1 + pipe.num_conditions),
|
| 252 |
+
prompt=prompt,
|
| 253 |
+
negative_prompt=args.negative_prompt,
|
| 254 |
+
height=args.height,
|
| 255 |
+
width=args.width,
|
| 256 |
+
num_inference_steps=args.steps,
|
| 257 |
+
guidance_scale=args.guidance_scale,
|
| 258 |
+
num_images_per_prompt=1,
|
| 259 |
+
generator=generator
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Apply post-processing for each modality
|
| 263 |
+
results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
|
| 264 |
+
results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
|
| 265 |
+
results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
|
| 266 |
+
|
| 267 |
+
# --------------------------
|
| 268 |
+
# Save results
|
| 269 |
+
# --------------------------
|
| 270 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 271 |
+
|
| 272 |
+
save_dir = Path(args.output_dir) / f"index_{index}" / f"sample_{num}" / f"iteration_{iter_num}"
|
| 273 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 274 |
+
|
| 275 |
+
for idx, img in enumerate(results):
|
| 276 |
+
name = modality_names[idx]
|
| 277 |
+
save_path = save_dir / f"{name}.png"
|
| 278 |
+
img.save(save_path)
|
| 279 |
+
print(f"💾 Saved {name} → {save_path}")
|
| 280 |
+
|
| 281 |
+
merged_path = save_dir / f"merged_iteration.png"
|
| 282 |
+
concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
|
| 283 |
+
|
| 284 |
+
print(f"\n✅ All results saved in: {save_dir}\n")
|
| 285 |
+
return save_dir
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@torch.inference_mode()
|
| 289 |
+
def evaluate_consistency(image_path, model, processor, prompt, ori_prompt, max_length=256):
|
| 290 |
+
|
| 291 |
+
main_objects = extract_main_objects(ori_prompt)
|
| 292 |
+
print(main_objects)
|
| 293 |
+
number = len(main_objects)
|
| 294 |
+
main_str = ", ".join(main_objects) if main_objects else "the main described objects"
|
| 295 |
+
# --- 构造 Qwen 输入 ---
|
| 296 |
+
#eval_prompt = f"""
|
| 297 |
+
#You are an image–text consistency evaluator.
|
| 298 |
+
#Given one RGB image and a textual description, evaluate how well the description matches
|
| 299 |
+
#the visual evidence in the image across the following semantic dimensions:
|
| 300 |
+
#{number} Main described objects (core subjects): {main_str}.
|
| 301 |
+
#1. **Entity (E)** – Are all mentioned object categories correct and clearly visible in the image?
|
| 302 |
+
#2. **Attribute (A)** – Are described colors, shapes, sizes, textures, and materials accurate?
|
| 303 |
+
#3. **Relation (R)** – Are spatial or logical relationships (e.g., left of, above, next to) correct?
|
| 304 |
+
#4. **Count/State (C)** – Are the numbers of objects and their states (open/closed, sitting/standing) consistent?
|
| 305 |
+
#5. **Global (G)** – Does the overall scene composition and meaning match the description?
|
| 306 |
+
#6. **Completeness (V)** – Are the *main described objects* ({main_str}) fully and clearly visible (not cropped, truncated, or hidden)?
|
| 307 |
+
#7. **Salience (S)** – Are the *main described objects* visually dominant and central, rather than small, distant, or partially obscured?
|
| 308 |
+
#If any of the main objects are only partially visible, occluded, or treated as background,
|
| 309 |
+
#reduce the score for Completeness and Salience.
|
| 310 |
+
#Score each aspect from 0.0 to 1.0 (0=wrong, 1=perfect).
|
| 311 |
+
#Then provide one short feedback sentence describing which aspects could be improved.
|
| 312 |
+
#Return JSON strictly:
|
| 313 |
+
#{{
|
| 314 |
+
# "Entity": <float>,
|
| 315 |
+
# "Attribute": <float>,
|
| 316 |
+
# "Relation": <float>,
|
| 317 |
+
# "CountState": <float>,
|
| 318 |
+
# "Global": <float>,
|
| 319 |
+
# "Completeness": <float>,
|
| 320 |
+
# "Salience": <float>,
|
| 321 |
+
# "Feedback": "<short sentence>"
|
| 322 |
+
#}}
|
| 323 |
+
#Description: "{prompt}"
|
| 324 |
+
#<image>
|
| 325 |
+
#"""
|
| 326 |
+
eval_prompt = f"""
|
| 327 |
+
You are an image–text alignment evaluator and visual correction advisor.
|
| 328 |
+
Given one RGB image evaluate how well the description "{ori_prompt}" matches what is visually shown.
|
| 329 |
+
Focus only on the main described objects: "{main_str}".
|
| 330 |
+
Each main object must appear clearly and completely in the image — not cropped, cut off, hidden, or only partially visible.
|
| 331 |
+
If any main object is incomplete, visual missing, has an incorrect attribute (such as color, size, or position) or only partly visible, reduce the score sharply (<0.6),
|
| 332 |
+
Then, give **a corrective feedback sentence that explicitly states what the object should be** according to the intended description "{ori_prompt}".
|
| 333 |
+
Your feedback must be **constructive**, not punitive:
|
| 334 |
+
For example:
|
| 335 |
+
- If the elephant appears gray but should be purple, say: "The elephant is not gray; it should be purple, so adjust it to purple color."
|
| 336 |
+
- If a car appears blue but should be red, say: "The car is not blue; it should be red."
|
| 337 |
+
- If one of three objects is missing, say: "Only two objects are visible; add one more to make three."
|
| 338 |
+
|
| 339 |
+
Return JSON only:
|
| 340 |
+
{{
|
| 341 |
+
"Consistency": <float 0–1>,
|
| 342 |
+
"Feedback": "<one short sentence explaining which object should be adjusted or reworded>"
|
| 343 |
+
}}
|
| 344 |
+
Description: "{ori_prompt}"
|
| 345 |
+
<image>
|
| 346 |
+
"""
|
| 347 |
+
messages = [
|
| 348 |
+
{
|
| 349 |
+
"role": "user",
|
| 350 |
+
"content": [
|
| 351 |
+
{"type": "image", "image": image_path},
|
| 352 |
+
{"type": "text", "text": eval_prompt},
|
| 353 |
+
],
|
| 354 |
+
}
|
| 355 |
+
]
|
| 356 |
+
|
| 357 |
+
# --- 推理 ---
|
| 358 |
+
inputs = processor.apply_chat_template(
|
| 359 |
+
messages,
|
| 360 |
+
tokenize=True,
|
| 361 |
+
add_generation_prompt=True,
|
| 362 |
+
return_dict=True,
|
| 363 |
+
return_tensors="pt"
|
| 364 |
+
).to(model.device)
|
| 365 |
+
|
| 366 |
+
out_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 367 |
+
out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
|
| 368 |
+
text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
|
| 369 |
+
|
| 370 |
+
# --- 解析输出 ---
|
| 371 |
+
try:
|
| 372 |
+
data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
|
| 373 |
+
score = float(data.get("Consistency", 0))
|
| 374 |
+
feedback = data.get("Feedback", "")
|
| 375 |
+
|
| 376 |
+
# 👇 手动计算 Overall
|
| 377 |
+
#score = e + a + r + c + g + v
|
| 378 |
+
|
| 379 |
+
except Exception:
|
| 380 |
+
score, feedback = 0.0, text.strip()
|
| 381 |
+
|
| 382 |
+
print(
|
| 383 |
+
#f"🧮 [E={e:.2f} | A={a:.2f} | R={r:.2f} | C={c:.2f} | G={g:.2f} | V={v:.2f}]"
|
| 384 |
+
f" → Overall={score:.3f}"
|
| 385 |
+
)
|
| 386 |
+
print(f"💡 Feedback: {feedback}")
|
| 387 |
+
return score, feedback
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def text_refine(root, model, processor, caption, prompt, feedback, iter_num, index, num, max_length=300):
|
| 391 |
+
messages = build_multimodal_message(root, caption, feedback, prompt)
|
| 392 |
+
inputs = processor.apply_chat_template(
|
| 393 |
+
messages,
|
| 394 |
+
tokenize=True,
|
| 395 |
+
add_generation_prompt=True,
|
| 396 |
+
return_dict=True,
|
| 397 |
+
return_tensors="pt"
|
| 398 |
+
)
|
| 399 |
+
inputs = inputs.to(model.device)
|
| 400 |
+
|
| 401 |
+
# Inference: Generation of the output
|
| 402 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 403 |
+
generated_ids_trimmed = [
|
| 404 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 405 |
+
]
|
| 406 |
+
output_text = processor.batch_decode(
|
| 407 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 408 |
+
)
|
| 409 |
+
print(output_text)
|
| 410 |
+
|
| 411 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 412 |
+
save_dir = Path(args.output_dir) / f"index_{index}" / f"sample_{num}" / f"iteration_{iter_num}"
|
| 413 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 414 |
+
caption_path = Path(save_dir) / f"caption.txt"
|
| 415 |
+
with open(caption_path, "w", encoding="utf-8") as f:
|
| 416 |
+
f.write(output_text[0].strip())
|
| 417 |
+
|
| 418 |
+
return output_text[0]
|
| 419 |
+
|
| 420 |
+
def refine_prompt_with_qwen(model, processor, raw_prompt, max_length=1024):
|
| 421 |
+
chi_prompt = """
|
| 422 |
+
You are a visual scene enhancement expert specialized in preparing prompts for image generation models.
|
| 423 |
+
Given a user prompt, rewrite it into an 'Enhanced prompt' that provides detailed, vivid, and spatially coherent visual descriptions.
|
| 424 |
+
Your enhancement should depend on the original prompt's level of detail:
|
| 425 |
+
- If the user prompt is brief or abstract, expand it with concrete details about colors, shapes, materials, lighting, textures, and spatial relationships between objects.
|
| 426 |
+
- If the user prompt is already detailed, refine and slightly enhance the existing descriptions to make them more visually precise and realistic without overcomplicating.
|
| 427 |
+
|
| 428 |
+
Follow these examples:
|
| 429 |
+
- User Prompt: A cat sleeping → Enhanced: A small, fluffy white cat curled up tightly on a sunny windowsill, light streaming through a lace curtain, highlighting the cat’s soft fur and the warm wooden frame.
|
| 430 |
+
- User Prompt: A busy city street → Enhanced: A bustling city street at dusk, glowing streetlights reflecting off wet asphalt, people in colorful coats crossing a crosswalk, and tall glass buildings illuminated by neon signs.
|
| 431 |
+
|
| 432 |
+
Rules:
|
| 433 |
+
1. Do not add new objects or unrelated elements.
|
| 434 |
+
2. Avoid emotional, stylistic, or narrative phrases; focus purely on visual reality.
|
| 435 |
+
3. Write one concise, self-contained sentence that fully describes the visible scene.
|
| 436 |
+
|
| 437 |
+
Now generate only the enhanced description for the following prompt:
|
| 438 |
+
User Prompt: "{}"
|
| 439 |
+
""".format(raw_prompt)
|
| 440 |
+
|
| 441 |
+
messages = [{"role": "user", "content": [{"type": "text", "text": chi_prompt}]}]
|
| 442 |
+
|
| 443 |
+
inputs = processor.apply_chat_template(
|
| 444 |
+
messages,
|
| 445 |
+
tokenize=True,
|
| 446 |
+
add_generation_prompt=True,
|
| 447 |
+
return_dict=True,
|
| 448 |
+
return_tensors="pt"
|
| 449 |
+
)
|
| 450 |
+
inputs = inputs.to(model.device)
|
| 451 |
+
|
| 452 |
+
# Inference: Generation of the output
|
| 453 |
+
generated_ids = model.generate(**inputs, max_new_tokens=max_length)
|
| 454 |
+
generated_ids_trimmed = [
|
| 455 |
+
out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
|
| 456 |
+
]
|
| 457 |
+
output_text = processor.batch_decode(
|
| 458 |
+
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
return output_text[0]
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def image_refine(caption, prompt, root, iter_num, modality_names, generator, index, num):
|
| 466 |
+
#control_images = []
|
| 467 |
+
#for name in modality_names:
|
| 468 |
+
#control_images.append(Image.open(os.path.join(root, name + '.png')).convert("RGB"))
|
| 469 |
+
|
| 470 |
+
print(f"🚀 Generating with prompt: {caption}")
|
| 471 |
+
|
| 472 |
+
outputs = pipe(
|
| 473 |
+
images=[None] * (1 + pipe.num_conditions),
|
| 474 |
+
role=[0] * (1 + pipe.num_conditions),
|
| 475 |
+
prompt=prompt,
|
| 476 |
+
negative_prompt=args.negative_prompt,
|
| 477 |
+
height=args.height,
|
| 478 |
+
width=args.width,
|
| 479 |
+
num_inference_steps=args.steps,
|
| 480 |
+
guidance_scale=args.guidance_scale,
|
| 481 |
+
num_images_per_prompt=1,
|
| 482 |
+
generator=generator,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# Apply post-processing for each modality
|
| 486 |
+
results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
|
| 487 |
+
results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
|
| 488 |
+
results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
|
| 489 |
+
|
| 490 |
+
# --------------------------
|
| 491 |
+
# Save results
|
| 492 |
+
# --------------------------
|
| 493 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 494 |
+
|
| 495 |
+
save_dir = Path(args.output_dir) / f"index_{index}" / f"sample_{num}" / f"iteration_{iter_num}"
|
| 496 |
+
save_dir.mkdir(parents=True, exist_ok=True)
|
| 497 |
+
|
| 498 |
+
for idx, img in enumerate(results):
|
| 499 |
+
name = modality_names[idx]
|
| 500 |
+
save_path = save_dir / f"{name}.png"
|
| 501 |
+
img.save(save_path)
|
| 502 |
+
print(f"💾 Saved {name} → {save_path}")
|
| 503 |
+
|
| 504 |
+
merged_path = save_dir / f"merged_iteration_{iter_num}.png"
|
| 505 |
+
concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
|
| 506 |
+
|
| 507 |
+
print(f"\n✅ All results saved in: {save_dir}\n")
|
| 508 |
+
return save_dir
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
# ------------------------------
|
| 512 |
+
# Entry Point
|
| 513 |
+
# ------------------------------
|
| 514 |
+
if __name__ == "__main__":
|
| 515 |
+
args = get_parser().parse_args()
|
| 516 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 517 |
+
print(f"✅ Using device: {device}")
|
| 518 |
+
|
| 519 |
+
processor = AutoProcessor.from_pretrained(
|
| 520 |
+
args.model_name_or_path,
|
| 521 |
+
)
|
| 522 |
+
|
| 523 |
+
model = Qwen3VLForConditionalGeneration.from_pretrained(
|
| 524 |
+
args.text_model_path,
|
| 525 |
+
attn_implementation="flash_attention_2",
|
| 526 |
+
dtype=(torch.bfloat16),
|
| 527 |
+
).to(device)
|
| 528 |
+
|
| 529 |
+
pipe = JodiPipeline(args.config)
|
| 530 |
+
pipe.from_pretrained(args.model_path)
|
| 531 |
+
|
| 532 |
+
modality_names = [
|
| 533 |
+
"image",
|
| 534 |
+
"annotation_lineart",
|
| 535 |
+
"annotation_edge",
|
| 536 |
+
"annotation_depth",
|
| 537 |
+
"annotation_normal",
|
| 538 |
+
"annotation_albedo",
|
| 539 |
+
"annotation_seg_12colors",
|
| 540 |
+
"annotation_openpose",
|
| 541 |
+
]
|
| 542 |
+
|
| 543 |
+
# Build post-processors
|
| 544 |
+
post_processors: list[Any] = [ImagePostProcessor()]
|
| 545 |
+
for condition in pipe.config.conditions: # type: ignore
|
| 546 |
+
if condition == "lineart":
|
| 547 |
+
post_processors.append(LineartPostProcessor())
|
| 548 |
+
elif condition == "edge":
|
| 549 |
+
post_processors.append(EdgePostProcessor())
|
| 550 |
+
elif condition == "depth":
|
| 551 |
+
post_processors.append(DepthPostProcessor())
|
| 552 |
+
elif condition == "normal":
|
| 553 |
+
post_processors.append(NormalPostProcessor())
|
| 554 |
+
elif condition == "albedo":
|
| 555 |
+
post_processors.append(AlbedoPostProcessor())
|
| 556 |
+
elif condition == "segmentation":
|
| 557 |
+
post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
|
| 558 |
+
elif condition == "openpose":
|
| 559 |
+
post_processors.append(OpenposePostProcessor())
|
| 560 |
+
else:
|
| 561 |
+
print(f"⚠️ Warning: Unknown condition: {condition}")
|
| 562 |
+
post_processors.append(ImagePostProcessor())
|
| 563 |
+
|
| 564 |
+
import json
|
| 565 |
+
|
| 566 |
+
with open('/home/efs/mjw/mjw/code/geneval/prompts/evaluation_metadata.jsonl') as fp:
|
| 567 |
+
metadatas = [json.loads(line) for line in fp][271:300]
|
| 568 |
+
|
| 569 |
+
for index, metadata in enumerate(metadatas):
|
| 570 |
+
index += 271
|
| 571 |
+
ori_caption = metadata['prompt']
|
| 572 |
+
|
| 573 |
+
for num in range(4):
|
| 574 |
+
|
| 575 |
+
best_score = 0
|
| 576 |
+
best_dir = None
|
| 577 |
+
best_caption = None
|
| 578 |
+
|
| 579 |
+
sample_seed = torch.randint(0, 100000, (1,)).item()
|
| 580 |
+
print(sample_seed)
|
| 581 |
+
|
| 582 |
+
torch.manual_seed(sample_seed)
|
| 583 |
+
generator = torch.Generator(device=device).manual_seed(sample_seed)
|
| 584 |
+
|
| 585 |
+
#caption = refine_prompt_with_qwen(model, processor, ori_caption)
|
| 586 |
+
caption = ori_caption
|
| 587 |
+
init_dir = init_t2i(args, caption, pipe, 0, post_processors, modality_names, generator, index, num)
|
| 588 |
+
|
| 589 |
+
save_dir = init_dir
|
| 590 |
+
prompt = caption
|
| 591 |
+
max_length = 1024
|
| 592 |
+
image_path = str(init_dir / "image.png")
|
| 593 |
+
score, feedback = evaluate_consistency(image_path, model, processor, prompt, ori_caption)
|
| 594 |
+
|
| 595 |
+
if score >= best_score:
|
| 596 |
+
best_score = score
|
| 597 |
+
best_dir = save_dir
|
| 598 |
+
best_caption = prompt
|
| 599 |
+
|
| 600 |
+
for step in range(1, args.iters):
|
| 601 |
+
prompt = text_refine(save_dir, model, processor, caption, prompt, feedback, step, index, num, max_length)
|
| 602 |
+
max_length += 100
|
| 603 |
+
save_dir = image_refine(caption, prompt, save_dir, step, modality_names, generator, index, num)
|
| 604 |
+
image_path = str(save_dir / "image.png")
|
| 605 |
+
score, feedback = evaluate_consistency(image_path, model, processor, prompt, ori_caption)
|
| 606 |
+
|
| 607 |
+
if score >= best_score:
|
| 608 |
+
best_score = score
|
| 609 |
+
best_dir = save_dir
|
| 610 |
+
best_caption = prompt
|
| 611 |
+
|
| 612 |
+
best_save_dir = Path(args.output_dir) / f"index_{index}" / f"sample_{num}" / f"iteration_best"
|
| 613 |
+
best_save_dir.mkdir(parents=True, exist_ok=True)
|
| 614 |
+
copy(os.path.join(best_dir,'image.png'), best_save_dir / 'image.png')
|
| 615 |
+
with open(best_save_dir / "caption.txt", "w", encoding="utf-8") as f:
|
| 616 |
+
f.write(best_caption.strip())
|
| 617 |
+
with open(best_save_dir / "score.txt", "w", encoding="utf-8") as f:
|
| 618 |
+
f.write(str(best_score))
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
|