JiaMao commited on
Commit
b3035f4
·
verified ·
1 Parent(s): 2753f9e

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
__pycache__/jodi_pipeline.cpython-310.pyc ADDED
Binary file (9.73 kB). View file
 
__pycache__/jodi_pipeline.cpython-312.pyc ADDED
Binary file (18.3 kB). View file
 
c2i.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--prompt", type=str, default="A mountain range.", help="Prompt text for generation.")
153
+ parser.add_argument("--image_root", type=str, default="./assets/1/", help="Prompt text for generation.")
154
+ parser.add_argument("--condition", type=list[str], default=['lineart'], help="Prompt text for generation.")
155
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
156
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
157
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
158
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
159
+ parser.add_argument("--height", type=int, default=1024)
160
+ parser.add_argument("--width", type=int, default=1024)
161
+ parser.add_argument("--seed", type=int, default=1234)
162
+ parser.add_argument("--output_dir", type=str, default="./demo_c2i_outputs", help="Directory to save results.")
163
+ return parser
164
+
165
+
166
+ # ------------------------------
167
+ # Main Inference Function
168
+ # ------------------------------
169
+ @torch.inference_mode()
170
+ def init_t2i(args, images, role, pipe, iter_num, post_processors, modality_names, generator):
171
+
172
+ # --------------------------
173
+ # Inference
174
+ # --------------------------
175
+
176
+ print(f"🚀 Generating with prompt: {args.prompt}")
177
+ outputs = pipe(
178
+ images=images,
179
+ role=role,
180
+ prompt=args.prompt,
181
+ negative_prompt=args.negative_prompt,
182
+ height=args.height,
183
+ width=args.width,
184
+ num_inference_steps=args.steps,
185
+ guidance_scale=args.guidance_scale,
186
+ num_images_per_prompt=1,
187
+ generator=generator
188
+ )
189
+
190
+ # Apply post-processing for each modality
191
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
192
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
193
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
194
+
195
+ # --------------------------
196
+ # Save results
197
+ # --------------------------
198
+ os.makedirs(args.output_dir, exist_ok=True)
199
+
200
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
201
+ save_dir.mkdir(parents=True, exist_ok=True)
202
+
203
+ for idx, img in enumerate(results):
204
+ name = modality_names[idx]
205
+ save_path = save_dir / f"{name}.png"
206
+ img.save(save_path)
207
+ print(f"💾 Saved {name} → {save_path}")
208
+
209
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
210
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
211
+
212
+ print(f"\n✅ All results saved in: {save_dir}\n")
213
+ return save_dir
214
+
215
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
216
+ messages = build_multimodal_message(root, prompt)
217
+ inputs = processor.apply_chat_template(
218
+ messages,
219
+ tokenize=True,
220
+ add_generation_prompt=True,
221
+ return_dict=True,
222
+ return_tensors="pt"
223
+ )
224
+ inputs = inputs.to(model.device)
225
+
226
+ # Inference: Generation of the output
227
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
228
+ generated_ids_trimmed = [
229
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
230
+ ]
231
+ output_text = processor.batch_decode(
232
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
233
+ )
234
+ print(output_text)
235
+
236
+ os.makedirs(args.output_dir, exist_ok=True)
237
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
238
+ save_dir.mkdir(parents=True, exist_ok=True)
239
+ caption_path = Path(save_dir) / f"caption.txt"
240
+ with open(caption_path, "w", encoding="utf-8") as f:
241
+ f.write(output_text[0].strip())
242
+
243
+ return output_text[0]
244
+
245
+ def image_refine(prompt, images, role, pipe, root, iter_num, modality_names, generator):
246
+
247
+ #control_images = []
248
+ #for name in modality_names:
249
+ # control_images.append(Image.open(os.path.join(root, name+'.png')).convert("RGB"))
250
+
251
+ print(f"🚀 Generating with prompt: {args.prompt}")
252
+ prompt = args.prompt + ' ' + prompt
253
+ outputs = pipe(
254
+ images=images,
255
+ role=role,
256
+ prompt=prompt,
257
+ negative_prompt=args.negative_prompt,
258
+ height=args.height,
259
+ width=args.width,
260
+ num_inference_steps=args.steps,
261
+ guidance_scale=args.guidance_scale,
262
+ num_images_per_prompt=1,
263
+ generator=generator,
264
+ task='t2i'
265
+ )
266
+
267
+ # Apply post-processing for each modality
268
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
269
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
270
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
271
+
272
+ # --------------------------
273
+ # Save results
274
+ # --------------------------
275
+ os.makedirs(args.output_dir, exist_ok=True)
276
+
277
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
278
+ save_dir.mkdir(parents=True, exist_ok=True)
279
+
280
+ for idx, img in enumerate(results):
281
+ name = modality_names[idx]
282
+ save_path = save_dir / f"{name}.png"
283
+ img.save(save_path)
284
+ print(f"💾 Saved {name} → {save_path}")
285
+
286
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
287
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
288
+
289
+ print(f"\n✅ All results saved in: {save_dir}\n")
290
+ return save_dir
291
+
292
+
293
+ # ------------------------------
294
+ # Entry Point
295
+ # ------------------------------
296
+ if __name__ == "__main__":
297
+ args = get_parser().parse_args()
298
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
299
+ print(f"✅ Using device: {device}")
300
+
301
+ processor = AutoProcessor.from_pretrained(
302
+ args.model_name_or_path,
303
+ )
304
+
305
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
306
+ args.text_model_path,
307
+ attn_implementation="flash_attention_2",
308
+ dtype=(torch.bfloat16),
309
+ ).to(device)
310
+
311
+ pipe = JodiPipeline(args.config)
312
+ pipe.from_pretrained(args.model_path)
313
+
314
+ modality_names = [
315
+ "image",
316
+ "annotation_lineart",
317
+ "annotation_edge",
318
+ "annotation_depth",
319
+ "annotation_normal",
320
+ "annotation_albedo",
321
+ "annotation_seg_12colors",
322
+ "annotation_openpose",
323
+ ]
324
+
325
+ # Build post-processors
326
+ post_processors: list[Any] = [ImagePostProcessor()]
327
+ for condition in pipe.config.conditions: # type: ignore
328
+ if condition == "lineart":
329
+ post_processors.append(LineartPostProcessor())
330
+ elif condition == "edge":
331
+ post_processors.append(EdgePostProcessor())
332
+ elif condition == "depth":
333
+ post_processors.append(DepthPostProcessor())
334
+ elif condition == "normal":
335
+ post_processors.append(NormalPostProcessor())
336
+ elif condition == "albedo":
337
+ post_processors.append(AlbedoPostProcessor())
338
+ elif condition == "segmentation":
339
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
340
+ elif condition == "openpose":
341
+ post_processors.append(OpenposePostProcessor())
342
+ else:
343
+ print(f"⚠️ Warning: Unknown condition: {condition}")
344
+ post_processors.append(ImagePostProcessor())
345
+
346
+ torch.manual_seed(args.seed)
347
+ generator = torch.Generator(device=device).manual_seed(args.seed)
348
+ import glob
349
+ image_paths = glob.glob(os.path.join(args.image_root, '*.jpg'))
350
+
351
+ control_images = []
352
+
353
+ for name in modality_names:
354
+ found_path = None
355
+ for c in args.condition:
356
+ matched_files = [f for f in image_paths if c in f and c in name]
357
+ if matched_files:
358
+ found_path = matched_files[0]
359
+ break
360
+ control_images.append(Image.open(found_path).convert("RGB") if found_path else None)
361
+
362
+
363
+ role = [0 if img is None else 1 for img in control_images]
364
+ print(role)
365
+
366
+ init_dir = init_t2i(args, control_images, role, pipe, 0, post_processors, modality_names, generator)
367
+
368
+ save_dir = init_dir
369
+ prompt = args.prompt
370
+ max_length = 1024
371
+ for step in range(1, args.iters):
372
+ prompt = text_refine(save_dir, model, processor, prompt, step, max_length)
373
+ max_length += 100
374
+ save_dir = image_refine(prompt, control_images, role, pipe, save_dir, step, modality_names, generator)
375
+
376
+
c2t.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_init_message(image_paths, role):
72
+ """
73
+ Build Qwen3-VL message for multi-modal image description.
74
+ - `image_paths`: list of image file paths in modality order.
75
+ - `role`: list[int] of 0/1, indicating which modalities are active.
76
+ - Includes per-modality visual descriptions.
77
+ - No coarse caption, fixed instruction: "Describe this image."
78
+ """
79
+
80
+ modality_names = [
81
+ "image",
82
+ "annotation_lineart",
83
+ "annotation_edge",
84
+ "annotation_depth",
85
+ "annotation_normal",
86
+ "annotation_albedo",
87
+ "annotation_seg_12colors",
88
+ "annotation_openpose",
89
+ ]
90
+
91
+ # --- 输入检查 ---
92
+ if len(role) != len(modality_names):
93
+ raise ValueError(f"role length {len(role)} must match modality_names length {len(modality_names)}")
94
+ if len(image_paths) != sum(role):
95
+ raise ValueError(f"image_paths length {len(image_paths)} must match modality_names length {len(modality_names)}")
96
+
97
+ # --- 每个模态的视觉提示定义 ---
98
+ modality_descriptions = {
99
+ "image": "provides color, texture, lighting, and overall visual appearance.",
100
+ "annotation_lineart": "reveals fine structural outlines, shapes, and proportions.",
101
+ "annotation_edge": "highlights boundaries and contours of objects.",
102
+ "annotation_depth": "shows spatial distance, perspective, and 3D geometry.",
103
+ "annotation_normal": "captures surface orientation and fine geometric curvature.",
104
+ "annotation_albedo": "shows intrinsic surface colors unaffected by lighting.",
105
+ "annotation_seg_12colors": "provides semantic regions and object boundaries.",
106
+ "annotation_openpose": "shows human body keypoints, orientation, and posture.",
107
+ }
108
+
109
+ readable_map = {
110
+ "image": "RGB image",
111
+ "annotation_lineart": "line drawing",
112
+ "annotation_edge": "edge map",
113
+ "annotation_depth": "depth map",
114
+ "annotation_normal": "normal map",
115
+ "annotation_albedo": "albedo map",
116
+ "annotation_seg_12colors": "segmentation map",
117
+ "annotation_openpose": "human pose map",
118
+ }
119
+
120
+ # --- 选择存在的模态与路径 ---
121
+ selected_modalities = [m for m, r in zip(modality_names, role) if r == 1]
122
+ available = [str(Path(p)) for p in image_paths]
123
+
124
+ if not available:
125
+ raise FileNotFoundError("No valid modality images found in image_paths for selected roles.")
126
+
127
+ # --- 拼接模态说明 ---
128
+ modality_desc_text = " ".join(
129
+ [f"- The {readable_map[m]} {modality_descriptions[m]}" for m in selected_modalities]
130
+ )
131
+
132
+ # --- 构造文本提示 ---
133
+ text_prompt = (
134
+ f"You are given multiple modalities of the same scene, including: "
135
+ f"{', '.join([readable_map[m] for m in selected_modalities])}. "
136
+ f"{modality_desc_text} "
137
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
138
+ f"Do NOT mention modality names explicitly. "
139
+ f"Describe this image."
140
+ + " " + " ".join(["<image>"] * len(available))
141
+ )
142
+
143
+ # --- 构建 Qwen3-VL 消息格式 ---
144
+ messages = [
145
+ {
146
+ "role": "user",
147
+ "content": [{"type": "image", "image": path} for path in available]
148
+ + [{"type": "text", "text": text_prompt}],
149
+ }
150
+ ]
151
+
152
+ return messages
153
+
154
+
155
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
156
+ """
157
+ Build Qwen3-VL message for multi-modal caption refinement.
158
+ Automatically detects available modalities under root.
159
+ """
160
+ modality_names = [
161
+ "image",
162
+ "annotation_lineart",
163
+ "annotation_edge",
164
+ "annotation_depth",
165
+ "annotation_normal",
166
+ "annotation_albedo",
167
+ "annotation_seg_12colors",
168
+ "annotation_openpose",
169
+ ]
170
+
171
+ # --- 检查存在的模态 ---
172
+ available = []
173
+ for name in modality_names:
174
+ # 优先匹配 .png 或 .jpg
175
+ for ext in [".png", ".jpg", ".jpeg"]:
176
+ path = Path(root) / f"{name}{ext}"
177
+ if path.exists():
178
+ available.append(str(path))
179
+ break
180
+
181
+ # --- 构建模态说明 ---
182
+ readable_map = {
183
+ "image": "RGB image",
184
+ "annotation_lineart": "line drawing",
185
+ "annotation_edge": "edge map",
186
+ "annotation_depth": "depth map",
187
+ "annotation_normal": "normal map",
188
+ "annotation_albedo": "albedo map",
189
+ "annotation_seg_12colors": "segmentation map",
190
+ "annotation_openpose": "human pose map",
191
+ }
192
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
193
+
194
+ # --- 构造文本指令 ---
195
+ text_prompt = (
196
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
197
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
198
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
199
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
200
+ f"- The edge map highlights object boundaries and contours. "
201
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
202
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
203
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
204
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
205
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
206
+ f"For each provided modality image, analyze it according to the above definitions and describe "
207
+ f"the specific visual information it contributes in this particular case. "
208
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
209
+ f"Do NOT describe each modality separately or mention modality names. "
210
+ f"Focus on merging their information into a single coherent image description. "
211
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
212
+ f"Refine the coarse caption into a more detailed and accurate image description. "
213
+ f"Coarse caption: '{coarse_caption}' " +
214
+ " ".join(["<image>"] * len(available))
215
+ )
216
+
217
+ # --- 构建 Qwen3-VL 消息格式 ---
218
+ messages = [
219
+ {
220
+ "role": "user",
221
+ "content": [{"type": "image", "image": path} for path in available]
222
+ + [{"type": "text", "text": text_prompt}],
223
+ }
224
+ ]
225
+ return messages
226
+
227
+ # ------------------------------
228
+ # Argument Parser
229
+ # ------------------------------
230
+ def get_parser():
231
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
232
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
233
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
234
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
235
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
236
+ parser.add_argument("--image_root", type=str, default="./assets/2/", help="Prompt text for generation.")
237
+ parser.add_argument("--condition", type=list[str], default=["normal"], help="Prompt text for generation.")
238
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
239
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
240
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
241
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
242
+ parser.add_argument("--height", type=int, default=768)
243
+ parser.add_argument("--width", type=int, default=1024)
244
+ parser.add_argument("--seed", type=int, default=1234)
245
+ parser.add_argument("--output_dir", type=str, default="./demo_c2t_outputs", help="Directory to save results.")
246
+ return parser
247
+
248
+
249
+ # ------------------------------
250
+ # Main Inference Function
251
+ # ------------------------------
252
+
253
+ @torch.inference_mode()
254
+ def init_i2t(model, processor, image_path, role, iter_num, max_length=300):
255
+ messages = build_init_message(image_path, role)
256
+
257
+ print(f'init prompt:{messages}')
258
+
259
+ inputs = processor.apply_chat_template(
260
+ messages,
261
+ tokenize=True,
262
+ add_generation_prompt=True,
263
+ return_dict=True,
264
+ return_tensors="pt"
265
+ )
266
+ inputs = inputs.to(model.device)
267
+
268
+ # Inference: Generation of the output
269
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
270
+ generated_ids_trimmed = [
271
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
272
+ ]
273
+ output_text = processor.batch_decode(
274
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
275
+ )
276
+ print(output_text)
277
+
278
+ os.makedirs(args.output_dir, exist_ok=True)
279
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
280
+ save_dir.mkdir(parents=True, exist_ok=True)
281
+ caption_path = Path(save_dir) / f"caption.txt"
282
+ with open(caption_path, "w", encoding="utf-8") as f:
283
+ f.write(output_text[0].strip())
284
+
285
+ return output_text[0]
286
+
287
+ @torch.inference_mode()
288
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
289
+ messages = build_multimodal_message(root, prompt)
290
+
291
+ print(messages)
292
+
293
+ inputs = processor.apply_chat_template(
294
+ messages,
295
+ tokenize=True,
296
+ add_generation_prompt=True,
297
+ return_dict=True,
298
+ return_tensors="pt"
299
+ )
300
+ inputs = inputs.to(model.device)
301
+
302
+ # Inference: Generation of the output
303
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
304
+ generated_ids_trimmed = [
305
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
306
+ ]
307
+ output_text = processor.batch_decode(
308
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
309
+ )
310
+ print(output_text)
311
+
312
+ os.makedirs(args.output_dir, exist_ok=True)
313
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
314
+ save_dir.mkdir(parents=True, exist_ok=True)
315
+ caption_path = Path(save_dir) / f"caption.txt"
316
+ with open(caption_path, "w", encoding="utf-8") as f:
317
+ f.write(output_text[0].strip())
318
+
319
+ return output_text[0]
320
+
321
+ @torch.inference_mode()
322
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator):
323
+
324
+ #print(f"🚀 Generating with prompt: {prompt}")
325
+ #prompt = args.prompt + ' ' + prompt
326
+ outputs = pipe(
327
+ images=images,
328
+ role=role,
329
+ prompt=prompt,
330
+ negative_prompt=args.negative_prompt,
331
+ height=args.height,
332
+ width=args.width,
333
+ num_inference_steps=args.steps,
334
+ guidance_scale=args.guidance_scale,
335
+ num_images_per_prompt=1,
336
+ generator=generator,
337
+ task='t2i'
338
+ )
339
+
340
+ # Apply post-processing for each modality
341
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
342
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
343
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
344
+
345
+ # --------------------------
346
+ # Save results
347
+ # --------------------------
348
+ os.makedirs(args.output_dir, exist_ok=True)
349
+
350
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
351
+ save_dir.mkdir(parents=True, exist_ok=True)
352
+
353
+ for idx, img in enumerate(results):
354
+ name = modality_names[idx]
355
+ save_path = save_dir / f"{name}.png"
356
+ img.save(save_path)
357
+ print(f"💾 Saved {name} → {save_path}")
358
+
359
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
360
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
361
+
362
+ print(f"\n✅ All results saved in: {save_dir}\n")
363
+ return save_dir
364
+
365
+
366
+ # ------------------------------
367
+ # Entry Point
368
+ # ------------------------------
369
+ if __name__ == "__main__":
370
+ args = get_parser().parse_args()
371
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
372
+ print(f"✅ Using device: {device}")
373
+
374
+ processor = AutoProcessor.from_pretrained(
375
+ args.model_name_or_path,
376
+ )
377
+
378
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
379
+ args.text_model_path,
380
+ attn_implementation="flash_attention_2",
381
+ dtype=(torch.bfloat16),
382
+ ).to(device)
383
+
384
+ pipe = JodiPipeline(args.config)
385
+ pipe.from_pretrained(args.model_path)
386
+
387
+ modality_names = [
388
+ "image",
389
+ "annotation_lineart",
390
+ "annotation_edge",
391
+ "annotation_depth",
392
+ "annotation_normal",
393
+ "annotation_albedo",
394
+ "annotation_seg_12colors",
395
+ "annotation_openpose",
396
+ ]
397
+
398
+ # Build post-processors
399
+ post_processors: list[Any] = [ImagePostProcessor()]
400
+ for condition in pipe.config.conditions: # type: ignore
401
+ if condition == "lineart":
402
+ post_processors.append(LineartPostProcessor())
403
+ elif condition == "edge":
404
+ post_processors.append(EdgePostProcessor())
405
+ elif condition == "depth":
406
+ post_processors.append(DepthPostProcessor())
407
+ elif condition == "normal":
408
+ post_processors.append(NormalPostProcessor())
409
+ elif condition == "albedo":
410
+ post_processors.append(AlbedoPostProcessor())
411
+ elif condition == "segmentation":
412
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
413
+ elif condition == "openpose":
414
+ post_processors.append(OpenposePostProcessor())
415
+ else:
416
+ print(f"⚠️ Warning: Unknown condition: {condition}")
417
+ post_processors.append(ImagePostProcessor())
418
+
419
+ torch.manual_seed(args.seed)
420
+ generator = torch.Generator(device=device).manual_seed(args.seed)
421
+
422
+ import glob
423
+ image_paths = glob.glob(os.path.join(args.image_root, '*.jpg')) + glob.glob(os.path.join(args.image_root, '*.png'))
424
+
425
+ control_images = []
426
+
427
+ for name in modality_names:
428
+ found_path = None
429
+ for c in args.condition:
430
+ matched_files = [f for f in image_paths if c in f and c in name]
431
+ if matched_files:
432
+ found_path = matched_files[0]
433
+ break
434
+ control_images.append(Image.open(found_path).convert("RGB") if found_path else None)
435
+
436
+
437
+ role = [0 if img is None else 1 for img in control_images]
438
+ print(role)
439
+
440
+ max_length = 1024
441
+ prompt = init_i2t(model, processor, image_paths, role, 0, max_length)
442
+
443
+ for step in range(1, args.iters):
444
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator)
445
+ max_length += 100
446
+ prompt = text_refine(save_dir, model, processor, prompt, step, max_length)
447
+
448
+
code/test_real1.py ADDED
@@ -0,0 +1,805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ---------- 构建内容序列(模态锚定) ----------
206
+ content = []
207
+ content.append({"type": "text", "text": text_prompt})
208
+ print(f'available:{available}')
209
+ for name, path in available:
210
+ readable = readable_map.get(name, "visual input")
211
+ # 在每张图像前显式标注模态类型
212
+ content.append({"type": "text", "text": f"This is the {readable}."})
213
+ content.append({"type": "image", "image": path})
214
+
215
+ # 最后加入主指令
216
+ #content.append({"type": "text", "text": text_prompt})
217
+
218
+ messages = [{"role": "user", "content": content}]
219
+ return messages
220
+
221
+
222
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
223
+ """
224
+ Build Qwen3-VL message for multi-modal caption refinement.
225
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
226
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
227
+ """
228
+
229
+ modality_names = [
230
+ "image",
231
+ "annotation_lineart",
232
+ "annotation_edge",
233
+ "annotation_depth",
234
+ "annotation_normal",
235
+ "annotation_albedo",
236
+ "annotation_seg_12colors",
237
+ # "annotation_openpose",
238
+ ]
239
+
240
+ # --- 检查存在的模态 ---
241
+ available = []
242
+ for name in modality_names:
243
+ for ext in [".png", ".jpg", ".jpeg"]:
244
+ path = Path(root) / f"{name}{ext}"
245
+ if path.exists():
246
+ available.append((name, str(path)))
247
+ break
248
+
249
+ # --- 构建模态说明 ---
250
+ readable_map = {
251
+ "image": "RGB image",
252
+ "annotation_lineart": "line drawing",
253
+ "annotation_edge": "edge map",
254
+ "annotation_depth": "depth map",
255
+ "annotation_normal": "normal map",
256
+ "annotation_albedo": "albedo map",
257
+ "annotation_seg_12colors": "segmentation map",
258
+ # "annotation_openpose": "human pose map",
259
+ }
260
+
261
+ present_modalities = [readable_map[n] for n, _ in available]
262
+
263
+ # --- 构造文本指令 ---
264
+ text_prompt = (
265
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
266
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
267
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
268
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
269
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
270
+ f"while maintaining faithfulness to the original visual content. "
271
+ f"Do not include any additional commentary or evaluations. "
272
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
273
+ f"Focus on describing the visual properties, including: "
274
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
275
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
276
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
277
+ f"Consider the following feedback when refining your description: '{feedback}'. "
278
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
279
+ f"Coarse caption: '{coarse_caption}' "
280
+ )
281
+
282
+ # text_prompt0 = (
283
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
284
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
285
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
286
+ # f"### Your Task:\n"
287
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
288
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
289
+ # f"### Guidelines:\n"
290
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
291
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
292
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
293
+ # f"4. Avoid including any additional commentary or evaluations.\n"
294
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
295
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
296
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
297
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
298
+ # )
299
+
300
+ # --- 构建消息内容:在每个图像前加模态标识 ---
301
+ content = []
302
+ content.append({"type": "text", "text": text_prompt})
303
+ for name, path in available:
304
+ readable = readable_map.get(name, "visual input")
305
+ content.append({
306
+ "type": "text",
307
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
308
+ })
309
+ content.append({"type": "image", "image": path})
310
+
311
+ # 最后附上总任务说明
312
+ #content.append({"type": "text", "text": text_prompt})
313
+
314
+ messages = [{"role": "user", "content": content}]
315
+ return messages
316
+
317
+
318
+ def get_modality_description(name: str) -> str:
319
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
320
+ desc_map = {
321
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
322
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
323
+ "annotation_edge": "strong boundaries and contrast edges between objects",
324
+ "annotation_depth": "distance and perspective information for spatial understanding",
325
+ "annotation_normal": "surface orientation and geometric curvature cues",
326
+ "annotation_albedo": "pure surface color without lighting or shading effects",
327
+ "annotation_seg_12colors": "semantic regions and object categories",
328
+ "annotation_openpose": "human body keypoints, joints, and orientation",
329
+ }
330
+ return desc_map.get(name, "complementary visual evidence")
331
+
332
+
333
+ # ------------------------------
334
+ # Argument Parser
335
+ # ------------------------------
336
+ def get_parser():
337
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
338
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
339
+ help="Path to model checkpoint.")
340
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
341
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
342
+ help="Path to model checkpoint.")
343
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
344
+ help="Path to model checkpoint.")
345
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
346
+ help="Prompt text for generation.")
347
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
348
+ help="Optional negative prompt.")
349
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
350
+ help="Prompt text for generation.")
351
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
352
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
353
+ help="Optional negative prompt.")
354
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
355
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
356
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
357
+ parser.add_argument("--seed", type=int, default=42)
358
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
359
+ return parser
360
+
361
+
362
+ # ------------------------------
363
+ # Main Inference Function
364
+ # ------------------------------
365
+
366
+
367
+ @torch.inference_mode()
368
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
369
+ messages = [
370
+ {
371
+ "role": "user",
372
+ "content": [
373
+ {
374
+ "type": "image",
375
+ "image": image_path,
376
+ },
377
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
378
+ ],
379
+ }
380
+ ]
381
+
382
+ print(messages)
383
+
384
+ inputs = processor.apply_chat_template(
385
+ messages,
386
+ tokenize=True,
387
+ add_generation_prompt=True,
388
+ return_dict=True,
389
+ return_tensors="pt"
390
+ )
391
+ inputs = inputs.to(model.device)
392
+
393
+ # Inference: Generation of the output
394
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
395
+ generated_ids_trimmed = [
396
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
397
+ ]
398
+ output_text = processor.batch_decode(
399
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
400
+ )
401
+ print(output_text)
402
+
403
+ os.makedirs(args.output_dir, exist_ok=True)
404
+ save_dir = Path(args.output_dir) / str(vqa_id)
405
+ save_dir.mkdir(parents=True, exist_ok=True)
406
+ caption_path = Path(save_dir) / f"caption.txt"
407
+ with open(caption_path, "w", encoding="utf-8") as f:
408
+ f.write(output_text[0].strip())
409
+
410
+ return output_text[0]
411
+
412
+
413
+ @torch.inference_mode()
414
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
415
+ messages = [
416
+ {
417
+ "role": "user",
418
+ "content": [
419
+ {
420
+ "type": "image",
421
+ "image": image_path,
422
+ },
423
+ {"type": "text", "text": f"Describe this image."},
424
+ ],
425
+ }
426
+ ]
427
+
428
+ inputs = processor.apply_chat_template(
429
+ messages,
430
+ tokenize=True,
431
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
432
+ )
433
+ inputs = inputs.to(model.device)
434
+
435
+ # Inference: Generation of the output
436
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
437
+ generated_ids_trimmed = [
438
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
439
+ ]
440
+ output_text = processor.batch_decode(
441
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
442
+ )
443
+ print(output_text)
444
+
445
+ os.makedirs(args.output_dir, exist_ok=True)
446
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
447
+ save_dir.mkdir(parents=True, exist_ok=True)
448
+ caption_path = Path(save_dir) / f"caption.txt"
449
+ with open(caption_path, "w", encoding="utf-8") as f:
450
+ f.write(output_text[0].strip())
451
+
452
+ return output_text[0]
453
+
454
+ @torch.inference_mode()
455
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
456
+ # --- 构造 Qwen 输入 ---
457
+ question = clean_eval_question(question)
458
+ eval_prompt = f"""
459
+ You are a VQA answer evaluator.
460
+ Given an image, a question, and a proposed answer,
461
+ score how correct the answer is according to the image evidence.
462
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
463
+ to make the answer more accurate or grounded in the image.
464
+ Return JSON strictly:
465
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
466
+
467
+ Question: "{question}"
468
+ Answer: "{answer}"
469
+ <image>
470
+ """
471
+
472
+ messages = [
473
+ {
474
+ "role": "user",
475
+ "content": [
476
+ {"type": "image", "image": image_path},
477
+ {"type": "text", "text": eval_prompt},
478
+ ],
479
+ }
480
+ ]
481
+
482
+ # --- 推理 ---
483
+ inputs = processor.apply_chat_template(
484
+ messages,
485
+ tokenize=True,
486
+ add_generation_prompt=True,
487
+ return_dict=True,
488
+ return_tensors="pt"
489
+ ).to(model.device)
490
+
491
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
492
+ #print(f'out_ids.logits:{out_ids.logit}')
493
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
494
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
495
+
496
+ # --- 解析输出 ---
497
+ try:
498
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
499
+ score = float(data.get("AnswerScore", 0))
500
+ feedback = data.get("Feedback", "")
501
+ except Exception:
502
+ score, feedback = 0.0, text.strip()
503
+
504
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
505
+ return score, feedback
506
+
507
+ @torch.inference_mode()
508
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
509
+ """
510
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
511
+ This reduces model bias and improves visual grounding reliability.
512
+ """
513
+
514
+ # 检查存在的模态文件
515
+ modality_names = [
516
+ "image", "annotation_lineart", "annotation_edge",
517
+ "annotation_depth", "annotation_normal", "annotation_albedo",
518
+ "annotation_seg_12colors", "annotation_openpose"
519
+ ]
520
+
521
+ available = []
522
+ for name in modality_names:
523
+ for ext in [".png", ".jpg", ".jpeg"]:
524
+ path = Path(root) / f"{name}{ext}"
525
+ if path.exists():
526
+ available.append((name, str(path)))
527
+ break
528
+
529
+ # 可读映射
530
+ readable_map = {
531
+ "image": "RGB image",
532
+ "annotation_lineart": "line drawing",
533
+ "annotation_edge": "edge map",
534
+ "annotation_depth": "depth map",
535
+ "annotation_normal": "normal map",
536
+ "annotation_albedo": "albedo map",
537
+ "annotation_seg_12colors": "segmentation map",
538
+ "annotation_openpose": "human pose map",
539
+ }
540
+
541
+ present_modalities = [readable_map[n] for n, _ in available]
542
+
543
+ # 构造 prompt
544
+ eval_prompt = f"""
545
+ You are a multimodal visual reasoning evaluator.
546
+
547
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
548
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
549
+ based purely on visual evidence from all modalities.
550
+
551
+ Follow this process:
552
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
553
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
554
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
555
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
556
+ 5. Penalize any parts that contradict the image, or ignore modalities.
557
+
558
+ Return JSON strictly:
559
+ {{
560
+ "AnswerScore": <float between 0 and 1>,
561
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
562
+ }}
563
+
564
+ Question: "{question}"
565
+ Answer: "{answer}"
566
+ """
567
+
568
+ # 构建内容序列(模态+图像)
569
+ content = []
570
+ content.append({"type": "text", "text": eval_prompt})
571
+ for name, path in available:
572
+ readable = readable_map.get(name, "visual input")
573
+ content.append({"type": "text", "text": f"This is the {readable}."})
574
+ content.append({"type": "image", "image": path})
575
+ #content.append({"type": "text", "text": eval_prompt})
576
+
577
+ messages = [{"role": "user", "content": content}]
578
+
579
+ # --- 推理 ---
580
+ inputs = processor.apply_chat_template(
581
+ messages, tokenize=True, add_generation_prompt=True,
582
+ return_dict=True, return_tensors="pt"
583
+ ).to(model.device)
584
+
585
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
586
+ #print(out_ids)
587
+ out_ids = outs['sequences']
588
+ scores = outs['scores']
589
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
590
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
591
+
592
+ # --- 解析输出 ---
593
+ try:
594
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
595
+ score = float(data.get("AnswerScore", 0))
596
+ feedback = data.get("Feedback", "")
597
+ except Exception:
598
+ score, feedback = 0.0, text.strip()
599
+
600
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
601
+ return score, feedback
602
+
603
+
604
+
605
+ @torch.inference_mode()
606
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
607
+ question = clean_prompt_question(question)
608
+ messages = build_multimodal_message(root, question, prompt, feedback)
609
+ inputs = processor.apply_chat_template(
610
+ messages,
611
+ tokenize=True,
612
+ add_generation_prompt=True,
613
+ return_dict=True,
614
+ return_tensors="pt"
615
+ )
616
+ inputs = inputs.to(model.device)
617
+
618
+ # Inference: Generation of the output
619
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
620
+ generated_ids_trimmed = [
621
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
622
+ ]
623
+ output_text = processor.batch_decode(
624
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
625
+ )
626
+ print(output_text)
627
+
628
+ os.makedirs(args.output_dir, exist_ok=True)
629
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
630
+ save_dir.mkdir(parents=True, exist_ok=True)
631
+ caption_path = Path(save_dir) / f"caption.txt"
632
+ with open(caption_path, "w", encoding="utf-8") as f:
633
+ f.write(output_text[0].strip())
634
+ return output_text[0]
635
+
636
+
637
+ @torch.inference_mode()
638
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
639
+ messages = build_vqa_message(root, prompt, question)
640
+ print(messages)
641
+ inputs = processor.apply_chat_template(
642
+ messages,
643
+ tokenize=True,
644
+ add_generation_prompt=True,
645
+ return_dict=True,
646
+ return_tensors="pt"
647
+ )
648
+ inputs = inputs.to(model.device)
649
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
650
+ generated_ids_trimmed = [
651
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
652
+ output_text = processor.batch_decode(
653
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
654
+ )
655
+ print(output_text)
656
+ os.makedirs(args.output_dir, exist_ok=True)
657
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
658
+ save_dir.mkdir(parents=True, exist_ok=True)
659
+ caption_path = Path(save_dir) / f"caption.txt"
660
+ with open(caption_path, "w", encoding="utf-8") as f:
661
+ f.write(output_text[0].strip())
662
+ return output_text[0]
663
+
664
+
665
+ @torch.inference_mode()
666
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
667
+ # print(f"🚀 Generating with prompt: {prompt}")
668
+ outputs = pipe(
669
+ images=images,
670
+ role=role,
671
+ prompt=prompt,
672
+ negative_prompt=args.negative_prompt,
673
+ height=height,
674
+ width=width,
675
+ num_inference_steps=args.steps,
676
+ guidance_scale=args.guidance_scale,
677
+ num_images_per_prompt=1,
678
+ generator=generator
679
+ )
680
+
681
+ # Apply post-processing for each modality
682
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
683
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
684
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
685
+
686
+ # --------------------------
687
+ # Save results
688
+ # --------------------------
689
+ os.makedirs(args.output_dir, exist_ok=True)
690
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
691
+ save_dir.mkdir(parents=True, exist_ok=True)
692
+ for idx, img in enumerate(results):
693
+ name = modality_names[idx]
694
+ save_path = save_dir / f"{name}.png"
695
+ img.save(save_path)
696
+ print(f"💾 Saved {name} → {save_path}")
697
+
698
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
699
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
700
+ print(f"\n✅ All results saved in: {save_dir}\n")
701
+ return save_dir
702
+
703
+
704
+ if __name__ == "__main__":
705
+ args = get_parser().parse_args()
706
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
707
+ print(f"✅ Using device: {device}")
708
+
709
+ processor = AutoProcessor.from_pretrained(
710
+ args.model_name_or_path,
711
+ )
712
+
713
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
714
+ args.text_model_path,
715
+ attn_implementation="flash_attention_2",
716
+ dtype=(torch.bfloat16),
717
+ ).to(device)
718
+
719
+ pipe = JodiPipeline(args.config)
720
+ pipe.from_pretrained(args.model_path)
721
+
722
+ modality_names = [
723
+ "image",
724
+ "annotation_lineart",
725
+ "annotation_edge",
726
+ "annotation_depth",
727
+ "annotation_normal",
728
+ "annotation_albedo",
729
+ "annotation_seg_12colors",
730
+ "annotation_openpose",
731
+ ]
732
+
733
+ # Build post-processors
734
+ post_processors: list[Any] = [ImagePostProcessor()]
735
+ for condition in pipe.config.conditions: # type: ignore
736
+ if condition == "lineart":
737
+ post_processors.append(LineartPostProcessor())
738
+ elif condition == "edge":
739
+ post_processors.append(EdgePostProcessor())
740
+ elif condition == "depth":
741
+ post_processors.append(DepthPostProcessor())
742
+ elif condition == "normal":
743
+ post_processors.append(NormalPostProcessor())
744
+ elif condition == "albedo":
745
+ post_processors.append(AlbedoPostProcessor())
746
+ elif condition == "segmentation":
747
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
748
+ elif condition == "openpose":
749
+ post_processors.append(OpenposePostProcessor())
750
+ else:
751
+ print(f"⚠️ Warning: Unknown condition: {condition}")
752
+ post_processors.append(ImagePostProcessor())
753
+
754
+ torch.manual_seed(args.seed)
755
+ generator = torch.Generator(device=device).manual_seed(args.seed)
756
+
757
+ with open(args.json, "r", encoding="utf-8") as f:
758
+ annotations = json.load(f)
759
+
760
+ for sample in annotations[1:306]:
761
+
762
+ image_path = os.path.join(args.data_path, sample["image"])
763
+ image_id = sample["image"].split('.')[0]
764
+ image = Image.open(image_path)
765
+ question = sample["question"]
766
+
767
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
768
+
769
+ role = [1] + [0] * pipe.num_conditions
770
+ print(role)
771
+
772
+ best_result, best_score = '', 0.0
773
+ max_length = 1024
774
+
775
+ # input_img = Image.open(image_path).convert("RGB")
776
+ width, height = image.size
777
+ print(f'ori width:{width}', f'ori height:{height}')
778
+
779
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
780
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
781
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
782
+
783
+ if score >= best_score:
784
+ best_result, best_score = result, score
785
+
786
+ for step in range(1, args.iters):
787
+ generator = torch.Generator(device=device).manual_seed(args.seed)
788
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
789
+ image_id)
790
+ max_length += 100
791
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
792
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
793
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
794
+
795
+ if score >= best_score:
796
+ best_result, best_score = result, score
797
+
798
+ os.makedirs(args.output_dir, exist_ok=True)
799
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
800
+ save_dir.mkdir(parents=True, exist_ok=True)
801
+ caption_path = Path(save_dir) / f"caption.txt"
802
+ with open(caption_path, "w", encoding="utf-8") as f:
803
+ f.write(best_result)
804
+ print(best_result)
805
+
code/test_realworldqa_vqa.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[:153]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')
i2t.py ADDED
@@ -0,0 +1,358 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_path", type=str, default="./assets/test_images/pexels-jplenio-1105378.jpg", help="Prompt text for generation.")
153
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
154
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
155
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
156
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
157
+ parser.add_argument("--height", type=int, default=768)
158
+ parser.add_argument("--width", type=int, default=1152)
159
+ parser.add_argument("--seed", type=int, default=42)
160
+ parser.add_argument("--output_dir", type=str, default="./demo_i2t_outputs", help="Directory to save results.")
161
+ return parser
162
+
163
+
164
+ # ------------------------------
165
+ # Main Inference Function
166
+ # ------------------------------
167
+
168
+ @torch.inference_mode()
169
+ def init_i2t(model, processor, image_path, iter_num, max_length=300):
170
+ messages = [
171
+ {
172
+ "role": "user",
173
+ "content": [
174
+ {
175
+ "type": "image",
176
+ "image": image_path,
177
+ },
178
+ {"type": "text", "text": "Describe this image."},
179
+ ],
180
+ }
181
+ ]
182
+
183
+ inputs = processor.apply_chat_template(
184
+ messages,
185
+ tokenize=True,
186
+ add_generation_prompt=True,
187
+ return_dict=True,
188
+ return_tensors="pt"
189
+ )
190
+ inputs = inputs.to(model.device)
191
+
192
+ # Inference: Generation of the output
193
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
194
+ generated_ids_trimmed = [
195
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
196
+ ]
197
+ output_text = processor.batch_decode(
198
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
199
+ )
200
+ print(output_text)
201
+
202
+ os.makedirs(args.output_dir, exist_ok=True)
203
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
204
+ save_dir.mkdir(parents=True, exist_ok=True)
205
+ caption_path = Path(save_dir) / f"caption.txt"
206
+ with open(caption_path, "w", encoding="utf-8") as f:
207
+ f.write(output_text[0].strip())
208
+
209
+ return output_text[0]
210
+
211
+ @torch.inference_mode()
212
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
213
+ messages = build_multimodal_message(root, prompt)
214
+ inputs = processor.apply_chat_template(
215
+ messages,
216
+ tokenize=True,
217
+ add_generation_prompt=True,
218
+ return_dict=True,
219
+ return_tensors="pt"
220
+ )
221
+ inputs = inputs.to(model.device)
222
+
223
+ # Inference: Generation of the output
224
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
225
+ generated_ids_trimmed = [
226
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
227
+ ]
228
+ output_text = processor.batch_decode(
229
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
230
+ )
231
+ print(output_text)
232
+
233
+ os.makedirs(args.output_dir, exist_ok=True)
234
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
235
+ save_dir.mkdir(parents=True, exist_ok=True)
236
+ caption_path = Path(save_dir) / f"caption.txt"
237
+ with open(caption_path, "w", encoding="utf-8") as f:
238
+ f.write(output_text[0].strip())
239
+
240
+ return output_text[0]
241
+
242
+ @torch.inference_mode()
243
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator):
244
+
245
+ print(f"🚀 Generating with prompt: {prompt}")
246
+ #prompt = args.prompt + ' ' + prompt
247
+ outputs = pipe(
248
+ images=images,
249
+ role=role,
250
+ prompt=prompt,
251
+ negative_prompt=args.negative_prompt,
252
+ height=args.height,
253
+ width=args.width,
254
+ num_inference_steps=args.steps,
255
+ guidance_scale=args.guidance_scale,
256
+ num_images_per_prompt=1,
257
+ generator=generator,
258
+ task='t2i'
259
+ )
260
+
261
+ # Apply post-processing for each modality
262
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
263
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
264
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
265
+
266
+ # --------------------------
267
+ # Save results
268
+ # --------------------------
269
+ os.makedirs(args.output_dir, exist_ok=True)
270
+
271
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
272
+ save_dir.mkdir(parents=True, exist_ok=True)
273
+
274
+ for idx, img in enumerate(results):
275
+ name = modality_names[idx]
276
+ save_path = save_dir / f"{name}.png"
277
+ img.save(save_path)
278
+ print(f"💾 Saved {name} → {save_path}")
279
+
280
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
281
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
282
+
283
+ print(f"\n✅ All results saved in: {save_dir}\n")
284
+ return save_dir
285
+
286
+
287
+ # ------------------------------
288
+ # Entry Point
289
+ # ------------------------------
290
+ if __name__ == "__main__":
291
+ args = get_parser().parse_args()
292
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
293
+ print(f"✅ Using device: {device}")
294
+
295
+ processor = AutoProcessor.from_pretrained(
296
+ args.model_name_or_path,
297
+ )
298
+
299
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
300
+ args.text_model_path,
301
+ attn_implementation="flash_attention_2",
302
+ dtype=(torch.bfloat16),
303
+ ).to(device)
304
+
305
+ pipe = JodiPipeline(args.config)
306
+ pipe.from_pretrained(args.model_path)
307
+
308
+ modality_names = [
309
+ "image",
310
+ "annotation_lineart",
311
+ "annotation_edge",
312
+ "annotation_depth",
313
+ "annotation_normal",
314
+ "annotation_albedo",
315
+ "annotation_seg_12colors",
316
+ "annotation_openpose",
317
+ ]
318
+
319
+ # Build post-processors
320
+ post_processors: list[Any] = [ImagePostProcessor()]
321
+ for condition in pipe.config.conditions: # type: ignore
322
+ if condition == "lineart":
323
+ post_processors.append(LineartPostProcessor())
324
+ elif condition == "edge":
325
+ post_processors.append(EdgePostProcessor())
326
+ elif condition == "depth":
327
+ post_processors.append(DepthPostProcessor())
328
+ elif condition == "normal":
329
+ post_processors.append(NormalPostProcessor())
330
+ elif condition == "albedo":
331
+ post_processors.append(AlbedoPostProcessor())
332
+ elif condition == "segmentation":
333
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
334
+ elif condition == "openpose":
335
+ post_processors.append(OpenposePostProcessor())
336
+ else:
337
+ print(f"⚠️ Warning: Unknown condition: {condition}")
338
+ post_processors.append(ImagePostProcessor())
339
+
340
+ torch.manual_seed(args.seed)
341
+ generator = torch.Generator(device=device).manual_seed(args.seed)
342
+ import glob
343
+ image_path = args.image_path
344
+
345
+ control_images = [Image.open(image_path).convert("RGB")] + [None] * pipe.num_conditions
346
+
347
+ role=[1] + [0] * pipe.num_conditions
348
+ print(role)
349
+
350
+ max_length = 1024
351
+ prompt = init_i2t(model, processor, image_path, 0, max_length)
352
+
353
+ for step in range(1, args.iters):
354
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator)
355
+ max_length += 100
356
+ prompt = text_refine(save_dir, model, processor, prompt, step, max_length)
357
+
358
+
jodi_pipeline.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #s file is modified from https://github.com/NVlabs/Sana
2
+
3
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+ # SPDX-License-Identifier: Apache-2.0
18
+
19
+ import os
20
+ import warnings
21
+ import pyrallis
22
+ from dataclasses import dataclass, field
23
+ from typing import Tuple, List
24
+ from PIL import Image
25
+
26
+ import torch
27
+ import torchvision.transforms as T
28
+
29
+ warnings.filterwarnings("ignore") # ignore warning
30
+
31
+
32
+ from diffusion import DPMS
33
+ from model.builder import build_model, get_tokenizer_and_text_encoder, get_vae, vae_decode, vae_encode
34
+ from model.utils import get_weight_dtype, prepare_prompt_ar
35
+ from utils.config import BaseConfig, ModelConfig, AEConfig, TextEncoderConfig, SchedulerConfig, model_init_config
36
+ from utils.logger import get_root_logger
37
+
38
+ from tools.download import find_model
39
+
40
+
41
+ def read_image(image):
42
+ if isinstance(image, str):
43
+ assert os.path.exists(image), f"Image {image} does not exist."
44
+ image = Image.open(image).convert("RGB")
45
+ transform = T.Compose([T.ToTensor(), T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
46
+ image = transform(image)
47
+ elif isinstance(image, Image.Image):
48
+ transform = T.Compose([T.ToTensor(), T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
49
+ image = transform(image)
50
+ elif isinstance(image, torch.Tensor):
51
+ assert image.ndim == 3, "Image tensor should be 3D."
52
+ else:
53
+ raise TypeError("Unsupported image type. Expected str, PIL Image, or Tensor.")
54
+ return image
55
+
56
+
57
+ def classify_height_width_bin(height: int, width: int, ratios: dict) -> Tuple[int, int]:
58
+ """Returns binned height and width."""
59
+ ar = float(height / width)
60
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
61
+ default_hw = ratios[closest_ratio]
62
+ return int(default_hw[0]), int(default_hw[1])
63
+
64
+
65
+ @dataclass
66
+ class JodiInference(BaseConfig):
67
+ model: ModelConfig
68
+ vae: AEConfig
69
+ text_encoder: TextEncoderConfig
70
+ scheduler: SchedulerConfig
71
+ config: str = "./configs/inference.yaml"
72
+ conditions: List[str] = field(default_factory=list)
73
+ work_dir: str = "output/"
74
+
75
+
76
+ class JodiPipeline:
77
+ def __init__(
78
+ self,
79
+ config: str,
80
+ device: torch.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu"),
81
+ ):
82
+ super().__init__()
83
+ config = pyrallis.load(JodiInference, open(config))
84
+ self.config = config
85
+ self.device = device
86
+ self.logger = get_root_logger()
87
+ self.progress_fn = lambda progress, desc: None
88
+
89
+ # set some hyperparameters
90
+ self.image_size = config.model.image_size
91
+ self.latent_size = self.image_size // config.vae.vae_downsample_rate
92
+ self.max_sequence_length = config.text_encoder.model_max_length
93
+ self.flow_shift = config.scheduler.flow_shift
94
+
95
+ self.weight_dtype = get_weight_dtype(config.model.mixed_precision)
96
+ self.vae_dtype = get_weight_dtype(config.vae.weight_dtype)
97
+
98
+ self.logger.info(f"flow_shift: {self.flow_shift}")
99
+ self.logger.info(f"Inference with {self.weight_dtype}")
100
+
101
+ self.num_conditions = len(config.conditions)
102
+
103
+ # 1. build vae and text encoder
104
+ self.vae = self.build_vae(config.vae)
105
+ self.tokenizer, self.text_encoder = self.build_text_encoder(config.text_encoder)
106
+
107
+ # 2. build Jodi
108
+ self.model = self.build_jodi(config).to(self.device)
109
+
110
+ # 3. pre-compute null embedding
111
+ with torch.no_grad():
112
+ null_caption_token = self.tokenizer(
113
+ "", max_length=self.max_sequence_length, padding="max_length", truncation=True, return_tensors="pt"
114
+ ).to(self.device)
115
+ self.null_caption_embs = self.text_encoder(
116
+ null_caption_token.input_ids, null_caption_token.attention_mask
117
+ )[0]
118
+
119
+ @property
120
+ def base_ratios(self):
121
+ return {
122
+ "0.25": [512.0, 2048.0], # 1:4
123
+ "0.33": [576.0, 1728.0], # 1:3
124
+ "0.4": [640.0, 1600.0], # 2:5
125
+ "0.5": [704.0, 1408.0], # 1:2
126
+ "0.67": [768.0, 1152.0], # 2:3
127
+ "0.75": [864.0, 1152.0], # 3:4
128
+ "0.82": [896.0, 1088.0], # 5:6
129
+ "1.0": [1024.0, 1024.0], # 1:1
130
+ "1.21": [1088.0, 896.0], # 6:5
131
+ "1.33": [1152.0, 864.0], # 4:3
132
+ "1.5": [1152.0, 768.0], # 3:2
133
+ "2.0": [1408.0, 704.0], # 2:1
134
+ "2.5": [1600.0, 640.0], # 5:2
135
+ "3.0": [1728.0, 576.0], # 3:1
136
+ "4.0": [2048.0, 512.0], # 4:1
137
+ }
138
+
139
+ def build_vae(self, config):
140
+ vae = get_vae(config.vae_type, config.vae_pretrained, self.device).to(self.vae_dtype)
141
+ return vae
142
+
143
+ def build_text_encoder(self, config):
144
+ tokenizer, text_encoder = get_tokenizer_and_text_encoder(name=config.text_encoder_name, device=self.device)
145
+ return tokenizer, text_encoder
146
+
147
+ def build_jodi(self, config):
148
+ # model setting
149
+ model_kwargs = model_init_config(config, latent_size=self.latent_size)
150
+ model = build_model(
151
+ config.model.model,
152
+ use_fp32_attention=config.model.get("fp32_attention", False) and config.model.mixed_precision != "bf16",
153
+ num_conditions=self.num_conditions,
154
+ **model_kwargs,
155
+ )
156
+ self.logger.info(f"use_fp32_attention: {model.fp32_attention}")
157
+ self.logger.info(
158
+ f"{model.__class__.__name__}:{config.model.model},"
159
+ f"Model Parameters: {sum(p.numel() for p in model.parameters()):,}"
160
+ )
161
+ return model
162
+
163
+ def from_pretrained(self, model_path):
164
+ state_dict = find_model(model_path)
165
+ state_dict = state_dict.get("state_dict", state_dict)
166
+ if "pos_embed" in state_dict:
167
+ del state_dict["pos_embed"]
168
+ missing, unexpected = self.model.load_state_dict(state_dict, strict=False)
169
+ self.model.eval().to(self.weight_dtype)
170
+
171
+ self.logger.info(f"Generating sample from ckpt: {model_path}")
172
+ self.logger.warning(f"Missing keys: {missing}")
173
+ self.logger.warning(f"Unexpected keys: {unexpected}")
174
+
175
+ def register_progress_bar(self, progress_fn=None):
176
+ self.progress_fn = progress_fn if progress_fn is not None else self.progress_fn
177
+
178
+ @torch.inference_mode()
179
+ def __call__(
180
+ self,
181
+ images,
182
+ role,
183
+ prompt="",
184
+ height=1024,
185
+ width=1024,
186
+ negative_prompt="",
187
+ num_inference_steps=20,
188
+ guidance_scale=4.5,
189
+ num_images_per_prompt=1,
190
+ generator=None,
191
+ latents=None,
192
+ ):
193
+ ori_height, ori_width = height, width
194
+ height, width = classify_height_width_bin(height, width, ratios=self.base_ratios)
195
+ latent_size_h, latent_size_w = (
196
+ height // self.config.vae.vae_downsample_rate,
197
+ width // self.config.vae.vae_downsample_rate,
198
+ )
199
+
200
+ # pre-compute negative embedding
201
+ if negative_prompt != "":
202
+ null_caption_token = self.tokenizer(
203
+ negative_prompt,
204
+ max_length=self.max_sequence_length,
205
+ padding="max_length",
206
+ truncation=True,
207
+ return_tensors="pt",
208
+ ).to(self.device)
209
+ self.null_caption_embs = self.text_encoder(
210
+ null_caption_token.input_ids, null_caption_token.attention_mask
211
+ )[0]
212
+
213
+ # compute clean_x
214
+ if len(images) != 1 + self.num_conditions:
215
+ raise ValueError(f"Number of images {len(images)} != {1 + self.num_conditions}.")
216
+ if len(role) != 1 + self.num_conditions:
217
+ raise ValueError(f"Number of roles {len(role)} != {1 + self.num_conditions}.")
218
+ clean_x = [
219
+ torch.zeros(
220
+ 1,
221
+ self.config.vae.vae_latent_dim,
222
+ latent_size_h,
223
+ latent_size_w,
224
+ device=self.device,
225
+ dtype=self.vae_dtype,
226
+ )
227
+ ] * (self.num_conditions + 1)
228
+ for i, image in enumerate(images):
229
+ if role[i] == 1:
230
+ assert image is not None
231
+ image = read_image(image).unsqueeze(0).to(self.device, self.vae_dtype)
232
+
233
+ image_height, image_width = image.shape[-2:]
234
+ if height / image_height > width / image_width:
235
+ resize_size = height, int(image_width * height / image_height)
236
+ else:
237
+ resize_size = int(image_height * width / image_width), width
238
+
239
+ resize_and_crop = T.Compose([
240
+ T.Resize(resize_size, interpolation=T.InterpolationMode.BILINEAR, antialias=True),
241
+ T.CenterCrop((height, width)),
242
+ ])
243
+ image = resize_and_crop(image)
244
+ clean_x[i] = vae_encode(
245
+ self.config.vae.vae_type, self.vae, image, self.config.vae.sample_posterior, self.device
246
+ )
247
+ clean_x = torch.stack(clean_x, dim=1) # (1, 1+K, 32, 32, 32)
248
+ role = torch.tensor(role).unsqueeze(0) # (1, 1+K)
249
+ role = role.to(dtype=torch.long, device=self.device)
250
+
251
+ prompts = [
252
+ prepare_prompt_ar(prompt, self.base_ratios, device=self.device, show=False)[0].strip()
253
+ for _ in range(num_images_per_prompt)
254
+ ]
255
+
256
+ with torch.no_grad():
257
+ # prepare text feature
258
+ if not self.config.text_encoder.chi_prompt:
259
+ max_length_all = self.config.text_encoder.model_max_length
260
+ prompts_all = prompts
261
+ else:
262
+ chi_prompt = "\n".join(self.config.text_encoder.chi_prompt)
263
+ prompts_all = [chi_prompt + prompt for prompt in prompts]
264
+ num_chi_prompt_tokens = len(self.tokenizer.encode(chi_prompt))
265
+ max_length_all = (
266
+ num_chi_prompt_tokens + self.config.text_encoder.model_max_length - 2
267
+ ) # magic number 2: [bos], [_]
268
+
269
+ caption_token = self.tokenizer(
270
+ prompts_all,
271
+ max_length=max_length_all,
272
+ padding="max_length",
273
+ truncation=True,
274
+ return_tensors="pt",
275
+ ).to(device=self.device)
276
+ select_index = [0] + list(range(-self.config.text_encoder.model_max_length + 1, 0))
277
+ caption_embs = self.text_encoder(caption_token.input_ids, caption_token.attention_mask)[0][:, None][
278
+ :, :, select_index
279
+ ].to(self.weight_dtype)
280
+ emb_masks = caption_token.attention_mask[:, select_index]
281
+ null_y = self.null_caption_embs.repeat(len(prompts), 1, 1)[:, None].to(self.weight_dtype)
282
+
283
+ n = len(prompts)
284
+ if latents is None:
285
+ z = torch.randn(
286
+ n,
287
+ 1 + self.num_conditions,
288
+ self.config.vae.vae_latent_dim,
289
+ latent_size_h,
290
+ latent_size_w,
291
+ generator=generator,
292
+ device=self.device,
293
+ )
294
+ else:
295
+ assert latents.shape == (
296
+ n,
297
+ 1 + self.num_conditions,
298
+ self.config.vae.vae_latent_dim,
299
+ latent_size_h,
300
+ latent_size_w,
301
+ )
302
+ z = latents.to(self.device)
303
+ role = role.repeat(n, 1)
304
+ clean_x = clean_x.repeat(n, 1, 1, 1, 1)
305
+
306
+ model_kwargs = dict(mask=emb_masks, role=role, clean_x=clean_x)
307
+ scheduler = DPMS(
308
+ self.model,
309
+ condition=caption_embs,
310
+ uncondition=null_y,
311
+ cfg_scale=guidance_scale,
312
+ model_type="flow",
313
+ model_kwargs=model_kwargs,
314
+ schedule="FLOW",
315
+ )
316
+ scheduler.register_progress_bar(self.progress_fn)
317
+ sample = scheduler.sample(
318
+ z,
319
+ steps=num_inference_steps,
320
+ order=2,
321
+ skip_type="time_uniform_flow",
322
+ method="multistep",
323
+ flow_shift=self.flow_shift,
324
+ )
325
+
326
+ sample = torch.where(torch.eq(role, 1)[:, :, None, None, None], clean_x, sample)
327
+ sample = sample.to(self.vae_dtype)
328
+ sample = torch.unbind(sample, dim=1)
329
+ with torch.no_grad():
330
+ sample = [vae_decode(self.config.vae.vae_type, self.vae, s) for s in sample]
331
+ resize = T.Resize((ori_height, ori_width), interpolation=T.InterpolationMode.BILINEAR)
332
+ sample = [resize(s).clamp(-1, 1) for s in sample]
333
+ return sample
old_code/test_realworldqa_vqa.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png"]:
94
+ image_path = str(root_path)
95
+ text_prompt = (
96
+ f"You are given one RGB image and a text description of the same scene.\n"
97
+ f"Scene description: \"{prompt}\"\n\n"
98
+ f"Now analyze the image carefully and answer the following question based only on what is visible.\n"
99
+ f"Do NOT guess or add details not supported by the image.\n"
100
+ f"Question: \"{question}\"\n"
101
+ "<image>"
102
+ )
103
+ messages = [
104
+ {
105
+ "role": "user",
106
+ "content": [
107
+ {"type": "image", "image": image_path},
108
+ {"type": "text", "text": text_prompt},
109
+ ],
110
+ }
111
+ ]
112
+ return messages
113
+
114
+ # ---------- 多模态文件夹情况 ----------
115
+ modality_names = [
116
+ "image",
117
+ "annotation_lineart",
118
+ "annotation_edge",
119
+ "annotation_depth",
120
+ "annotation_normal",
121
+ "annotation_albedo",
122
+ "annotation_seg_12colors",
123
+ "annotation_openpose",
124
+ ]
125
+
126
+ # 检查存在的模态文件
127
+ available = []
128
+ for name in modality_names:
129
+ for ext in [".png", ".jpg", ".jpeg"]:
130
+ path = Path(root) / f"{name}{ext}"
131
+ if path.exists():
132
+ available.append((name, str(path)))
133
+ break
134
+
135
+ # 可读名称映射
136
+ readable_map = {
137
+ "image": "RGB image",
138
+ "annotation_lineart": "line drawing",
139
+ "annotation_edge": "edge map",
140
+ "annotation_depth": "depth map",
141
+ "annotation_normal": "normal map",
142
+ "annotation_albedo": "albedo map",
143
+ "annotation_seg_12colors": "segmentation map",
144
+ "annotation_openpose": "human pose map",
145
+ }
146
+
147
+ present_modalities = [readable_map[n] for n, _ in available]
148
+
149
+ # ---------- 指令文本 ----------
150
+ text_prompt = (
151
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
152
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
153
+ f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
154
+ f"so use them only as optional references for additional context. "
155
+ f"Each modality provides complementary information about the same visual content:\n"
156
+ f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
157
+ f"- The edge map emphasizes boundaries and contours.\n"
158
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
159
+ f"- The normal map shows surface orientation and geometric curvature.\n"
160
+ f"- The albedo map presents true surface color without illumination or shadows.\n"
161
+ f"- The segmentation map divides the scene into semantic regions and object categories.\n"
162
+ f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
163
+ f"Together, these modalities offer a unified, rich understanding of the scene.\n"
164
+ f"Scene description: \"{prompt}\"\n\n"
165
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
166
+ f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
167
+ f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
168
+ f"Question: \"{question}\"\n"
169
+ )
170
+
171
+ # ---------- 构建内容序列(模态锚定) ----------
172
+ content = []
173
+ for name, path in available:
174
+ readable = readable_map.get(name, "visual input")
175
+ # 在每张图像前显式标注模态类型
176
+ content.append({"type": "text", "text": f"This is the {readable}."})
177
+ content.append({"type": "image", "image": path})
178
+
179
+ # 最后加入主指令
180
+ content.append({"type": "text", "text": text_prompt})
181
+
182
+ messages = [{"role": "user", "content": content}]
183
+ return messages
184
+
185
+
186
+
187
+
188
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
189
+ """
190
+ Build Qwen3-VL message for multi-modal caption refinement.
191
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
192
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
193
+ """
194
+
195
+ modality_names = [
196
+ "image",
197
+ "annotation_lineart",
198
+ "annotation_edge",
199
+ "annotation_depth",
200
+ "annotation_normal",
201
+ "annotation_albedo",
202
+ "annotation_seg_12colors",
203
+ "annotation_openpose",
204
+ ]
205
+
206
+ # --- 检查存在的模态 ---
207
+ available = []
208
+ for name in modality_names:
209
+ for ext in [".png", ".jpg", ".jpeg"]:
210
+ path = Path(root) / f"{name}{ext}"
211
+ if path.exists():
212
+ available.append((name, str(path)))
213
+ break
214
+
215
+ # --- 构建模态说明 ---
216
+ readable_map = {
217
+ "image": "RGB image",
218
+ "annotation_lineart": "line drawing",
219
+ "annotation_edge": "edge map",
220
+ "annotation_depth": "depth map",
221
+ "annotation_normal": "normal map",
222
+ "annotation_albedo": "albedo map",
223
+ "annotation_seg_12colors": "segmentation map",
224
+ "annotation_openpose": "human pose map",
225
+ }
226
+
227
+ present_modalities = [readable_map[n] for n, _ in available]
228
+
229
+ # --- 构造文本指令 ---
230
+
231
+ # --- 构建消息内容:在每个图像前加模态标识 ---
232
+
233
+
234
+ content = []
235
+
236
+ text_prompt = ("you are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}.\n"
237
+ f"Each modality provides a different aspect of visual information about the same scene.\n\n"
238
+ f"### Modality Information:\n"
239
+ f"- **RGB image:** shows colors, textures, lighting, and overall appearance.\n"
240
+ f"- **Line drawing:** reveals outlines, object contours, and structural details.\n"
241
+ f"- **Edge map:** highlights strong edges and object boundaries.\n"
242
+ f"- **Depth map:** encodes per-object spatial distance and perspective. "
243
+ f"For each main object, estimate its approximate physical distance from the camera or ground reference "
244
+ f"in **meters**. "
245
+ f"If multiple objects are visible, provide numeric distances rather than qualitative terms like "
246
+ f"'closer' or 'farther'.\n"
247
+ f"- **Normal map:** provides surface orientation and facing direction.\n"
248
+ f"- **Albedo map:** shows true surface color unaffected by lighting or shadows.\n"
249
+ f"- **Segmentation map:** divides the image into semantic regions and object categories.\n"
250
+ f"- **Human pose map:** depicts human keypoints, poses, and orientations if present.\n\n"
251
+ f"### Your Task:\n"
252
+ f"Refine the coarse caption into a detailed, modality-wise visual description. "
253
+ f"For each available modality listed above, generate one corresponding description paragraph "
254
+ f"based only on what that modality shows.\n\n"
255
+ f"### Rules:\n"
256
+ f"1. Follow the order and modality names given in 'Modality Information'.\n"
257
+ f"2. Start each paragraph with the modality name (e.g., 'RGB image:').\n"
258
+ f"3. Describe only what is visible in that modality—do NOT merge or summarize multiple modalities.\n"
259
+ f"4. Use **numeric distance estimates in meters** for the depth map whenever possible.\n"
260
+ f"5. Use clear and factual language (no imagination or hallucination).\n"
261
+ #f"6. You may use the following feedback for improvement: '{feedback}'\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"Now, according to the 'Modality Information' above, write one detailed description for each available modality below."
264
+ )
265
+
266
+ for name, path in available:
267
+ readable = readable_map.get(name, "visual input")
268
+ content.append({
269
+ "type": "text",
270
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
271
+ })
272
+ content.append({"type": "image", "image": path})
273
+
274
+ # 最后附上总任务说明
275
+ content.append({"type": "text", "text": text_prompt})
276
+
277
+ messages = [{"role": "user", "content": content}]
278
+ return messages
279
+
280
+
281
+ def get_modality_description(name: str) -> str:
282
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
283
+ desc_map = {
284
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
285
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
286
+ "annotation_edge": "strong boundaries and contrast edges between objects",
287
+ "annotation_depth": "distance and perspective information for spatial understanding",
288
+ "annotation_normal": "surface orientation and geometric curvature cues",
289
+ "annotation_albedo": "pure surface color without lighting or shading effects",
290
+ "annotation_seg_12colors": "semantic regions and object categories",
291
+ "annotation_openpose": "human body keypoints, joints, and orientation",
292
+ }
293
+ return desc_map.get(name, "complementary visual evidence")
294
+
295
+
296
+
297
+
298
+ # ------------------------------
299
+ # Argument Parser
300
+ # ------------------------------
301
+ def get_parser():
302
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
303
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
304
+ help="Path to model checkpoint.")
305
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
306
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
307
+ help="Path to model checkpoint.")
308
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
309
+ help="Path to model checkpoint.")
310
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
311
+ help="Prompt text for generation.")
312
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
313
+ help="Optional negative prompt.")
314
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
317
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
318
+ help="Optional negative prompt.")
319
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
320
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
321
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
322
+ parser.add_argument("--seed", type=int, default=41)
323
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
324
+ return parser
325
+
326
+
327
+ # ------------------------------
328
+ # Main Inference Function
329
+ # ------------------------------
330
+
331
+ @torch.inference_mode()
332
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
333
+ messages = [
334
+ {
335
+ "role": "user",
336
+ "content": [
337
+ {
338
+ "type": "image",
339
+ "image": image_path,
340
+ },
341
+ {"type": "text", "text": f"Describe this image."},
342
+ ],
343
+ }
344
+ ]
345
+
346
+ inputs = processor.apply_chat_template(
347
+ messages,
348
+ tokenize=True,
349
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
350
+ )
351
+ inputs = inputs.to(model.device)
352
+
353
+ # Inference: Generation of the output
354
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
355
+ generated_ids_trimmed = [
356
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
357
+ ]
358
+ output_text = processor.batch_decode(
359
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
360
+ )
361
+ print(output_text)
362
+
363
+ os.makedirs(args.output_dir, exist_ok=True)
364
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
365
+ save_dir.mkdir(parents=True, exist_ok=True)
366
+ caption_path = Path(save_dir) / f"caption.txt"
367
+ with open(caption_path, "w", encoding="utf-8") as f:
368
+ f.write(output_text[0].strip())
369
+
370
+ return output_text[0]
371
+
372
+
373
+ @torch.inference_mode()
374
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
375
+
376
+ # --- 构造 Qwen 输入 ---
377
+ eval_prompt = f"""
378
+ You are an image-text alignment evaluator.
379
+ You are given one RGB image and a description that may include references
380
+ to multiple visual modalities (e.g., depth map, normal map, segmentation map, etc.).
381
+ These terms are just analytical perspectives of the same scene — they should not reduce
382
+ the consistency score. Focus only on whether the described visual content matches what
383
+ is visible in the RGB image.
384
+ Your task:
385
+ 1. Judge how accurately the text describes what is visually present in the image.
386
+ 2. Ignore mentions of modality names (such as 'depth map' or 'normal map').
387
+ 3. Provide a consistency score between 0.0 (completely mismatched) and 1.0 (perfect match).
388
+ 4. Provide one short feedback sentence suggesting how to make the description better aligned.
389
+ Return JSON strictly in this format:
390
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
391
+ Description: "{caption}"
392
+ <image>
393
+ """
394
+
395
+ messages = [
396
+ {
397
+ "role": "user",
398
+ "content": [
399
+ {"type": "image", "image": image_path},
400
+ {"type": "text", "text": eval_prompt},
401
+ ],
402
+ }
403
+ ]
404
+
405
+ # --- 推理 ---
406
+ inputs = processor.apply_chat_template(
407
+ messages,
408
+ tokenize=True,
409
+ add_generation_prompt=True,
410
+ return_dict=True,
411
+ return_tensors="pt"
412
+ ).to(model.device)
413
+
414
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
415
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
416
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
417
+
418
+ # --- 解析输出 ---
419
+ try:
420
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
421
+ score = float(data.get("Consistency", 0))
422
+ feedback = data.get("Feedback", "")
423
+ except Exception:
424
+ score, feedback = 0.0, text.strip()
425
+
426
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
427
+ return score, feedback
428
+
429
+
430
+ @torch.inference_mode()
431
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
432
+ messages = build_multimodal_message(root, prompt, feedback)
433
+ inputs = processor.apply_chat_template(
434
+ messages,
435
+ tokenize=True,
436
+ add_generation_prompt=True,
437
+ return_dict=True,
438
+ return_tensors="pt"
439
+ )
440
+ inputs = inputs.to(model.device)
441
+
442
+ # Inference: Generation of the output
443
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
444
+ generated_ids_trimmed = [
445
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
446
+ ]
447
+ output_text = processor.batch_decode(
448
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
449
+ )
450
+ print(output_text)
451
+
452
+ os.makedirs(args.output_dir, exist_ok=True)
453
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
454
+ save_dir.mkdir(parents=True, exist_ok=True)
455
+ caption_path = Path(save_dir) / f"caption.txt"
456
+ with open(caption_path, "w", encoding="utf-8") as f:
457
+ f.write(output_text[0].strip())
458
+ return output_text[0]
459
+
460
+ @torch.inference_mode()
461
+ def vqa(root, model, processor, prompt, question, vqa_id, max_length=300):
462
+ messages = build_vqa_message(root, prompt, question)
463
+ print(messages)
464
+ inputs = processor.apply_chat_template(
465
+ messages,
466
+ tokenize=True,
467
+ add_generation_prompt=True,
468
+ return_dict=True,
469
+ return_tensors="pt"
470
+ )
471
+ inputs = inputs.to(model.device)
472
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
473
+ generated_ids_trimmed = [
474
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
475
+ output_text = processor.batch_decode(
476
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
477
+ )
478
+ print(output_text)
479
+ os.makedirs(args.output_dir, exist_ok=True)
480
+ save_dir = Path(args.output_dir) / vqa_id / 'vqa_answer'
481
+ save_dir.mkdir(parents=True, exist_ok=True)
482
+ caption_path = Path(save_dir) / f"caption.txt"
483
+ with open(caption_path, "w", encoding="utf-8") as f:
484
+ f.write(output_text[0].strip())
485
+ return output_text[0]
486
+
487
+ @torch.inference_mode()
488
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
489
+ # print(f"🚀 Generating with prompt: {prompt}")
490
+ outputs = pipe(
491
+ images=images,
492
+ role=role,
493
+ prompt=prompt,
494
+ negative_prompt=args.negative_prompt,
495
+ height=height,
496
+ width=width,
497
+ num_inference_steps=args.steps,
498
+ guidance_scale=args.guidance_scale,
499
+ num_images_per_prompt=1,
500
+ generator=generator,
501
+ task='t2i'
502
+ )
503
+
504
+ # Apply post-processing for each modality
505
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
506
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
507
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
508
+
509
+ # --------------------------
510
+ # Save results
511
+ # --------------------------
512
+ os.makedirs(args.output_dir, exist_ok=True)
513
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
514
+ save_dir.mkdir(parents=True, exist_ok=True)
515
+ for idx, img in enumerate(results):
516
+ name = modality_names[idx]
517
+ save_path = save_dir / f"{name}.png"
518
+ img.save(save_path)
519
+ print(f"💾 Saved {name} → {save_path}")
520
+
521
+
522
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
523
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
524
+ print(f"\n✅ All results saved in: {save_dir}\n")
525
+ return save_dir
526
+
527
+ if __name__ == "__main__":
528
+ args = get_parser().parse_args()
529
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
530
+ print(f"✅ Using device: {device}")
531
+
532
+ processor = AutoProcessor.from_pretrained(
533
+ args.model_name_or_path,
534
+ )
535
+
536
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
537
+ args.text_model_path,
538
+ attn_implementation="flash_attention_2",
539
+ dtype=(torch.bfloat16),
540
+ ).to(device)
541
+
542
+ pipe = JodiPipeline(args.config)
543
+ pipe.from_pretrained(args.model_path)
544
+
545
+ modality_names = [
546
+ "image",
547
+ "annotation_lineart",
548
+ "annotation_edge",
549
+ "annotation_depth",
550
+ "annotation_normal",
551
+ "annotation_albedo",
552
+ "annotation_seg_12colors",
553
+ "annotation_openpose",
554
+ ]
555
+
556
+ # Build post-processors
557
+ post_processors: list[Any] = [ImagePostProcessor()]
558
+ for condition in pipe.config.conditions: # type: ignore
559
+ if condition == "lineart":
560
+ post_processors.append(LineartPostProcessor())
561
+ elif condition == "edge":
562
+ post_processors.append(EdgePostProcessor())
563
+ elif condition == "depth":
564
+ post_processors.append(DepthPostProcessor())
565
+ elif condition == "normal":
566
+ post_processors.append(NormalPostProcessor())
567
+ elif condition == "albedo":
568
+ post_processors.append(AlbedoPostProcessor())
569
+ elif condition == "segmentation":
570
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
571
+ elif condition == "openpose":
572
+ post_processors.append(OpenposePostProcessor())
573
+ else:
574
+ print(f"⚠️ Warning: Unknown condition: {condition}")
575
+ post_processors.append(ImagePostProcessor())
576
+
577
+ torch.manual_seed(args.seed)
578
+ generator = torch.Generator(device=device).manual_seed(args.seed)
579
+
580
+ with open(args.json, "r", encoding="utf-8") as f:
581
+ annotations = json.load(f)
582
+
583
+ for sample in annotations[1:255]:
584
+ image_path = os.path.join(args.data_path, sample["image"])
585
+ image_id = sample["image"].split('.')[0]
586
+ image = Image.open(image_path)
587
+ question = sample["question"]
588
+
589
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
590
+
591
+ role = [1] + [0] * pipe.num_conditions
592
+ print(role)
593
+
594
+ best_dir, best_caption, best_score = '', '', 0.0
595
+ max_length = 1024
596
+
597
+ # input_img = Image.open(image_path).convert("RGB")
598
+ width, height = image.size
599
+ print(f'ori width:{width}', f'ori height:{height}')
600
+
601
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
602
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
603
+
604
+ if score >= best_score:
605
+ best_caption, best_score = prompt, score
606
+ best_dir = image_path
607
+
608
+ for step in range(1, args.iters):
609
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
610
+ image_id)
611
+ max_length += 100
612
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
613
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
614
+
615
+ #if score >= best_score:
616
+ best_caption, best_score = prompt, score
617
+ best_dir = save_dir
618
+
619
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, max_length)
620
+ print(f'result:{result}')
old_code/test_realworldqa_vqa1.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[:153]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ generator = torch.Generator(device=device).manual_seed(args.seed)
657
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
658
+ image_id)
659
+ max_length += 100
660
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
661
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
662
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
663
+
664
+ if score >= best_score:
665
+ best_caption, best_score = prompt, score
666
+ best_dir = save_dir
667
+
668
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
669
+ print(f'result:{result}')
old_code/test_realworldqa_vqa2.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[153:306]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')
old_code/test_realworldqa_vqa3.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[306:459]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')
old_code/test_realworldqa_vqa4.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[459:612]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')
old_code/test_realworldqa_vqa5.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[612:]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')
qwen_real.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+ from PIL import Image
31
+ import json
32
+
33
+ def clean_question(q: str) -> str:
34
+ if not isinstance(q, str):
35
+ q = str(q)
36
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
37
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
38
+ # 再清理多余空白
39
+ q = re.sub(r"\s+", " ", q).strip()
40
+ return q
41
+
42
+ def dump_image(image, save_root):
43
+ os.makedirs(save_root, exist_ok=True)
44
+ save_path = os.path.join(save_root, "input.jpg")
45
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
46
+ return save_path
47
+
48
+
49
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
50
+ """
51
+ 将多个图像拼接成一张大图并保存。
52
+ Args:
53
+ image_paths: List[str] 图像路径列表
54
+ save_path: 保存路径(包括文件名)
55
+ images_per_row: 每行图像数量(默认为全部在一行)
56
+ image_format: 保存格式
57
+ """
58
+ from PIL import Image
59
+ import io
60
+
61
+ # 读取图像
62
+ images = [Image.open(p).convert("RGB") for p in image_paths]
63
+
64
+ if images_per_row is None:
65
+ images_per_row = len(images)
66
+
67
+ # 调整尺寸(可选)
68
+ target_size = min(1024, images[0].size[0])
69
+ images = [img.resize((target_size, target_size)) for img in images]
70
+
71
+ # 拼接
72
+ widths, heights = zip(*(img.size for img in images))
73
+ max_width = max(widths)
74
+ rows = (len(images) + images_per_row - 1) // images_per_row
75
+ total_height = sum(heights[:images_per_row]) * rows
76
+
77
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
78
+ y_offset = 0
79
+ for i in range(0, len(images), images_per_row):
80
+ row_imgs = images[i:i+images_per_row]
81
+ x_offset = 0
82
+ for img in row_imgs:
83
+ new_im.paste(img, (x_offset, y_offset))
84
+ x_offset += max_width
85
+ y_offset += heights[0]
86
+
87
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
88
+ new_im.save(save_path, format=image_format.upper())
89
+ print(f"🧩 Saved merged image → {save_path}")
90
+ return save_path
91
+
92
+
93
+ def build_vqa_message(root, prompt, question):
94
+ """
95
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
96
+ """
97
+ modality_names = [
98
+ "image",
99
+ "annotation_lineart",
100
+ "annotation_edge",
101
+ "annotation_depth",
102
+ "annotation_normal", "annotation_albedo",
103
+ "annotation_seg_12colors",
104
+ "annotation_openpose",
105
+ ]
106
+
107
+ # --- 检查存在的模态 ---
108
+ available = []
109
+ for name in modality_names: # 优先匹配 .png 或 .jpg
110
+ for ext in [".png", ".jpg", ".jpeg"]:
111
+ path = Path(root) / f"{name}{ext}"
112
+ if path.exists():
113
+ available.append(str(path))
114
+ break
115
+ # --- 构建模态说明 ---
116
+ readable_map = {
117
+ "image": "RGB image",
118
+ "annotation_lineart": "line drawing",
119
+ "annotation_edge": "edge map",
120
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
121
+ "annotation_albedo": "albedo map",
122
+ "annotation_seg_12colors": "segmentation map",
123
+ "annotation_openpose": "human pose map",
124
+ }
125
+
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Now, based on both the multimodal visual information and the given scene description, "
142
+ f"analyze the scene carefully to answer a question. "
143
+ f"Your analysis should proceed in two stages:\n\n"
144
+ f"**Stage 1 — Modality-wise Observation:**\n"
145
+ f"For each provided modality image, analyze what specific visual information it contributes "
146
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
147
+ f"such as color, shape, structure, spatial depth, or object positions. "
148
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow question: "
149
+ f"Question: \"{question}\" "
150
+ + " ".join(["<image>"] * len(available))
151
+ )
152
+
153
+ # --- 构建 Qwen3-VL 消息格式 ---
154
+ messages = [
155
+ {
156
+ "role": "user",
157
+ "content": [{"type": "image", "image": path} for path in available]
158
+ + [{"type": "text", "text": text_prompt}],
159
+ }
160
+ ]
161
+ return messages
162
+
163
+
164
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
165
+ """
166
+ Build Qwen3-VL message for multi-modal caption refinement.
167
+ Automatically detects available modalities under root.
168
+ """
169
+ modality_names = [
170
+ "image",
171
+ "annotation_lineart",
172
+ "annotation_edge",
173
+ "annotation_depth",
174
+ "annotation_normal",
175
+ "annotation_albedo",
176
+ "annotation_seg_12colors",
177
+ "annotation_openpose",
178
+ ]
179
+
180
+ # --- 检查存在的模态 ---
181
+ available = []
182
+ for name in modality_names:
183
+ # 优先匹配 .png 或 .jpg
184
+ for ext in [".png", ".jpg", ".jpeg"]:
185
+ path = Path(root) / f"{name}{ext}"
186
+ if path.exists():
187
+ available.append(str(path))
188
+ break
189
+
190
+ # --- 构建模态说明 ---
191
+ readable_map = {
192
+ "image": "RGB image",
193
+ "annotation_lineart": "line drawing",
194
+ "annotation_edge": "edge map",
195
+ "annotation_depth": "depth map",
196
+ "annotation_normal": "normal map",
197
+ "annotation_albedo": "albedo map",
198
+ "annotation_seg_12colors": "segmentation map",
199
+ "annotation_openpose": "human pose map",
200
+ }
201
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
202
+
203
+ # --- 构造文本指令 ---
204
+ text_prompt = (
205
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
206
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
207
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
208
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
209
+ f"- The edge map highlights object boundaries and contours. "
210
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
211
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
212
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
213
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
214
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
215
+ f"For each provided modality image, analyze it according to the above definitions and describe "
216
+ f"the specific visual information it contributes in this particular case. "
217
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
218
+ f"Do NOT describe each modality separately or mention modality names. "
219
+ f"Focus on merging their information into a single coherent image description. "
220
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
221
+ f"Refine the coarse caption into a more detailed and accurate image description. "
222
+ f"Coarse caption: '{coarse_caption}' " +
223
+ " ".join(["<image>"] * len(available))
224
+ )
225
+
226
+ # --- 构建 Qwen3-VL 消息格式 ---
227
+ messages = [
228
+ {
229
+ "role": "user",
230
+ "content": [{"type": "image", "image": path} for path in available]
231
+ + [{"type": "text", "text": text_prompt}],
232
+ }
233
+ ]
234
+ return messages
235
+
236
+ # ------------------------------
237
+ # Argument Parser
238
+ # ------------------------------
239
+ def get_parser():
240
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
241
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
242
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
243
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
244
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
245
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images", help="Prompt text for generation.")
246
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json", help="Optional negative prompt.")
247
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
248
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
249
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
250
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
251
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
252
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
253
+ parser.add_argument("--seed", type=int, default=1234)
254
+ parser.add_argument("--output_dir", type=str, default="./qwen_realworld_outputs", help="Directory to save results.")
255
+ return parser
256
+
257
+
258
+ # ------------------------------
259
+ # Main Inference Function
260
+ # ------------------------------
261
+
262
+ @torch.inference_mode()
263
+ def init_i2t(model, processor, image_path, question, vqa_id, max_length=300):
264
+ messages = [
265
+ {
266
+ "role": "user",
267
+ "content": [
268
+ {
269
+ "type": "image",
270
+ "image": image_path,
271
+ },
272
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
273
+ ],
274
+ }
275
+ ]
276
+
277
+ print(messages)
278
+
279
+ inputs = processor.apply_chat_template(
280
+ messages,
281
+ tokenize=True,
282
+ add_generation_prompt=True,
283
+ return_dict=True,
284
+ return_tensors="pt"
285
+ )
286
+ inputs = inputs.to(model.device)
287
+
288
+ # Inference: Generation of the output
289
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
290
+ generated_ids_trimmed = [
291
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
292
+ ]
293
+ output_text = processor.batch_decode(
294
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
295
+ )
296
+ print(output_text)
297
+
298
+ os.makedirs(args.output_dir, exist_ok=True)
299
+ save_dir = Path(args.output_dir) / str(vqa_id)
300
+ save_dir.mkdir(parents=True, exist_ok=True)
301
+ caption_path = Path(save_dir) / f"caption.txt"
302
+ with open(caption_path, "w", encoding="utf-8") as f:
303
+ f.write(output_text[0].strip())
304
+
305
+ return output_text[0]
306
+
307
+ @torch.inference_mode()
308
+ def text_refine(root, model, processor, prompt, iter_num, vqa_id, max_length=300):
309
+ messages = build_multimodal_message(root, prompt)
310
+ inputs = processor.apply_chat_template(
311
+ messages,
312
+ tokenize=True,
313
+ add_generation_prompt=True,
314
+ return_dict=True,
315
+ return_tensors="pt"
316
+ )
317
+ inputs = inputs.to(model.device)
318
+
319
+ # Inference: Generation of the output
320
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
321
+ generated_ids_trimmed = [
322
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
323
+ ]
324
+ output_text = processor.batch_decode(
325
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
326
+ )
327
+ print(output_text)
328
+
329
+ os.makedirs(args.output_dir, exist_ok=True)
330
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
331
+ save_dir.mkdir(parents=True, exist_ok=True)
332
+ caption_path = Path(save_dir) / f"caption.txt"
333
+ with open(caption_path, "w", encoding="utf-8") as f:
334
+ f.write(output_text[0].strip())
335
+
336
+ return output_text[0]
337
+
338
+ @torch.inference_mode()
339
+ def vqa(root, model, processor, prompt, question, vqa_id, max_length=300):
340
+ messages = build_vqa_message(root, prompt, question)
341
+ print(messages)
342
+ inputs = processor.apply_chat_template(
343
+ messages,
344
+ tokenize=True,
345
+ add_generation_prompt=True,
346
+ return_dict=True,
347
+ return_tensors="pt"
348
+ )
349
+ inputs = inputs.to(model.device)
350
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
351
+ generated_ids_trimmed = [
352
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
353
+ output_text = processor.batch_decode(
354
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
355
+ )
356
+ print(output_text)
357
+ os.makedirs(args.output_dir, exist_ok=True)
358
+ save_dir = Path(args.output_dir) / vqa_id / 'vqa_answer'
359
+ save_dir.mkdir(parents=True, exist_ok=True)
360
+ caption_path = Path(save_dir) / f"caption.txt"
361
+ with open(caption_path, "w", encoding="utf-8") as f:
362
+ f.write(output_text[0].strip())
363
+ return output_text[0]
364
+
365
+ @torch.inference_mode()
366
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
367
+
368
+ print(f"🚀 Generating with prompt: {prompt}")
369
+ outputs = pipe(
370
+ images=images,
371
+ role=role,
372
+ prompt=prompt,
373
+ negative_prompt=args.negative_prompt,
374
+ height=height,
375
+ width=width,
376
+ num_inference_steps=args.steps,
377
+ guidance_scale=args.guidance_scale,
378
+ num_images_per_prompt=1,
379
+ generator=generator,
380
+ task='t2i'
381
+ )
382
+
383
+ # Apply post-processing for each modality
384
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
385
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
386
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
387
+
388
+ # --------------------------
389
+ # Save results
390
+ # --------------------------
391
+ os.makedirs(args.output_dir, exist_ok=True)
392
+
393
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
394
+ save_dir.mkdir(parents=True, exist_ok=True)
395
+
396
+ for idx, img in enumerate(results):
397
+ name = modality_names[idx]
398
+ save_path = save_dir / f"{name}.png"
399
+ img.save(save_path)
400
+ print(f"💾 Saved {name} → {save_path}")
401
+
402
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
403
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
404
+
405
+ print(f"\n✅ All results saved in: {save_dir}\n")
406
+ return save_dir
407
+
408
+
409
+ # ------------------------------
410
+ # Entry Point
411
+ # ------------------------------
412
+ if __name__ == "__main__":
413
+ args = get_parser().parse_args()
414
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
415
+ print(f"✅ Using device: {device}")
416
+
417
+ processor = AutoProcessor.from_pretrained(
418
+ args.model_name_or_path,
419
+ )
420
+
421
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
422
+ args.text_model_path,
423
+ attn_implementation="flash_attention_2",
424
+ dtype=(torch.bfloat16),
425
+ ).to(device)
426
+
427
+
428
+ torch.manual_seed(args.seed)
429
+ generator = torch.Generator(device=device).manual_seed(args.seed)
430
+
431
+ with open(args.json, "r", encoding="utf-8") as f:
432
+ annotations = json.load(f)
433
+
434
+ for sample in annotations:
435
+
436
+ image_path = os.path.join(args.data_path, sample["image"])
437
+ image_id = sample["image"].split('.')[0]
438
+ image = Image.open(image_path)
439
+ question = sample["question"]
440
+
441
+ max_length = 1024
442
+
443
+ #input_img = Image.open(image_path).convert("RGB")
444
+ width, height = image.size
445
+ print(f'ori width:{width}', f'ori height:{height}')
446
+
447
+ prompt = init_i2t(model, processor, image_path, question, image_id, max_length)
448
+
449
+
qwen_vqa_Agricultur.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+
31
+ def clean_question(q: str) -> str:
32
+ if not isinstance(q, str):
33
+ q = str(q)
34
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
35
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
36
+ # 再清理多余空白
37
+ q = re.sub(r"\s+", " ", q).strip()
38
+ return q
39
+
40
+ def dump_image(image, save_root):
41
+ os.makedirs(save_root, exist_ok=True)
42
+ save_path = os.path.join(save_root, "input.jpg")
43
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
44
+ return save_path
45
+
46
+
47
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
48
+ """
49
+ 将多个图像拼接成一张大图并保存。
50
+ Args:
51
+ image_paths: List[str] 图像路径列表
52
+ save_path: 保存路径(包括文件名)
53
+ images_per_row: 每行图像数量(默认为全部在一行)
54
+ image_format: 保存格式
55
+ """
56
+ from PIL import Image
57
+ import io
58
+
59
+ # 读取图像
60
+ images = [Image.open(p).convert("RGB") for p in image_paths]
61
+
62
+ if images_per_row is None:
63
+ images_per_row = len(images)
64
+
65
+ # 调整尺寸(可选)
66
+ target_size = min(1024, images[0].size[0])
67
+ images = [img.resize((target_size, target_size)) for img in images]
68
+
69
+ # 拼接
70
+ widths, heights = zip(*(img.size for img in images))
71
+ max_width = max(widths)
72
+ rows = (len(images) + images_per_row - 1) // images_per_row
73
+ total_height = sum(heights[:images_per_row]) * rows
74
+
75
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
76
+ y_offset = 0
77
+ for i in range(0, len(images), images_per_row):
78
+ row_imgs = images[i:i+images_per_row]
79
+ x_offset = 0
80
+ for img in row_imgs:
81
+ new_im.paste(img, (x_offset, y_offset))
82
+ x_offset += max_width
83
+ y_offset += heights[0]
84
+
85
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
86
+ new_im.save(save_path, format=image_format.upper())
87
+ print(f"🧩 Saved merged image → {save_path}")
88
+ return save_path
89
+
90
+
91
+ def build_vqa_message(root, prompt, question, options, subfield):
92
+ """
93
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
94
+ """
95
+ modality_names = [
96
+ "image",
97
+ "annotation_lineart",
98
+ "annotation_edge",
99
+ "annotation_depth",
100
+ "annotation_normal", "annotation_albedo",
101
+ "annotation_seg_12colors",
102
+ "annotation_openpose",
103
+ ]
104
+
105
+ # --- 检查存在的模态 ---
106
+ available = []
107
+ for name in modality_names: # 优先匹配 .png 或 .jpg
108
+ for ext in [".png", ".jpg", ".jpeg"]:
109
+ path = Path(root) / f"{name}{ext}"
110
+ if path.exists():
111
+ available.append(str(path))
112
+ break
113
+ # --- 构建模态说明 ---
114
+ readable_map = {
115
+ "image": "RGB image",
116
+ "annotation_lineart": "line drawing",
117
+ "annotation_edge": "edge map",
118
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
119
+ "annotation_albedo": "albedo map",
120
+ "annotation_seg_12colors": "segmentation map",
121
+ "annotation_openpose": "human pose map",
122
+ }
123
+
124
+ options_list = ast.literal_eval(options)
125
+ option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)])
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Scientific Subfield: \"{subfield}\" "
142
+ f"Now, based on both the multimodal visual information and the given scene description, "
143
+ f"analyze the scene carefully to answer a question. "
144
+ f"Your analysis should proceed in two stages:\n\n"
145
+ f"**Stage 1 — Modality-wise Observation:**\n"
146
+ f"For each provided modality image, analyze what specific visual information it contributes "
147
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
148
+ f"such as color, shape, structure, spatial depth, or object positions. "
149
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: "
150
+ f"Question: \"{question}\" "
151
+ f"Options: \"{option_text}\" "
152
+ + " ".join(["<image>"] * len(available))
153
+ )
154
+
155
+ # --- 构建 Qwen3-VL 消息格式 ---
156
+ messages = [
157
+ {
158
+ "role": "user",
159
+ "content": [{"type": "image", "image": path} for path in available]
160
+ + [{"type": "text", "text": text_prompt}],
161
+ }
162
+ ]
163
+ return messages
164
+
165
+
166
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
167
+ """
168
+ Build Qwen3-VL message for multi-modal caption refinement.
169
+ Automatically detects available modalities under root.
170
+ """
171
+ modality_names = [
172
+ "image",
173
+ "annotation_lineart",
174
+ "annotation_edge",
175
+ "annotation_depth",
176
+ "annotation_normal",
177
+ "annotation_albedo",
178
+ "annotation_seg_12colors",
179
+ "annotation_openpose",
180
+ ]
181
+
182
+ # --- 检查存在的模态 ---
183
+ available = []
184
+ for name in modality_names:
185
+ # 优先匹配 .png 或 .jpg
186
+ for ext in [".png", ".jpg", ".jpeg"]:
187
+ path = Path(root) / f"{name}{ext}"
188
+ if path.exists():
189
+ available.append(str(path))
190
+ break
191
+
192
+ # --- 构建模态说明 ---
193
+ readable_map = {
194
+ "image": "RGB image",
195
+ "annotation_lineart": "line drawing",
196
+ "annotation_edge": "edge map",
197
+ "annotation_depth": "depth map",
198
+ "annotation_normal": "normal map",
199
+ "annotation_albedo": "albedo map",
200
+ "annotation_seg_12colors": "segmentation map",
201
+ "annotation_openpose": "human pose map",
202
+ }
203
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
204
+
205
+ # --- 构造文本指令 ---
206
+ text_prompt = (
207
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
208
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
209
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
210
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
211
+ f"- The edge map highlights object boundaries and contours. "
212
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
213
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
214
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
215
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
216
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
217
+ f"For each provided modality image, analyze it according to the above definitions and describe "
218
+ f"the specific visual information it contributes in this particular case. "
219
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
220
+ f"Do NOT describe each modality separately or mention modality names. "
221
+ f"Focus on merging their information into a single coherent image description. "
222
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
223
+ f"Refine the coarse caption into a more detailed and accurate image description. "
224
+ f"Coarse caption: '{coarse_caption}' " +
225
+ " ".join(["<image>"] * len(available))
226
+ )
227
+
228
+ # --- 构建 Qwen3-VL 消息格式 ---
229
+ messages = [
230
+ {
231
+ "role": "user",
232
+ "content": [{"type": "image", "image": path} for path in available]
233
+ + [{"type": "text", "text": text_prompt}],
234
+ }
235
+ ]
236
+ return messages
237
+
238
+ # ------------------------------
239
+ # Argument Parser
240
+ # ------------------------------
241
+ def get_parser():
242
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
243
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
244
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
245
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
246
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
247
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/MMMU/Agriculture/validation-00000-of-00001.parquet", help="Prompt text for generation.")
248
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
249
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
250
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
251
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
252
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
253
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
254
+ parser.add_argument("--seed", type=int, default=1234)
255
+ parser.add_argument("--output_dir", type=str, default="./qwen_Agricultur_outputs", help="Directory to save results.")
256
+ return parser
257
+
258
+
259
+ # ------------------------------
260
+ # Main Inference Function
261
+ # ------------------------------
262
+
263
+ @torch.inference_mode()
264
+ def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300):
265
+
266
+ options_list = ast.literal_eval(option)
267
+ option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)])
268
+
269
+ question = clean_question(question)
270
+
271
+ text_prompt = (
272
+ f"Analyze the given image <image> and answer the following question."
273
+ f"Question: \"{question}\" \n"
274
+ f"Options: \"{option_text}\" "
275
+ )
276
+
277
+ messages = [
278
+ {
279
+ "role": "user",
280
+ "content": [
281
+ {
282
+ "type": "image",
283
+ "image": image_path,
284
+ },
285
+ {"type": "text", "text": text_prompt},
286
+ ],
287
+ }
288
+ ]
289
+
290
+ print(messages)
291
+
292
+ inputs = processor.apply_chat_template(
293
+ messages,
294
+ tokenize=True,
295
+ add_generation_prompt=True,
296
+ return_dict=True,
297
+ return_tensors="pt"
298
+ )
299
+ inputs = inputs.to(model.device)
300
+
301
+ # Inference: Generation of the output
302
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
303
+ generated_ids_trimmed = [
304
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
305
+ ]
306
+ output_text = processor.batch_decode(
307
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
308
+ )
309
+ print(output_text)
310
+
311
+ os.makedirs(args.output_dir, exist_ok=True)
312
+ save_dir = Path(args.output_dir) / vqa_id
313
+ save_dir.mkdir(parents=True, exist_ok=True)
314
+ caption_path = Path(save_dir) / f"caption.txt"
315
+ with open(caption_path, "w", encoding="utf-8") as f:
316
+ f.write(output_text[0].strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
322
+ messages = build_multimodal_message(root, prompt)
323
+ inputs = processor.apply_chat_template(
324
+ messages,
325
+ tokenize=True,
326
+ add_generation_prompt=True,
327
+ return_dict=True,
328
+ return_tensors="pt"
329
+ )
330
+ inputs = inputs.to(model.device)
331
+
332
+ # Inference: Generation of the output
333
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
334
+ generated_ids_trimmed = [
335
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
336
+ ]
337
+ output_text = processor.batch_decode(
338
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
339
+ )
340
+ print(output_text)
341
+
342
+ os.makedirs(args.output_dir, exist_ok=True)
343
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
344
+ save_dir.mkdir(parents=True, exist_ok=True)
345
+ caption_path = Path(save_dir) / f"caption.txt"
346
+ with open(caption_path, "w", encoding="utf-8") as f:
347
+ f.write(output_text[0].strip())
348
+
349
+ return output_text[0]
350
+
351
+ @torch.inference_mode()
352
+ def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300):
353
+ messages = build_vqa_message(root, prompt, question, options, subfield)
354
+ print(messages)
355
+ inputs = processor.apply_chat_template(
356
+ messages,
357
+ tokenize=True,
358
+ add_generation_prompt=True,
359
+ return_dict=True,
360
+ return_tensors="pt"
361
+ )
362
+ inputs = inputs.to(model.device)
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
366
+ output_text = processor.batch_decode(
367
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
368
+ )
369
+ print(output_text)
370
+ os.makedirs(args.output_dir, exist_ok=True)
371
+ save_dir = Path(args.output_dir) / vqa_id
372
+ save_dir.mkdir(parents=True, exist_ok=True)
373
+ caption_path = Path(save_dir) / f"caption.txt"
374
+ with open(caption_path, "w", encoding="utf-8") as f:
375
+ f.write(output_text[0].strip())
376
+ return output_text[0]
377
+
378
+ @torch.inference_mode()
379
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield):
380
+
381
+ print(f"🚀 Generating with prompt: {prompt}")
382
+ prompt = f'{subfield} image,' + ' ' + prompt
383
+ outputs = pipe(
384
+ images=images,
385
+ role=role,
386
+ prompt=prompt,
387
+ negative_prompt=args.negative_prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=args.steps,
391
+ guidance_scale=args.guidance_scale,
392
+ num_images_per_prompt=1,
393
+ generator=generator,
394
+ task='t2i'
395
+ )
396
+
397
+ # Apply post-processing for each modality
398
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
399
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
400
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
401
+
402
+ # --------------------------
403
+ # Save results
404
+ # --------------------------
405
+ os.makedirs(args.output_dir, exist_ok=True)
406
+
407
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
408
+ save_dir.mkdir(parents=True, exist_ok=True)
409
+
410
+ for idx, img in enumerate(results):
411
+ name = modality_names[idx]
412
+ save_path = save_dir / f"{name}.png"
413
+ img.save(save_path)
414
+ print(f"💾 Saved {name} → {save_path}")
415
+
416
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
417
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
418
+
419
+ print(f"\n✅ All results saved in: {save_dir}\n")
420
+ return save_dir
421
+
422
+
423
+ # ------------------------------
424
+ # Entry Point
425
+ # ------------------------------
426
+ if __name__ == "__main__":
427
+ args = get_parser().parse_args()
428
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
429
+ print(f"✅ Using device: {device}")
430
+
431
+ processor = AutoProcessor.from_pretrained(
432
+ args.model_name_or_path,
433
+ )
434
+
435
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
436
+ args.text_model_path,
437
+ attn_implementation="flash_attention_2",
438
+ dtype=(torch.bfloat16),
439
+ ).to(device)
440
+
441
+ torch.manual_seed(args.seed)
442
+ generator = torch.Generator(device=device).manual_seed(args.seed)
443
+
444
+ dataset = load_dataset(
445
+ "parquet",
446
+ data_files=args.data_path,
447
+ split="train")
448
+
449
+ for sample in dataset:
450
+
451
+ image_keys = [f"image_{i}" for i in range(1, 8)]
452
+ num_images = sum(1 for key in image_keys if key in sample and isinstance(sample[key], type(sample["image_1"])) and sample[key] is not None)
453
+
454
+ if num_images > 1:
455
+ continue
456
+
457
+ image = sample["image_1"]
458
+ image_path = dump_image(image, args.temp_dir)
459
+ question = clean_question(sample["question"])
460
+ image_id = sample["id"]
461
+ options = sample["options"]
462
+ field = sample["subfield"]
463
+
464
+ max_length = 1024
465
+
466
+ #input_img = Image.open(image_path).convert("RGB")
467
+ width, height = image.size
468
+ print(f'ori width:{width}', f'ori height:{height}')
469
+
470
+ prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)
471
+
qwen_vqa_Art.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+
31
+ def clean_question(q: str) -> str:
32
+ if not isinstance(q, str):
33
+ q = str(q)
34
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
35
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
36
+ # 再清理多余空白
37
+ q = re.sub(r"\s+", " ", q).strip()
38
+ return q
39
+
40
+ def dump_image(image, save_root):
41
+ os.makedirs(save_root, exist_ok=True)
42
+ save_path = os.path.join(save_root, "input.jpg")
43
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
44
+ return save_path
45
+
46
+
47
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
48
+ """
49
+ 将多个图像拼接成一张大图并保存。
50
+ Args:
51
+ image_paths: List[str] 图像路径列表
52
+ save_path: 保存路径(包括文件名)
53
+ images_per_row: 每行图像数量(默认为全部在一行)
54
+ image_format: 保存格式
55
+ """
56
+ from PIL import Image
57
+ import io
58
+
59
+ # 读取图像
60
+ images = [Image.open(p).convert("RGB") for p in image_paths]
61
+
62
+ if images_per_row is None:
63
+ images_per_row = len(images)
64
+
65
+ # 调整尺寸(可选)
66
+ target_size = min(1024, images[0].size[0])
67
+ images = [img.resize((target_size, target_size)) for img in images]
68
+
69
+ # 拼接
70
+ widths, heights = zip(*(img.size for img in images))
71
+ max_width = max(widths)
72
+ rows = (len(images) + images_per_row - 1) // images_per_row
73
+ total_height = sum(heights[:images_per_row]) * rows
74
+
75
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
76
+ y_offset = 0
77
+ for i in range(0, len(images), images_per_row):
78
+ row_imgs = images[i:i+images_per_row]
79
+ x_offset = 0
80
+ for img in row_imgs:
81
+ new_im.paste(img, (x_offset, y_offset))
82
+ x_offset += max_width
83
+ y_offset += heights[0]
84
+
85
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
86
+ new_im.save(save_path, format=image_format.upper())
87
+ print(f"🧩 Saved merged image → {save_path}")
88
+ return save_path
89
+
90
+
91
+ def build_vqa_message(root, prompt, question, options, subfield):
92
+ """
93
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
94
+ """
95
+ modality_names = [
96
+ "image",
97
+ "annotation_lineart",
98
+ "annotation_edge",
99
+ "annotation_depth",
100
+ "annotation_normal", "annotation_albedo",
101
+ "annotation_seg_12colors",
102
+ "annotation_openpose",
103
+ ]
104
+
105
+ # --- 检查存在的模态 ---
106
+ available = []
107
+ for name in modality_names: # 优先匹配 .png 或 .jpg
108
+ for ext in [".png", ".jpg", ".jpeg"]:
109
+ path = Path(root) / f"{name}{ext}"
110
+ if path.exists():
111
+ available.append(str(path))
112
+ break
113
+ # --- 构建模态说明 ---
114
+ readable_map = {
115
+ "image": "RGB image",
116
+ "annotation_lineart": "line drawing",
117
+ "annotation_edge": "edge map",
118
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
119
+ "annotation_albedo": "albedo map",
120
+ "annotation_seg_12colors": "segmentation map",
121
+ "annotation_openpose": "human pose map",
122
+ }
123
+
124
+ options_list = ast.literal_eval(options)
125
+ option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)])
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Scientific Subfield: \"{subfield}\" "
142
+ f"Now, based on both the multimodal visual information and the given scene description, "
143
+ f"analyze the scene carefully to answer a question. "
144
+ f"Your analysis should proceed in two stages:\n\n"
145
+ f"**Stage 1 — Modality-wise Observation:**\n"
146
+ f"For each provided modality image, analyze what specific visual information it contributes "
147
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
148
+ f"such as color, shape, structure, spatial depth, or object positions. "
149
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: "
150
+ f"Question: \"{question}\" "
151
+ f"Options: \"{option_text}\" "
152
+ + " ".join(["<image>"] * len(available))
153
+ )
154
+
155
+ # --- 构建 Qwen3-VL 消息格式 ---
156
+ messages = [
157
+ {
158
+ "role": "user",
159
+ "content": [{"type": "image", "image": path} for path in available]
160
+ + [{"type": "text", "text": text_prompt}],
161
+ }
162
+ ]
163
+ return messages
164
+
165
+
166
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
167
+ """
168
+ Build Qwen3-VL message for multi-modal caption refinement.
169
+ Automatically detects available modalities under root.
170
+ """
171
+ modality_names = [
172
+ "image",
173
+ "annotation_lineart",
174
+ "annotation_edge",
175
+ "annotation_depth",
176
+ "annotation_normal",
177
+ "annotation_albedo",
178
+ "annotation_seg_12colors",
179
+ "annotation_openpose",
180
+ ]
181
+
182
+ # --- 检查存在的模态 ---
183
+ available = []
184
+ for name in modality_names:
185
+ # 优先匹配 .png 或 .jpg
186
+ for ext in [".png", ".jpg", ".jpeg"]:
187
+ path = Path(root) / f"{name}{ext}"
188
+ if path.exists():
189
+ available.append(str(path))
190
+ break
191
+
192
+ # --- 构建模态说明 ---
193
+ readable_map = {
194
+ "image": "RGB image",
195
+ "annotation_lineart": "line drawing",
196
+ "annotation_edge": "edge map",
197
+ "annotation_depth": "depth map",
198
+ "annotation_normal": "normal map",
199
+ "annotation_albedo": "albedo map",
200
+ "annotation_seg_12colors": "segmentation map",
201
+ "annotation_openpose": "human pose map",
202
+ }
203
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
204
+
205
+ # --- 构造文本指令 ---
206
+ text_prompt = (
207
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
208
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
209
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
210
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
211
+ f"- The edge map highlights object boundaries and contours. "
212
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
213
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
214
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
215
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
216
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
217
+ f"For each provided modality image, analyze it according to the above definitions and describe "
218
+ f"the specific visual information it contributes in this particular case. "
219
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
220
+ f"Do NOT describe each modality separately or mention modality names. "
221
+ f"Focus on merging their information into a single coherent image description. "
222
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
223
+ f"Refine the coarse caption into a more detailed and accurate image description. "
224
+ f"Coarse caption: '{coarse_caption}' " +
225
+ " ".join(["<image>"] * len(available))
226
+ )
227
+
228
+ # --- 构建 Qwen3-VL 消息格式 ---
229
+ messages = [
230
+ {
231
+ "role": "user",
232
+ "content": [{"type": "image", "image": path} for path in available]
233
+ + [{"type": "text", "text": text_prompt}],
234
+ }
235
+ ]
236
+ return messages
237
+
238
+ # ------------------------------
239
+ # Argument Parser
240
+ # ------------------------------
241
+ def get_parser():
242
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
243
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
244
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
245
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
246
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
247
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/MMMU/Art/validation-00000-of-00001.parquet", help="Prompt text for generation.")
248
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
249
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
250
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
251
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
252
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
253
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
254
+ parser.add_argument("--seed", type=int, default=1234)
255
+ parser.add_argument("--output_dir", type=str, default="./qwen_Art_outputs", help="Directory to save results.")
256
+ return parser
257
+
258
+
259
+ # ------------------------------
260
+ # Main Inference Function
261
+ # ------------------------------
262
+
263
+ @torch.inference_mode()
264
+ def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300):
265
+
266
+ options_list = ast.literal_eval(option)
267
+ option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)])
268
+
269
+ question = clean_question(question)
270
+
271
+ text_prompt = (
272
+ f"Analyze the given image <image> and answer the following question."
273
+ f"Question: \"{question}\" \n"
274
+ f"Options: \"{option_text}\" "
275
+ )
276
+
277
+ messages = [
278
+ {
279
+ "role": "user",
280
+ "content": [
281
+ {
282
+ "type": "image",
283
+ "image": image_path,
284
+ },
285
+ {"type": "text", "text": text_prompt},
286
+ ],
287
+ }
288
+ ]
289
+
290
+ print(messages)
291
+
292
+ inputs = processor.apply_chat_template(
293
+ messages,
294
+ tokenize=True,
295
+ add_generation_prompt=True,
296
+ return_dict=True,
297
+ return_tensors="pt"
298
+ )
299
+ inputs = inputs.to(model.device)
300
+
301
+ # Inference: Generation of the output
302
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
303
+ generated_ids_trimmed = [
304
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
305
+ ]
306
+ output_text = processor.batch_decode(
307
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
308
+ )
309
+ print(output_text)
310
+
311
+ os.makedirs(args.output_dir, exist_ok=True)
312
+ save_dir = Path(args.output_dir) / vqa_id
313
+ save_dir.mkdir(parents=True, exist_ok=True)
314
+ caption_path = Path(save_dir) / f"caption.txt"
315
+ with open(caption_path, "w", encoding="utf-8") as f:
316
+ f.write(output_text[0].strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
322
+ messages = build_multimodal_message(root, prompt)
323
+ inputs = processor.apply_chat_template(
324
+ messages,
325
+ tokenize=True,
326
+ add_generation_prompt=True,
327
+ return_dict=True,
328
+ return_tensors="pt"
329
+ )
330
+ inputs = inputs.to(model.device)
331
+
332
+ # Inference: Generation of the output
333
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
334
+ generated_ids_trimmed = [
335
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
336
+ ]
337
+ output_text = processor.batch_decode(
338
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
339
+ )
340
+ print(output_text)
341
+
342
+ os.makedirs(args.output_dir, exist_ok=True)
343
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
344
+ save_dir.mkdir(parents=True, exist_ok=True)
345
+ caption_path = Path(save_dir) / f"caption.txt"
346
+ with open(caption_path, "w", encoding="utf-8") as f:
347
+ f.write(output_text[0].strip())
348
+
349
+ return output_text[0]
350
+
351
+ @torch.inference_mode()
352
+ def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300):
353
+ messages = build_vqa_message(root, prompt, question, options, subfield)
354
+ print(messages)
355
+ inputs = processor.apply_chat_template(
356
+ messages,
357
+ tokenize=True,
358
+ add_generation_prompt=True,
359
+ return_dict=True,
360
+ return_tensors="pt"
361
+ )
362
+ inputs = inputs.to(model.device)
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
366
+ output_text = processor.batch_decode(
367
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
368
+ )
369
+ print(output_text)
370
+ os.makedirs(args.output_dir, exist_ok=True)
371
+ save_dir = Path(args.output_dir) / vqa_id
372
+ save_dir.mkdir(parents=True, exist_ok=True)
373
+ caption_path = Path(save_dir) / f"caption.txt"
374
+ with open(caption_path, "w", encoding="utf-8") as f:
375
+ f.write(output_text[0].strip())
376
+ return output_text[0]
377
+
378
+ @torch.inference_mode()
379
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield):
380
+
381
+ print(f"🚀 Generating with prompt: {prompt}")
382
+ prompt = f'{subfield} image,' + ' ' + prompt
383
+ outputs = pipe(
384
+ images=images,
385
+ role=role,
386
+ prompt=prompt,
387
+ negative_prompt=args.negative_prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=args.steps,
391
+ guidance_scale=args.guidance_scale,
392
+ num_images_per_prompt=1,
393
+ generator=generator,
394
+ task='t2i'
395
+ )
396
+
397
+ # Apply post-processing for each modality
398
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
399
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
400
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
401
+
402
+ # --------------------------
403
+ # Save results
404
+ # --------------------------
405
+ os.makedirs(args.output_dir, exist_ok=True)
406
+
407
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
408
+ save_dir.mkdir(parents=True, exist_ok=True)
409
+
410
+ for idx, img in enumerate(results):
411
+ name = modality_names[idx]
412
+ save_path = save_dir / f"{name}.png"
413
+ img.save(save_path)
414
+ print(f"💾 Saved {name} → {save_path}")
415
+
416
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
417
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
418
+
419
+ print(f"\n✅ All results saved in: {save_dir}\n")
420
+ return save_dir
421
+
422
+
423
+ # ------------------------------
424
+ # Entry Point
425
+ # ------------------------------
426
+ if __name__ == "__main__":
427
+ args = get_parser().parse_args()
428
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
429
+ print(f"✅ Using device: {device}")
430
+
431
+ processor = AutoProcessor.from_pretrained(
432
+ args.model_name_or_path,
433
+ )
434
+
435
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
436
+ args.text_model_path,
437
+ attn_implementation="flash_attention_2",
438
+ dtype=(torch.bfloat16),
439
+ ).to(device)
440
+
441
+ torch.manual_seed(args.seed)
442
+ generator = torch.Generator(device=device).manual_seed(args.seed)
443
+
444
+ dataset = load_dataset(
445
+ "parquet",
446
+ data_files=args.data_path,
447
+ split="train")
448
+
449
+ for sample in dataset:
450
+
451
+ image_keys = [f"image_{i}" for i in range(1, 8)]
452
+ num_images = sum(1 for key in image_keys if key in sample and isinstance(sample[key], type(sample["image_1"])) and sample[key] is not None)
453
+
454
+ if num_images > 1:
455
+ continue
456
+
457
+ image = sample["image_1"]
458
+ image_path = dump_image(image, args.temp_dir)
459
+ question = clean_question(sample["question"])
460
+ image_id = sample["id"]
461
+ options = sample["options"]
462
+ field = sample["subfield"]
463
+
464
+ max_length = 1024
465
+
466
+ #input_img = Image.open(image_path).convert("RGB")
467
+ width, height = image.size
468
+ print(f'ori width:{width}', f'ori height:{height}')
469
+
470
+ prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)
471
+
qwen_vqa_Artthepry.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+
31
+ def clean_question(q: str) -> str:
32
+ if not isinstance(q, str):
33
+ q = str(q)
34
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
35
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
36
+ # 再清理多余空白
37
+ q = re.sub(r"\s+", " ", q).strip()
38
+ return q
39
+
40
+ def dump_image(image, save_root):
41
+ os.makedirs(save_root, exist_ok=True)
42
+ save_path = os.path.join(save_root, "input.jpg")
43
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
44
+ return save_path
45
+
46
+
47
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
48
+ """
49
+ 将多个图像拼接成一张大图并保存。
50
+ Args:
51
+ image_paths: List[str] 图像路径列表
52
+ save_path: 保存路径(包括文件名)
53
+ images_per_row: 每行图像数量(默认为全部在一行)
54
+ image_format: 保存格式
55
+ """
56
+ from PIL import Image
57
+ import io
58
+
59
+ # 读取图像
60
+ images = [Image.open(p).convert("RGB") for p in image_paths]
61
+
62
+ if images_per_row is None:
63
+ images_per_row = len(images)
64
+
65
+ # 调整尺寸(可选)
66
+ target_size = min(1024, images[0].size[0])
67
+ images = [img.resize((target_size, target_size)) for img in images]
68
+
69
+ # 拼接
70
+ widths, heights = zip(*(img.size for img in images))
71
+ max_width = max(widths)
72
+ rows = (len(images) + images_per_row - 1) // images_per_row
73
+ total_height = sum(heights[:images_per_row]) * rows
74
+
75
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
76
+ y_offset = 0
77
+ for i in range(0, len(images), images_per_row):
78
+ row_imgs = images[i:i+images_per_row]
79
+ x_offset = 0
80
+ for img in row_imgs:
81
+ new_im.paste(img, (x_offset, y_offset))
82
+ x_offset += max_width
83
+ y_offset += heights[0]
84
+
85
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
86
+ new_im.save(save_path, format=image_format.upper())
87
+ print(f"🧩 Saved merged image → {save_path}")
88
+ return save_path
89
+
90
+
91
+ def build_vqa_message(root, prompt, question, options, subfield):
92
+ """
93
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
94
+ """
95
+ modality_names = [
96
+ "image",
97
+ "annotation_lineart",
98
+ "annotation_edge",
99
+ "annotation_depth",
100
+ "annotation_normal", "annotation_albedo",
101
+ "annotation_seg_12colors",
102
+ "annotation_openpose",
103
+ ]
104
+
105
+ # --- 检查存在的模态 ---
106
+ available = []
107
+ for name in modality_names: # 优先匹配 .png 或 .jpg
108
+ for ext in [".png", ".jpg", ".jpeg"]:
109
+ path = Path(root) / f"{name}{ext}"
110
+ if path.exists():
111
+ available.append(str(path))
112
+ break
113
+ # --- 构建模态说明 ---
114
+ readable_map = {
115
+ "image": "RGB image",
116
+ "annotation_lineart": "line drawing",
117
+ "annotation_edge": "edge map",
118
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
119
+ "annotation_albedo": "albedo map",
120
+ "annotation_seg_12colors": "segmentation map",
121
+ "annotation_openpose": "human pose map",
122
+ }
123
+
124
+ options_list = ast.literal_eval(options)
125
+ option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)])
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Scientific Subfield: \"{subfield}\" "
142
+ f"Now, based on both the multimodal visual information and the given scene description, "
143
+ f"analyze the scene carefully to answer a question. "
144
+ f"Your analysis should proceed in two stages:\n\n"
145
+ f"**Stage 1 — Modality-wise Observation:**\n"
146
+ f"For each provided modality image, analyze what specific visual information it contributes "
147
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
148
+ f"such as color, shape, structure, spatial depth, or object positions. "
149
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: "
150
+ f"Question: \"{question}\" "
151
+ f"Options: \"{option_text}\" "
152
+ + " ".join(["<image>"] * len(available))
153
+ )
154
+
155
+ # --- 构建 Qwen3-VL 消息格式 ---
156
+ messages = [
157
+ {
158
+ "role": "user",
159
+ "content": [{"type": "image", "image": path} for path in available]
160
+ + [{"type": "text", "text": text_prompt}],
161
+ }
162
+ ]
163
+ return messages
164
+
165
+
166
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
167
+ """
168
+ Build Qwen3-VL message for multi-modal caption refinement.
169
+ Automatically detects available modalities under root.
170
+ """
171
+ modality_names = [
172
+ "image",
173
+ "annotation_lineart",
174
+ "annotation_edge",
175
+ "annotation_depth",
176
+ "annotation_normal",
177
+ "annotation_albedo",
178
+ "annotation_seg_12colors",
179
+ "annotation_openpose",
180
+ ]
181
+
182
+ # --- 检查存在的模态 ---
183
+ available = []
184
+ for name in modality_names:
185
+ # 优先匹配 .png 或 .jpg
186
+ for ext in [".png", ".jpg", ".jpeg"]:
187
+ path = Path(root) / f"{name}{ext}"
188
+ if path.exists():
189
+ available.append(str(path))
190
+ break
191
+
192
+ # --- 构建模态说明 ---
193
+ readable_map = {
194
+ "image": "RGB image",
195
+ "annotation_lineart": "line drawing",
196
+ "annotation_edge": "edge map",
197
+ "annotation_depth": "depth map",
198
+ "annotation_normal": "normal map",
199
+ "annotation_albedo": "albedo map",
200
+ "annotation_seg_12colors": "segmentation map",
201
+ "annotation_openpose": "human pose map",
202
+ }
203
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
204
+
205
+ # --- 构造文本指令 ---
206
+ text_prompt = (
207
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
208
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
209
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
210
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
211
+ f"- The edge map highlights object boundaries and contours. "
212
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
213
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
214
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
215
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
216
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
217
+ f"For each provided modality image, analyze it according to the above definitions and describe "
218
+ f"the specific visual information it contributes in this particular case. "
219
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
220
+ f"Do NOT describe each modality separately or mention modality names. "
221
+ f"Focus on merging their information into a single coherent image description. "
222
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
223
+ f"Refine the coarse caption into a more detailed and accurate image description. "
224
+ f"Coarse caption: '{coarse_caption}' " +
225
+ " ".join(["<image>"] * len(available))
226
+ )
227
+
228
+ # --- 构建 Qwen3-VL 消息格式 ---
229
+ messages = [
230
+ {
231
+ "role": "user",
232
+ "content": [{"type": "image", "image": path} for path in available]
233
+ + [{"type": "text", "text": text_prompt}],
234
+ }
235
+ ]
236
+ return messages
237
+
238
+ # ------------------------------
239
+ # Argument Parser
240
+ # ------------------------------
241
+ def get_parser():
242
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
243
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
244
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
245
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
246
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
247
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/MMMU/Art_Theory/validation-00000-of-00001.parquet", help="Prompt text for generation.")
248
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
249
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
250
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
251
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
252
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
253
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
254
+ parser.add_argument("--seed", type=int, default=1234)
255
+ parser.add_argument("--output_dir", type=str, default="./qwen_Art_theory_outputs", help="Directory to save results.")
256
+ return parser
257
+
258
+
259
+ # ------------------------------
260
+ # Main Inference Function
261
+ # ------------------------------
262
+
263
+ @torch.inference_mode()
264
+ def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300):
265
+
266
+ options_list = ast.literal_eval(option)
267
+ option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)])
268
+
269
+ question = clean_question(question)
270
+
271
+ text_prompt = (
272
+ f"Analyze the given image <image> and answer the following question."
273
+ f"Question: \"{question}\" \n"
274
+ f"Options: \"{option_text}\" "
275
+ )
276
+
277
+ messages = [
278
+ {
279
+ "role": "user",
280
+ "content": [
281
+ {
282
+ "type": "image",
283
+ "image": image_path,
284
+ },
285
+ {"type": "text", "text": text_prompt},
286
+ ],
287
+ }
288
+ ]
289
+
290
+ print(messages)
291
+
292
+ inputs = processor.apply_chat_template(
293
+ messages,
294
+ tokenize=True,
295
+ add_generation_prompt=True,
296
+ return_dict=True,
297
+ return_tensors="pt"
298
+ )
299
+ inputs = inputs.to(model.device)
300
+
301
+ # Inference: Generation of the output
302
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
303
+ generated_ids_trimmed = [
304
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
305
+ ]
306
+ output_text = processor.batch_decode(
307
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
308
+ )
309
+ print(output_text)
310
+
311
+ os.makedirs(args.output_dir, exist_ok=True)
312
+ save_dir = Path(args.output_dir) / vqa_id
313
+ save_dir.mkdir(parents=True, exist_ok=True)
314
+ caption_path = Path(save_dir) / f"caption.txt"
315
+ with open(caption_path, "w", encoding="utf-8") as f:
316
+ f.write(output_text[0].strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
322
+ messages = build_multimodal_message(root, prompt)
323
+ inputs = processor.apply_chat_template(
324
+ messages,
325
+ tokenize=True,
326
+ add_generation_prompt=True,
327
+ return_dict=True,
328
+ return_tensors="pt"
329
+ )
330
+ inputs = inputs.to(model.device)
331
+
332
+ # Inference: Generation of the output
333
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
334
+ generated_ids_trimmed = [
335
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
336
+ ]
337
+ output_text = processor.batch_decode(
338
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
339
+ )
340
+ print(output_text)
341
+
342
+ os.makedirs(args.output_dir, exist_ok=True)
343
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
344
+ save_dir.mkdir(parents=True, exist_ok=True)
345
+ caption_path = Path(save_dir) / f"caption.txt"
346
+ with open(caption_path, "w", encoding="utf-8") as f:
347
+ f.write(output_text[0].strip())
348
+
349
+ return output_text[0]
350
+
351
+ @torch.inference_mode()
352
+ def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300):
353
+ messages = build_vqa_message(root, prompt, question, options, subfield)
354
+ print(messages)
355
+ inputs = processor.apply_chat_template(
356
+ messages,
357
+ tokenize=True,
358
+ add_generation_prompt=True,
359
+ return_dict=True,
360
+ return_tensors="pt"
361
+ )
362
+ inputs = inputs.to(model.device)
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
366
+ output_text = processor.batch_decode(
367
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
368
+ )
369
+ print(output_text)
370
+ os.makedirs(args.output_dir, exist_ok=True)
371
+ save_dir = Path(args.output_dir) / vqa_id
372
+ save_dir.mkdir(parents=True, exist_ok=True)
373
+ caption_path = Path(save_dir) / f"caption.txt"
374
+ with open(caption_path, "w", encoding="utf-8") as f:
375
+ f.write(output_text[0].strip())
376
+ return output_text[0]
377
+
378
+ @torch.inference_mode()
379
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield):
380
+
381
+ print(f"🚀 Generating with prompt: {prompt}")
382
+ prompt = f'{subfield} image,' + ' ' + prompt
383
+ outputs = pipe(
384
+ images=images,
385
+ role=role,
386
+ prompt=prompt,
387
+ negative_prompt=args.negative_prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=args.steps,
391
+ guidance_scale=args.guidance_scale,
392
+ num_images_per_prompt=1,
393
+ generator=generator,
394
+ task='t2i'
395
+ )
396
+
397
+ # Apply post-processing for each modality
398
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
399
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
400
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
401
+
402
+ # --------------------------
403
+ # Save results
404
+ # --------------------------
405
+ os.makedirs(args.output_dir, exist_ok=True)
406
+
407
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
408
+ save_dir.mkdir(parents=True, exist_ok=True)
409
+
410
+ for idx, img in enumerate(results):
411
+ name = modality_names[idx]
412
+ save_path = save_dir / f"{name}.png"
413
+ img.save(save_path)
414
+ print(f"💾 Saved {name} → {save_path}")
415
+
416
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
417
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
418
+
419
+ print(f"\n✅ All results saved in: {save_dir}\n")
420
+ return save_dir
421
+
422
+
423
+ # ------------------------------
424
+ # Entry Point
425
+ # ------------------------------
426
+ if __name__ == "__main__":
427
+ args = get_parser().parse_args()
428
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
429
+ print(f"✅ Using device: {device}")
430
+
431
+ processor = AutoProcessor.from_pretrained(
432
+ args.model_name_or_path,
433
+ )
434
+
435
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
436
+ args.text_model_path,
437
+ attn_implementation="flash_attention_2",
438
+ dtype=(torch.bfloat16),
439
+ ).to(device)
440
+
441
+ torch.manual_seed(args.seed)
442
+ generator = torch.Generator(device=device).manual_seed(args.seed)
443
+
444
+ dataset = load_dataset(
445
+ "parquet",
446
+ data_files=args.data_path,
447
+ split="train")
448
+
449
+ for sample in dataset:
450
+
451
+ image_keys = [f"image_{i}" for i in range(1, 8)]
452
+ num_images = sum(1 for key in image_keys if key in sample and isinstance(sample[key], type(sample["image_1"])) and sample[key] is not None)
453
+
454
+ if num_images > 1:
455
+ continue
456
+
457
+ image = sample["image_1"]
458
+ image_path = dump_image(image, args.temp_dir)
459
+ question = clean_question(sample["question"])
460
+ image_id = sample["id"]
461
+ options = sample["options"]
462
+ field = sample["subfield"]
463
+
464
+ max_length = 1024
465
+
466
+ #input_img = Image.open(image_path).convert("RGB")
467
+ width, height = image.size
468
+ print(f'ori width:{width}', f'ori height:{height}')
469
+
470
+ prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)
471
+
qwen_vqa_Design.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+
31
+ def clean_question(q: str) -> str:
32
+ if not isinstance(q, str):
33
+ q = str(q)
34
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
35
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
36
+ # 再清理多余空白
37
+ q = re.sub(r"\s+", " ", q).strip()
38
+ return q
39
+
40
+ def dump_image(image, save_root):
41
+ os.makedirs(save_root, exist_ok=True)
42
+ save_path = os.path.join(save_root, "input.jpg")
43
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
44
+ return save_path
45
+
46
+
47
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
48
+ """
49
+ 将多个图像拼接成一张大图并保存。
50
+ Args:
51
+ image_paths: List[str] 图像路径列表
52
+ save_path: 保存路径(包括文件名)
53
+ images_per_row: 每行图像数量(默认为全部在一行)
54
+ image_format: 保存格式
55
+ """
56
+ from PIL import Image
57
+ import io
58
+
59
+ # 读取图像
60
+ images = [Image.open(p).convert("RGB") for p in image_paths]
61
+
62
+ if images_per_row is None:
63
+ images_per_row = len(images)
64
+
65
+ # 调整尺寸(可选)
66
+ target_size = min(1024, images[0].size[0])
67
+ images = [img.resize((target_size, target_size)) for img in images]
68
+
69
+ # 拼接
70
+ widths, heights = zip(*(img.size for img in images))
71
+ max_width = max(widths)
72
+ rows = (len(images) + images_per_row - 1) // images_per_row
73
+ total_height = sum(heights[:images_per_row]) * rows
74
+
75
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
76
+ y_offset = 0
77
+ for i in range(0, len(images), images_per_row):
78
+ row_imgs = images[i:i+images_per_row]
79
+ x_offset = 0
80
+ for img in row_imgs:
81
+ new_im.paste(img, (x_offset, y_offset))
82
+ x_offset += max_width
83
+ y_offset += heights[0]
84
+
85
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
86
+ new_im.save(save_path, format=image_format.upper())
87
+ print(f"🧩 Saved merged image → {save_path}")
88
+ return save_path
89
+
90
+
91
+ def build_vqa_message(root, prompt, question, options, subfield):
92
+ """
93
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
94
+ """
95
+ modality_names = [
96
+ "image",
97
+ "annotation_lineart",
98
+ "annotation_edge",
99
+ "annotation_depth",
100
+ "annotation_normal", "annotation_albedo",
101
+ "annotation_seg_12colors",
102
+ "annotation_openpose",
103
+ ]
104
+
105
+ # --- 检查存在的模态 ---
106
+ available = []
107
+ for name in modality_names: # 优先匹配 .png 或 .jpg
108
+ for ext in [".png", ".jpg", ".jpeg"]:
109
+ path = Path(root) / f"{name}{ext}"
110
+ if path.exists():
111
+ available.append(str(path))
112
+ break
113
+ # --- 构建模态说明 ---
114
+ readable_map = {
115
+ "image": "RGB image",
116
+ "annotation_lineart": "line drawing",
117
+ "annotation_edge": "edge map",
118
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
119
+ "annotation_albedo": "albedo map",
120
+ "annotation_seg_12colors": "segmentation map",
121
+ "annotation_openpose": "human pose map",
122
+ }
123
+
124
+ options_list = ast.literal_eval(options)
125
+ option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)])
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Scientific Subfield: \"{subfield}\" "
142
+ f"Now, based on both the multimodal visual information and the given scene description, "
143
+ f"analyze the scene carefully to answer a question. "
144
+ f"Your analysis should proceed in two stages:\n\n"
145
+ f"**Stage 1 — Modality-wise Observation:**\n"
146
+ f"For each provided modality image, analyze what specific visual information it contributes "
147
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
148
+ f"such as color, shape, structure, spatial depth, or object positions. "
149
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: "
150
+ f"Question: \"{question}\" "
151
+ f"Options: \"{option_text}\" "
152
+ + " ".join(["<image>"] * len(available))
153
+ )
154
+
155
+ # --- 构建 Qwen3-VL 消息格式 ---
156
+ messages = [
157
+ {
158
+ "role": "user",
159
+ "content": [{"type": "image", "image": path} for path in available]
160
+ + [{"type": "text", "text": text_prompt}],
161
+ }
162
+ ]
163
+ return messages
164
+
165
+
166
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
167
+ """
168
+ Build Qwen3-VL message for multi-modal caption refinement.
169
+ Automatically detects available modalities under root.
170
+ """
171
+ modality_names = [
172
+ "image",
173
+ "annotation_lineart",
174
+ "annotation_edge",
175
+ "annotation_depth",
176
+ "annotation_normal",
177
+ "annotation_albedo",
178
+ "annotation_seg_12colors",
179
+ "annotation_openpose",
180
+ ]
181
+
182
+ # --- 检查存在的模态 ---
183
+ available = []
184
+ for name in modality_names:
185
+ # 优先匹配 .png 或 .jpg
186
+ for ext in [".png", ".jpg", ".jpeg"]:
187
+ path = Path(root) / f"{name}{ext}"
188
+ if path.exists():
189
+ available.append(str(path))
190
+ break
191
+
192
+ # --- 构建模态说明 ---
193
+ readable_map = {
194
+ "image": "RGB image",
195
+ "annotation_lineart": "line drawing",
196
+ "annotation_edge": "edge map",
197
+ "annotation_depth": "depth map",
198
+ "annotation_normal": "normal map",
199
+ "annotation_albedo": "albedo map",
200
+ "annotation_seg_12colors": "segmentation map",
201
+ "annotation_openpose": "human pose map",
202
+ }
203
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
204
+
205
+ # --- 构造文本指令 ---
206
+ text_prompt = (
207
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
208
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
209
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
210
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
211
+ f"- The edge map highlights object boundaries and contours. "
212
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
213
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
214
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
215
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
216
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
217
+ f"For each provided modality image, analyze it according to the above definitions and describe "
218
+ f"the specific visual information it contributes in this particular case. "
219
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
220
+ f"Do NOT describe each modality separately or mention modality names. "
221
+ f"Focus on merging their information into a single coherent image description. "
222
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
223
+ f"Refine the coarse caption into a more detailed and accurate image description. "
224
+ f"Coarse caption: '{coarse_caption}' " +
225
+ " ".join(["<image>"] * len(available))
226
+ )
227
+
228
+ # --- 构建 Qwen3-VL 消息格式 ---
229
+ messages = [
230
+ {
231
+ "role": "user",
232
+ "content": [{"type": "image", "image": path} for path in available]
233
+ + [{"type": "text", "text": text_prompt}],
234
+ }
235
+ ]
236
+ return messages
237
+
238
+ # ------------------------------
239
+ # Argument Parser
240
+ # ------------------------------
241
+ def get_parser():
242
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
243
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
244
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
245
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
246
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
247
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/MMMU/Design/validation-00000-of-00001.parquet", help="Prompt text for generation.")
248
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
249
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
250
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
251
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
252
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
253
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
254
+ parser.add_argument("--seed", type=int, default=1234)
255
+ parser.add_argument("--output_dir", type=str, default="./qwen_Design_outputs", help="Directory to save results.")
256
+ return parser
257
+
258
+
259
+ # ------------------------------
260
+ # Main Inference Function
261
+ # ------------------------------
262
+
263
+ @torch.inference_mode()
264
+ def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300):
265
+
266
+ options_list = ast.literal_eval(option)
267
+ option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)])
268
+
269
+ question = clean_question(question)
270
+
271
+ text_prompt = (
272
+ f"Analyze the given image <image> and answer the following question."
273
+ f"Question: \"{question}\" \n"
274
+ f"Options: \"{option_text}\" "
275
+ )
276
+
277
+ messages = [
278
+ {
279
+ "role": "user",
280
+ "content": [
281
+ {
282
+ "type": "image",
283
+ "image": image_path,
284
+ },
285
+ {"type": "text", "text": text_prompt},
286
+ ],
287
+ }
288
+ ]
289
+
290
+ print(messages)
291
+
292
+ inputs = processor.apply_chat_template(
293
+ messages,
294
+ tokenize=True,
295
+ add_generation_prompt=True,
296
+ return_dict=True,
297
+ return_tensors="pt"
298
+ )
299
+ inputs = inputs.to(model.device)
300
+
301
+ # Inference: Generation of the output
302
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
303
+ generated_ids_trimmed = [
304
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
305
+ ]
306
+ output_text = processor.batch_decode(
307
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
308
+ )
309
+ print(output_text)
310
+
311
+ os.makedirs(args.output_dir, exist_ok=True)
312
+ save_dir = Path(args.output_dir) / vqa_id
313
+ save_dir.mkdir(parents=True, exist_ok=True)
314
+ caption_path = Path(save_dir) / f"caption.txt"
315
+ with open(caption_path, "w", encoding="utf-8") as f:
316
+ f.write(output_text[0].strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
322
+ messages = build_multimodal_message(root, prompt)
323
+ inputs = processor.apply_chat_template(
324
+ messages,
325
+ tokenize=True,
326
+ add_generation_prompt=True,
327
+ return_dict=True,
328
+ return_tensors="pt"
329
+ )
330
+ inputs = inputs.to(model.device)
331
+
332
+ # Inference: Generation of the output
333
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
334
+ generated_ids_trimmed = [
335
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
336
+ ]
337
+ output_text = processor.batch_decode(
338
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
339
+ )
340
+ print(output_text)
341
+
342
+ os.makedirs(args.output_dir, exist_ok=True)
343
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
344
+ save_dir.mkdir(parents=True, exist_ok=True)
345
+ caption_path = Path(save_dir) / f"caption.txt"
346
+ with open(caption_path, "w", encoding="utf-8") as f:
347
+ f.write(output_text[0].strip())
348
+
349
+ return output_text[0]
350
+
351
+ @torch.inference_mode()
352
+ def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300):
353
+ messages = build_vqa_message(root, prompt, question, options, subfield)
354
+ print(messages)
355
+ inputs = processor.apply_chat_template(
356
+ messages,
357
+ tokenize=True,
358
+ add_generation_prompt=True,
359
+ return_dict=True,
360
+ return_tensors="pt"
361
+ )
362
+ inputs = inputs.to(model.device)
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
366
+ output_text = processor.batch_decode(
367
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
368
+ )
369
+ print(output_text)
370
+ os.makedirs(args.output_dir, exist_ok=True)
371
+ save_dir = Path(args.output_dir) / vqa_id
372
+ save_dir.mkdir(parents=True, exist_ok=True)
373
+ caption_path = Path(save_dir) / f"caption.txt"
374
+ with open(caption_path, "w", encoding="utf-8") as f:
375
+ f.write(output_text[0].strip())
376
+ return output_text[0]
377
+
378
+ @torch.inference_mode()
379
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield):
380
+
381
+ print(f"🚀 Generating with prompt: {prompt}")
382
+ prompt = f'{subfield} image,' + ' ' + prompt
383
+ outputs = pipe(
384
+ images=images,
385
+ role=role,
386
+ prompt=prompt,
387
+ negative_prompt=args.negative_prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=args.steps,
391
+ guidance_scale=args.guidance_scale,
392
+ num_images_per_prompt=1,
393
+ generator=generator,
394
+ task='t2i'
395
+ )
396
+
397
+ # Apply post-processing for each modality
398
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
399
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
400
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
401
+
402
+ # --------------------------
403
+ # Save results
404
+ # --------------------------
405
+ os.makedirs(args.output_dir, exist_ok=True)
406
+
407
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
408
+ save_dir.mkdir(parents=True, exist_ok=True)
409
+
410
+ for idx, img in enumerate(results):
411
+ name = modality_names[idx]
412
+ save_path = save_dir / f"{name}.png"
413
+ img.save(save_path)
414
+ print(f"💾 Saved {name} → {save_path}")
415
+
416
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
417
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
418
+
419
+ print(f"\n✅ All results saved in: {save_dir}\n")
420
+ return save_dir
421
+
422
+
423
+ # ------------------------------
424
+ # Entry Point
425
+ # ------------------------------
426
+ if __name__ == "__main__":
427
+ args = get_parser().parse_args()
428
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
429
+ print(f"✅ Using device: {device}")
430
+
431
+ processor = AutoProcessor.from_pretrained(
432
+ args.model_name_or_path,
433
+ )
434
+
435
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
436
+ args.text_model_path,
437
+ attn_implementation="flash_attention_2",
438
+ dtype=(torch.bfloat16),
439
+ ).to(device)
440
+
441
+ torch.manual_seed(args.seed)
442
+ generator = torch.Generator(device=device).manual_seed(args.seed)
443
+
444
+ dataset = load_dataset(
445
+ "parquet",
446
+ data_files=args.data_path,
447
+ split="train")
448
+
449
+ for sample in dataset:
450
+
451
+ image_keys = [f"image_{i}" for i in range(1, 8)]
452
+ num_images = sum(1 for key in image_keys if key in sample and isinstance(sample[key], type(sample["image_1"])) and sample[key] is not None)
453
+
454
+ if num_images > 1:
455
+ continue
456
+
457
+ image = sample["image_1"]
458
+ image_path = dump_image(image, args.temp_dir)
459
+ question = clean_question(sample["question"])
460
+ image_id = sample["id"]
461
+ options = sample["options"]
462
+ field = sample["subfield"]
463
+
464
+ max_length = 1024
465
+
466
+ #input_img = Image.open(image_path).convert("RGB")
467
+ width, height = image.size
468
+ print(f'ori width:{width}', f'ori height:{height}')
469
+
470
+ prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)
471
+
qwen_vqa_Literature.py ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
14
+ from jodi_pipeline import JodiPipeline
15
+ from model.postprocess import (
16
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
17
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
18
+ )
19
+ from transformers import (
20
+ Qwen2VLForConditionalGeneration,
21
+ Qwen2_5_VLForConditionalGeneration,
22
+ Qwen3VLForConditionalGeneration,
23
+ Qwen3VLMoeForConditionalGeneration
24
+ )
25
+ from transformers import AutoProcessor, Trainer
26
+ from pathlib import Path
27
+ import itertools
28
+ import ast
29
+ import re
30
+
31
+ def clean_question(q: str) -> str:
32
+ if not isinstance(q, str):
33
+ q = str(q)
34
+ # 删除 <image 1>、<image1>、<image 2> 等占位符
35
+ q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
36
+ # 再清理多余空白
37
+ q = re.sub(r"\s+", " ", q).strip()
38
+ return q
39
+
40
+ def dump_image(image, save_root):
41
+ os.makedirs(save_root, exist_ok=True)
42
+ save_path = os.path.join(save_root, "input.jpg")
43
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
44
+ return save_path
45
+
46
+
47
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
48
+ """
49
+ 将多个图像拼接成一张大图并保存。
50
+ Args:
51
+ image_paths: List[str] 图像路径列表
52
+ save_path: 保存路径(包括文件名)
53
+ images_per_row: 每行图像数量(默认为全部在一行)
54
+ image_format: 保存格式
55
+ """
56
+ from PIL import Image
57
+ import io
58
+
59
+ # 读取图像
60
+ images = [Image.open(p).convert("RGB") for p in image_paths]
61
+
62
+ if images_per_row is None:
63
+ images_per_row = len(images)
64
+
65
+ # 调整尺寸(可选)
66
+ target_size = min(1024, images[0].size[0])
67
+ images = [img.resize((target_size, target_size)) for img in images]
68
+
69
+ # 拼接
70
+ widths, heights = zip(*(img.size for img in images))
71
+ max_width = max(widths)
72
+ rows = (len(images) + images_per_row - 1) // images_per_row
73
+ total_height = sum(heights[:images_per_row]) * rows
74
+
75
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
76
+ y_offset = 0
77
+ for i in range(0, len(images), images_per_row):
78
+ row_imgs = images[i:i+images_per_row]
79
+ x_offset = 0
80
+ for img in row_imgs:
81
+ new_im.paste(img, (x_offset, y_offset))
82
+ x_offset += max_width
83
+ y_offset += heights[0]
84
+
85
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
86
+ new_im.save(save_path, format=image_format.upper())
87
+ print(f"🧩 Saved merged image → {save_path}")
88
+ return save_path
89
+
90
+
91
+ def build_vqa_message(root, prompt, question, options, subfield):
92
+ """
93
+ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root.
94
+ """
95
+ modality_names = [
96
+ "image",
97
+ "annotation_lineart",
98
+ "annotation_edge",
99
+ "annotation_depth",
100
+ "annotation_normal", "annotation_albedo",
101
+ "annotation_seg_12colors",
102
+ "annotation_openpose",
103
+ ]
104
+
105
+ # --- 检查存在的模态 ---
106
+ available = []
107
+ for name in modality_names: # 优先匹配 .png 或 .jpg
108
+ for ext in [".png", ".jpg", ".jpeg"]:
109
+ path = Path(root) / f"{name}{ext}"
110
+ if path.exists():
111
+ available.append(str(path))
112
+ break
113
+ # --- 构建模态说明 ---
114
+ readable_map = {
115
+ "image": "RGB image",
116
+ "annotation_lineart": "line drawing",
117
+ "annotation_edge": "edge map",
118
+ "annotation_depth": "depth map", "annotation_normal": "normal map",
119
+ "annotation_albedo": "albedo map",
120
+ "annotation_seg_12colors": "segmentation map",
121
+ "annotation_openpose": "human pose map",
122
+ }
123
+
124
+ options_list = ast.literal_eval(options)
125
+ option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)])
126
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
127
+ # --- 构造文本指令 ---
128
+ text_prompt = (
129
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
130
+ f"Each modality provides complementary information about the same visual content: "
131
+ f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. "
132
+ f"- The line drawing highlights object outlines, shapes, and fine structures. "
133
+ f"- The edge map emphasizes boundaries and contours. "
134
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships. "
135
+ f"- The normal map shows surface orientation and geometric curvature. "
136
+ f"- The albedo map presents true surface color without illumination or shadows. "
137
+ f"- The segmentation map divides the scene into semantic regions and object categories. "
138
+ f"- The human pose map indicates body orientation, structure, and articulation. "
139
+ f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. "
140
+ f"Scene description: \"{prompt}\" "
141
+ f"Scientific Subfield: \"{subfield}\" "
142
+ f"Now, based on both the multimodal visual information and the given scene description, "
143
+ f"analyze the scene carefully to answer a question. "
144
+ f"Your analysis should proceed in two stages:\n\n"
145
+ f"**Stage 1 — Modality-wise Observation:**\n"
146
+ f"For each provided modality image, analyze what specific visual information it contributes "
147
+ f"based on the above definitions. Describe what can be directly observed from each modality, "
148
+ f"such as color, shape, structure, spatial depth, or object positions. "
149
+ f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: "
150
+ f"Question: \"{question}\" "
151
+ f"Options: \"{option_text}\" "
152
+ + " ".join(["<image>"] * len(available))
153
+ )
154
+
155
+ # --- 构建 Qwen3-VL 消息格式 ---
156
+ messages = [
157
+ {
158
+ "role": "user",
159
+ "content": [{"type": "image", "image": path} for path in available]
160
+ + [{"type": "text", "text": text_prompt}],
161
+ }
162
+ ]
163
+ return messages
164
+
165
+
166
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
167
+ """
168
+ Build Qwen3-VL message for multi-modal caption refinement.
169
+ Automatically detects available modalities under root.
170
+ """
171
+ modality_names = [
172
+ "image",
173
+ "annotation_lineart",
174
+ "annotation_edge",
175
+ "annotation_depth",
176
+ "annotation_normal",
177
+ "annotation_albedo",
178
+ "annotation_seg_12colors",
179
+ "annotation_openpose",
180
+ ]
181
+
182
+ # --- 检查存在的模态 ---
183
+ available = []
184
+ for name in modality_names:
185
+ # 优先匹配 .png 或 .jpg
186
+ for ext in [".png", ".jpg", ".jpeg"]:
187
+ path = Path(root) / f"{name}{ext}"
188
+ if path.exists():
189
+ available.append(str(path))
190
+ break
191
+
192
+ # --- 构建模态说明 ---
193
+ readable_map = {
194
+ "image": "RGB image",
195
+ "annotation_lineart": "line drawing",
196
+ "annotation_edge": "edge map",
197
+ "annotation_depth": "depth map",
198
+ "annotation_normal": "normal map",
199
+ "annotation_albedo": "albedo map",
200
+ "annotation_seg_12colors": "segmentation map",
201
+ "annotation_openpose": "human pose map",
202
+ }
203
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
204
+
205
+ # --- 构造文本指令 ---
206
+ text_prompt = (
207
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
208
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
209
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
210
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
211
+ f"- The edge map highlights object boundaries and contours. "
212
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
213
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
214
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
215
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
216
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
217
+ f"For each provided modality image, analyze it according to the above definitions and describe "
218
+ f"the specific visual information it contributes in this particular case. "
219
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
220
+ f"Do NOT describe each modality separately or mention modality names. "
221
+ f"Focus on merging their information into a single coherent image description. "
222
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
223
+ f"Refine the coarse caption into a more detailed and accurate image description. "
224
+ f"Coarse caption: '{coarse_caption}' " +
225
+ " ".join(["<image>"] * len(available))
226
+ )
227
+
228
+ # --- 构建 Qwen3-VL 消息格式 ---
229
+ messages = [
230
+ {
231
+ "role": "user",
232
+ "content": [{"type": "image", "image": path} for path in available]
233
+ + [{"type": "text", "text": text_prompt}],
234
+ }
235
+ ]
236
+ return messages
237
+
238
+ # ------------------------------
239
+ # Argument Parser
240
+ # ------------------------------
241
+ def get_parser():
242
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
243
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
244
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
245
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
246
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
247
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/MMMU/Literature/validation-00000-of-00001.parquet", help="Prompt text for generation.")
248
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.")
249
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
250
+ parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.")
251
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
252
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
253
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
254
+ parser.add_argument("--seed", type=int, default=1234)
255
+ parser.add_argument("--output_dir", type=str, default="./qwen_Literature_outputs", help="Directory to save results.")
256
+ return parser
257
+
258
+
259
+ # ------------------------------
260
+ # Main Inference Function
261
+ # ------------------------------
262
+
263
+ @torch.inference_mode()
264
+ def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300):
265
+
266
+ options_list = ast.literal_eval(option)
267
+ option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)])
268
+
269
+ question = clean_question(question)
270
+
271
+ text_prompt = (
272
+ f"Analyze the given image <image> and answer the following question."
273
+ f"Question: \"{question}\" \n"
274
+ f"Options: \"{option_text}\" "
275
+ )
276
+
277
+ messages = [
278
+ {
279
+ "role": "user",
280
+ "content": [
281
+ {
282
+ "type": "image",
283
+ "image": image_path,
284
+ },
285
+ {"type": "text", "text": text_prompt},
286
+ ],
287
+ }
288
+ ]
289
+
290
+ print(messages)
291
+
292
+ inputs = processor.apply_chat_template(
293
+ messages,
294
+ tokenize=True,
295
+ add_generation_prompt=True,
296
+ return_dict=True,
297
+ return_tensors="pt"
298
+ )
299
+ inputs = inputs.to(model.device)
300
+
301
+ # Inference: Generation of the output
302
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
303
+ generated_ids_trimmed = [
304
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
305
+ ]
306
+ output_text = processor.batch_decode(
307
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
308
+ )
309
+ print(output_text)
310
+
311
+ os.makedirs(args.output_dir, exist_ok=True)
312
+ save_dir = Path(args.output_dir) / vqa_id
313
+ save_dir.mkdir(parents=True, exist_ok=True)
314
+ caption_path = Path(save_dir) / f"caption.txt"
315
+ with open(caption_path, "w", encoding="utf-8") as f:
316
+ f.write(output_text[0].strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
322
+ messages = build_multimodal_message(root, prompt)
323
+ inputs = processor.apply_chat_template(
324
+ messages,
325
+ tokenize=True,
326
+ add_generation_prompt=True,
327
+ return_dict=True,
328
+ return_tensors="pt"
329
+ )
330
+ inputs = inputs.to(model.device)
331
+
332
+ # Inference: Generation of the output
333
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
334
+ generated_ids_trimmed = [
335
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
336
+ ]
337
+ output_text = processor.batch_decode(
338
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
339
+ )
340
+ print(output_text)
341
+
342
+ os.makedirs(args.output_dir, exist_ok=True)
343
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
344
+ save_dir.mkdir(parents=True, exist_ok=True)
345
+ caption_path = Path(save_dir) / f"caption.txt"
346
+ with open(caption_path, "w", encoding="utf-8") as f:
347
+ f.write(output_text[0].strip())
348
+
349
+ return output_text[0]
350
+
351
+ @torch.inference_mode()
352
+ def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300):
353
+ messages = build_vqa_message(root, prompt, question, options, subfield)
354
+ print(messages)
355
+ inputs = processor.apply_chat_template(
356
+ messages,
357
+ tokenize=True,
358
+ add_generation_prompt=True,
359
+ return_dict=True,
360
+ return_tensors="pt"
361
+ )
362
+ inputs = inputs.to(model.device)
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
366
+ output_text = processor.batch_decode(
367
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
368
+ )
369
+ print(output_text)
370
+ os.makedirs(args.output_dir, exist_ok=True)
371
+ save_dir = Path(args.output_dir) / vqa_id
372
+ save_dir.mkdir(parents=True, exist_ok=True)
373
+ caption_path = Path(save_dir) / f"caption.txt"
374
+ with open(caption_path, "w", encoding="utf-8") as f:
375
+ f.write(output_text[0].strip())
376
+ return output_text[0]
377
+
378
+ @torch.inference_mode()
379
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield):
380
+
381
+ print(f"🚀 Generating with prompt: {prompt}")
382
+ prompt = f'{subfield} image,' + ' ' + prompt
383
+ outputs = pipe(
384
+ images=images,
385
+ role=role,
386
+ prompt=prompt,
387
+ negative_prompt=args.negative_prompt,
388
+ height=height,
389
+ width=width,
390
+ num_inference_steps=args.steps,
391
+ guidance_scale=args.guidance_scale,
392
+ num_images_per_prompt=1,
393
+ generator=generator,
394
+ task='t2i'
395
+ )
396
+
397
+ # Apply post-processing for each modality
398
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
399
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
400
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
401
+
402
+ # --------------------------
403
+ # Save results
404
+ # --------------------------
405
+ os.makedirs(args.output_dir, exist_ok=True)
406
+
407
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
408
+ save_dir.mkdir(parents=True, exist_ok=True)
409
+
410
+ for idx, img in enumerate(results):
411
+ name = modality_names[idx]
412
+ save_path = save_dir / f"{name}.png"
413
+ img.save(save_path)
414
+ print(f"💾 Saved {name} → {save_path}")
415
+
416
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
417
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
418
+
419
+ print(f"\n✅ All results saved in: {save_dir}\n")
420
+ return save_dir
421
+
422
+
423
+ # ------------------------------
424
+ # Entry Point
425
+ # ------------------------------
426
+ if __name__ == "__main__":
427
+ args = get_parser().parse_args()
428
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
429
+ print(f"✅ Using device: {device}")
430
+
431
+ processor = AutoProcessor.from_pretrained(
432
+ args.model_name_or_path,
433
+ )
434
+
435
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
436
+ args.text_model_path,
437
+ attn_implementation="flash_attention_2",
438
+ dtype=(torch.bfloat16),
439
+ ).to(device)
440
+
441
+ torch.manual_seed(args.seed)
442
+ generator = torch.Generator(device=device).manual_seed(args.seed)
443
+
444
+ dataset = load_dataset(
445
+ "parquet",
446
+ data_files=args.data_path,
447
+ split="train")
448
+
449
+ for sample in dataset:
450
+
451
+ image_keys = [f"image_{i}" for i in range(1, 8)]
452
+ num_images = sum(1 for key in image_keys if key in sample and isinstance(sample[key], type(sample["image_1"])) and sample[key] is not None)
453
+
454
+ if num_images > 1:
455
+ continue
456
+
457
+ image = sample["image_1"]
458
+ image_path = dump_image(image, args.temp_dir)
459
+ question = clean_question(sample["question"])
460
+ image_id = sample["id"]
461
+ options = sample["options"]
462
+ field = sample["subfield"]
463
+
464
+ max_length = 1024
465
+
466
+ #input_img = Image.open(image_path).convert("RGB")
467
+ width, height = image.size
468
+ print(f'ori width:{width}', f'ori height:{height}')
469
+
470
+ prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)
471
+
t2i.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--prompt", type=str, default="cat.", help="Prompt text for generation.")
153
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
154
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
155
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
156
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
157
+ parser.add_argument("--height", type=int, default=1024)
158
+ parser.add_argument("--width", type=int, default=1024)
159
+ parser.add_argument("--seed", type=int, default=1234)
160
+ parser.add_argument("--output_dir", type=str, default="./demo_t2i_outputs", help="Directory to save results.")
161
+ return parser
162
+
163
+
164
+ # ------------------------------
165
+ # Main Inference Function
166
+ # ------------------------------
167
+ @torch.inference_mode()
168
+ def init_t2i(args, pipe, iter_num, post_processors, modality_names, generator):
169
+
170
+ # --------------------------
171
+ # Inference
172
+ # --------------------------
173
+
174
+ print(f"🚀 Generating with prompt: {args.prompt}")
175
+ outputs = pipe(
176
+ images=[None] * (1 + pipe.num_conditions),
177
+ role=[0] * (1 + pipe.num_conditions),
178
+ prompt=args.prompt,
179
+ negative_prompt=args.negative_prompt,
180
+ height=args.height,
181
+ width=args.width,
182
+ num_inference_steps=args.steps,
183
+ guidance_scale=args.guidance_scale,
184
+ num_images_per_prompt=1,
185
+ generator=generator
186
+ )
187
+
188
+ # Apply post-processing for each modality
189
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
190
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
191
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
192
+
193
+ # --------------------------
194
+ # Save results
195
+ # --------------------------
196
+ os.makedirs(args.output_dir, exist_ok=True)
197
+
198
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
199
+ save_dir.mkdir(parents=True, exist_ok=True)
200
+
201
+ for idx, img in enumerate(results):
202
+ name = modality_names[idx]
203
+ save_path = save_dir / f"{name}.png"
204
+ img.save(save_path)
205
+ print(f"💾 Saved {name} → {save_path}")
206
+
207
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
208
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
209
+
210
+ print(f"\n✅ All results saved in: {save_dir}\n")
211
+ return save_dir
212
+
213
+ def text_refine(root, model, processor, prompt, iter_num, max_length=300):
214
+ messages = build_multimodal_message(root, prompt)
215
+ inputs = processor.apply_chat_template(
216
+ messages,
217
+ tokenize=True,
218
+ add_generation_prompt=True,
219
+ return_dict=True,
220
+ return_tensors="pt"
221
+ )
222
+ inputs = inputs.to(model.device)
223
+
224
+ # Inference: Generation of the output
225
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
226
+ generated_ids_trimmed = [
227
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
228
+ ]
229
+ output_text = processor.batch_decode(
230
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
231
+ )
232
+ print(output_text)
233
+
234
+ os.makedirs(args.output_dir, exist_ok=True)
235
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
236
+ save_dir.mkdir(parents=True, exist_ok=True)
237
+ caption_path = Path(save_dir) / f"caption.txt"
238
+ with open(caption_path, "w", encoding="utf-8") as f:
239
+ f.write(output_text[0].strip())
240
+
241
+ return output_text[0]
242
+
243
+ def image_refine(prompt, root, iter_num, modality_names, generator):
244
+
245
+ control_images = []
246
+ for name in modality_names:
247
+ control_images.append(Image.open(os.path.join(root, name+'.png')).convert("RGB"))
248
+
249
+ print(f"🚀 Generating with prompt: {args.prompt}")
250
+ prompt = args.prompt + ' ' + prompt
251
+ outputs = pipe(
252
+ images=control_images,
253
+ role=[0] * (1 + pipe.num_conditions),
254
+ prompt=prompt,
255
+ negative_prompt=args.negative_prompt,
256
+ height=args.height,
257
+ width=args.width,
258
+ num_inference_steps=args.steps,
259
+ guidance_scale=args.guidance_scale,
260
+ num_images_per_prompt=1,
261
+ generator=generator,
262
+ task='t2i'
263
+ )
264
+
265
+ # Apply post-processing for each modality
266
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
267
+ results = torch.stack(results, dim=1).reshape(-1, 3, args.height, args.width)
268
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
269
+
270
+ # --------------------------
271
+ # Save results
272
+ # --------------------------
273
+ os.makedirs(args.output_dir, exist_ok=True)
274
+
275
+ save_dir = Path(args.output_dir) / f"iteration_{iter_num}"
276
+ save_dir.mkdir(parents=True, exist_ok=True)
277
+
278
+ for idx, img in enumerate(results):
279
+ name = modality_names[idx]
280
+ save_path = save_dir / f"{name}.png"
281
+ img.save(save_path)
282
+ print(f"💾 Saved {name} → {save_path}")
283
+
284
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
285
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
286
+
287
+ print(f"\n✅ All results saved in: {save_dir}\n")
288
+ return save_dir
289
+
290
+
291
+ # ------------------------------
292
+ # Entry Point
293
+ # ------------------------------
294
+ if __name__ == "__main__":
295
+ args = get_parser().parse_args()
296
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
297
+ print(f"✅ Using device: {device}")
298
+
299
+ processor = AutoProcessor.from_pretrained(
300
+ args.model_name_or_path,
301
+ )
302
+
303
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
304
+ args.text_model_path,
305
+ attn_implementation="flash_attention_2",
306
+ dtype=(torch.bfloat16),
307
+ ).to(device)
308
+
309
+ pipe = JodiPipeline(args.config)
310
+ pipe.from_pretrained(args.model_path)
311
+
312
+ modality_names = [
313
+ "image",
314
+ "annotation_lineart",
315
+ "annotation_edge",
316
+ "annotation_depth",
317
+ "annotation_normal",
318
+ "annotation_albedo",
319
+ "annotation_seg_12colors",
320
+ "annotation_openpose",
321
+ ]
322
+
323
+ # Build post-processors
324
+ post_processors: list[Any] = [ImagePostProcessor()]
325
+ for condition in pipe.config.conditions: # type: ignore
326
+ if condition == "lineart":
327
+ post_processors.append(LineartPostProcessor())
328
+ elif condition == "edge":
329
+ post_processors.append(EdgePostProcessor())
330
+ elif condition == "depth":
331
+ post_processors.append(DepthPostProcessor())
332
+ elif condition == "normal":
333
+ post_processors.append(NormalPostProcessor())
334
+ elif condition == "albedo":
335
+ post_processors.append(AlbedoPostProcessor())
336
+ elif condition == "segmentation":
337
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
338
+ elif condition == "openpose":
339
+ post_processors.append(OpenposePostProcessor())
340
+ else:
341
+ print(f"⚠️ Warning: Unknown condition: {condition}")
342
+ post_processors.append(ImagePostProcessor())
343
+
344
+ torch.manual_seed(args.seed)
345
+ generator = torch.Generator(device=device).manual_seed(args.seed)
346
+
347
+ init_dir = init_t2i(args, pipe, 0, post_processors, modality_names, generator)
348
+
349
+ save_dir = init_dir
350
+ prompt = args.prompt
351
+ max_length = 1024
352
+ for step in range(1, args.iters):
353
+ prompt = text_refine(save_dir,model, processor, prompt, step, max_length)
354
+ max_length += 100
355
+ save_dir = image_refine(prompt, save_dir, step, modality_names, generator)
356
+
357
+
test_i2t_coco.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[:123]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco1.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[123:246]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco2.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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 re
28
+
29
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
30
+ """
31
+ 将多个图像拼接成一张大图并保存。
32
+ Args:
33
+ image_paths: List[str] 图像路径列表
34
+ save_path: 保存路径(包括文件名)
35
+ images_per_row: 每行图像数量(默认为全部在一行)
36
+ image_format: 保存格式
37
+ """
38
+ from PIL import Image
39
+ import io
40
+
41
+ # 读取图像
42
+ images = [Image.open(p).convert("RGB") for p in image_paths]
43
+
44
+ if images_per_row is None:
45
+ images_per_row = len(images)
46
+
47
+ # 调整尺寸(可选)
48
+ target_size = min(1024, images[0].size[0])
49
+ images = [img.resize((target_size, target_size)) for img in images]
50
+
51
+ # 拼接
52
+ widths, heights = zip(*(img.size for img in images))
53
+ max_width = max(widths)
54
+ rows = (len(images) + images_per_row - 1) // images_per_row
55
+ total_height = sum(heights[:images_per_row]) * rows
56
+
57
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
58
+ y_offset = 0
59
+ for i in range(0, len(images), images_per_row):
60
+ row_imgs = images[i:i+images_per_row]
61
+ x_offset = 0
62
+ for img in row_imgs:
63
+ new_im.paste(img, (x_offset, y_offset))
64
+ x_offset += max_width
65
+ y_offset += heights[0]
66
+
67
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
68
+ new_im.save(save_path, format=image_format.upper())
69
+ print(f"🧩 Saved merged image → {save_path}")
70
+ return save_path
71
+
72
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=''):
73
+ """
74
+ Build Qwen3-VL message for multi-modal caption refinement.
75
+ Automatically detects available modalities under root.
76
+ """
77
+ modality_names = [
78
+ "image",
79
+ "annotation_lineart",
80
+ "annotation_edge",
81
+ "annotation_depth",
82
+ "annotation_normal",
83
+ "annotation_albedo",
84
+ "annotation_seg_12colors",
85
+ "annotation_openpose",
86
+ ]
87
+
88
+ # --- 检查存在的模态 ---
89
+ available = []
90
+ for name in modality_names:
91
+ # 优先匹配 .png 或 .jpg
92
+ for ext in [".png", ".jpg", ".jpeg"]:
93
+ path = Path(root) / f"{name}{ext}"
94
+ if path.exists():
95
+ available.append(str(path))
96
+ break
97
+
98
+ # --- 构建模态说明 ---
99
+ readable_map = {
100
+ "image": "RGB image",
101
+ "annotation_lineart": "line drawing",
102
+ "annotation_edge": "edge map",
103
+ "annotation_depth": "depth map",
104
+ "annotation_normal": "normal map",
105
+ "annotation_albedo": "albedo map",
106
+ "annotation_seg_12colors": "segmentation map",
107
+ "annotation_openpose": "human pose map",
108
+ }
109
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
110
+
111
+ # --- 构造文本指令 ---
112
+ text_prompt = (
113
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
114
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
115
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
116
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
117
+ f"- The edge map highlights object boundaries and contours. "
118
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
119
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
120
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
121
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
122
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
123
+ f"For each provided modality image, analyze it according to the above definitions and describe "
124
+ f"the specific visual information it contributes in this particular case. "
125
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
126
+ f"Do NOT describe each modality separately or mention modality names. "
127
+ f"Focus on merging their information into a single coherent image description. "
128
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
129
+ f"Consider the following feedback when refining your description: '{feedback}'. "
130
+ f"Refine the coarse caption into a more detailed and accurate image description. "
131
+ f"Coarse caption: '{coarse_caption}' " +
132
+ " ".join(["<image>"] * len(available))
133
+ )
134
+
135
+ # --- 构建 Qwen3-VL 消息格式 ---
136
+ messages = [
137
+ {
138
+ "role": "user",
139
+ "content": [{"type": "image", "image": path} for path in available]
140
+ + [{"type": "text", "text": text_prompt}],
141
+ }
142
+ ]
143
+ return messages
144
+
145
+ # ------------------------------
146
+ # Argument Parser
147
+ # ------------------------------
148
+ def get_parser():
149
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
150
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
151
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
152
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
153
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
154
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
155
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
156
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
157
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
158
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
159
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
160
+ parser.add_argument("--seed", type=int, default=42)
161
+ parser.add_argument("--output_dir", type=str, default="./example_coco_i2t_outputs", help="Directory to save results.")
162
+ return parser
163
+
164
+
165
+ # ------------------------------
166
+ # Main Inference Function
167
+ # ------------------------------
168
+
169
+ @torch.inference_mode()
170
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
171
+ messages = [
172
+ {
173
+ "role": "user",
174
+ "content": [
175
+ {
176
+ "type": "image",
177
+ "image": image_path,
178
+ },
179
+ {"type": "text", "text": "Describe this image."},
180
+ ],
181
+ }
182
+ ]
183
+
184
+ inputs = processor.apply_chat_template(
185
+ messages,
186
+ tokenize=True,
187
+ add_generation_prompt=True,
188
+ return_dict=True,
189
+ return_tensors="pt"
190
+ )
191
+ inputs = inputs.to(model.device)
192
+
193
+ # Inference: Generation of the output
194
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
195
+ generated_ids_trimmed = [
196
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
197
+ ]
198
+ output_text = processor.batch_decode(
199
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
200
+ )
201
+ #print(output_text)
202
+
203
+ os.makedirs(args.output_dir, exist_ok=True)
204
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
205
+ save_dir.mkdir(parents=True, exist_ok=True)
206
+ caption_path = Path(save_dir) / f"caption.txt"
207
+ with open(caption_path, "w", encoding="utf-8") as f:
208
+ f.write(output_text[0].strip())
209
+
210
+ return output_text[0]
211
+
212
+
213
+
214
+ @torch.inference_mode()
215
+ def evaluate_caption(image_path, model, processor, caption, max_length=256):
216
+ """
217
+ Evaluate how well the generated caption truthfully describes the given image.
218
+ """
219
+ eval_prompt = f"""
220
+ You are an image–caption alignment evaluator and factuality advisor.
221
+ Given one RGB image and a textual caption, evaluate how well the caption
222
+ truthfully and comprehensively describes what is visually shown.
223
+
224
+ Caption: "{caption}"
225
+
226
+ ## Evaluation focus
227
+ - Describe whether all **objects, attributes, and relations** mentioned in the caption are actually visible.
228
+ - The caption should only include what is clearly seen in the image — no imaginary or hallucinated content.
229
+ - The caption should also cover the **main visible objects** and their essential attributes (color, count, relative position) if possible.
230
+ - If the caption adds nonexistent objects or attributes, reduce the score sharply (<0.6).
231
+ - If the caption omits minor details but remains overall faithful, keep a moderate score (~0.8–0.9).
232
+ - If the caption perfectly matches and fully reflects the visual scene, score near 1.0.
233
+
234
+ ## Feedback instruction
235
+ Provide **one short constructive feedback sentence** to improve the caption.
236
+ - Focus on what should be *added, adjusted, or rephrased* for truthfulness.
237
+ - Do NOT mention errors or missing things directly (avoid "not", "no", "missing", "wrong", "fail").
238
+ - Start with a verb such as "Add", "Replace", "Adjust", "Rephrase", "Include", "Describe".
239
+ - Example:
240
+ - If the caption says "a cat and a dog" but only a cat is visible → "Remove the dog and describe only the cat."
241
+ - If the caption omits a visible red car → "Add the red car on the right side of the road."
242
+ - If the color or quantity is inaccurate → "Replace with the correct color and number as seen."
243
+
244
+ Return JSON only:
245
+ {{
246
+ "Consistency": <float 0–1>,
247
+ "Feedback": "<one short sentence suggesting how to make the caption more accurate>"
248
+ }}
249
+
250
+ <image>
251
+ """
252
+
253
+ messages = [
254
+ {
255
+ "role": "user",
256
+ "content": [
257
+ {"type": "image", "image": image_path},
258
+ {"type": "text", "text": eval_prompt},
259
+ ],
260
+ }
261
+ ]
262
+
263
+ print(f'eval:{messages}')
264
+
265
+ inputs = processor.apply_chat_template(
266
+ messages,
267
+ tokenize=True,
268
+ add_generation_prompt=True,
269
+ return_dict=True,
270
+ return_tensors="pt"
271
+ ).to(model.device)
272
+
273
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
274
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
275
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
276
+
277
+ try:
278
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
279
+ score = float(data.get("Consistency", 0))
280
+ feedback = data.get("Feedback", "")
281
+ except Exception:
282
+ score, feedback = 0.0, text.strip()
283
+
284
+ #print(f" → Overall={score:.3f}")
285
+ #print(f"💡 Feedback: {feedback}")
286
+ return score, feedback
287
+
288
+
289
+
290
+ @torch.inference_mode()
291
+ def text_refine(root, model, processor, prompt, feedback, iter_num, name, max_length=300):
292
+ messages = build_multimodal_message(root, prompt, feedback)
293
+ print(f'refine message:{messages}')
294
+ inputs = processor.apply_chat_template(
295
+ messages,
296
+ tokenize=True,
297
+ add_generation_prompt=True,
298
+ return_dict=True,
299
+ return_tensors="pt"
300
+ )
301
+ inputs = inputs.to(model.device)
302
+
303
+ # Inference: Generation of the output
304
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
305
+ generated_ids_trimmed = [
306
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
307
+ ]
308
+ output_text = processor.batch_decode(
309
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
310
+ )
311
+ #print(output_text)
312
+
313
+ os.makedirs(args.output_dir, exist_ok=True)
314
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
315
+ save_dir.mkdir(parents=True, exist_ok=True)
316
+ caption_path = Path(save_dir) / f"caption.txt"
317
+ with open(caption_path, "w", encoding="utf-8") as f:
318
+ f.write(output_text[0].strip())
319
+
320
+ return output_text[0]
321
+
322
+ @torch.inference_mode()
323
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
324
+
325
+ #print(f"🚀 Generating with prompt: {prompt}")
326
+ #prompt = args.prompt + ' ' + prompt
327
+ outputs = pipe(
328
+ images=images,
329
+ role=role,
330
+ prompt=prompt,
331
+ negative_prompt=args.negative_prompt,
332
+ height=height,
333
+ width=width,
334
+ num_inference_steps=args.steps,
335
+ guidance_scale=args.guidance_scale,
336
+ num_images_per_prompt=1,
337
+ generator=generator,
338
+ )
339
+
340
+ # Apply post-processing for each modality
341
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
342
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
343
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
344
+
345
+ # --------------------------
346
+ # Save results
347
+ # --------------------------
348
+ os.makedirs(args.output_dir, exist_ok=True)
349
+
350
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
351
+ save_dir.mkdir(parents=True, exist_ok=True)
352
+
353
+ for idx, img in enumerate(results):
354
+ name = modality_names[idx]
355
+ save_path = save_dir / f"{name}.png"
356
+ img.save(save_path)
357
+ #print(f"💾 Saved {name} → {save_path}")
358
+
359
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
360
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
361
+
362
+ #print(f"\n✅ All results saved in: {save_dir}\n")
363
+ return save_dir
364
+
365
+
366
+ # ------------------------------
367
+ # Entry Point
368
+ # ------------------------------
369
+ if __name__ == "__main__":
370
+ args = get_parser().parse_args()
371
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
372
+ print(f"✅ Using device: {device}")
373
+
374
+ processor = AutoProcessor.from_pretrained(
375
+ args.model_name_or_path,
376
+ )
377
+
378
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
379
+ args.text_model_path,
380
+ attn_implementation="flash_attention_2",
381
+ dtype=(torch.bfloat16),
382
+ ).to(device)
383
+
384
+ pipe = JodiPipeline(args.config)
385
+ pipe.from_pretrained(args.model_path)
386
+
387
+ modality_names = [
388
+ "image",
389
+ "annotation_lineart",
390
+ "annotation_edge",
391
+ "annotation_depth",
392
+ "annotation_normal",
393
+ "annotation_albedo",
394
+ "annotation_seg_12colors",
395
+ "annotation_openpose",
396
+ ]
397
+
398
+ # Build post-processors
399
+ post_processors: list[Any] = [ImagePostProcessor()]
400
+ for condition in pipe.config.conditions: # type: ignore
401
+ if condition == "lineart":
402
+ post_processors.append(LineartPostProcessor())
403
+ elif condition == "edge":
404
+ post_processors.append(EdgePostProcessor())
405
+ elif condition == "depth":
406
+ post_processors.append(DepthPostProcessor())
407
+ elif condition == "normal":
408
+ post_processors.append(NormalPostProcessor())
409
+ elif condition == "albedo":
410
+ post_processors.append(AlbedoPostProcessor())
411
+ elif condition == "segmentation":
412
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
413
+ elif condition == "openpose":
414
+ post_processors.append(OpenposePostProcessor())
415
+ else:
416
+ print(f"⚠️ Warning: Unknown condition: {condition}")
417
+ post_processors.append(ImagePostProcessor())
418
+
419
+ torch.manual_seed(args.seed)
420
+ generator = torch.Generator(device=device).manual_seed(args.seed)
421
+ import glob
422
+ image_root = args.image_root
423
+ json_path = args.json_path
424
+
425
+ with open(json_path, "r") as f:
426
+ data = json.load(f)
427
+
428
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
429
+ image_names = [item["image_path"] for item in data][4021:]
430
+
431
+ for image_name in image_names[246:369]:
432
+
433
+ if image_name in save_image_names:
434
+ print(f'already got {image_name} in ', f'our {save_image_names}')
435
+
436
+ image_path = os.path.join(image_root, image_name)
437
+ image = Image.open(image_path).convert("RGB")
438
+ width, height = image.size
439
+
440
+ control_images = [image] + [None] * pipe.num_conditions
441
+
442
+ role=[1] + [0] * pipe.num_conditions
443
+ print(role)
444
+
445
+ max_length = 1024
446
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
447
+
448
+ score, feedback = evaluate_caption(image_path, model, processor, prompt)
449
+
450
+ for step in range(1, args.iters):
451
+ generator = torch.Generator(device=device).manual_seed(args.seed)
452
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
453
+ max_length += 100
454
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_name, max_length)
455
+ score, feedback = evaluate_caption(image_path, model, processor, prompt)
456
+
457
+
test_i2t_coco3.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[369:492]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco4.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[492:615]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco5.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[615:738]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco6.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[738:861]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_coco7.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/COCO_Karpathy/karpathy_test.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./coco_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ )
258
+
259
+ # Apply post-processing for each modality
260
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
261
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
262
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
263
+
264
+ # --------------------------
265
+ # Save results
266
+ # --------------------------
267
+ os.makedirs(args.output_dir, exist_ok=True)
268
+
269
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
270
+ save_dir.mkdir(parents=True, exist_ok=True)
271
+
272
+ for idx, img in enumerate(results):
273
+ name = modality_names[idx]
274
+ save_path = save_dir / f"{name}.png"
275
+ img.save(save_path)
276
+ print(f"💾 Saved {name} → {save_path}")
277
+
278
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
279
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
280
+
281
+ print(f"\n✅ All results saved in: {save_dir}\n")
282
+ return save_dir
283
+
284
+
285
+ # ------------------------------
286
+ # Entry Point
287
+ # ------------------------------
288
+ if __name__ == "__main__":
289
+ args = get_parser().parse_args()
290
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
291
+ print(f"✅ Using device: {device}")
292
+
293
+ processor = AutoProcessor.from_pretrained(
294
+ args.model_name_or_path,
295
+ )
296
+
297
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
298
+ args.text_model_path,
299
+ attn_implementation="flash_attention_2",
300
+ dtype=(torch.bfloat16),
301
+ ).to(device)
302
+
303
+ pipe = JodiPipeline(args.config)
304
+ pipe.from_pretrained(args.model_path)
305
+
306
+ modality_names = [
307
+ "image",
308
+ "annotation_lineart",
309
+ "annotation_edge",
310
+ "annotation_depth",
311
+ "annotation_normal",
312
+ "annotation_albedo",
313
+ "annotation_seg_12colors",
314
+ "annotation_openpose",
315
+ ]
316
+
317
+ # Build post-processors
318
+ post_processors: list[Any] = [ImagePostProcessor()]
319
+ for condition in pipe.config.conditions: # type: ignore
320
+ if condition == "lineart":
321
+ post_processors.append(LineartPostProcessor())
322
+ elif condition == "edge":
323
+ post_processors.append(EdgePostProcessor())
324
+ elif condition == "depth":
325
+ post_processors.append(DepthPostProcessor())
326
+ elif condition == "normal":
327
+ post_processors.append(NormalPostProcessor())
328
+ elif condition == "albedo":
329
+ post_processors.append(AlbedoPostProcessor())
330
+ elif condition == "segmentation":
331
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
332
+ elif condition == "openpose":
333
+ post_processors.append(OpenposePostProcessor())
334
+ else:
335
+ print(f"⚠️ Warning: Unknown condition: {condition}")
336
+ post_processors.append(ImagePostProcessor())
337
+
338
+ torch.manual_seed(args.seed)
339
+ generator = torch.Generator(device=device).manual_seed(args.seed)
340
+ import glob
341
+ image_root = args.image_root
342
+ json_path = args.json_path
343
+
344
+ with open(json_path, "r") as f:
345
+ data = json.load(f)
346
+
347
+ save_image_names = os.listdir("/home/efs/mjw/mjw/code/Jodi/coco_i2t_outputs/val2014")
348
+ image_names = [item["image_path"] for item in data][4021:]
349
+
350
+ for image_name in image_names[861:]:
351
+
352
+ if image_name in save_image_names:
353
+ print(f'already got {image_name} in ', f'our {save_image_names}')
354
+
355
+ image_path = os.path.join(image_root, image_name)
356
+ image = Image.open(image_path).convert("RGB")
357
+ width, height = image.size
358
+
359
+ control_images = [image] + [None] * pipe.num_conditions
360
+
361
+ role=[1] + [0] * pipe.num_conditions
362
+ print(role)
363
+
364
+ max_length = 1024
365
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
366
+
367
+ for step in range(1, args.iters):
368
+ generator = torch.Generator(device=device).manual_seed(args.seed)
369
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
370
+ max_length += 100
371
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
372
+
373
+
test_i2t_nocaps.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./nocaps_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ task='t2i'
258
+ )
259
+
260
+ # Apply post-processing for each modality
261
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
262
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
263
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
264
+
265
+ # --------------------------
266
+ # Save results
267
+ # --------------------------
268
+ os.makedirs(args.output_dir, exist_ok=True)
269
+
270
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
271
+ save_dir.mkdir(parents=True, exist_ok=True)
272
+
273
+ for idx, img in enumerate(results):
274
+ name = modality_names[idx]
275
+ save_path = save_dir / f"{name}.png"
276
+ img.save(save_path)
277
+ print(f"💾 Saved {name} → {save_path}")
278
+
279
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
280
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
281
+
282
+ print(f"\n✅ All results saved in: {save_dir}\n")
283
+ return save_dir
284
+
285
+
286
+ # ------------------------------
287
+ # Entry Point
288
+ # ------------------------------
289
+ if __name__ == "__main__":
290
+ args = get_parser().parse_args()
291
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
292
+ print(f"✅ Using device: {device}")
293
+
294
+ processor = AutoProcessor.from_pretrained(
295
+ args.model_name_or_path,
296
+ )
297
+
298
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
299
+ args.text_model_path,
300
+ attn_implementation="flash_attention_2",
301
+ dtype=(torch.bfloat16),
302
+ ).to(device)
303
+
304
+ pipe = JodiPipeline(args.config)
305
+ pipe.from_pretrained(args.model_path)
306
+
307
+ modality_names = [
308
+ "image",
309
+ "annotation_lineart",
310
+ "annotation_edge",
311
+ "annotation_depth",
312
+ "annotation_normal",
313
+ "annotation_albedo",
314
+ "annotation_seg_12colors",
315
+ "annotation_openpose",
316
+ ]
317
+
318
+ # Build post-processors
319
+ post_processors: list[Any] = [ImagePostProcessor()]
320
+ for condition in pipe.config.conditions: # type: ignore
321
+ if condition == "lineart":
322
+ post_processors.append(LineartPostProcessor())
323
+ elif condition == "edge":
324
+ post_processors.append(EdgePostProcessor())
325
+ elif condition == "depth":
326
+ post_processors.append(DepthPostProcessor())
327
+ elif condition == "normal":
328
+ post_processors.append(NormalPostProcessor())
329
+ elif condition == "albedo":
330
+ post_processors.append(AlbedoPostProcessor())
331
+ elif condition == "segmentation":
332
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
333
+ elif condition == "openpose":
334
+ post_processors.append(OpenposePostProcessor())
335
+ else:
336
+ print(f"⚠️ Warning: Unknown condition: {condition}")
337
+ post_processors.append(ImagePostProcessor())
338
+
339
+ torch.manual_seed(args.seed)
340
+ generator = torch.Generator(device=device).manual_seed(args.seed)
341
+ import glob
342
+ image_root = args.image_root
343
+ json_path = args.json_path
344
+
345
+ with open(json_path, "r") as f:
346
+ data = json.load(f)
347
+
348
+ image_names = [item["image_name"] for item in data][:750]
349
+
350
+ for image_name in image_names:
351
+ image_path = os.path.join(image_root, image_name)
352
+ image = Image.open(image_path).convert("RGB")
353
+ width, height = image.size
354
+
355
+ control_images = [image] + [None] * pipe.num_conditions
356
+
357
+ role=[1] + [0] * pipe.num_conditions
358
+ print(role)
359
+
360
+ max_length = 1024
361
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
362
+
363
+ for step in range(1, args.iters):
364
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
365
+ max_length += 100
366
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
367
+
368
+
test_i2t_nocaps1.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./nocaps_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ task='t2i'
258
+ )
259
+
260
+ # Apply post-processing for each modality
261
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
262
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
263
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
264
+
265
+ # --------------------------
266
+ # Save results
267
+ # --------------------------
268
+ os.makedirs(args.output_dir, exist_ok=True)
269
+
270
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
271
+ save_dir.mkdir(parents=True, exist_ok=True)
272
+
273
+ for idx, img in enumerate(results):
274
+ name = modality_names[idx]
275
+ save_path = save_dir / f"{name}.png"
276
+ img.save(save_path)
277
+ print(f"💾 Saved {name} → {save_path}")
278
+
279
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
280
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
281
+
282
+ print(f"\n✅ All results saved in: {save_dir}\n")
283
+ return save_dir
284
+
285
+
286
+ # ------------------------------
287
+ # Entry Point
288
+ # ------------------------------
289
+ if __name__ == "__main__":
290
+ args = get_parser().parse_args()
291
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
292
+ print(f"✅ Using device: {device}")
293
+
294
+ processor = AutoProcessor.from_pretrained(
295
+ args.model_name_or_path,
296
+ )
297
+
298
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
299
+ args.text_model_path,
300
+ attn_implementation="flash_attention_2",
301
+ dtype=(torch.bfloat16),
302
+ ).to(device)
303
+
304
+ pipe = JodiPipeline(args.config)
305
+ pipe.from_pretrained(args.model_path)
306
+
307
+ modality_names = [
308
+ "image",
309
+ "annotation_lineart",
310
+ "annotation_edge",
311
+ "annotation_depth",
312
+ "annotation_normal",
313
+ "annotation_albedo",
314
+ "annotation_seg_12colors",
315
+ "annotation_openpose",
316
+ ]
317
+
318
+ # Build post-processors
319
+ post_processors: list[Any] = [ImagePostProcessor()]
320
+ for condition in pipe.config.conditions: # type: ignore
321
+ if condition == "lineart":
322
+ post_processors.append(LineartPostProcessor())
323
+ elif condition == "edge":
324
+ post_processors.append(EdgePostProcessor())
325
+ elif condition == "depth":
326
+ post_processors.append(DepthPostProcessor())
327
+ elif condition == "normal":
328
+ post_processors.append(NormalPostProcessor())
329
+ elif condition == "albedo":
330
+ post_processors.append(AlbedoPostProcessor())
331
+ elif condition == "segmentation":
332
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
333
+ elif condition == "openpose":
334
+ post_processors.append(OpenposePostProcessor())
335
+ else:
336
+ print(f"⚠️ Warning: Unknown condition: {condition}")
337
+ post_processors.append(ImagePostProcessor())
338
+
339
+ torch.manual_seed(args.seed)
340
+ generator = torch.Generator(device=device).manual_seed(args.seed)
341
+ import glob
342
+ image_root = args.image_root
343
+ json_path = args.json_path
344
+
345
+ with open(json_path, "r") as f:
346
+ data = json.load(f)
347
+
348
+ image_names = [item["image_name"] for item in data][750:1500]
349
+
350
+ for image_name in image_names:
351
+ image_path = os.path.join(image_root, image_name)
352
+ image = Image.open(image_path).convert("RGB")
353
+ width, height = image.size
354
+
355
+ control_images = [image] + [None] * pipe.num_conditions
356
+
357
+ role=[1] + [0] * pipe.num_conditions
358
+ print(role)
359
+
360
+ max_length = 1024
361
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
362
+
363
+ for step in range(1, args.iters):
364
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
365
+ max_length += 100
366
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
367
+
368
+
test_i2t_nocaps2.py ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ import re
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, feedback, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Consider the following feedback when refining your description: '{feedback}'. "
129
+ f"Refine the coarse caption into a more detailed and accurate image description. "
130
+ f"Coarse caption: '{coarse_caption}' " +
131
+ " ".join(["<image>"] * len(available))
132
+ )
133
+
134
+ # --- 构建 Qwen3-VL 消息格式 ---
135
+ messages = [
136
+ {
137
+ "role": "user",
138
+ "content": [{"type": "image", "image": path} for path in available]
139
+ + [{"type": "text", "text": text_prompt}],
140
+ }
141
+ ]
142
+ return messages
143
+
144
+ # ------------------------------
145
+ # Argument Parser
146
+ # ------------------------------
147
+ def get_parser():
148
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
149
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
150
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
151
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
152
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
153
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
154
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
155
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
156
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
157
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
158
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
159
+ parser.add_argument("--seed", type=int, default=42)
160
+ parser.add_argument("--output_dir", type=str, default="./example_nocaps_i2t_outputs", help="Directory to save results.")
161
+ return parser
162
+
163
+
164
+ # ------------------------------
165
+ # Main Inference Function
166
+ # ------------------------------
167
+
168
+ @torch.inference_mode()
169
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
170
+ messages = [
171
+ {
172
+ "role": "user",
173
+ "content": [
174
+ {
175
+ "type": "image",
176
+ "image": image_path,
177
+ },
178
+ {"type": "text", "text": "Describe this image."},
179
+ ],
180
+ }
181
+ ]
182
+
183
+ inputs = processor.apply_chat_template(
184
+ messages,
185
+ tokenize=True,
186
+ add_generation_prompt=True,
187
+ return_dict=True,
188
+ return_tensors="pt"
189
+ )
190
+ inputs = inputs.to(model.device)
191
+
192
+ # Inference: Generation of the output
193
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
194
+ generated_ids_trimmed = [
195
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
196
+ ]
197
+ output_text = processor.batch_decode(
198
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
199
+ )
200
+ print(output_text)
201
+
202
+ os.makedirs(args.output_dir, exist_ok=True)
203
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
204
+ save_dir.mkdir(parents=True, exist_ok=True)
205
+ caption_path = Path(save_dir) / f"caption.txt"
206
+ with open(caption_path, "w", encoding="utf-8") as f:
207
+ f.write(output_text[0].strip())
208
+
209
+ return output_text[0]
210
+
211
+
212
+ @torch.inference_mode()
213
+ def evaluate_caption(image_path, model, processor, caption, max_length=256):
214
+ """
215
+ Evaluate how well the generated caption truthfully describes the given image.
216
+ """
217
+ eval_prompt = f"""
218
+ You are an image–caption alignment evaluator and factuality advisor.
219
+ Given one RGB image and a textual caption, evaluate how well the caption
220
+ truthfully and comprehensively describes what is visually shown.
221
+
222
+ Caption: "{caption}"
223
+
224
+ ## Evaluation focus
225
+ - Describe whether all **objects, attributes, and relations** mentioned in the caption are actually visible.
226
+ - The caption should only include what is clearly seen in the image — no imaginary or hallucinated content.
227
+ - The caption should also cover the **main visible objects** and their essential attributes (color, count, relative position) if possible.
228
+ - If the caption adds nonexistent objects or attributes, reduce the score sharply (<0.6).
229
+ - If the caption omits minor details but remains overall faithful, keep a moderate score (~0.8–0.9).
230
+ - If the caption perfectly matches and fully reflects the visual scene, score near 1.0.
231
+
232
+ ## Feedback instruction
233
+ Provide **one short constructive feedback sentence** to improve the caption.
234
+ - Focus on what should be *added, adjusted, or rephrased* for truthfulness.
235
+ - Do NOT mention errors or missing things directly (avoid "not", "no", "missing", "wrong", "fail").
236
+ - Start with a verb such as "Add", "Replace", "Adjust", "Rephrase", "Include", "Describe".
237
+ - Example:
238
+ - If the caption says "a cat and a dog" but only a cat is visible → "Remove the dog and describe only the cat."
239
+ - If the caption omits a visible red car → "Add the red car on the right side of the road."
240
+ - If the color or quantity is inaccurate → "Replace with the correct color and number as seen."
241
+
242
+ Return JSON only:
243
+ {{
244
+ "Consistency": <float 0–1>,
245
+ "Feedback": "<one short sentence suggesting how to make the caption more accurate>"
246
+ }}
247
+
248
+ <image>
249
+ """
250
+
251
+ messages = [
252
+ {
253
+ "role": "user",
254
+ "content": [
255
+ {"type": "image", "image": image_path},
256
+ {"type": "text", "text": eval_prompt},
257
+ ],
258
+ }
259
+ ]
260
+
261
+ inputs = processor.apply_chat_template(
262
+ messages,
263
+ tokenize=True,
264
+ add_generation_prompt=True,
265
+ return_dict=True,
266
+ return_tensors="pt"
267
+ ).to(model.device)
268
+
269
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
270
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
271
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
272
+
273
+ try:
274
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
275
+ score = float(data.get("Consistency", 0))
276
+ feedback = data.get("Feedback", "")
277
+ except Exception:
278
+ score, feedback = 0.0, text.strip()
279
+
280
+ print(f" → Overall={score:.3f}")
281
+ print(f"💡 Feedback: {feedback}")
282
+ return score, feedback
283
+
284
+
285
+ @torch.inference_mode()
286
+ def text_refine(root, model, processor, prompt, feedback, iter_num, name, max_length=300):
287
+ messages = build_multimodal_message(root, feedback, prompt)
288
+ inputs = processor.apply_chat_template(
289
+ messages,
290
+ tokenize=True,
291
+ add_generation_prompt=True,
292
+ return_dict=True,
293
+ return_tensors="pt"
294
+ )
295
+ inputs = inputs.to(model.device)
296
+
297
+ # Inference: Generation of the output
298
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
299
+ generated_ids_trimmed = [
300
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
301
+ ]
302
+ output_text = processor.batch_decode(
303
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
304
+ )
305
+ print(output_text)
306
+
307
+ os.makedirs(args.output_dir, exist_ok=True)
308
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
309
+ save_dir.mkdir(parents=True, exist_ok=True)
310
+ caption_path = Path(save_dir) / f"caption.txt"
311
+ feedback_path = Path(save_dir) / f"feed.txt"
312
+ with open(caption_path, "w", encoding="utf-8") as f:
313
+ f.write(output_text[0].strip())
314
+
315
+ with open(feedback_path, "w", encoding="utf-8") as f:
316
+ f.write(feedback.strip())
317
+
318
+ return output_text[0]
319
+
320
+ @torch.inference_mode()
321
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
322
+
323
+ print(f"🚀 Generating with prompt: {prompt}")
324
+ #prompt = args.prompt + ' ' + prompt
325
+ outputs = pipe(
326
+ images=images,
327
+ role=role,
328
+ prompt=prompt,
329
+ negative_prompt=args.negative_prompt,
330
+ height=height,
331
+ width=width,
332
+ num_inference_steps=args.steps,
333
+ guidance_scale=args.guidance_scale,
334
+ num_images_per_prompt=1,
335
+ generator=generator,
336
+ )
337
+
338
+ # Apply post-processing for each modality
339
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
340
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
341
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
342
+
343
+ # --------------------------
344
+ # Save results
345
+ # --------------------------
346
+ os.makedirs(args.output_dir, exist_ok=True)
347
+
348
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
349
+ save_dir.mkdir(parents=True, exist_ok=True)
350
+
351
+ for idx, img in enumerate(results):
352
+ name = modality_names[idx]
353
+ save_path = save_dir / f"{name}.png"
354
+ img.save(save_path)
355
+ print(f"💾 Saved {name} → {save_path}")
356
+
357
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
358
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
359
+
360
+ print(f"\n✅ All results saved in: {save_dir}\n")
361
+ return save_dir
362
+
363
+
364
+ # ------------------------------
365
+ # Entry Point
366
+ # ------------------------------
367
+ if __name__ == "__main__":
368
+ args = get_parser().parse_args()
369
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
370
+ print(f"✅ Using device: {device}")
371
+
372
+ processor = AutoProcessor.from_pretrained(
373
+ args.model_name_or_path,
374
+ )
375
+
376
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
377
+ args.text_model_path,
378
+ attn_implementation="flash_attention_2",
379
+ dtype=(torch.bfloat16),
380
+ ).to(device)
381
+
382
+ pipe = JodiPipeline(args.config)
383
+ pipe.from_pretrained(args.model_path)
384
+
385
+ modality_names = [
386
+ "image",
387
+ "annotation_lineart",
388
+ "annotation_edge",
389
+ "annotation_depth",
390
+ "annotation_normal",
391
+ "annotation_albedo",
392
+ "annotation_seg_12colors",
393
+ "annotation_openpose",
394
+ ]
395
+
396
+ # Build post-processors
397
+ post_processors: list[Any] = [ImagePostProcessor()]
398
+ for condition in pipe.config.conditions: # type: ignore
399
+ if condition == "lineart":
400
+ post_processors.append(LineartPostProcessor())
401
+ elif condition == "edge":
402
+ post_processors.append(EdgePostProcessor())
403
+ elif condition == "depth":
404
+ post_processors.append(DepthPostProcessor())
405
+ elif condition == "normal":
406
+ post_processors.append(NormalPostProcessor())
407
+ elif condition == "albedo":
408
+ post_processors.append(AlbedoPostProcessor())
409
+ elif condition == "segmentation":
410
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
411
+ elif condition == "openpose":
412
+ post_processors.append(OpenposePostProcessor())
413
+ else:
414
+ print(f"⚠️ Warning: Unknown condition: {condition}")
415
+ post_processors.append(ImagePostProcessor())
416
+
417
+ torch.manual_seed(args.seed)
418
+ generator = torch.Generator(device=device).manual_seed(args.seed)
419
+ import glob
420
+ image_root = args.image_root
421
+ json_path = args.json_path
422
+
423
+ with open(json_path, "r") as f:
424
+ data = json.load(f)
425
+
426
+ image_names = [item["image_name"] for item in data]
427
+
428
+ for image_name in image_names[97:]:
429
+ image_path = os.path.join(image_root, image_name)
430
+ image = Image.open(image_path).convert("RGB")
431
+ width, height = image.size
432
+
433
+ control_images = [image] + [None] * pipe.num_conditions
434
+
435
+ role=[1] + [0] * pipe.num_conditions
436
+ print(role)
437
+
438
+ max_length = 1024
439
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
440
+ score, feedback = evaluate_caption(image_path, model, processor, prompt)
441
+
442
+ for step in range(1, args.iters):
443
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
444
+ max_length += 100
445
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_name, max_length)
446
+ score, feedback = evaluate_caption(image_path, model, processor, prompt)
447
+
448
+
test_i2t_nocaps3.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./nocaps_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ task='t2i'
258
+ )
259
+
260
+ # Apply post-processing for each modality
261
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
262
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
263
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
264
+
265
+ # --------------------------
266
+ # Save results
267
+ # --------------------------
268
+ os.makedirs(args.output_dir, exist_ok=True)
269
+
270
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
271
+ save_dir.mkdir(parents=True, exist_ok=True)
272
+
273
+ for idx, img in enumerate(results):
274
+ name = modality_names[idx]
275
+ save_path = save_dir / f"{name}.png"
276
+ img.save(save_path)
277
+ print(f"💾 Saved {name} → {save_path}")
278
+
279
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
280
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
281
+
282
+ print(f"\n✅ All results saved in: {save_dir}\n")
283
+ return save_dir
284
+
285
+
286
+ # ------------------------------
287
+ # Entry Point
288
+ # ------------------------------
289
+ if __name__ == "__main__":
290
+ args = get_parser().parse_args()
291
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
292
+ print(f"✅ Using device: {device}")
293
+
294
+ processor = AutoProcessor.from_pretrained(
295
+ args.model_name_or_path,
296
+ )
297
+
298
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
299
+ args.text_model_path,
300
+ attn_implementation="flash_attention_2",
301
+ dtype=(torch.bfloat16),
302
+ ).to(device)
303
+
304
+ pipe = JodiPipeline(args.config)
305
+ pipe.from_pretrained(args.model_path)
306
+
307
+ modality_names = [
308
+ "image",
309
+ "annotation_lineart",
310
+ "annotation_edge",
311
+ "annotation_depth",
312
+ "annotation_normal",
313
+ "annotation_albedo",
314
+ "annotation_seg_12colors",
315
+ "annotation_openpose",
316
+ ]
317
+
318
+ # Build post-processors
319
+ post_processors: list[Any] = [ImagePostProcessor()]
320
+ for condition in pipe.config.conditions: # type: ignore
321
+ if condition == "lineart":
322
+ post_processors.append(LineartPostProcessor())
323
+ elif condition == "edge":
324
+ post_processors.append(EdgePostProcessor())
325
+ elif condition == "depth":
326
+ post_processors.append(DepthPostProcessor())
327
+ elif condition == "normal":
328
+ post_processors.append(NormalPostProcessor())
329
+ elif condition == "albedo":
330
+ post_processors.append(AlbedoPostProcessor())
331
+ elif condition == "segmentation":
332
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
333
+ elif condition == "openpose":
334
+ post_processors.append(OpenposePostProcessor())
335
+ else:
336
+ print(f"⚠️ Warning: Unknown condition: {condition}")
337
+ post_processors.append(ImagePostProcessor())
338
+
339
+ torch.manual_seed(args.seed)
340
+ generator = torch.Generator(device=device).manual_seed(args.seed)
341
+ import glob
342
+ image_root = args.image_root
343
+ json_path = args.json_path
344
+
345
+ with open(json_path, "r") as f:
346
+ data = json.load(f)
347
+
348
+ image_names = [item["image_name"] for item in data][2250:3000]
349
+
350
+ for image_name in image_names:
351
+ image_path = os.path.join(image_root, image_name)
352
+ image = Image.open(image_path).convert("RGB")
353
+ width, height = image.size
354
+
355
+ control_images = [image] + [None] * pipe.num_conditions
356
+
357
+ role=[1] + [0] * pipe.num_conditions
358
+ print(role)
359
+
360
+ max_length = 1024
361
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
362
+
363
+ for step in range(1, args.iters):
364
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
365
+ max_length += 100
366
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
367
+
368
+
test_i2t_nocaps4.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./nocaps_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ task='t2i'
258
+ )
259
+
260
+ # Apply post-processing for each modality
261
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
262
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
263
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
264
+
265
+ # --------------------------
266
+ # Save results
267
+ # --------------------------
268
+ os.makedirs(args.output_dir, exist_ok=True)
269
+
270
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
271
+ save_dir.mkdir(parents=True, exist_ok=True)
272
+
273
+ for idx, img in enumerate(results):
274
+ name = modality_names[idx]
275
+ save_path = save_dir / f"{name}.png"
276
+ img.save(save_path)
277
+ print(f"💾 Saved {name} → {save_path}")
278
+
279
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
280
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
281
+
282
+ print(f"\n✅ All results saved in: {save_dir}\n")
283
+ return save_dir
284
+
285
+
286
+ # ------------------------------
287
+ # Entry Point
288
+ # ------------------------------
289
+ if __name__ == "__main__":
290
+ args = get_parser().parse_args()
291
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
292
+ print(f"✅ Using device: {device}")
293
+
294
+ processor = AutoProcessor.from_pretrained(
295
+ args.model_name_or_path,
296
+ )
297
+
298
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
299
+ args.text_model_path,
300
+ attn_implementation="flash_attention_2",
301
+ dtype=(torch.bfloat16),
302
+ ).to(device)
303
+
304
+ pipe = JodiPipeline(args.config)
305
+ pipe.from_pretrained(args.model_path)
306
+
307
+ modality_names = [
308
+ "image",
309
+ "annotation_lineart",
310
+ "annotation_edge",
311
+ "annotation_depth",
312
+ "annotation_normal",
313
+ "annotation_albedo",
314
+ "annotation_seg_12colors",
315
+ "annotation_openpose",
316
+ ]
317
+
318
+ # Build post-processors
319
+ post_processors: list[Any] = [ImagePostProcessor()]
320
+ for condition in pipe.config.conditions: # type: ignore
321
+ if condition == "lineart":
322
+ post_processors.append(LineartPostProcessor())
323
+ elif condition == "edge":
324
+ post_processors.append(EdgePostProcessor())
325
+ elif condition == "depth":
326
+ post_processors.append(DepthPostProcessor())
327
+ elif condition == "normal":
328
+ post_processors.append(NormalPostProcessor())
329
+ elif condition == "albedo":
330
+ post_processors.append(AlbedoPostProcessor())
331
+ elif condition == "segmentation":
332
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
333
+ elif condition == "openpose":
334
+ post_processors.append(OpenposePostProcessor())
335
+ else:
336
+ print(f"⚠️ Warning: Unknown condition: {condition}")
337
+ post_processors.append(ImagePostProcessor())
338
+
339
+ torch.manual_seed(args.seed)
340
+ generator = torch.Generator(device=device).manual_seed(args.seed)
341
+ import glob
342
+ image_root = args.image_root
343
+ json_path = args.json_path
344
+
345
+ with open(json_path, "r") as f:
346
+ data = json.load(f)
347
+
348
+ image_names = [item["image_name"] for item in data][3000:3750]
349
+
350
+ for image_name in image_names:
351
+ image_path = os.path.join(image_root, image_name)
352
+ image = Image.open(image_path).convert("RGB")
353
+ width, height = image.size
354
+
355
+ control_images = [image] + [None] * pipe.num_conditions
356
+
357
+ role=[1] + [0] * pipe.num_conditions
358
+ print(role)
359
+
360
+ max_length = 1024
361
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
362
+
363
+ for step in range(1, args.iters):
364
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
365
+ max_length += 100
366
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
367
+
368
+
test_i2t_nocaps5.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
10
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+
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
+
28
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
29
+ """
30
+ 将多个图像拼接成一张大图并保存。
31
+ Args:
32
+ image_paths: List[str] 图像路径列表
33
+ save_path: 保存路径(包括文件名)
34
+ images_per_row: 每行图像数量(默认为全部在一行)
35
+ image_format: 保存格式
36
+ """
37
+ from PIL import Image
38
+ import io
39
+
40
+ # 读取图像
41
+ images = [Image.open(p).convert("RGB") for p in image_paths]
42
+
43
+ if images_per_row is None:
44
+ images_per_row = len(images)
45
+
46
+ # 调整尺寸(可选)
47
+ target_size = min(1024, images[0].size[0])
48
+ images = [img.resize((target_size, target_size)) for img in images]
49
+
50
+ # 拼接
51
+ widths, heights = zip(*(img.size for img in images))
52
+ max_width = max(widths)
53
+ rows = (len(images) + images_per_row - 1) // images_per_row
54
+ total_height = sum(heights[:images_per_row]) * rows
55
+
56
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
57
+ y_offset = 0
58
+ for i in range(0, len(images), images_per_row):
59
+ row_imgs = images[i:i+images_per_row]
60
+ x_offset = 0
61
+ for img in row_imgs:
62
+ new_im.paste(img, (x_offset, y_offset))
63
+ x_offset += max_width
64
+ y_offset += heights[0]
65
+
66
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
67
+ new_im.save(save_path, format=image_format.upper())
68
+ print(f"🧩 Saved merged image → {save_path}")
69
+ return save_path
70
+
71
+ def build_multimodal_message(root, coarse_caption="a generic scene"):
72
+ """
73
+ Build Qwen3-VL message for multi-modal caption refinement.
74
+ Automatically detects available modalities under root.
75
+ """
76
+ modality_names = [
77
+ "image",
78
+ "annotation_lineart",
79
+ "annotation_edge",
80
+ "annotation_depth",
81
+ "annotation_normal",
82
+ "annotation_albedo",
83
+ "annotation_seg_12colors",
84
+ "annotation_openpose",
85
+ ]
86
+
87
+ # --- 检查存在的模态 ---
88
+ available = []
89
+ for name in modality_names:
90
+ # 优先匹配 .png 或 .jpg
91
+ for ext in [".png", ".jpg", ".jpeg"]:
92
+ path = Path(root) / f"{name}{ext}"
93
+ if path.exists():
94
+ available.append(str(path))
95
+ break
96
+
97
+ # --- 构建模态说明 ---
98
+ readable_map = {
99
+ "image": "RGB image",
100
+ "annotation_lineart": "line drawing",
101
+ "annotation_edge": "edge map",
102
+ "annotation_depth": "depth map",
103
+ "annotation_normal": "normal map",
104
+ "annotation_albedo": "albedo map",
105
+ "annotation_seg_12colors": "segmentation map",
106
+ "annotation_openpose": "human pose map",
107
+ }
108
+ present_modalities = [readable_map[m] for m in modality_names if any(str(Path(root)/f"{m}{ext}") in available for ext in [".png",".jpg",".jpeg"])]
109
+
110
+ # --- 构造文本指令 ---
111
+ text_prompt = (
112
+ f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. "
113
+ f"Each modality provides distinct types of visual information that together describe the same subject: "
114
+ f"- The RGB image provides color, texture, lighting, and the overall visual appearance. "
115
+ f"- The line drawing reveals detailed structural outlines, shapes, and proportions. "
116
+ f"- The edge map highlights object boundaries and contours. "
117
+ f"- The depth map shows spatial distance, perspective, and 3D depth relationships. "
118
+ f"- The normal map captures fine surface orientation, curvature, and geometric details. "
119
+ f"- The albedo map shows true surface colors without lighting or shadow effects. "
120
+ f"- The segmentation map provides semantic regions and object boundaries for scene composition. "
121
+ f"- The human pose map shows body structure, orientation, and posture of subjects. "
122
+ f"For each provided modality image, analyze it according to the above definitions and describe "
123
+ f"the specific visual information it contributes in this particular case. "
124
+ f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. "
125
+ f"Do NOT describe each modality separately or mention modality names. "
126
+ f"Focus on merging their information into a single coherent image description. "
127
+ #f"the subject’s appearance, lighting, form, and spatial depth. "
128
+ f"Refine the coarse caption into a more detailed and accurate image description. "
129
+ f"Coarse caption: '{coarse_caption}' " +
130
+ " ".join(["<image>"] * len(available))
131
+ )
132
+
133
+ # --- 构建 Qwen3-VL 消息格式 ---
134
+ messages = [
135
+ {
136
+ "role": "user",
137
+ "content": [{"type": "image", "image": path} for path in available]
138
+ + [{"type": "text", "text": text_prompt}],
139
+ }
140
+ ]
141
+ return messages
142
+
143
+ # ------------------------------
144
+ # Argument Parser
145
+ # ------------------------------
146
+ def get_parser():
147
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
148
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
149
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
150
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.")
151
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.")
152
+ parser.add_argument("--image_root", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/images", help="Prompt text for generation.")
153
+ parser.add_argument("--json_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/NoCaps_hf_validation/captions.json", help="Prompt text for generation.")
154
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
155
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
156
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
157
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
158
+ parser.add_argument("--seed", type=int, default=42)
159
+ parser.add_argument("--output_dir", type=str, default="./nocaps_i2t_outputs", help="Directory to save results.")
160
+ return parser
161
+
162
+
163
+ # ------------------------------
164
+ # Main Inference Function
165
+ # ------------------------------
166
+
167
+ @torch.inference_mode()
168
+ def init_i2t(model, processor, image_path, iter_num, name, max_length=300):
169
+ messages = [
170
+ {
171
+ "role": "user",
172
+ "content": [
173
+ {
174
+ "type": "image",
175
+ "image": image_path,
176
+ },
177
+ {"type": "text", "text": "Describe this image."},
178
+ ],
179
+ }
180
+ ]
181
+
182
+ inputs = processor.apply_chat_template(
183
+ messages,
184
+ tokenize=True,
185
+ add_generation_prompt=True,
186
+ return_dict=True,
187
+ return_tensors="pt"
188
+ )
189
+ inputs = inputs.to(model.device)
190
+
191
+ # Inference: Generation of the output
192
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
193
+ generated_ids_trimmed = [
194
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
195
+ ]
196
+ output_text = processor.batch_decode(
197
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
198
+ )
199
+ print(output_text)
200
+
201
+ os.makedirs(args.output_dir, exist_ok=True)
202
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
203
+ save_dir.mkdir(parents=True, exist_ok=True)
204
+ caption_path = Path(save_dir) / f"caption.txt"
205
+ with open(caption_path, "w", encoding="utf-8") as f:
206
+ f.write(output_text[0].strip())
207
+
208
+ return output_text[0]
209
+
210
+ @torch.inference_mode()
211
+ def text_refine(root, model, processor, prompt, iter_num, name, max_length=300):
212
+ messages = build_multimodal_message(root, prompt)
213
+ inputs = processor.apply_chat_template(
214
+ messages,
215
+ tokenize=True,
216
+ add_generation_prompt=True,
217
+ return_dict=True,
218
+ return_tensors="pt"
219
+ )
220
+ inputs = inputs.to(model.device)
221
+
222
+ # Inference: Generation of the output
223
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
224
+ generated_ids_trimmed = [
225
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
226
+ ]
227
+ output_text = processor.batch_decode(
228
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
229
+ )
230
+ print(output_text)
231
+
232
+ os.makedirs(args.output_dir, exist_ok=True)
233
+ save_dir = Path(args.output_dir) / name / f"iteration_{iter_num}"
234
+ save_dir.mkdir(parents=True, exist_ok=True)
235
+ caption_path = Path(save_dir) / f"caption.txt"
236
+ with open(caption_path, "w", encoding="utf-8") as f:
237
+ f.write(output_text[0].strip())
238
+
239
+ return output_text[0]
240
+
241
+ @torch.inference_mode()
242
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, name):
243
+
244
+ print(f"🚀 Generating with prompt: {prompt}")
245
+ #prompt = args.prompt + ' ' + prompt
246
+ outputs = pipe(
247
+ images=images,
248
+ role=role,
249
+ prompt=prompt,
250
+ negative_prompt=args.negative_prompt,
251
+ height=height,
252
+ width=width,
253
+ num_inference_steps=args.steps,
254
+ guidance_scale=args.guidance_scale,
255
+ num_images_per_prompt=1,
256
+ generator=generator,
257
+ task='t2i'
258
+ )
259
+
260
+ # Apply post-processing for each modality
261
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
262
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
263
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
264
+
265
+ # --------------------------
266
+ # Save results
267
+ # --------------------------
268
+ os.makedirs(args.output_dir, exist_ok=True)
269
+
270
+ save_dir = Path(args.output_dir) / name/ f"iteration_{iter_num}"
271
+ save_dir.mkdir(parents=True, exist_ok=True)
272
+
273
+ for idx, img in enumerate(results):
274
+ name = modality_names[idx]
275
+ save_path = save_dir / f"{name}.png"
276
+ img.save(save_path)
277
+ print(f"💾 Saved {name} → {save_path}")
278
+
279
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
280
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
281
+
282
+ print(f"\n✅ All results saved in: {save_dir}\n")
283
+ return save_dir
284
+
285
+
286
+ # ------------------------------
287
+ # Entry Point
288
+ # ------------------------------
289
+ if __name__ == "__main__":
290
+ args = get_parser().parse_args()
291
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
292
+ print(f"✅ Using device: {device}")
293
+
294
+ processor = AutoProcessor.from_pretrained(
295
+ args.model_name_or_path,
296
+ )
297
+
298
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
299
+ args.text_model_path,
300
+ attn_implementation="flash_attention_2",
301
+ dtype=(torch.bfloat16),
302
+ ).to(device)
303
+
304
+ pipe = JodiPipeline(args.config)
305
+ pipe.from_pretrained(args.model_path)
306
+
307
+ modality_names = [
308
+ "image",
309
+ "annotation_lineart",
310
+ "annotation_edge",
311
+ "annotation_depth",
312
+ "annotation_normal",
313
+ "annotation_albedo",
314
+ "annotation_seg_12colors",
315
+ "annotation_openpose",
316
+ ]
317
+
318
+ # Build post-processors
319
+ post_processors: list[Any] = [ImagePostProcessor()]
320
+ for condition in pipe.config.conditions: # type: ignore
321
+ if condition == "lineart":
322
+ post_processors.append(LineartPostProcessor())
323
+ elif condition == "edge":
324
+ post_processors.append(EdgePostProcessor())
325
+ elif condition == "depth":
326
+ post_processors.append(DepthPostProcessor())
327
+ elif condition == "normal":
328
+ post_processors.append(NormalPostProcessor())
329
+ elif condition == "albedo":
330
+ post_processors.append(AlbedoPostProcessor())
331
+ elif condition == "segmentation":
332
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
333
+ elif condition == "openpose":
334
+ post_processors.append(OpenposePostProcessor())
335
+ else:
336
+ print(f"⚠️ Warning: Unknown condition: {condition}")
337
+ post_processors.append(ImagePostProcessor())
338
+
339
+ torch.manual_seed(args.seed)
340
+ generator = torch.Generator(device=device).manual_seed(args.seed)
341
+ import glob
342
+ image_root = args.image_root
343
+ json_path = args.json_path
344
+
345
+ with open(json_path, "r") as f:
346
+ data = json.load(f)
347
+
348
+ image_names = [item["image_name"] for item in data][3750:]
349
+
350
+ for image_name in image_names:
351
+ image_path = os.path.join(image_root, image_name)
352
+ image = Image.open(image_path).convert("RGB")
353
+ width, height = image.size
354
+
355
+ control_images = [image] + [None] * pipe.num_conditions
356
+
357
+ role=[1] + [0] * pipe.num_conditions
358
+ print(role)
359
+
360
+ max_length = 1024
361
+ prompt = init_i2t(model, processor, image_path, 0, image_name, max_length)
362
+
363
+ for step in range(1, args.iters):
364
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width, image_name)
365
+ max_length += 100
366
+ prompt = text_refine(save_dir, model, processor, prompt, step, image_name, max_length)
367
+
368
+
test_pope.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch.nn.functional as F
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
+ text_prompt = (
205
+ f"Answer the question using ONLY visual evidence from the images, including: {', '.join(present_modalities)}. "
206
+ f"Do NOT rely on prior knowledge or assumptions. "
207
+ f"Carefully inspect all visible objects and count them precisely. "
208
+ f"If objects appear similar or are located at different heights or positions, "
209
+ f"they MUST be counted separately if they are distinct and not connected. "
210
+ f"Cross-check all modalities (RGB, lines, edges, depth, segmentation) "
211
+ f"to ensure you do not merge distinct objects into one. "
212
+ f"Your answer MUST strictly follow what is visible, even if it seems unusual. "
213
+ f"Just response yes or no. "
214
+ f"Now answer the question:\n{question}\n")
215
+
216
+
217
+ # ---------- 构建内容序列(模态锚定) ----------
218
+ content = []
219
+ #print(f'available:{available}')
220
+ for name, path in available:
221
+ readable = readable_map.get(name, "visual input")
222
+ # 在每张图像前显式标注模态类型
223
+ content.append({"type": "text", "text": f"This is the {readable}."})
224
+ content.append({"type": "image", "image": path})
225
+
226
+ # 最后加入主指令
227
+ content.append({"type": "text", "text": text_prompt})
228
+
229
+ messages = [{"role": "user", "content": content}]
230
+ return messages
231
+
232
+
233
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
234
+ """
235
+ Build Qwen3-VL message for multi-modal caption refinement.
236
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
237
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
238
+ """
239
+
240
+ modality_names = [
241
+ "image",
242
+ "annotation_lineart",
243
+ "annotation_edge",
244
+ "annotation_depth",
245
+ "annotation_normal",
246
+ "annotation_albedo",
247
+ "annotation_seg_12colors",
248
+ # "annotation_openpose",
249
+ ]
250
+
251
+ # --- 检查存在的模态 ---
252
+ available = []
253
+ for name in modality_names:
254
+ for ext in [".png", ".jpg", ".jpeg"]:
255
+ path = Path(root) / f"{name}{ext}"
256
+ if path.exists():
257
+ available.append((name, str(path)))
258
+ break
259
+
260
+ # --- 构建模态说明 ---
261
+ readable_map = {
262
+ "image": "RGB image",
263
+ "annotation_lineart": "line drawing",
264
+ "annotation_edge": "edge map",
265
+ "annotation_depth": "depth map",
266
+ "annotation_normal": "normal map",
267
+ "annotation_albedo": "albedo map",
268
+ "annotation_seg_12colors": "segmentation map",
269
+ # "annotation_openpose": "human pose map",
270
+ }
271
+
272
+ present_modalities = [readable_map[n] for n, _ in available]
273
+
274
+ # --- 构造文本指令 ---
275
+ text_prompt = (
276
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
277
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
278
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
279
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
280
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
281
+ f"while maintaining faithfulness to the original visual content. "
282
+ f"Do not include any additional commentary or evaluations. "
283
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
284
+ f"Focus on describing the visual properties, including: "
285
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
286
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
287
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
288
+ f"Consider the following feedback when refining your description: '{feedback}'. "
289
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
290
+ f"Coarse caption: '{coarse_caption}' "
291
+ )
292
+
293
+ # text_prompt0 = (
294
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
295
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
296
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
297
+ # f"### Your Task:\n"
298
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
299
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
300
+ # f"### Guidelines:\n"
301
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
302
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
303
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
304
+ # f"4. Avoid including any additional commentary or evaluations.\n"
305
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
306
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
307
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
308
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
309
+ # )
310
+
311
+ # --- 构建消息内容:在每个图像前加模态标识 ---
312
+ content = []
313
+ for name, path in available:
314
+ readable = readable_map.get(name, "visual input")
315
+ content.append({
316
+ "type": "text",
317
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
318
+ })
319
+ content.append({"type": "image", "image": path})
320
+
321
+ # 最后附上总任务说明
322
+ content.append({"type": "text", "text": text_prompt})
323
+
324
+ messages = [{"role": "user", "content": content}]
325
+ return messages
326
+
327
+
328
+ def get_modality_description(name: str) -> str:
329
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
330
+ desc_map = {
331
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
332
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
333
+ "annotation_edge": "strong boundaries and contrast edges between objects",
334
+ "annotation_depth": "distance and perspective information for spatial understanding",
335
+ "annotation_normal": "surface orientation and geometric curvature cues",
336
+ "annotation_albedo": "pure surface color without lighting or shading effects",
337
+ "annotation_seg_12colors": "semantic regions and object categories",
338
+ "annotation_openpose": "human body keypoints, joints, and orientation",
339
+ }
340
+ return desc_map.get(name, "complementary visual evidence")
341
+
342
+
343
+ # ------------------------------
344
+ # Argument Parser
345
+ # ------------------------------
346
+ def get_parser():
347
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
348
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
349
+ help="Path to model checkpoint.")
350
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
351
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
352
+ help="Path to model checkpoint.")
353
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
354
+ help="Path to model checkpoint.")
355
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
356
+ help="Prompt text for generation.")
357
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
358
+ help="Optional negative prompt.")
359
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
360
+ help="Prompt text for generation.")
361
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
362
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
363
+ help="Optional negative prompt.")
364
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
365
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
366
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
367
+ parser.add_argument("--seed", type=int, default=42)
368
+ parser.add_argument("--tmp", type=str, default="/home/efs/mjw/mjw/code/Jodi/pope_tmp")
369
+ parser.add_argument("--output_dir", type=str, default="./vqa_pope_output", help="Directory to save results.")
370
+ return parser
371
+
372
+
373
+ # ------------------------------
374
+ # Main Inference Function
375
+ # ------------------------------
376
+
377
+
378
+ @torch.inference_mode()
379
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
380
+ messages = [
381
+ {
382
+ "role": "user",
383
+ "content": [
384
+ {
385
+ "type": "image",
386
+ "image": image_path,
387
+ },
388
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
389
+ ],
390
+ }
391
+ ]
392
+
393
+ print(f'vqa messages:{messages}')
394
+
395
+ inputs = processor.apply_chat_template(
396
+ messages,
397
+ tokenize=True,
398
+ add_generation_prompt=True,
399
+ return_dict=True,
400
+ return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ #print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / str(vqa_id)
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
426
+ messages = [
427
+ {
428
+ "role": "user",
429
+ "content": [
430
+ {
431
+ "type": "image",
432
+ "image": image_path,
433
+ },
434
+ {"type": "text", "text": f"Describe this image."},
435
+ ],
436
+ }
437
+ ]
438
+
439
+ inputs = processor.apply_chat_template(
440
+ messages,
441
+ tokenize=True,
442
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
443
+ )
444
+ inputs = inputs.to(model.device)
445
+
446
+ # Inference: Generation of the output
447
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
448
+ generated_ids_trimmed = [
449
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
450
+ ]
451
+ output_text = processor.batch_decode(
452
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
453
+ )
454
+ #print(output_text)
455
+
456
+ os.makedirs(args.output_dir, exist_ok=True)
457
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
458
+ save_dir.mkdir(parents=True, exist_ok=True)
459
+ caption_path = Path(save_dir) / f"caption.txt"
460
+ with open(caption_path, "w", encoding="utf-8") as f:
461
+ f.write(output_text[0].strip())
462
+
463
+ return output_text[0]
464
+
465
+ @torch.inference_mode()
466
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
467
+ # --- 构造 Qwen 输入 ---
468
+ question = clean_eval_question(question)
469
+ eval_prompt = f"""
470
+ You are a VQA answer evaluator.
471
+ Given an image, a question, and a proposed answer,
472
+ score how correct the answer is according to the image evidence.
473
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
474
+ to make the answer more accurate or grounded in the image.
475
+ Return JSON strictly:
476
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
477
+
478
+ Question: "{question}"
479
+ Answer: "{answer}"
480
+ <image>
481
+ """
482
+
483
+ messages = [
484
+ {
485
+ "role": "user",
486
+ "content": [
487
+ {"type": "image", "image": image_path},
488
+ {"type": "text", "text": eval_prompt},
489
+ ],
490
+ }
491
+ ]
492
+
493
+ print(f'eval_message:{messages}')
494
+
495
+ # --- 推理 ---
496
+ inputs = processor.apply_chat_template(
497
+ messages,
498
+ tokenize=True,
499
+ add_generation_prompt=True,
500
+ return_dict=True,
501
+ return_tensors="pt"
502
+ ).to(model.device)
503
+
504
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
505
+ #print(f'out_ids.logits:{out_ids.logit}')
506
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
507
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
508
+
509
+ # --- 解析输出 ---
510
+ try:
511
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
512
+ score = float(data.get("AnswerScore", 0))
513
+ feedback = data.get("Feedback", "")
514
+ except Exception:
515
+ score, feedback = 0.0, text.strip()
516
+
517
+ #print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
518
+ return score, feedback
519
+
520
+ @torch.inference_mode()
521
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
522
+ """
523
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
524
+ This reduces model bias and improves visual grounding reliability.
525
+ """
526
+
527
+ # 检查存在的模态文件
528
+ modality_names = [
529
+ "image", "annotation_lineart", "annotation_edge",
530
+ "annotation_depth", "annotation_normal", "annotation_albedo",
531
+ "annotation_seg_12colors", "annotation_openpose"
532
+ ]
533
+
534
+ available = []
535
+ for name in modality_names:
536
+ for ext in [".png", ".jpg", ".jpeg"]:
537
+ path = Path(root) / f"{name}{ext}"
538
+ if path.exists():
539
+ available.append((name, str(path)))
540
+ break
541
+
542
+ # 可读映射
543
+ readable_map = {
544
+ "image": "RGB image",
545
+ "annotation_lineart": "line drawing",
546
+ "annotation_edge": "edge map",
547
+ "annotation_depth": "depth map",
548
+ "annotation_normal": "normal map",
549
+ "annotation_albedo": "albedo map",
550
+ "annotation_seg_12colors": "segmentation map",
551
+ "annotation_openpose": "human pose map",
552
+ }
553
+
554
+ present_modalities = [readable_map[n] for n, _ in available]
555
+
556
+ # 构造 prompt
557
+ eval_prompt = f"""
558
+ You are a multimodal visual reasoning evaluator.
559
+
560
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
561
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
562
+ based purely on visual evidence from all modalities.
563
+
564
+ Follow this process:
565
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
566
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
567
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
568
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
569
+ 5. Penalize any parts that contradict the image, or ignore modalities.
570
+
571
+ Return JSON strictly:
572
+ {{
573
+ "AnswerScore": <float between 0 and 1>,
574
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
575
+ }}
576
+
577
+ Question: "{question}"
578
+ Answer: "{answer}"
579
+ """
580
+
581
+ # 构建内容序列(模态+图像)
582
+ content = []
583
+ for name, path in available:
584
+ readable = readable_map.get(name, "visual input")
585
+ content.append({"type": "text", "text": f"This is the {readable}."})
586
+ content.append({"type": "image", "image": path})
587
+ content.append({"type": "text", "text": eval_prompt})
588
+
589
+ messages = [{"role": "user", "content": content}]
590
+
591
+ print(f'eval message:{messages}')
592
+
593
+ # --- 推理 ---
594
+ inputs = processor.apply_chat_template(
595
+ messages, tokenize=True, add_generation_prompt=True,
596
+ return_dict=True, return_tensors="pt"
597
+ ).to(model.device)
598
+
599
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
600
+ #print(out_ids)
601
+ out_ids = outs['sequences']
602
+ scores = outs['scores']
603
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
604
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
605
+
606
+ # --- 解析输出 ---
607
+ try:
608
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
609
+ score = float(data.get("AnswerScore", 0))
610
+ feedback = data.get("Feedback", "")
611
+ except Exception:
612
+ score, feedback = 0.0, text.strip()
613
+
614
+ gen_start = inputs["input_ids"].shape[1]
615
+ gen_ids = out_ids[:, gen_start:]
616
+ #gen_ids = out_ids[:, gen_start:]
617
+ gen_text = processor.tokenizer.decode(gen_ids[0], skip_special_tokens=False)
618
+ num_match = re.search(r"AnswerScore\"\s*:\s*([0-9\.]+)", gen_text)
619
+ conf = 0.0
620
+ if num_match:
621
+ num_text = num_match.group(1)
622
+ num_ids = processor.tokenizer.encode(num_text, add_special_tokens=False)
623
+ num_str = processor.tokenizer.decode(num_ids)
624
+ gen_id_list = gen_ids[0].tolist()
625
+ match_positions = []
626
+ for i in range(len(gen_id_list) - len(num_ids) + 1):
627
+ if gen_id_list[i:i+len(num_ids)] == num_ids:
628
+ match_positions = list(range(i, i+len(num_ids)))
629
+ break
630
+
631
+ if match_positions:
632
+ probs = []
633
+ for pos in match_positions:
634
+ step_prob = F.softmax(scores[pos], dim=-1)
635
+ token_id = gen_ids[0, pos]
636
+ probs.append(step_prob[0, token_id])
637
+ conf = torch.stack(probs).mean().item()
638
+
639
+ #print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
640
+ #print(f"📊 [Confidence(AnswerScore)] {conf:.4f}")
641
+
642
+ return score, feedback
643
+
644
+
645
+
646
+ @torch.inference_mode()
647
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
648
+ question = clean_prompt_question(question)
649
+ messages = build_multimodal_message(root, question, prompt, feedback)
650
+ print(f'refine message:{messages}')
651
+ inputs = processor.apply_chat_template(
652
+ messages,
653
+ tokenize=True,
654
+ add_generation_prompt=True,
655
+ return_dict=True,
656
+ return_tensors="pt"
657
+ )
658
+ inputs = inputs.to(model.device)
659
+
660
+ # Inference: Generation of the output
661
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
662
+ generated_ids_trimmed = [
663
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
664
+ ]
665
+ output_text = processor.batch_decode(
666
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
667
+ )
668
+ #print(output_text)
669
+
670
+ os.makedirs(args.output_dir, exist_ok=True)
671
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
672
+ save_dir.mkdir(parents=True, exist_ok=True)
673
+ caption_path = Path(save_dir) / f"caption.txt"
674
+ feedback_path = Path(save_dir) / f"feedback.txt"
675
+ with open(feedback_path, "w", encoding="utf-8") as f:
676
+ f.write(feedback.strip())
677
+ with open(caption_path, "w", encoding="utf-8") as f:
678
+ f.write(output_text[0].strip())
679
+ return output_text[0]
680
+
681
+
682
+ @torch.inference_mode()
683
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
684
+ messages = build_vqa_message(root, prompt, question)
685
+ print(f'vqa messages:{messages}')
686
+ inputs = processor.apply_chat_template(
687
+ messages,
688
+ tokenize=True,
689
+ add_generation_prompt=True,
690
+ return_dict=True,
691
+ return_tensors="pt"
692
+ )
693
+ inputs = inputs.to(model.device)
694
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
695
+ generated_ids_trimmed = [
696
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
697
+ output_text = processor.batch_decode(
698
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
699
+ )
700
+ #print(output_text)
701
+ os.makedirs(args.output_dir, exist_ok=True)
702
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
703
+ save_dir.mkdir(parents=True, exist_ok=True)
704
+ caption_path = Path(save_dir) / f"caption.txt"
705
+ with open(caption_path, "w", encoding="utf-8") as f:
706
+ f.write(output_text[0].strip())
707
+ return output_text[0]
708
+
709
+
710
+ @torch.inference_mode()
711
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
712
+ # print(f"🚀 Generating with prompt: {prompt}")
713
+ outputs = pipe(
714
+ images=images,
715
+ role=role,
716
+ prompt=prompt,
717
+ negative_prompt=args.negative_prompt,
718
+ height=height,
719
+ width=width,
720
+ num_inference_steps=args.steps,
721
+ guidance_scale=args.guidance_scale,
722
+ num_images_per_prompt=1,
723
+ generator=generator
724
+ )
725
+
726
+ # Apply post-processing for each modality
727
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
728
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
729
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
730
+
731
+ # --------------------------
732
+ # Save results
733
+ # --------------------------
734
+ os.makedirs(args.output_dir, exist_ok=True)
735
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
736
+ save_dir.mkdir(parents=True, exist_ok=True)
737
+ for idx, img in enumerate(results):
738
+ name = modality_names[idx]
739
+ save_path = save_dir / f"{name}.png"
740
+ img.save(save_path)
741
+ print(f"💾 Saved {name} → {save_path}")
742
+
743
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
744
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
745
+ print(f"\n✅ All results saved in: {save_dir}\n")
746
+ return save_dir
747
+
748
+
749
+ if __name__ == "__main__":
750
+ args = get_parser().parse_args()
751
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
752
+ print(f"✅ Using device: {device}")
753
+
754
+ processor = AutoProcessor.from_pretrained(
755
+ args.model_name_or_path,
756
+ )
757
+
758
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
759
+ args.text_model_path,
760
+ attn_implementation="flash_attention_2",
761
+ dtype=(torch.bfloat16),
762
+ ).to(device)
763
+
764
+ pipe = JodiPipeline(args.config)
765
+ pipe.from_pretrained(args.model_path)
766
+
767
+ modality_names = [
768
+ "image",
769
+ "annotation_lineart",
770
+ "annotation_edge",
771
+ "annotation_depth",
772
+ "annotation_normal",
773
+ "annotation_albedo",
774
+ "annotation_seg_12colors",
775
+ "annotation_openpose",
776
+ ]
777
+
778
+ # Build post-processors
779
+ post_processors: list[Any] = [ImagePostProcessor()]
780
+ for condition in pipe.config.conditions: # type: ignore
781
+ if condition == "lineart":
782
+ post_processors.append(LineartPostProcessor())
783
+ elif condition == "edge":
784
+ post_processors.append(EdgePostProcessor())
785
+ elif condition == "depth":
786
+ post_processors.append(DepthPostProcessor())
787
+ elif condition == "normal":
788
+ post_processors.append(NormalPostProcessor())
789
+ elif condition == "albedo":
790
+ post_processors.append(AlbedoPostProcessor())
791
+ elif condition == "segmentation":
792
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
793
+ elif condition == "openpose":
794
+ post_processors.append(OpenposePostProcessor())
795
+ else:
796
+ print(f"⚠️ Warning: Unknown condition: {condition}")
797
+ post_processors.append(ImagePostProcessor())
798
+
799
+ torch.manual_seed(args.seed)
800
+ generator = torch.Generator(device=device).manual_seed(args.seed)
801
+
802
+ #with open(args.json, "r", encoding="utf-8") as f:
803
+ # annotations = json.load(f)
804
+
805
+ dataset = load_dataset("lmms-lab/POPE", split="test")
806
+ subset = dataset.select(range(4500,len(dataset)))
807
+
808
+ for sample in subset:
809
+ #image_path = os.path.join(args.data_path, sample["image"])
810
+ #image_id = sample["image"].split('.')[0]
811
+ image_path = os.path.join(args.tmp, sample["image_source"]+'.jpg')
812
+
813
+ print(type(sample["image"]))
814
+
815
+ image_id = sample["id"]
816
+ image = sample["image"].convert("RGB")
817
+ image.save(image_path)
818
+ question = sample["question"]
819
+
820
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
821
+
822
+ role = [1] + [0] * pipe.num_conditions
823
+ print(role)
824
+
825
+ best_result, best_score = '', 0.0
826
+ max_length = 1024
827
+
828
+ # input_img = Image.open(image_path).convert("RGB")
829
+ width, height = image.size
830
+ print(f'ori width:{width}', f'ori height:{height}')
831
+
832
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
833
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
834
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
835
+
836
+ if score >= best_score:
837
+ best_result, best_score = result, score
838
+
839
+ for step in range(1, args.iters):
840
+ generator = torch.Generator(device=device).manual_seed(args.seed)
841
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
842
+ image_id)
843
+ max_length += 100
844
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
845
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
846
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
847
+
848
+ if score >= best_score:
849
+ best_result, best_score = result, score
850
+
851
+ os.makedirs(args.output_dir, exist_ok=True)
852
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
853
+ save_dir.mkdir(parents=True, exist_ok=True)
854
+ caption_path = Path(save_dir) / f"caption.txt"
855
+ with open(caption_path, "w", encoding="utf-8") as f:
856
+ f.write(best_result)
857
+ print(best_result)
858
+
test_real1.py ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response Yes or No"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/POPEv2/images",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/POPEv2/annotations.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_popev2_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations:
766
+
767
+ out_names = os.listdir(args.output_dir)
768
+
769
+ image_path = os.path.join(args.data_path, sample["image_name"].split('/')[-1])
770
+ image_id = sample["image_name"].split('/')[-1].split('.')[0]
771
+
772
+ if image_id in out_names:
773
+ print(f'this {image_id} is exist.')
774
+ continue
775
+
776
+ image = Image.open(image_path)
777
+ question = sample["query"]
778
+
779
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
780
+
781
+ role = [1] + [0] * pipe.num_conditions
782
+ print(role)
783
+
784
+ best_result, best_score = '', 0.0
785
+ max_length = 1024
786
+
787
+ # input_img = Image.open(image_path).convert("RGB")
788
+ width, height = image.size
789
+ print(f'ori width:{width}', f'ori height:{height}')
790
+
791
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
792
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
793
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
794
+
795
+ if score >= best_score:
796
+ best_result, best_score = result, score
797
+
798
+ for step in range(1, args.iters):
799
+ generator = torch.Generator(device=device).manual_seed(args.seed)
800
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
801
+ image_id)
802
+ max_length += 100
803
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
804
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
805
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
806
+
807
+ if score >= best_score:
808
+ best_result, best_score = result, score
809
+
810
+ os.makedirs(args.output_dir, exist_ok=True)
811
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
812
+ save_dir.mkdir(parents=True, exist_ok=True)
813
+ caption_path = Path(save_dir) / f"caption.txt"
814
+ with open(caption_path, "w", encoding="utf-8") as f:
815
+ f.write(best_result)
816
+ print(best_result)
817
+
test_real2.py ADDED
@@ -0,0 +1,857 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import torch.nn.functional as F
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
+ text_prompt = (
205
+ f"Answer the question using ONLY visual evidence from the images, including: {', '.join(present_modalities)}. "
206
+ f"Do NOT rely on prior knowledge or assumptions. "
207
+ f"Carefully inspect all visible objects and count them precisely. "
208
+ f"If objects appear similar or are located at different heights or positions, "
209
+ f"they MUST be counted separately if they are distinct and not connected. "
210
+ f"Cross-check all modalities (RGB, lines, edges, depth, segmentation) "
211
+ f"to ensure you do not merge distinct objects into one. "
212
+ f"Your answer MUST strictly follow what is visible, even if it seems unusual. "
213
+ f"Just response yes or no. "
214
+ f"Now answer the question:\n{question}\n")
215
+
216
+
217
+ # ---------- 构建内容序列(模态锚定) ----------
218
+ content = []
219
+ #print(f'available:{available}')
220
+ for name, path in available:
221
+ readable = readable_map.get(name, "visual input")
222
+ # 在每张图像前显式标注模态类型
223
+ content.append({"type": "text", "text": f"This is the {readable}."})
224
+ content.append({"type": "image", "image": path})
225
+
226
+ # 最后加入主指令
227
+ content.append({"type": "text", "text": text_prompt})
228
+
229
+ messages = [{"role": "user", "content": content}]
230
+ return messages
231
+
232
+
233
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
234
+ """
235
+ Build Qwen3-VL message for multi-modal caption refinement.
236
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
237
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
238
+ """
239
+
240
+ modality_names = [
241
+ "image",
242
+ "annotation_lineart",
243
+ "annotation_edge",
244
+ "annotation_depth",
245
+ "annotation_normal",
246
+ "annotation_albedo",
247
+ "annotation_seg_12colors",
248
+ # "annotation_openpose",
249
+ ]
250
+
251
+ # --- 检查存在的模态 ---
252
+ available = []
253
+ for name in modality_names:
254
+ for ext in [".png", ".jpg", ".jpeg"]:
255
+ path = Path(root) / f"{name}{ext}"
256
+ if path.exists():
257
+ available.append((name, str(path)))
258
+ break
259
+
260
+ # --- 构建模态说明 ---
261
+ readable_map = {
262
+ "image": "RGB image",
263
+ "annotation_lineart": "line drawing",
264
+ "annotation_edge": "edge map",
265
+ "annotation_depth": "depth map",
266
+ "annotation_normal": "normal map",
267
+ "annotation_albedo": "albedo map",
268
+ "annotation_seg_12colors": "segmentation map",
269
+ # "annotation_openpose": "human pose map",
270
+ }
271
+
272
+ present_modalities = [readable_map[n] for n, _ in available]
273
+
274
+ # --- 构造文本指令 ---
275
+ text_prompt = (
276
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
277
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
278
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
279
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
280
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
281
+ f"while maintaining faithfulness to the original visual content. "
282
+ f"Do not include any additional commentary or evaluations. "
283
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
284
+ f"Focus on describing the visual properties, including: "
285
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
286
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
287
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
288
+ f"Consider the following feedback when refining your description: '{feedback}'. "
289
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
290
+ f"Coarse caption: '{coarse_caption}' "
291
+ )
292
+
293
+ # text_prompt0 = (
294
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
295
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
296
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
297
+ # f"### Your Task:\n"
298
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
299
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
300
+ # f"### Guidelines:\n"
301
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
302
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
303
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
304
+ # f"4. Avoid including any additional commentary or evaluations.\n"
305
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
306
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
307
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
308
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
309
+ # )
310
+
311
+ # --- 构建消息内容:在每个图像前加模态标识 ---
312
+ content = []
313
+ for name, path in available:
314
+ readable = readable_map.get(name, "visual input")
315
+ content.append({
316
+ "type": "text",
317
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
318
+ })
319
+ content.append({"type": "image", "image": path})
320
+
321
+ # 最后附上总任务说明
322
+ content.append({"type": "text", "text": text_prompt})
323
+
324
+ messages = [{"role": "user", "content": content}]
325
+ return messages
326
+
327
+
328
+ def get_modality_description(name: str) -> str:
329
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
330
+ desc_map = {
331
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
332
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
333
+ "annotation_edge": "strong boundaries and contrast edges between objects",
334
+ "annotation_depth": "distance and perspective information for spatial understanding",
335
+ "annotation_normal": "surface orientation and geometric curvature cues",
336
+ "annotation_albedo": "pure surface color without lighting or shading effects",
337
+ "annotation_seg_12colors": "semantic regions and object categories",
338
+ "annotation_openpose": "human body keypoints, joints, and orientation",
339
+ }
340
+ return desc_map.get(name, "complementary visual evidence")
341
+
342
+
343
+ # ------------------------------
344
+ # Argument Parser
345
+ # ------------------------------
346
+ def get_parser():
347
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
348
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
349
+ help="Path to model checkpoint.")
350
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
351
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
352
+ help="Path to model checkpoint.")
353
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
354
+ help="Path to model checkpoint.")
355
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
356
+ help="Prompt text for generation.")
357
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
358
+ help="Optional negative prompt.")
359
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
360
+ help="Prompt text for generation.")
361
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
362
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
363
+ help="Optional negative prompt.")
364
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
365
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
366
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
367
+ parser.add_argument("--seed", type=int, default=42)
368
+ parser.add_argument("--tmp", type=str, default="/home/efs/mjw/mjw/code/Jodi/pope_tmp")
369
+ parser.add_argument("--output_dir", type=str, default="./vqa_pope_output", help="Directory to save results.")
370
+ return parser
371
+
372
+
373
+ # ------------------------------
374
+ # Main Inference Function
375
+ # ------------------------------
376
+
377
+
378
+ @torch.inference_mode()
379
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
380
+ messages = [
381
+ {
382
+ "role": "user",
383
+ "content": [
384
+ {
385
+ "type": "image",
386
+ "image": image_path,
387
+ },
388
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
389
+ ],
390
+ }
391
+ ]
392
+
393
+ print(f'vqa messages:{messages}')
394
+
395
+ inputs = processor.apply_chat_template(
396
+ messages,
397
+ tokenize=True,
398
+ add_generation_prompt=True,
399
+ return_dict=True,
400
+ return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ #print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / str(vqa_id)
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
426
+ messages = [
427
+ {
428
+ "role": "user",
429
+ "content": [
430
+ {
431
+ "type": "image",
432
+ "image": image_path,
433
+ },
434
+ {"type": "text", "text": f"Describe this image."},
435
+ ],
436
+ }
437
+ ]
438
+
439
+ inputs = processor.apply_chat_template(
440
+ messages,
441
+ tokenize=True,
442
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
443
+ )
444
+ inputs = inputs.to(model.device)
445
+
446
+ # Inference: Generation of the output
447
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
448
+ generated_ids_trimmed = [
449
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
450
+ ]
451
+ output_text = processor.batch_decode(
452
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
453
+ )
454
+ #print(output_text)
455
+
456
+ os.makedirs(args.output_dir, exist_ok=True)
457
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
458
+ save_dir.mkdir(parents=True, exist_ok=True)
459
+ caption_path = Path(save_dir) / f"caption.txt"
460
+ with open(caption_path, "w", encoding="utf-8") as f:
461
+ f.write(output_text[0].strip())
462
+
463
+ return output_text[0]
464
+
465
+ @torch.inference_mode()
466
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
467
+ # --- 构造 Qwen 输入 ---
468
+ question = clean_eval_question(question)
469
+ eval_prompt = f"""
470
+ You are a VQA answer evaluator.
471
+ Given an image, a question, and a proposed answer,
472
+ score how correct the answer is according to the image evidence.
473
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
474
+ to make the answer more accurate or grounded in the image.
475
+ Return JSON strictly:
476
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
477
+
478
+ Question: "{question}"
479
+ Answer: "{answer}"
480
+ <image>
481
+ """
482
+
483
+ messages = [
484
+ {
485
+ "role": "user",
486
+ "content": [
487
+ {"type": "image", "image": image_path},
488
+ {"type": "text", "text": eval_prompt},
489
+ ],
490
+ }
491
+ ]
492
+
493
+ print(f'eval_message:{messages}')
494
+
495
+ # --- 推理 ---
496
+ inputs = processor.apply_chat_template(
497
+ messages,
498
+ tokenize=True,
499
+ add_generation_prompt=True,
500
+ return_dict=True,
501
+ return_tensors="pt"
502
+ ).to(model.device)
503
+
504
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
505
+ #print(f'out_ids.logits:{out_ids.logit}')
506
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
507
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
508
+
509
+ # --- 解析输出 ---
510
+ try:
511
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
512
+ score = float(data.get("AnswerScore", 0))
513
+ feedback = data.get("Feedback", "")
514
+ except Exception:
515
+ score, feedback = 0.0, text.strip()
516
+
517
+ #print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
518
+ return score, feedback
519
+
520
+ @torch.inference_mode()
521
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
522
+ """
523
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
524
+ This reduces model bias and improves visual grounding reliability.
525
+ """
526
+
527
+ # 检查存在的模态文件
528
+ modality_names = [
529
+ "image", "annotation_lineart", "annotation_edge",
530
+ "annotation_depth", "annotation_normal", "annotation_albedo",
531
+ "annotation_seg_12colors", "annotation_openpose"
532
+ ]
533
+
534
+ available = []
535
+ for name in modality_names:
536
+ for ext in [".png", ".jpg", ".jpeg"]:
537
+ path = Path(root) / f"{name}{ext}"
538
+ if path.exists():
539
+ available.append((name, str(path)))
540
+ break
541
+
542
+ # 可读映射
543
+ readable_map = {
544
+ "image": "RGB image",
545
+ "annotation_lineart": "line drawing",
546
+ "annotation_edge": "edge map",
547
+ "annotation_depth": "depth map",
548
+ "annotation_normal": "normal map",
549
+ "annotation_albedo": "albedo map",
550
+ "annotation_seg_12colors": "segmentation map",
551
+ "annotation_openpose": "human pose map",
552
+ }
553
+
554
+ present_modalities = [readable_map[n] for n, _ in available]
555
+
556
+ # 构造 prompt
557
+ eval_prompt = f"""
558
+ You are a multimodal visual reasoning evaluator.
559
+
560
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
561
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
562
+ based purely on visual evidence from all modalities.
563
+
564
+ Follow this process:
565
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
566
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
567
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
568
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
569
+ 5. Penalize any parts that contradict the image, or ignore modalities.
570
+
571
+ Return JSON strictly:
572
+ {{
573
+ "AnswerScore": <float between 0 and 1>,
574
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
575
+ }}
576
+
577
+ Question: "{question}"
578
+ Answer: "{answer}"
579
+ """
580
+
581
+ # 构建内容序列(模态+图像)
582
+ content = []
583
+ for name, path in available:
584
+ readable = readable_map.get(name, "visual input")
585
+ content.append({"type": "text", "text": f"This is the {readable}."})
586
+ content.append({"type": "image", "image": path})
587
+ content.append({"type": "text", "text": eval_prompt})
588
+
589
+ messages = [{"role": "user", "content": content}]
590
+
591
+ print(f'eval message:{messages}')
592
+
593
+ # --- 推理 ---
594
+ inputs = processor.apply_chat_template(
595
+ messages, tokenize=True, add_generation_prompt=True,
596
+ return_dict=True, return_tensors="pt"
597
+ ).to(model.device)
598
+
599
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
600
+ #print(out_ids)
601
+ out_ids = outs['sequences']
602
+ scores = outs['scores']
603
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
604
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
605
+
606
+ # --- 解析输出 ---
607
+ try:
608
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
609
+ score = float(data.get("AnswerScore", 0))
610
+ feedback = data.get("Feedback", "")
611
+ except Exception:
612
+ score, feedback = 0.0, text.strip()
613
+
614
+ gen_start = inputs["input_ids"].shape[1]
615
+ gen_ids = out_ids[:, gen_start:]
616
+ #gen_ids = out_ids[:, gen_start:]
617
+ gen_text = processor.tokenizer.decode(gen_ids[0], skip_special_tokens=False)
618
+ num_match = re.search(r"AnswerScore\"\s*:\s*([0-9\.]+)", gen_text)
619
+ conf = 0.0
620
+ if num_match:
621
+ num_text = num_match.group(1)
622
+ num_ids = processor.tokenizer.encode(num_text, add_special_tokens=False)
623
+ num_str = processor.tokenizer.decode(num_ids)
624
+ gen_id_list = gen_ids[0].tolist()
625
+ match_positions = []
626
+ for i in range(len(gen_id_list) - len(num_ids) + 1):
627
+ if gen_id_list[i:i+len(num_ids)] == num_ids:
628
+ match_positions = list(range(i, i+len(num_ids)))
629
+ break
630
+
631
+ if match_positions:
632
+ probs = []
633
+ for pos in match_positions:
634
+ step_prob = F.softmax(scores[pos], dim=-1)
635
+ token_id = gen_ids[0, pos]
636
+ probs.append(step_prob[0, token_id])
637
+ conf = torch.stack(probs).mean().item()
638
+
639
+ #print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
640
+ #print(f"📊 [Confidence(AnswerScore)] {conf:.4f}")
641
+
642
+ return score, feedback
643
+
644
+
645
+
646
+ @torch.inference_mode()
647
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
648
+ question = clean_prompt_question(question)
649
+ messages = build_multimodal_message(root, question, prompt, feedback)
650
+ print(f'refine message:{messages}')
651
+ inputs = processor.apply_chat_template(
652
+ messages,
653
+ tokenize=True,
654
+ add_generation_prompt=True,
655
+ return_dict=True,
656
+ return_tensors="pt"
657
+ )
658
+ inputs = inputs.to(model.device)
659
+
660
+ # Inference: Generation of the output
661
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
662
+ generated_ids_trimmed = [
663
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
664
+ ]
665
+ output_text = processor.batch_decode(
666
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
667
+ )
668
+ #print(output_text)
669
+
670
+ os.makedirs(args.output_dir, exist_ok=True)
671
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
672
+ save_dir.mkdir(parents=True, exist_ok=True)
673
+ caption_path = Path(save_dir) / f"caption.txt"
674
+ feedback_path = Path(save_dir) / f"feedback.txt"
675
+ with open(feedback_path, "w", encoding="utf-8") as f:
676
+ f.write(feedback.strip())
677
+ with open(caption_path, "w", encoding="utf-8") as f:
678
+ f.write(output_text[0].strip())
679
+ return output_text[0]
680
+
681
+
682
+ @torch.inference_mode()
683
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
684
+ messages = build_vqa_message(root, prompt, question)
685
+ print(f'vqa messages:{messages}')
686
+ inputs = processor.apply_chat_template(
687
+ messages,
688
+ tokenize=True,
689
+ add_generation_prompt=True,
690
+ return_dict=True,
691
+ return_tensors="pt"
692
+ )
693
+ inputs = inputs.to(model.device)
694
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
695
+ generated_ids_trimmed = [
696
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
697
+ output_text = processor.batch_decode(
698
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
699
+ )
700
+ #print(output_text)
701
+ os.makedirs(args.output_dir, exist_ok=True)
702
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
703
+ save_dir.mkdir(parents=True, exist_ok=True)
704
+ caption_path = Path(save_dir) / f"caption.txt"
705
+ with open(caption_path, "w", encoding="utf-8") as f:
706
+ f.write(output_text[0].strip())
707
+ return output_text[0]
708
+
709
+
710
+ @torch.inference_mode()
711
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
712
+ # print(f"🚀 Generating with prompt: {prompt}")
713
+ outputs = pipe(
714
+ images=images,
715
+ role=role,
716
+ prompt=prompt,
717
+ negative_prompt=args.negative_prompt,
718
+ height=height,
719
+ width=width,
720
+ num_inference_steps=args.steps,
721
+ guidance_scale=args.guidance_scale,
722
+ num_images_per_prompt=1,
723
+ generator=generator
724
+ )
725
+
726
+ # Apply post-processing for each modality
727
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
728
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
729
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
730
+
731
+ # --------------------------
732
+ # Save results
733
+ # --------------------------
734
+ os.makedirs(args.output_dir, exist_ok=True)
735
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
736
+ save_dir.mkdir(parents=True, exist_ok=True)
737
+ for idx, img in enumerate(results):
738
+ name = modality_names[idx]
739
+ save_path = save_dir / f"{name}.png"
740
+ img.save(save_path)
741
+ print(f"💾 Saved {name} → {save_path}")
742
+
743
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
744
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
745
+ print(f"\n✅ All results saved in: {save_dir}\n")
746
+ return save_dir
747
+
748
+
749
+ if __name__ == "__main__":
750
+ args = get_parser().parse_args()
751
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
752
+ print(f"✅ Using device: {device}")
753
+
754
+ processor = AutoProcessor.from_pretrained(
755
+ args.model_name_or_path,
756
+ )
757
+
758
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
759
+ args.text_model_path,
760
+ attn_implementation="flash_attention_2",
761
+ dtype=(torch.bfloat16),
762
+ ).to(device)
763
+
764
+ pipe = JodiPipeline(args.config)
765
+ pipe.from_pretrained(args.model_path)
766
+
767
+ modality_names = [
768
+ "image",
769
+ "annotation_lineart",
770
+ "annotation_edge",
771
+ "annotation_depth",
772
+ "annotation_normal",
773
+ "annotation_albedo",
774
+ "annotation_seg_12colors",
775
+ "annotation_openpose",
776
+ ]
777
+
778
+ # Build post-processors
779
+ post_processors: list[Any] = [ImagePostProcessor()]
780
+ for condition in pipe.config.conditions: # type: ignore
781
+ if condition == "lineart":
782
+ post_processors.append(LineartPostProcessor())
783
+ elif condition == "edge":
784
+ post_processors.append(EdgePostProcessor())
785
+ elif condition == "depth":
786
+ post_processors.append(DepthPostProcessor())
787
+ elif condition == "normal":
788
+ post_processors.append(NormalPostProcessor())
789
+ elif condition == "albedo":
790
+ post_processors.append(AlbedoPostProcessor())
791
+ elif condition == "segmentation":
792
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
793
+ elif condition == "openpose":
794
+ post_processors.append(OpenposePostProcessor())
795
+ else:
796
+ print(f"⚠️ Warning: Unknown condition: {condition}")
797
+ post_processors.append(ImagePostProcessor())
798
+
799
+ torch.manual_seed(args.seed)
800
+ generator = torch.Generator(device=device).manual_seed(args.seed)
801
+
802
+ #with open(args.json, "r", encoding="utf-8") as f:
803
+ # annotations = json.load(f)
804
+
805
+ dataset = load_dataset("lmms-lab/POPE", split="test")
806
+
807
+ for sample in dataset:
808
+ #image_path = os.path.join(args.data_path, sample["image"])
809
+ #image_id = sample["image"].split('.')[0]
810
+ image_path = os.path.join(args.tmp, sample["image_source"]+'.jpg')
811
+
812
+ print(type(sample["image"]))
813
+
814
+ image_id = sample["id"]
815
+ image = sample["image"].convert("RGB")
816
+ image.save(image_path)
817
+ question = sample["question"]
818
+
819
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
820
+
821
+ role = [1] + [0] * pipe.num_conditions
822
+ print(role)
823
+
824
+ best_result, best_score = '', 0.0
825
+ max_length = 1024
826
+
827
+ # input_img = Image.open(image_path).convert("RGB")
828
+ width, height = image.size
829
+ print(f'ori width:{width}', f'ori height:{height}')
830
+
831
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
832
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
833
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
834
+
835
+ if score >= best_score:
836
+ best_result, best_score = result, score
837
+
838
+ for step in range(1, args.iters):
839
+ generator = torch.Generator(device=device).manual_seed(args.seed)
840
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
841
+ image_id)
842
+ max_length += 100
843
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
844
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
845
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
846
+
847
+ if score >= best_score:
848
+ best_result, best_score = result, score
849
+
850
+ os.makedirs(args.output_dir, exist_ok=True)
851
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
852
+ save_dir.mkdir(parents=True, exist_ok=True)
853
+ caption_path = Path(save_dir) / f"caption.txt"
854
+ with open(caption_path, "w", encoding="utf-8") as f:
855
+ f.write(best_result)
856
+ print(best_result)
857
+
test_real3.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
452
+ @torch.inference_mode()
453
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
454
+ # --- 构造 Qwen 输入 ---
455
+ question = clean_eval_question(question)
456
+ eval_prompt = f"""
457
+ You are a VQA answer evaluator.
458
+ Given an image, a question, and a proposed answer,
459
+ score how correct the answer is according to the image evidence.
460
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
461
+ to make the answer more accurate or grounded in the image.
462
+ Return JSON strictly:
463
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
464
+
465
+ Question: "{question}"
466
+ Answer: "{answer}"
467
+ <image>
468
+ """
469
+
470
+ messages = [
471
+ {
472
+ "role": "user",
473
+ "content": [
474
+ {"type": "image", "image": image_path},
475
+ {"type": "text", "text": eval_prompt},
476
+ ],
477
+ }
478
+ ]
479
+
480
+ # --- 推理 ---
481
+ inputs = processor.apply_chat_template(
482
+ messages,
483
+ tokenize=True,
484
+ add_generation_prompt=True,
485
+ return_dict=True,
486
+ return_tensors="pt"
487
+ ).to(model.device)
488
+
489
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
491
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
492
+
493
+ # --- 解析输出 ---
494
+ try:
495
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
496
+ score = float(data.get("AnswerScore", 0))
497
+ feedback = data.get("Feedback", "")
498
+ except Exception:
499
+ score, feedback = 0.0, text.strip()
500
+
501
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
502
+ return score, feedback
503
+
504
+
505
+ @torch.inference_mode()
506
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
507
+ question = clean_prompt_question(question)
508
+ messages = build_multimodal_message(root, question, prompt, feedback)
509
+ inputs = processor.apply_chat_template(
510
+ messages,
511
+ tokenize=True,
512
+ add_generation_prompt=True,
513
+ return_dict=True,
514
+ return_tensors="pt"
515
+ )
516
+ inputs = inputs.to(model.device)
517
+
518
+ # Inference: Generation of the output
519
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
520
+ generated_ids_trimmed = [
521
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
522
+ ]
523
+ output_text = processor.batch_decode(
524
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
525
+ )
526
+ print(output_text)
527
+
528
+ os.makedirs(args.output_dir, exist_ok=True)
529
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
530
+ save_dir.mkdir(parents=True, exist_ok=True)
531
+ caption_path = Path(save_dir) / f"caption.txt"
532
+ with open(caption_path, "w", encoding="utf-8") as f:
533
+ f.write(output_text[0].strip())
534
+ return output_text[0]
535
+
536
+
537
+ @torch.inference_mode()
538
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
539
+ messages = build_vqa_message(root, prompt, question)
540
+ print(messages)
541
+ inputs = processor.apply_chat_template(
542
+ messages,
543
+ tokenize=True,
544
+ add_generation_prompt=True,
545
+ return_dict=True,
546
+ return_tensors="pt"
547
+ )
548
+ inputs = inputs.to(model.device)
549
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
550
+ generated_ids_trimmed = [
551
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
552
+ output_text = processor.batch_decode(
553
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
554
+ )
555
+ print(output_text)
556
+ os.makedirs(args.output_dir, exist_ok=True)
557
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
558
+ save_dir.mkdir(parents=True, exist_ok=True)
559
+ caption_path = Path(save_dir) / f"caption.txt"
560
+ with open(caption_path, "w", encoding="utf-8") as f:
561
+ f.write(output_text[0].strip())
562
+ return output_text[0]
563
+
564
+
565
+ @torch.inference_mode()
566
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
567
+ # print(f"🚀 Generating with prompt: {prompt}")
568
+ outputs = pipe(
569
+ images=images,
570
+ role=role,
571
+ prompt=prompt,
572
+ negative_prompt=args.negative_prompt,
573
+ height=height,
574
+ width=width,
575
+ num_inference_steps=args.steps,
576
+ guidance_scale=args.guidance_scale,
577
+ num_images_per_prompt=1,
578
+ generator=generator,
579
+ task='t2i'
580
+ )
581
+
582
+ # Apply post-processing for each modality
583
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
584
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
585
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
586
+
587
+ # --------------------------
588
+ # Save results
589
+ # --------------------------
590
+ os.makedirs(args.output_dir, exist_ok=True)
591
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
592
+ save_dir.mkdir(parents=True, exist_ok=True)
593
+ for idx, img in enumerate(results):
594
+ name = modality_names[idx]
595
+ save_path = save_dir / f"{name}.png"
596
+ img.save(save_path)
597
+ print(f"💾 Saved {name} → {save_path}")
598
+
599
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
600
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
601
+ print(f"\n✅ All results saved in: {save_dir}\n")
602
+ return save_dir
603
+
604
+
605
+ if __name__ == "__main__":
606
+ args = get_parser().parse_args()
607
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
608
+ print(f"✅ Using device: {device}")
609
+
610
+ processor = AutoProcessor.from_pretrained(
611
+ args.model_name_or_path,
612
+ )
613
+
614
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
615
+ args.text_model_path,
616
+ attn_implementation="flash_attention_2",
617
+ dtype=(torch.bfloat16),
618
+ ).to(device)
619
+
620
+ pipe = JodiPipeline(args.config)
621
+ pipe.from_pretrained(args.model_path)
622
+
623
+ modality_names = [
624
+ "image",
625
+ "annotation_lineart",
626
+ "annotation_edge",
627
+ "annotation_depth",
628
+ "annotation_normal",
629
+ "annotation_albedo",
630
+ "annotation_seg_12colors",
631
+ "annotation_openpose",
632
+ ]
633
+
634
+ # Build post-processors
635
+ post_processors: list[Any] = [ImagePostProcessor()]
636
+ for condition in pipe.config.conditions: # type: ignore
637
+ if condition == "lineart":
638
+ post_processors.append(LineartPostProcessor())
639
+ elif condition == "edge":
640
+ post_processors.append(EdgePostProcessor())
641
+ elif condition == "depth":
642
+ post_processors.append(DepthPostProcessor())
643
+ elif condition == "normal":
644
+ post_processors.append(NormalPostProcessor())
645
+ elif condition == "albedo":
646
+ post_processors.append(AlbedoPostProcessor())
647
+ elif condition == "segmentation":
648
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
649
+ elif condition == "openpose":
650
+ post_processors.append(OpenposePostProcessor())
651
+ else:
652
+ print(f"⚠️ Warning: Unknown condition: {condition}")
653
+ post_processors.append(ImagePostProcessor())
654
+
655
+ torch.manual_seed(args.seed)
656
+ generator = torch.Generator(device=device).manual_seed(args.seed)
657
+
658
+ with open(args.json, "r", encoding="utf-8") as f:
659
+ annotations = json.load(f)
660
+
661
+ for sample in annotations[306:459]:
662
+ image_path = os.path.join(args.data_path, sample["image"])
663
+ image_id = sample["image"].split('.')[0]
664
+ image = Image.open(image_path)
665
+ question = sample["question"]
666
+
667
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
668
+
669
+ role = [1] + [0] * pipe.num_conditions
670
+ print(role)
671
+
672
+ best_dir, best_caption, best_score = '', '', 0.0
673
+ max_length = 1024
674
+
675
+ # input_img = Image.open(image_path).convert("RGB")
676
+ width, height = image.size
677
+ print(f'ori width:{width}', f'ori height:{height}')
678
+
679
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
680
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
681
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
682
+
683
+ if score >= best_score:
684
+ best_caption, best_score = prompt, score
685
+ best_dir = image_path
686
+
687
+ for step in range(1, args.iters):
688
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
689
+ image_id)
690
+ max_length += 100
691
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
692
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
693
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
694
+
695
+ if score >= best_score:
696
+ best_caption, best_score = prompt, score
697
+ best_dir = save_dir
698
+
699
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
700
+ print(f'result:{result}')
701
+
test_real4.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
452
+ @torch.inference_mode()
453
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
454
+ # --- 构造 Qwen 输入 ---
455
+ question = clean_eval_question(question)
456
+ eval_prompt = f"""
457
+ You are a VQA answer evaluator.
458
+ Given an image, a question, and a proposed answer,
459
+ score how correct the answer is according to the image evidence.
460
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
461
+ to make the answer more accurate or grounded in the image.
462
+ Return JSON strictly:
463
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
464
+
465
+ Question: "{question}"
466
+ Answer: "{answer}"
467
+ <image>
468
+ """
469
+
470
+ messages = [
471
+ {
472
+ "role": "user",
473
+ "content": [
474
+ {"type": "image", "image": image_path},
475
+ {"type": "text", "text": eval_prompt},
476
+ ],
477
+ }
478
+ ]
479
+
480
+ # --- 推理 ---
481
+ inputs = processor.apply_chat_template(
482
+ messages,
483
+ tokenize=True,
484
+ add_generation_prompt=True,
485
+ return_dict=True,
486
+ return_tensors="pt"
487
+ ).to(model.device)
488
+
489
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
491
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
492
+
493
+ # --- 解析输出 ---
494
+ try:
495
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
496
+ score = float(data.get("AnswerScore", 0))
497
+ feedback = data.get("Feedback", "")
498
+ except Exception:
499
+ score, feedback = 0.0, text.strip()
500
+
501
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
502
+ return score, feedback
503
+
504
+
505
+ @torch.inference_mode()
506
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
507
+ question = clean_prompt_question(question)
508
+ messages = build_multimodal_message(root, question, prompt, feedback)
509
+ inputs = processor.apply_chat_template(
510
+ messages,
511
+ tokenize=True,
512
+ add_generation_prompt=True,
513
+ return_dict=True,
514
+ return_tensors="pt"
515
+ )
516
+ inputs = inputs.to(model.device)
517
+
518
+ # Inference: Generation of the output
519
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
520
+ generated_ids_trimmed = [
521
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
522
+ ]
523
+ output_text = processor.batch_decode(
524
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
525
+ )
526
+ print(output_text)
527
+
528
+ os.makedirs(args.output_dir, exist_ok=True)
529
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
530
+ save_dir.mkdir(parents=True, exist_ok=True)
531
+ caption_path = Path(save_dir) / f"caption.txt"
532
+ with open(caption_path, "w", encoding="utf-8") as f:
533
+ f.write(output_text[0].strip())
534
+ return output_text[0]
535
+
536
+
537
+ @torch.inference_mode()
538
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
539
+ messages = build_vqa_message(root, prompt, question)
540
+ print(messages)
541
+ inputs = processor.apply_chat_template(
542
+ messages,
543
+ tokenize=True,
544
+ add_generation_prompt=True,
545
+ return_dict=True,
546
+ return_tensors="pt"
547
+ )
548
+ inputs = inputs.to(model.device)
549
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
550
+ generated_ids_trimmed = [
551
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
552
+ output_text = processor.batch_decode(
553
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
554
+ )
555
+ print(output_text)
556
+ os.makedirs(args.output_dir, exist_ok=True)
557
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
558
+ save_dir.mkdir(parents=True, exist_ok=True)
559
+ caption_path = Path(save_dir) / f"caption.txt"
560
+ with open(caption_path, "w", encoding="utf-8") as f:
561
+ f.write(output_text[0].strip())
562
+ return output_text[0]
563
+
564
+
565
+ @torch.inference_mode()
566
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
567
+ # print(f"🚀 Generating with prompt: {prompt}")
568
+ outputs = pipe(
569
+ images=images,
570
+ role=role,
571
+ prompt=prompt,
572
+ negative_prompt=args.negative_prompt,
573
+ height=height,
574
+ width=width,
575
+ num_inference_steps=args.steps,
576
+ guidance_scale=args.guidance_scale,
577
+ num_images_per_prompt=1,
578
+ generator=generator,
579
+ task='t2i'
580
+ )
581
+
582
+ # Apply post-processing for each modality
583
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
584
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
585
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
586
+
587
+ # --------------------------
588
+ # Save results
589
+ # --------------------------
590
+ os.makedirs(args.output_dir, exist_ok=True)
591
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
592
+ save_dir.mkdir(parents=True, exist_ok=True)
593
+ for idx, img in enumerate(results):
594
+ name = modality_names[idx]
595
+ save_path = save_dir / f"{name}.png"
596
+ img.save(save_path)
597
+ print(f"💾 Saved {name} → {save_path}")
598
+
599
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
600
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
601
+ print(f"\n✅ All results saved in: {save_dir}\n")
602
+ return save_dir
603
+
604
+
605
+ if __name__ == "__main__":
606
+ args = get_parser().parse_args()
607
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
608
+ print(f"✅ Using device: {device}")
609
+
610
+ processor = AutoProcessor.from_pretrained(
611
+ args.model_name_or_path,
612
+ )
613
+
614
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
615
+ args.text_model_path,
616
+ attn_implementation="flash_attention_2",
617
+ dtype=(torch.bfloat16),
618
+ ).to(device)
619
+
620
+ pipe = JodiPipeline(args.config)
621
+ pipe.from_pretrained(args.model_path)
622
+
623
+ modality_names = [
624
+ "image",
625
+ "annotation_lineart",
626
+ "annotation_edge",
627
+ "annotation_depth",
628
+ "annotation_normal",
629
+ "annotation_albedo",
630
+ "annotation_seg_12colors",
631
+ "annotation_openpose",
632
+ ]
633
+
634
+ # Build post-processors
635
+ post_processors: list[Any] = [ImagePostProcessor()]
636
+ for condition in pipe.config.conditions: # type: ignore
637
+ if condition == "lineart":
638
+ post_processors.append(LineartPostProcessor())
639
+ elif condition == "edge":
640
+ post_processors.append(EdgePostProcessor())
641
+ elif condition == "depth":
642
+ post_processors.append(DepthPostProcessor())
643
+ elif condition == "normal":
644
+ post_processors.append(NormalPostProcessor())
645
+ elif condition == "albedo":
646
+ post_processors.append(AlbedoPostProcessor())
647
+ elif condition == "segmentation":
648
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
649
+ elif condition == "openpose":
650
+ post_processors.append(OpenposePostProcessor())
651
+ else:
652
+ print(f"⚠️ Warning: Unknown condition: {condition}")
653
+ post_processors.append(ImagePostProcessor())
654
+
655
+ torch.manual_seed(args.seed)
656
+ generator = torch.Generator(device=device).manual_seed(args.seed)
657
+
658
+ with open(args.json, "r", encoding="utf-8") as f:
659
+ annotations = json.load(f)
660
+
661
+ for sample in annotations[459:612]:
662
+ image_path = os.path.join(args.data_path, sample["image"])
663
+ image_id = sample["image"].split('.')[0]
664
+ image = Image.open(image_path)
665
+ question = sample["question"]
666
+
667
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
668
+
669
+ role = [1] + [0] * pipe.num_conditions
670
+ print(role)
671
+
672
+ best_dir, best_caption, best_score = '', '', 0.0
673
+ max_length = 1024
674
+
675
+ # input_img = Image.open(image_path).convert("RGB")
676
+ width, height = image.size
677
+ print(f'ori width:{width}', f'ori height:{height}')
678
+
679
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
680
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
681
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
682
+
683
+ if score >= best_score:
684
+ best_caption, best_score = prompt, score
685
+ best_dir = image_path
686
+
687
+ for step in range(1, args.iters):
688
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
689
+ image_id)
690
+ max_length += 100
691
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
692
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
693
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
694
+
695
+ if score >= best_score:
696
+ best_caption, best_score = prompt, score
697
+ best_dir = save_dir
698
+
699
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
700
+ print(f'result:{result}')
701
+
test_real5.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
452
+ @torch.inference_mode()
453
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
454
+ # --- 构造 Qwen 输入 ---
455
+ question = clean_eval_question(question)
456
+ eval_prompt = f"""
457
+ You are a VQA answer evaluator.
458
+ Given an image, a question, and a proposed answer,
459
+ score how correct the answer is according to the image evidence.
460
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
461
+ to make the answer more accurate or grounded in the image.
462
+ Return JSON strictly:
463
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
464
+
465
+ Question: "{question}"
466
+ Answer: "{answer}"
467
+ <image>
468
+ """
469
+
470
+ messages = [
471
+ {
472
+ "role": "user",
473
+ "content": [
474
+ {"type": "image", "image": image_path},
475
+ {"type": "text", "text": eval_prompt},
476
+ ],
477
+ }
478
+ ]
479
+
480
+ # --- 推理 ---
481
+ inputs = processor.apply_chat_template(
482
+ messages,
483
+ tokenize=True,
484
+ add_generation_prompt=True,
485
+ return_dict=True,
486
+ return_tensors="pt"
487
+ ).to(model.device)
488
+
489
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
491
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
492
+
493
+ # --- 解析输出 ---
494
+ try:
495
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
496
+ score = float(data.get("AnswerScore", 0))
497
+ feedback = data.get("Feedback", "")
498
+ except Exception:
499
+ score, feedback = 0.0, text.strip()
500
+
501
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
502
+ return score, feedback
503
+
504
+
505
+ @torch.inference_mode()
506
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
507
+ question = clean_prompt_question(question)
508
+ messages = build_multimodal_message(root, question, prompt, feedback)
509
+ inputs = processor.apply_chat_template(
510
+ messages,
511
+ tokenize=True,
512
+ add_generation_prompt=True,
513
+ return_dict=True,
514
+ return_tensors="pt"
515
+ )
516
+ inputs = inputs.to(model.device)
517
+
518
+ # Inference: Generation of the output
519
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
520
+ generated_ids_trimmed = [
521
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
522
+ ]
523
+ output_text = processor.batch_decode(
524
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
525
+ )
526
+ print(output_text)
527
+
528
+ os.makedirs(args.output_dir, exist_ok=True)
529
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
530
+ save_dir.mkdir(parents=True, exist_ok=True)
531
+ caption_path = Path(save_dir) / f"caption.txt"
532
+ with open(caption_path, "w", encoding="utf-8") as f:
533
+ f.write(output_text[0].strip())
534
+ return output_text[0]
535
+
536
+
537
+ @torch.inference_mode()
538
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
539
+ messages = build_vqa_message(root, prompt, question)
540
+ print(messages)
541
+ inputs = processor.apply_chat_template(
542
+ messages,
543
+ tokenize=True,
544
+ add_generation_prompt=True,
545
+ return_dict=True,
546
+ return_tensors="pt"
547
+ )
548
+ inputs = inputs.to(model.device)
549
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
550
+ generated_ids_trimmed = [
551
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
552
+ output_text = processor.batch_decode(
553
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
554
+ )
555
+ print(output_text)
556
+ os.makedirs(args.output_dir, exist_ok=True)
557
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
558
+ save_dir.mkdir(parents=True, exist_ok=True)
559
+ caption_path = Path(save_dir) / f"caption.txt"
560
+ with open(caption_path, "w", encoding="utf-8") as f:
561
+ f.write(output_text[0].strip())
562
+ return output_text[0]
563
+
564
+
565
+ @torch.inference_mode()
566
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
567
+ # print(f"🚀 Generating with prompt: {prompt}")
568
+ outputs = pipe(
569
+ images=images,
570
+ role=role,
571
+ prompt=prompt,
572
+ negative_prompt=args.negative_prompt,
573
+ height=height,
574
+ width=width,
575
+ num_inference_steps=args.steps,
576
+ guidance_scale=args.guidance_scale,
577
+ num_images_per_prompt=1,
578
+ generator=generator,
579
+ task='t2i'
580
+ )
581
+
582
+ # Apply post-processing for each modality
583
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
584
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
585
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
586
+
587
+ # --------------------------
588
+ # Save results
589
+ # --------------------------
590
+ os.makedirs(args.output_dir, exist_ok=True)
591
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
592
+ save_dir.mkdir(parents=True, exist_ok=True)
593
+ for idx, img in enumerate(results):
594
+ name = modality_names[idx]
595
+ save_path = save_dir / f"{name}.png"
596
+ img.save(save_path)
597
+ print(f"💾 Saved {name} → {save_path}")
598
+
599
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
600
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
601
+ print(f"\n✅ All results saved in: {save_dir}\n")
602
+ return save_dir
603
+
604
+
605
+ if __name__ == "__main__":
606
+ args = get_parser().parse_args()
607
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
608
+ print(f"✅ Using device: {device}")
609
+
610
+ processor = AutoProcessor.from_pretrained(
611
+ args.model_name_or_path,
612
+ )
613
+
614
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
615
+ args.text_model_path,
616
+ attn_implementation="flash_attention_2",
617
+ dtype=(torch.bfloat16),
618
+ ).to(device)
619
+
620
+ pipe = JodiPipeline(args.config)
621
+ pipe.from_pretrained(args.model_path)
622
+
623
+ modality_names = [
624
+ "image",
625
+ "annotation_lineart",
626
+ "annotation_edge",
627
+ "annotation_depth",
628
+ "annotation_normal",
629
+ "annotation_albedo",
630
+ "annotation_seg_12colors",
631
+ "annotation_openpose",
632
+ ]
633
+
634
+ # Build post-processors
635
+ post_processors: list[Any] = [ImagePostProcessor()]
636
+ for condition in pipe.config.conditions: # type: ignore
637
+ if condition == "lineart":
638
+ post_processors.append(LineartPostProcessor())
639
+ elif condition == "edge":
640
+ post_processors.append(EdgePostProcessor())
641
+ elif condition == "depth":
642
+ post_processors.append(DepthPostProcessor())
643
+ elif condition == "normal":
644
+ post_processors.append(NormalPostProcessor())
645
+ elif condition == "albedo":
646
+ post_processors.append(AlbedoPostProcessor())
647
+ elif condition == "segmentation":
648
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
649
+ elif condition == "openpose":
650
+ post_processors.append(OpenposePostProcessor())
651
+ else:
652
+ print(f"⚠️ Warning: Unknown condition: {condition}")
653
+ post_processors.append(ImagePostProcessor())
654
+
655
+ torch.manual_seed(args.seed)
656
+ generator = torch.Generator(device=device).manual_seed(args.seed)
657
+
658
+ with open(args.json, "r", encoding="utf-8") as f:
659
+ annotations = json.load(f)
660
+
661
+ for sample in annotations[612:]:
662
+ image_path = os.path.join(args.data_path, sample["image"])
663
+ image_id = sample["image"].split('.')[0]
664
+ image = Image.open(image_path)
665
+ question = sample["question"]
666
+
667
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
668
+
669
+ role = [1] + [0] * pipe.num_conditions
670
+ print(role)
671
+
672
+ best_dir, best_caption, best_score = '', '', 0.0
673
+ max_length = 1024
674
+
675
+ # input_img = Image.open(image_path).convert("RGB")
676
+ width, height = image.size
677
+ print(f'ori width:{width}', f'ori height:{height}')
678
+
679
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
680
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
681
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
682
+
683
+ if score >= best_score:
684
+ best_caption, best_score = prompt, score
685
+ best_dir = image_path
686
+
687
+ for step in range(1, args.iters):
688
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
689
+ image_id)
690
+ max_length += 100
691
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
692
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
693
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
694
+
695
+ if score >= best_score:
696
+ best_caption, best_score = prompt, score
697
+ best_dir = save_dir
698
+
699
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
700
+ print(f'result:{result}')
701
+
test_real_amber.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[:3432]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_real_amber1.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[3432:6864]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_real_amber2.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[6864:10296]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_real_amber3.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[10296:13728]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_real_amber4.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[13728:17160]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_real_amber5.py ADDED
@@ -0,0 +1,810 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ f"Just response yes or no"
203
+ )
204
+
205
+
206
+ # ---------- 构建内容序列(模态锚定) ----------
207
+ content = []
208
+ #content.append({"type": "text", "text": text_prompt})
209
+ print(f'available:{available}')
210
+ for name, path in available:
211
+ readable = readable_map.get(name, "visual input")
212
+ # 在每张图像前显式标注模态类型
213
+ content.append({"type": "text", "text": f"This is the {readable}."})
214
+ content.append({"type": "image", "image": path})
215
+
216
+ # 最后加入主指令
217
+ content.append({"type": "text", "text": text_prompt})
218
+
219
+ messages = [{"role": "user", "content": content}]
220
+ return messages
221
+
222
+
223
+ def build_multimodal_message(root, question, coarse_caption="a generic scene", feedback=""):
224
+ """
225
+ Build Qwen3-VL message for multi-modal caption refinement.
226
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
227
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
228
+ """
229
+
230
+ modality_names = [
231
+ "image",
232
+ "annotation_lineart",
233
+ "annotation_edge",
234
+ "annotation_depth",
235
+ "annotation_normal",
236
+ "annotation_albedo",
237
+ "annotation_seg_12colors",
238
+ # "annotation_openpose",
239
+ ]
240
+
241
+ # --- 检查存在的模态 ---
242
+ available = []
243
+ for name in modality_names:
244
+ for ext in [".png", ".jpg", ".jpeg"]:
245
+ path = Path(root) / f"{name}{ext}"
246
+ if path.exists():
247
+ available.append((name, str(path)))
248
+ break
249
+
250
+ # --- 构建模态说明 ---
251
+ readable_map = {
252
+ "image": "RGB image",
253
+ "annotation_lineart": "line drawing",
254
+ "annotation_edge": "edge map",
255
+ "annotation_depth": "depth map",
256
+ "annotation_normal": "normal map",
257
+ "annotation_albedo": "albedo map",
258
+ "annotation_seg_12colors": "segmentation map",
259
+ # "annotation_openpose": "human pose map",
260
+ }
261
+
262
+ present_modalities = [readable_map[n] for n, _ in available]
263
+
264
+ # --- 构造文本指令 ---
265
+ text_prompt = (
266
+ f"You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}. "
267
+ f"Use all available modalities jointly to reason about the same scene rather than describing them separately. "
268
+ f"Generate an enhanced visual description that focuses on the aspects most relevant to answering the following question: '{question}'. "
269
+ f"Your task is to refine the description of the scene based on all visual modalities so that it highlights visual cues "
270
+ f"that are crucial for accurately addressing the question, such as object appearance, count, position, or relation, "
271
+ f"while maintaining faithfulness to the original visual content. "
272
+ f"Do not include any additional commentary or evaluations. "
273
+ f"Do NOT introduce any new objects, background environments, emotional tones, or storytelling context. "
274
+ f"Focus on describing the visual properties, including: "
275
+ f"(1) object category and identity, (2) object attributes such as color, shape, size, and texture, "
276
+ f"(3) spatial or relational positioning between objects if present, (4) object part–whole structure or state, and (5) object count or quantity. "
277
+ f"Exclude any stylistic, environmental, emotional, or narrative information. "
278
+ f"Consider the following feedback when refining your description: '{feedback}'. "
279
+ f"Describe the scene in an objective and concise tone, emphasizing the details that help answer the question: '{question}'. "
280
+ f"Coarse caption: '{coarse_caption}' "
281
+ )
282
+
283
+ # text_prompt0 = (
284
+ # f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
285
+ # f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
286
+ # f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
287
+ # f"### Your Task:\n"
288
+ # f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
289
+ # f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
290
+ # f"### Guidelines:\n"
291
+ # f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
292
+ # f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
293
+ # f"3. Do NOT invent or assume anything not visually supported.\n"
294
+ # f"4. Avoid including any additional commentary or evaluations.\n"
295
+ # f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
296
+ # f"### Coarse Caption:\n'{coarse_caption}'\n\n"
297
+ # f"### Feedback to Incorporate:\n'{feedback}'\n\n"
298
+ # f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
299
+ # )
300
+
301
+ # --- 构建消息内容:在每个图像前加模态标识 ---
302
+ content = []
303
+ #content.append({"type": "text", "text": text_prompt})
304
+ for name, path in available:
305
+ readable = readable_map.get(name, "visual input")
306
+ content.append({
307
+ "type": "text",
308
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
309
+ })
310
+ content.append({"type": "image", "image": path})
311
+
312
+ # 最后附上总任务说明
313
+ content.append({"type": "text", "text": text_prompt})
314
+
315
+ messages = [{"role": "user", "content": content}]
316
+ return messages
317
+
318
+
319
+ def get_modality_description(name: str) -> str:
320
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
321
+ desc_map = {
322
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
323
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
324
+ "annotation_edge": "strong boundaries and contrast edges between objects",
325
+ "annotation_depth": "distance and perspective information for spatial understanding",
326
+ "annotation_normal": "surface orientation and geometric curvature cues",
327
+ "annotation_albedo": "pure surface color without lighting or shading effects",
328
+ "annotation_seg_12colors": "semantic regions and object categories",
329
+ "annotation_openpose": "human body keypoints, joints, and orientation",
330
+ }
331
+ return desc_map.get(name, "complementary visual evidence")
332
+
333
+
334
+ # ------------------------------
335
+ # Argument Parser
336
+ # ------------------------------
337
+ def get_parser():
338
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
339
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
340
+ help="Path to model checkpoint.")
341
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
342
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
343
+ help="Path to model checkpoint.")
344
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
345
+ help="Path to model checkpoint.")
346
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/image",
347
+ help="Prompt text for generation.")
348
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/miw/dataset/dataset/AMBER/merged.json",
349
+ help="Optional negative prompt.")
350
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
351
+ help="Prompt text for generation.")
352
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
353
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
354
+ help="Optional negative prompt.")
355
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
356
+ parser.add_argument("--iters", type=int, default=5, help="Number of inference steps.")
357
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
358
+ parser.add_argument("--seed", type=int, default=42)
359
+ parser.add_argument("--output_dir", type=str, default="./vqa_amber_outputs", help="Directory to save results.")
360
+ return parser
361
+
362
+
363
+ # ------------------------------
364
+ # Main Inference Function
365
+ # ------------------------------
366
+
367
+
368
+ @torch.inference_mode()
369
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
370
+ messages = [
371
+ {
372
+ "role": "user",
373
+ "content": [
374
+ {
375
+ "type": "image",
376
+ "image": image_path,
377
+ },
378
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
379
+ ],
380
+ }
381
+ ]
382
+
383
+ print(messages)
384
+
385
+ inputs = processor.apply_chat_template(
386
+ messages,
387
+ tokenize=True,
388
+ add_generation_prompt=True,
389
+ return_dict=True,
390
+ return_tensors="pt"
391
+ )
392
+ inputs = inputs.to(model.device)
393
+
394
+ # Inference: Generation of the output
395
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
396
+ generated_ids_trimmed = [
397
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
398
+ ]
399
+ output_text = processor.batch_decode(
400
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
401
+ )
402
+ print(output_text)
403
+
404
+ os.makedirs(args.output_dir, exist_ok=True)
405
+ save_dir = Path(args.output_dir) / str(vqa_id)
406
+ save_dir.mkdir(parents=True, exist_ok=True)
407
+ caption_path = Path(save_dir) / f"caption.txt"
408
+ with open(caption_path, "w", encoding="utf-8") as f:
409
+ f.write(output_text[0].strip())
410
+
411
+ return output_text[0]
412
+
413
+
414
+ @torch.inference_mode()
415
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
416
+ messages = [
417
+ {
418
+ "role": "user",
419
+ "content": [
420
+ {
421
+ "type": "image",
422
+ "image": image_path,
423
+ },
424
+ {"type": "text", "text": f"Describe this image."},
425
+ ],
426
+ }
427
+ ]
428
+
429
+ inputs = processor.apply_chat_template(
430
+ messages,
431
+ tokenize=True,
432
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
433
+ )
434
+ inputs = inputs.to(model.device)
435
+
436
+ # Inference: Generation of the output
437
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
438
+ generated_ids_trimmed = [
439
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
440
+ ]
441
+ output_text = processor.batch_decode(
442
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
443
+ )
444
+ print(output_text)
445
+
446
+ os.makedirs(args.output_dir, exist_ok=True)
447
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
448
+ save_dir.mkdir(parents=True, exist_ok=True)
449
+ caption_path = Path(save_dir) / f"caption.txt"
450
+ with open(caption_path, "w", encoding="utf-8") as f:
451
+ f.write(output_text[0].strip())
452
+
453
+ return output_text[0]
454
+
455
+ @torch.inference_mode()
456
+ def evaluate_consistency(image_path, model, processor, question, answer, max_length=256):
457
+ # --- 构造 Qwen 输入 ---
458
+ question = clean_eval_question(question)
459
+ eval_prompt = f"""
460
+ You are a VQA answer evaluator.
461
+ Given an image, a question, and a proposed answer,
462
+ score how correct the answer is according to the image evidence.
463
+ Then provide one short feedback sentence suggesting what kind of visual information related to {question} or reasoning should be improved
464
+ to make the answer more accurate or grounded in the image.
465
+ Return JSON strictly:
466
+ {{"AnswerScore": <float 0-1>, "Feedback": "<short suggestion>"}}
467
+
468
+ Question: "{question}"
469
+ Answer: "{answer}"
470
+ <image>
471
+ """
472
+
473
+ messages = [
474
+ {
475
+ "role": "user",
476
+ "content": [
477
+ {"type": "image", "image": image_path},
478
+ {"type": "text", "text": eval_prompt},
479
+ ],
480
+ }
481
+ ]
482
+
483
+ # --- 推理 ---
484
+ inputs = processor.apply_chat_template(
485
+ messages,
486
+ tokenize=True,
487
+ add_generation_prompt=True,
488
+ return_dict=True,
489
+ return_tensors="pt"
490
+ ).to(model.device)
491
+
492
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
493
+ #print(f'out_ids.logits:{out_ids.logit}')
494
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
495
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
496
+
497
+ # --- 解析输出 ---
498
+ try:
499
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
500
+ score = float(data.get("AnswerScore", 0))
501
+ feedback = data.get("Feedback", "")
502
+ except Exception:
503
+ score, feedback = 0.0, text.strip()
504
+
505
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
506
+ return score, feedback
507
+
508
+ @torch.inference_mode()
509
+ def evaluate_multimodal_consistency(root, model, processor, question, answer, max_length=256):
510
+ """
511
+ Evaluate VQA answer correctness using all available modalities (not just RGB).
512
+ This reduces model bias and improves visual grounding reliability.
513
+ """
514
+
515
+ # 检查存在的模态文件
516
+ modality_names = [
517
+ "image", "annotation_lineart", "annotation_edge",
518
+ "annotation_depth", "annotation_normal", "annotation_albedo",
519
+ "annotation_seg_12colors", "annotation_openpose"
520
+ ]
521
+
522
+ available = []
523
+ for name in modality_names:
524
+ for ext in [".png", ".jpg", ".jpeg"]:
525
+ path = Path(root) / f"{name}{ext}"
526
+ if path.exists():
527
+ available.append((name, str(path)))
528
+ break
529
+
530
+ # 可读映射
531
+ readable_map = {
532
+ "image": "RGB image",
533
+ "annotation_lineart": "line drawing",
534
+ "annotation_edge": "edge map",
535
+ "annotation_depth": "depth map",
536
+ "annotation_normal": "normal map",
537
+ "annotation_albedo": "albedo map",
538
+ "annotation_seg_12colors": "segmentation map",
539
+ "annotation_openpose": "human pose map",
540
+ }
541
+
542
+ present_modalities = [readable_map[n] for n, _ in available]
543
+
544
+ # 构造 prompt
545
+ eval_prompt = f"""
546
+ You are a multimodal visual reasoning evaluator.
547
+
548
+ You are given multiple complementary visual modalities of the same scene, including: {', '.join(present_modalities)}.
549
+ Your task is to judge **how correct and visually grounded** the given answer is for the question,
550
+ based purely on visual evidence from all modalities.
551
+
552
+ Follow this process:
553
+ 1. Identify the key visual concepts mentioned in the question (e.g., objects, counts, relations, colors).
554
+ 2. Check whether these visual concepts are **clearly supported** or **contradicted** by the modalities.
555
+ 3. If the question is multiple-choice (options A, B, C...), identify which one best matches the evidence.
556
+ 4. Otherwise, directly evaluate how accurate the free-form answer is.
557
+ 5. Penalize any parts that contradict the image, or ignore modalities.
558
+
559
+ Return JSON strictly:
560
+ {{
561
+ "AnswerScore": <float between 0 and 1>,
562
+ "Feedback": "<short and specific suggestion mentioning what aspect (e.g., object count, relation, visibility) could be improved>"
563
+ }}
564
+
565
+ Question: "{question}"
566
+ Answer: "{answer}"
567
+ """
568
+
569
+ # 构建内容序列(模态+图像)
570
+ content = []
571
+ #content.append({"type": "text", "text": eval_prompt})
572
+ for name, path in available:
573
+ readable = readable_map.get(name, "visual input")
574
+ content.append({"type": "text", "text": f"This is the {readable}."})
575
+ content.append({"type": "image", "image": path})
576
+ content.append({"type": "text", "text": eval_prompt})
577
+
578
+ messages = [{"role": "user", "content": content}]
579
+
580
+ # --- 推理 ---
581
+ inputs = processor.apply_chat_template(
582
+ messages, tokenize=True, add_generation_prompt=True,
583
+ return_dict=True, return_tensors="pt"
584
+ ).to(model.device)
585
+
586
+ outs = model.generate(**inputs, max_new_tokens=max_length, output_scores=True, return_dict_in_generate=True)
587
+ #print(out_ids)
588
+ out_ids = outs['sequences']
589
+ scores = outs['scores']
590
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
591
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
592
+
593
+ # --- 解析输出 ---
594
+ try:
595
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
596
+ score = float(data.get("AnswerScore", 0))
597
+ feedback = data.get("Feedback", "")
598
+ except Exception:
599
+ score, feedback = 0.0, text.strip()
600
+
601
+ print(f"🧮 [AnswerScore] {score:.3f} | Feedback: {feedback}")
602
+ return score, feedback
603
+
604
+
605
+
606
+ @torch.inference_mode()
607
+ def text_refine(root, model, processor, prompt, question, feedback, iter_num, vqa_id, max_length=300):
608
+ question = clean_prompt_question(question)
609
+ messages = build_multimodal_message(root, question, prompt, feedback)
610
+ inputs = processor.apply_chat_template(
611
+ messages,
612
+ tokenize=True,
613
+ add_generation_prompt=True,
614
+ return_dict=True,
615
+ return_tensors="pt"
616
+ )
617
+ inputs = inputs.to(model.device)
618
+
619
+ # Inference: Generation of the output
620
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
621
+ generated_ids_trimmed = [
622
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
623
+ ]
624
+ output_text = processor.batch_decode(
625
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
626
+ )
627
+ print(output_text)
628
+
629
+ os.makedirs(args.output_dir, exist_ok=True)
630
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
631
+ save_dir.mkdir(parents=True, exist_ok=True)
632
+ caption_path = Path(save_dir) / f"caption.txt"
633
+ feedback_path = Path(save_dir) / f"feedback.txt"
634
+ with open(caption_path, "w", encoding="utf-8") as f:
635
+ f.write(output_text[0].strip())
636
+ with open(feedback_path, "w", encoding="utf-8") as f:
637
+ f.write(feedback.strip())
638
+ return output_text[0]
639
+
640
+
641
+ @torch.inference_mode()
642
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
643
+ messages = build_vqa_message(root, prompt, question)
644
+ print(messages)
645
+ inputs = processor.apply_chat_template(
646
+ messages,
647
+ tokenize=True,
648
+ add_generation_prompt=True,
649
+ return_dict=True,
650
+ return_tensors="pt"
651
+ )
652
+ inputs = inputs.to(model.device)
653
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
654
+ generated_ids_trimmed = [
655
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
656
+ output_text = processor.batch_decode(
657
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
658
+ )
659
+ print(output_text)
660
+ os.makedirs(args.output_dir, exist_ok=True)
661
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' / 'vqa_answer'
662
+ save_dir.mkdir(parents=True, exist_ok=True)
663
+ caption_path = Path(save_dir) / f"caption.txt"
664
+ with open(caption_path, "w", encoding="utf-8") as f:
665
+ f.write(output_text[0].strip())
666
+ return output_text[0]
667
+
668
+
669
+ @torch.inference_mode()
670
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
671
+ # print(f"🚀 Generating with prompt: {prompt}")
672
+ outputs = pipe(
673
+ images=images,
674
+ role=role,
675
+ prompt=prompt,
676
+ negative_prompt=args.negative_prompt,
677
+ height=height,
678
+ width=width,
679
+ num_inference_steps=args.steps,
680
+ guidance_scale=args.guidance_scale,
681
+ num_images_per_prompt=1,
682
+ generator=generator
683
+ )
684
+
685
+ # Apply post-processing for each modality
686
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
687
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
688
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
689
+
690
+ # --------------------------
691
+ # Save results
692
+ # --------------------------
693
+ os.makedirs(args.output_dir, exist_ok=True)
694
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
695
+ save_dir.mkdir(parents=True, exist_ok=True)
696
+ for idx, img in enumerate(results):
697
+ name = modality_names[idx]
698
+ save_path = save_dir / f"{name}.png"
699
+ img.save(save_path)
700
+ print(f"💾 Saved {name} → {save_path}")
701
+
702
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
703
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
704
+ print(f"\n✅ All results saved in: {save_dir}\n")
705
+ return save_dir
706
+
707
+
708
+ if __name__ == "__main__":
709
+ args = get_parser().parse_args()
710
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
711
+ print(f"✅ Using device: {device}")
712
+
713
+ processor = AutoProcessor.from_pretrained(
714
+ args.model_name_or_path,
715
+ )
716
+
717
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
718
+ args.text_model_path,
719
+ attn_implementation="flash_attention_2",
720
+ #attn_implementation="sdpa",
721
+ dtype=(torch.bfloat16),
722
+ ).to(device)
723
+
724
+ pipe = JodiPipeline(args.config)
725
+ pipe.from_pretrained(args.model_path)
726
+
727
+ modality_names = [
728
+ "image",
729
+ "annotation_lineart",
730
+ "annotation_edge",
731
+ "annotation_depth",
732
+ "annotation_normal",
733
+ "annotation_albedo",
734
+ "annotation_seg_12colors",
735
+ "annotation_openpose",
736
+ ]
737
+
738
+ # Build post-processors
739
+ post_processors: list[Any] = [ImagePostProcessor()]
740
+ for condition in pipe.config.conditions: # type: ignore
741
+ if condition == "lineart":
742
+ post_processors.append(LineartPostProcessor())
743
+ elif condition == "edge":
744
+ post_processors.append(EdgePostProcessor())
745
+ elif condition == "depth":
746
+ post_processors.append(DepthPostProcessor())
747
+ elif condition == "normal":
748
+ post_processors.append(NormalPostProcessor())
749
+ elif condition == "albedo":
750
+ post_processors.append(AlbedoPostProcessor())
751
+ elif condition == "segmentation":
752
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
753
+ elif condition == "openpose":
754
+ post_processors.append(OpenposePostProcessor())
755
+ else:
756
+ print(f"⚠️ Warning: Unknown condition: {condition}")
757
+ post_processors.append(ImagePostProcessor())
758
+
759
+ torch.manual_seed(args.seed)
760
+ generator = torch.Generator(device=device).manual_seed(args.seed)
761
+
762
+ with open(args.json, "r", encoding="utf-8") as f:
763
+ annotations = json.load(f)
764
+
765
+ for sample in annotations[17160:]:
766
+
767
+ image_path = os.path.join(args.data_path, sample["image"])
768
+ image_id = str(sample["id"])
769
+ image = Image.open(image_path)
770
+ question = sample["query"]
771
+
772
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
773
+
774
+ role = [1] + [0] * pipe.num_conditions
775
+ print(role)
776
+
777
+ best_result, best_score = '', 0.0
778
+ max_length = 1024
779
+
780
+ # input_img = Image.open(image_path).convert("RGB")
781
+ width, height = image.size
782
+ print(f'ori width:{width}', f'ori height:{height}')
783
+
784
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
785
+ result = vqa_i2t(model, processor, image_path, question, 100, max_length)
786
+ score, feedback = evaluate_consistency(image_path, model, processor, question, result)
787
+
788
+ if score >= best_score:
789
+ best_result, best_score = result, score
790
+
791
+ for step in range(1, args.iters):
792
+ generator = torch.Generator(device=device).manual_seed(args.seed)
793
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
794
+ image_id)
795
+ max_length += 100
796
+ prompt = text_refine(save_dir, model, processor, prompt, question, feedback, step, image_id, max_length)
797
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
798
+ score, feedback = evaluate_multimodal_consistency(save_dir, model, processor, question, result)
799
+
800
+ if score >= best_score:
801
+ best_result, best_score = result, score
802
+
803
+ os.makedirs(args.output_dir, exist_ok=True)
804
+ save_dir = Path(args.output_dir) / image_id / f'iteration_best' / 'vqa_answer'
805
+ save_dir.mkdir(parents=True, exist_ok=True)
806
+ caption_path = Path(save_dir) / f"caption.txt"
807
+ with open(caption_path, "w", encoding="utf-8") as f:
808
+ f.write(best_result)
809
+ print(best_result)
810
+
test_realworldqa_vqa.py ADDED
@@ -0,0 +1,620 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png"]:
94
+ image_path = str(root_path)
95
+ text_prompt = (
96
+ f"You are given one RGB image and a text description of the same scene.\n"
97
+ f"Scene description: \"{prompt}\"\n\n"
98
+ f"Now analyze the image carefully and answer the following question based only on what is visible.\n"
99
+ f"Do NOT guess or add details not supported by the image.\n"
100
+ f"Question: \"{question}\"\n"
101
+ "<image>"
102
+ )
103
+ messages = [
104
+ {
105
+ "role": "user",
106
+ "content": [
107
+ {"type": "image", "image": image_path},
108
+ {"type": "text", "text": text_prompt},
109
+ ],
110
+ }
111
+ ]
112
+ return messages
113
+
114
+ # ---------- 多模态文件夹情况 ----------
115
+ modality_names = [
116
+ "image",
117
+ "annotation_lineart",
118
+ "annotation_edge",
119
+ "annotation_depth",
120
+ "annotation_normal",
121
+ "annotation_albedo",
122
+ "annotation_seg_12colors",
123
+ "annotation_openpose",
124
+ ]
125
+
126
+ # 检查存在的模态文件
127
+ available = []
128
+ for name in modality_names:
129
+ for ext in [".png", ".jpg", ".jpeg"]:
130
+ path = Path(root) / f"{name}{ext}"
131
+ if path.exists():
132
+ available.append((name, str(path)))
133
+ break
134
+
135
+ # 可读名称映射
136
+ readable_map = {
137
+ "image": "RGB image",
138
+ "annotation_lineart": "line drawing",
139
+ "annotation_edge": "edge map",
140
+ "annotation_depth": "depth map",
141
+ "annotation_normal": "normal map",
142
+ "annotation_albedo": "albedo map",
143
+ "annotation_seg_12colors": "segmentation map",
144
+ "annotation_openpose": "human pose map",
145
+ }
146
+
147
+ present_modalities = [readable_map[n] for n, _ in available]
148
+
149
+ # ---------- 指令文本 ----------
150
+ text_prompt = (
151
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
152
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
153
+ f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
154
+ f"so use them only as optional references for additional context. "
155
+ f"Each modality provides complementary information about the same visual content:\n"
156
+ f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
157
+ f"- The edge map emphasizes boundaries and contours.\n"
158
+ f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
159
+ f"- The normal map shows surface orientation and geometric curvature.\n"
160
+ f"- The albedo map presents true surface color without illumination or shadows.\n"
161
+ f"- The segmentation map divides the scene into semantic regions and object categories.\n"
162
+ f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
163
+ f"Together, these modalities offer a unified, rich understanding of the scene.\n"
164
+ f"Scene description: \"{prompt}\"\n\n"
165
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
166
+ f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
167
+ f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
168
+ f"Question: \"{question}\"\n"
169
+ )
170
+
171
+ # ---------- 构建内容序列(模态锚定) ----------
172
+ content = []
173
+ for name, path in available:
174
+ readable = readable_map.get(name, "visual input")
175
+ # 在每张图像前显式标注模态类型
176
+ content.append({"type": "text", "text": f"This is the {readable}."})
177
+ content.append({"type": "image", "image": path})
178
+
179
+ # 最后加入主指令
180
+ content.append({"type": "text", "text": text_prompt})
181
+
182
+ messages = [{"role": "user", "content": content}]
183
+ return messages
184
+
185
+
186
+
187
+
188
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
189
+ """
190
+ Build Qwen3-VL message for multi-modal caption refinement.
191
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
192
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
193
+ """
194
+
195
+ modality_names = [
196
+ "image",
197
+ "annotation_lineart",
198
+ "annotation_edge",
199
+ "annotation_depth",
200
+ "annotation_normal",
201
+ "annotation_albedo",
202
+ "annotation_seg_12colors",
203
+ "annotation_openpose",
204
+ ]
205
+
206
+ # --- 检查存在的模态 ---
207
+ available = []
208
+ for name in modality_names:
209
+ for ext in [".png", ".jpg", ".jpeg"]:
210
+ path = Path(root) / f"{name}{ext}"
211
+ if path.exists():
212
+ available.append((name, str(path)))
213
+ break
214
+
215
+ # --- 构建模态说明 ---
216
+ readable_map = {
217
+ "image": "RGB image",
218
+ "annotation_lineart": "line drawing",
219
+ "annotation_edge": "edge map",
220
+ "annotation_depth": "depth map",
221
+ "annotation_normal": "normal map",
222
+ "annotation_albedo": "albedo map",
223
+ "annotation_seg_12colors": "segmentation map",
224
+ "annotation_openpose": "human pose map",
225
+ }
226
+
227
+ present_modalities = [readable_map[n] for n, _ in available]
228
+
229
+ # --- 构造文本指令 ---
230
+
231
+ # --- 构建消息内容:在每个图像前加模态标识 ---
232
+
233
+
234
+ content = []
235
+
236
+ text_prompt = ("you are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}.\n"
237
+ f"Each modality provides a different aspect of visual information about the same scene.\n\n"
238
+ f"### Modality Information:\n"
239
+ f"- **RGB image:** shows colors, textures, lighting, and overall appearance.\n"
240
+ f"- **Line drawing:** reveals outlines, object contours, and structural details.\n"
241
+ f"- **Edge map:** highlights strong edges and object boundaries.\n"
242
+ f"- **Depth map:** encodes per-object spatial distance and perspective. "
243
+ f"For each main object, estimate its approximate physical distance from the camera or ground reference "
244
+ f"in **meters**. "
245
+ f"If multiple objects are visible, provide numeric distances rather than qualitative terms like "
246
+ f"'closer' or 'farther'.\n"
247
+ f"- **Normal map:** provides surface orientation and facing direction.\n"
248
+ f"- **Albedo map:** shows true surface color unaffected by lighting or shadows.\n"
249
+ f"- **Segmentation map:** divides the image into semantic regions and object categories.\n"
250
+ f"- **Human pose map:** depicts human keypoints, poses, and orientations if present.\n\n"
251
+ f"### Your Task:\n"
252
+ f"Refine the coarse caption into a detailed, modality-wise visual description. "
253
+ f"For each available modality listed above, generate one corresponding description paragraph "
254
+ f"based only on what that modality shows.\n\n"
255
+ f"### Rules:\n"
256
+ f"1. Follow the order and modality names given in 'Modality Information'.\n"
257
+ f"2. Start each paragraph with the modality name (e.g., 'RGB image:').\n"
258
+ f"3. Describe only what is visible in that modality—do NOT merge or summarize multiple modalities.\n"
259
+ f"4. Use **numeric distance estimates in meters** for the depth map whenever possible.\n"
260
+ f"5. Use clear and factual language (no imagination or hallucination).\n"
261
+ #f"6. You may use the following feedback for improvement: '{feedback}'\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"Now, according to the 'Modality Information' above, write one detailed description for each available modality below."
264
+ )
265
+
266
+ for name, path in available:
267
+ readable = readable_map.get(name, "visual input")
268
+ content.append({
269
+ "type": "text",
270
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
271
+ })
272
+ content.append({"type": "image", "image": path})
273
+
274
+ # 最后附上总任务说明
275
+ content.append({"type": "text", "text": text_prompt})
276
+
277
+ messages = [{"role": "user", "content": content}]
278
+ return messages
279
+
280
+
281
+ def get_modality_description(name: str) -> str:
282
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
283
+ desc_map = {
284
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
285
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
286
+ "annotation_edge": "strong boundaries and contrast edges between objects",
287
+ "annotation_depth": "distance and perspective information for spatial understanding",
288
+ "annotation_normal": "surface orientation and geometric curvature cues",
289
+ "annotation_albedo": "pure surface color without lighting or shading effects",
290
+ "annotation_seg_12colors": "semantic regions and object categories",
291
+ "annotation_openpose": "human body keypoints, joints, and orientation",
292
+ }
293
+ return desc_map.get(name, "complementary visual evidence")
294
+
295
+
296
+
297
+
298
+ # ------------------------------
299
+ # Argument Parser
300
+ # ------------------------------
301
+ def get_parser():
302
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
303
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
304
+ help="Path to model checkpoint.")
305
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
306
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
307
+ help="Path to model checkpoint.")
308
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
309
+ help="Path to model checkpoint.")
310
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
311
+ help="Prompt text for generation.")
312
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
313
+ help="Optional negative prompt.")
314
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
317
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
318
+ help="Optional negative prompt.")
319
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
320
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
321
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
322
+ parser.add_argument("--seed", type=int, default=41)
323
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
324
+ return parser
325
+
326
+
327
+ # ------------------------------
328
+ # Main Inference Function
329
+ # ------------------------------
330
+
331
+ @torch.inference_mode()
332
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
333
+ messages = [
334
+ {
335
+ "role": "user",
336
+ "content": [
337
+ {
338
+ "type": "image",
339
+ "image": image_path,
340
+ },
341
+ {"type": "text", "text": f"Describe this image."},
342
+ ],
343
+ }
344
+ ]
345
+
346
+ inputs = processor.apply_chat_template(
347
+ messages,
348
+ tokenize=True,
349
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
350
+ )
351
+ inputs = inputs.to(model.device)
352
+
353
+ # Inference: Generation of the output
354
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
355
+ generated_ids_trimmed = [
356
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
357
+ ]
358
+ output_text = processor.batch_decode(
359
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
360
+ )
361
+ print(output_text)
362
+
363
+ os.makedirs(args.output_dir, exist_ok=True)
364
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
365
+ save_dir.mkdir(parents=True, exist_ok=True)
366
+ caption_path = Path(save_dir) / f"caption.txt"
367
+ with open(caption_path, "w", encoding="utf-8") as f:
368
+ f.write(output_text[0].strip())
369
+
370
+ return output_text[0]
371
+
372
+
373
+ @torch.inference_mode()
374
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
375
+
376
+ # --- 构造 Qwen 输入 ---
377
+ eval_prompt = f"""
378
+ You are an image-text alignment evaluator.
379
+ You are given one RGB image and a description that may include references
380
+ to multiple visual modalities (e.g., depth map, normal map, segmentation map, etc.).
381
+ These terms are just analytical perspectives of the same scene — they should not reduce
382
+ the consistency score. Focus only on whether the described visual content matches what
383
+ is visible in the RGB image.
384
+ Your task:
385
+ 1. Judge how accurately the text describes what is visually present in the image.
386
+ 2. Ignore mentions of modality names (such as 'depth map' or 'normal map').
387
+ 3. Provide a consistency score between 0.0 (completely mismatched) and 1.0 (perfect match).
388
+ 4. Provide one short feedback sentence suggesting how to make the description better aligned.
389
+ Return JSON strictly in this format:
390
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
391
+ Description: "{caption}"
392
+ <image>
393
+ """
394
+
395
+ messages = [
396
+ {
397
+ "role": "user",
398
+ "content": [
399
+ {"type": "image", "image": image_path},
400
+ {"type": "text", "text": eval_prompt},
401
+ ],
402
+ }
403
+ ]
404
+
405
+ # --- 推理 ---
406
+ inputs = processor.apply_chat_template(
407
+ messages,
408
+ tokenize=True,
409
+ add_generation_prompt=True,
410
+ return_dict=True,
411
+ return_tensors="pt"
412
+ ).to(model.device)
413
+
414
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
415
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
416
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
417
+
418
+ # --- 解析输出 ---
419
+ try:
420
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
421
+ score = float(data.get("Consistency", 0))
422
+ feedback = data.get("Feedback", "")
423
+ except Exception:
424
+ score, feedback = 0.0, text.strip()
425
+
426
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
427
+ return score, feedback
428
+
429
+
430
+ @torch.inference_mode()
431
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
432
+ messages = build_multimodal_message(root, prompt, feedback)
433
+ inputs = processor.apply_chat_template(
434
+ messages,
435
+ tokenize=True,
436
+ add_generation_prompt=True,
437
+ return_dict=True,
438
+ return_tensors="pt"
439
+ )
440
+ inputs = inputs.to(model.device)
441
+
442
+ # Inference: Generation of the output
443
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
444
+ generated_ids_trimmed = [
445
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
446
+ ]
447
+ output_text = processor.batch_decode(
448
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
449
+ )
450
+ print(output_text)
451
+
452
+ os.makedirs(args.output_dir, exist_ok=True)
453
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
454
+ save_dir.mkdir(parents=True, exist_ok=True)
455
+ caption_path = Path(save_dir) / f"caption.txt"
456
+ with open(caption_path, "w", encoding="utf-8") as f:
457
+ f.write(output_text[0].strip())
458
+ return output_text[0]
459
+
460
+ @torch.inference_mode()
461
+ def vqa(root, model, processor, prompt, question, vqa_id, max_length=300):
462
+ messages = build_vqa_message(root, prompt, question)
463
+ print(messages)
464
+ inputs = processor.apply_chat_template(
465
+ messages,
466
+ tokenize=True,
467
+ add_generation_prompt=True,
468
+ return_dict=True,
469
+ return_tensors="pt"
470
+ )
471
+ inputs = inputs.to(model.device)
472
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
473
+ generated_ids_trimmed = [
474
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
475
+ output_text = processor.batch_decode(
476
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
477
+ )
478
+ print(output_text)
479
+ os.makedirs(args.output_dir, exist_ok=True)
480
+ save_dir = Path(args.output_dir) / vqa_id / 'vqa_answer'
481
+ save_dir.mkdir(parents=True, exist_ok=True)
482
+ caption_path = Path(save_dir) / f"caption.txt"
483
+ with open(caption_path, "w", encoding="utf-8") as f:
484
+ f.write(output_text[0].strip())
485
+ return output_text[0]
486
+
487
+ @torch.inference_mode()
488
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
489
+ # print(f"🚀 Generating with prompt: {prompt}")
490
+ outputs = pipe(
491
+ images=images,
492
+ role=role,
493
+ prompt=prompt,
494
+ negative_prompt=args.negative_prompt,
495
+ height=height,
496
+ width=width,
497
+ num_inference_steps=args.steps,
498
+ guidance_scale=args.guidance_scale,
499
+ num_images_per_prompt=1,
500
+ generator=generator,
501
+ task='t2i'
502
+ )
503
+
504
+ # Apply post-processing for each modality
505
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
506
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
507
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
508
+
509
+ # --------------------------
510
+ # Save results
511
+ # --------------------------
512
+ os.makedirs(args.output_dir, exist_ok=True)
513
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
514
+ save_dir.mkdir(parents=True, exist_ok=True)
515
+ for idx, img in enumerate(results):
516
+ name = modality_names[idx]
517
+ save_path = save_dir / f"{name}.png"
518
+ img.save(save_path)
519
+ print(f"💾 Saved {name} → {save_path}")
520
+
521
+
522
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
523
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
524
+ print(f"\n✅ All results saved in: {save_dir}\n")
525
+ return save_dir
526
+
527
+ if __name__ == "__main__":
528
+ args = get_parser().parse_args()
529
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
530
+ print(f"✅ Using device: {device}")
531
+
532
+ processor = AutoProcessor.from_pretrained(
533
+ args.model_name_or_path,
534
+ )
535
+
536
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
537
+ args.text_model_path,
538
+ attn_implementation="flash_attention_2",
539
+ dtype=(torch.bfloat16),
540
+ ).to(device)
541
+
542
+ pipe = JodiPipeline(args.config)
543
+ pipe.from_pretrained(args.model_path)
544
+
545
+ modality_names = [
546
+ "image",
547
+ "annotation_lineart",
548
+ "annotation_edge",
549
+ "annotation_depth",
550
+ "annotation_normal",
551
+ "annotation_albedo",
552
+ "annotation_seg_12colors",
553
+ "annotation_openpose",
554
+ ]
555
+
556
+ # Build post-processors
557
+ post_processors: list[Any] = [ImagePostProcessor()]
558
+ for condition in pipe.config.conditions: # type: ignore
559
+ if condition == "lineart":
560
+ post_processors.append(LineartPostProcessor())
561
+ elif condition == "edge":
562
+ post_processors.append(EdgePostProcessor())
563
+ elif condition == "depth":
564
+ post_processors.append(DepthPostProcessor())
565
+ elif condition == "normal":
566
+ post_processors.append(NormalPostProcessor())
567
+ elif condition == "albedo":
568
+ post_processors.append(AlbedoPostProcessor())
569
+ elif condition == "segmentation":
570
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
571
+ elif condition == "openpose":
572
+ post_processors.append(OpenposePostProcessor())
573
+ else:
574
+ print(f"⚠️ Warning: Unknown condition: {condition}")
575
+ post_processors.append(ImagePostProcessor())
576
+
577
+ torch.manual_seed(args.seed)
578
+ generator = torch.Generator(device=device).manual_seed(args.seed)
579
+
580
+ with open(args.json, "r", encoding="utf-8") as f:
581
+ annotations = json.load(f)
582
+
583
+ for sample in annotations[1:255]:
584
+ image_path = os.path.join(args.data_path, sample["image"])
585
+ image_id = sample["image"].split('.')[0]
586
+ image = Image.open(image_path)
587
+ question = sample["question"]
588
+
589
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
590
+
591
+ role = [1] + [0] * pipe.num_conditions
592
+ print(role)
593
+
594
+ best_dir, best_caption, best_score = '', '', 0.0
595
+ max_length = 1024
596
+
597
+ # input_img = Image.open(image_path).convert("RGB")
598
+ width, height = image.size
599
+ print(f'ori width:{width}', f'ori height:{height}')
600
+
601
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
602
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
603
+
604
+ if score >= best_score:
605
+ best_caption, best_score = prompt, score
606
+ best_dir = image_path
607
+
608
+ for step in range(1, args.iters):
609
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
610
+ image_id)
611
+ max_length += 100
612
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
613
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
614
+
615
+ #if score >= best_score:
616
+ best_caption, best_score = prompt, score
617
+ best_dir = save_dir
618
+
619
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, max_length)
620
+ print(f'result:{result}')
test_realworldqa_vqa1.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[:153]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ generator = torch.Generator(device=device).manual_seed(args.seed)
657
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
658
+ image_id)
659
+ max_length += 100
660
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
661
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
662
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
663
+
664
+ if score >= best_score:
665
+ best_caption, best_score = prompt, score
666
+ best_dir = save_dir
667
+
668
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
669
+ print(f'result:{result}')
test_realworldqa_vqa2.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
+ os.environ["GRADIO_TEMP_DIR"] = "./tmp"
12
+ from jodi_pipeline import JodiPipeline
13
+ from model.postprocess import (
14
+ ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor,
15
+ NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor,
16
+ )
17
+ from transformers import (
18
+ Qwen2VLForConditionalGeneration,
19
+ Qwen2_5_VLForConditionalGeneration,
20
+ Qwen3VLForConditionalGeneration,
21
+ Qwen3VLMoeForConditionalGeneration
22
+ )
23
+ from transformers import AutoProcessor, Trainer
24
+ from pathlib import Path
25
+ import itertools
26
+ import ast
27
+ import re
28
+ from PIL import Image
29
+ import json
30
+ def clean_question(q: str) -> str:
31
+ if not isinstance(q, str):
32
+ q = str(q)
33
+ # 删除 <image 1>、<image1>、<image 2> 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE)
34
+ # 再清理多余空白
35
+ q = re.sub(r"\s+", " ", q).strip()
36
+ return q
37
+ def dump_image(image, save_root):
38
+ os.makedirs(save_root, exist_ok=True)
39
+ save_path = os.path.join(save_root, "input.jpg")
40
+ image.convert("RGB").save(save_path, format="JPEG", quality=95)
41
+ return save_path
42
+
43
+ def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"):
44
+ """ 将多个图像拼接成一张大图并保存。
45
+ Args: image_paths: List[str] 图像路径列表
46
+ save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行)
47
+ image_format: 保存格式
48
+ """
49
+ from PIL import Image
50
+ import io
51
+ # 读取图像
52
+ images = [Image.open(p).convert("RGB") for p in image_paths]
53
+
54
+ if images_per_row is None:
55
+ images_per_row = len(images)
56
+
57
+ # 调整尺寸(可选)
58
+ target_size = min(1024, images[0].size[0])
59
+ images = [img.resize((target_size, target_size)) for img in images]
60
+
61
+ # 拼接
62
+ widths, heights = zip(*(img.size for img in images))
63
+ max_width = max(widths)
64
+ rows = (len(images) + images_per_row - 1) // images_per_row
65
+ total_height = sum(heights[:images_per_row]) * rows
66
+
67
+ new_im = Image.new("RGB", (max_width * images_per_row, total_height))
68
+ y_offset = 0
69
+ for i in range(0, len(images), images_per_row):
70
+ row_imgs = images[i:i + images_per_row]
71
+ x_offset = 0
72
+ for img in row_imgs:
73
+ new_im.paste(img, (x_offset, y_offset))
74
+ x_offset += max_width
75
+ y_offset += heights[0]
76
+
77
+ os.makedirs(os.path.dirname(save_path), exist_ok=True)
78
+ new_im.save(save_path, format=image_format.upper())
79
+ print(f"🧩 Saved merged image → {save_path}")
80
+ return save_path
81
+
82
+
83
+ def build_vqa_message(root, prompt, question):
84
+ """
85
+ Build Qwen3-VL message for multimodal or single-image VQA.
86
+ Now explicitly tags each modality image before feeding into Qwen3-VL,
87
+ so that the model can distinguish RGB, edge, depth, normal, etc.
88
+ """
89
+
90
+ root_path = Path(root)
91
+
92
+ # ---------- 单图像情况 ----------
93
+ if root_path.is_file() and root_path.suffix.lower() in [".jpg", ".jpeg", ".png", ".webp"]:
94
+ image_path = str(root)
95
+ messages = [
96
+ {
97
+ "role": "user",
98
+ "content": [
99
+ {"type": "image", "image": image_path},
100
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
101
+ ],
102
+ }
103
+ ]
104
+ return messages
105
+
106
+ # ---------- 多模态文件夹情况 ----------
107
+ modality_names = [
108
+ "image",
109
+ "annotation_lineart",
110
+ "annotation_edge",
111
+ "annotation_depth",
112
+ "annotation_normal",
113
+ "annotation_albedo",
114
+ "annotation_seg_12colors",
115
+ #"annotation_openpose",
116
+ ]
117
+
118
+ # 检查存在的模态文件
119
+ available = []
120
+ for name in modality_names:
121
+ for ext in [".png", ".jpg", ".jpeg"]:
122
+ path = Path(root) / f"{name}{ext}"
123
+ if path.exists():
124
+ available.append((name, str(path)))
125
+ break
126
+
127
+
128
+
129
+ # 可读名称映射
130
+ readable_map = {
131
+ "image": "RGB image",
132
+ "annotation_lineart": "line drawing",
133
+ "annotation_edge": "edge map",
134
+ "annotation_depth": "depth map",
135
+ "annotation_normal": "normal map",
136
+ "annotation_albedo": "albedo map",
137
+ "annotation_seg_12colors": "segmentation map",
138
+ #"annotation_openpose": "human pose map",
139
+ }
140
+
141
+ present_modalities = [readable_map[n] for n, _ in available]
142
+
143
+ # ---------- 指令文本 ----------
144
+ text_prompt = (
145
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
146
+ f"The **RGB image** is the primary and most reliable modality that truly represents the scene. "
147
+ #f"Other modalities (e.g., depth, normal, segmentation) may contain small errors or artifacts, "
148
+ #f"so use them only as optional references for additional context. "
149
+ #f"Each modality provides complementary information about the same visual content:\n"
150
+ #f"- The line drawing highlights object outlines, shapes, and fine structures.\n"
151
+ #f"- The edge map emphasizes boundaries and contours.\n"
152
+ #f"- The depth map reveals spatial distances, perspective, and 3D relationships.\n"
153
+ #f"- The normal map shows surface orientation and geometric curvature.\n"
154
+ #f"- The albedo map presents true surface color without illumination or shadows.\n"
155
+ #f"- The segmentation map divides the scene into semantic regions and object categories.\n"
156
+ #f"- The human pose map indicates body orientation, structure, and articulation.\n\n"
157
+ #f"Together, these modalities offer a unified, rich understanding of the scene.\n"
158
+ #f"Scene description: \"{prompt}\"\n\n"
159
+ f"Please answer the following question using visual reasoning primarily grounded in the RGB image, "
160
+ #f"while cross-checking with other modalities (e.g., edge or depth) when relevant.\n"
161
+ #f"If multiple correct answers are possible, choose the most precise and visually supported one.\n\n"
162
+ f"Question: \"{question}\"\n"
163
+ )
164
+
165
+ # ---------- 构建内容序列(模态锚定) ----------
166
+ content = []
167
+ print(f'available:{available}')
168
+ for name, path in available:
169
+ readable = readable_map.get(name, "visual input")
170
+ # 在每张图像前显式标注模态类型
171
+ content.append({"type": "text", "text": f"This is the {readable}."})
172
+ content.append({"type": "image", "image": path})
173
+
174
+ # 最后加入主指令
175
+ content.append({"type": "text", "text": text_prompt})
176
+
177
+ messages = [{"role": "user", "content": content}]
178
+ return messages
179
+
180
+
181
+
182
+
183
+ def build_multimodal_message(root, coarse_caption="a generic scene", feedback=""):
184
+ """
185
+ Build Qwen3-VL message for multi-modal caption refinement.
186
+ Explicitly binds each image to its modality name (RGB, edge, depth, etc.)
187
+ so Qwen3-VL can reason over them correctly and refine the caption faithfully.
188
+ """
189
+
190
+ modality_names = [
191
+ "image",
192
+ "annotation_lineart",
193
+ "annotation_edge",
194
+ "annotation_depth",
195
+ "annotation_normal",
196
+ "annotation_albedo",
197
+ "annotation_seg_12colors",
198
+ #"annotation_openpose",
199
+ ]
200
+
201
+ # --- 检查存在的模态 ---
202
+ available = []
203
+ for name in modality_names:
204
+ for ext in [".png", ".jpg", ".jpeg"]:
205
+ path = Path(root) / f"{name}{ext}"
206
+ if path.exists():
207
+ available.append((name, str(path)))
208
+ break
209
+
210
+ # --- 构建模态说明 ---
211
+ readable_map = {
212
+ "image": "RGB image",
213
+ "annotation_lineart": "line drawing",
214
+ "annotation_edge": "edge map",
215
+ "annotation_depth": "depth map",
216
+ "annotation_normal": "normal map",
217
+ "annotation_albedo": "albedo map",
218
+ "annotation_seg_12colors": "segmentation map",
219
+ #"annotation_openpose": "human pose map",
220
+ }
221
+
222
+ present_modalities = [readable_map[n] for n, _ in available]
223
+
224
+ # --- 构造文本指令 ---
225
+ text_prompt = (
226
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
227
+ f"The **RGB image** is the primary modality that provides the most reliable view of the scene. "
228
+ #f"Other modalities (depth, normal, edge, segmentation, etc.) serve as structural or semantic references.\n\n"
229
+ #f"Each modality provides distinct complementary information:\n"
230
+ #f"- The line drawing highlights structure and contours.\n"
231
+ #f"- The edge map emphasizes object boundaries.\n"
232
+ #f"- The depth map shows spatial distance and perspective.\n"
233
+ #f"- The normal map captures surface orientation and geometry.\n"
234
+ #f"- The albedo map shows intrinsic surface color.\n"
235
+ #f"- The segmentation map reveals semantic regions.\n"
236
+ #f"- The human pose map indicates body structure and articulation.\n\n"
237
+ f"### Your Task:\n"
238
+ f"Refine the coarse caption into a more accurate, realistic, and visually grounded description "
239
+ f"of the scene, integrating information from all available modalities.\n\n"
240
+ f"### Rules:\n"
241
+ f"1. Describe only what is visible in the images — do NOT hallucinate.\n"
242
+ #f"2. Use the RGB image as your main reference, and use other modalities to verify geometric or structural details.\n"
243
+ f"3. Incorporate the following feedback into your refinement: '{feedback}'\n"
244
+ f"4. Focus on correcting inaccuracies or missing details from the coarse caption.\n\n"
245
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
246
+ f"Now refine the caption according to the multimodal evidence below."
247
+ )
248
+
249
+ text_prompt0 = (
250
+ f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. "
251
+ f"The **RGB image** provides the most accurate and realistic appearance of the scene, "
252
+ f"while other modalities (e.g., depth, normal, edge, segmentation) offer complementary structural and semantic details.\n\n"
253
+ f"### Your Task:\n"
254
+ f"Generate a refined, detailed, and visually grounded description of the scene shown in the images. "
255
+ f"Use the RGB image as the main reference, and consult other modalities to verify geometry, boundaries, and spatial relations.\n\n"
256
+ f"### Guidelines:\n"
257
+ f"1. Describe what is *visibly present* — objects, materials, lighting, spatial layout, and relationships.\n"
258
+ f"2. Integrate helpful information from auxiliary modalities (e.g., depth for distance, edges for structure).\n"
259
+ f"3. Do NOT invent or assume anything not visually supported.\n"
260
+ f"4. Avoid including any additional commentary or evaluations.\n"
261
+ f"5. You may rephrase and expand upon the coarse caption for clarity and accuracy.\n\n"
262
+ f"### Coarse Caption:\n'{coarse_caption}'\n\n"
263
+ f"### Feedback to Incorporate:\n'{feedback}'\n\n"
264
+ f"Now produce the final refined caption describing the scene based on the multimodal evidence below."
265
+ )
266
+
267
+
268
+ # --- 构建消息内容:在每个图像前加模态标识 ---
269
+ content = []
270
+ for name, path in available:
271
+ readable = readable_map.get(name, "visual input")
272
+ content.append({
273
+ "type": "text",
274
+ "text": f"This is the {readable}, which provides {get_modality_description(name)}."
275
+ })
276
+ content.append({"type": "image", "image": path})
277
+
278
+ # 最后附上总任务说明
279
+ content.append({"type": "text", "text": text_prompt})
280
+
281
+ messages = [{"role": "user", "content": content}]
282
+ return messages
283
+
284
+
285
+ def get_modality_description(name: str) -> str:
286
+ """为每个模态生成一句说明,用于提示模型理解模态功能"""
287
+ desc_map = {
288
+ "image": "the main visual appearance of the scene, including color, texture, and lighting",
289
+ "annotation_lineart": "structural outlines, object contours, and fine geometry",
290
+ "annotation_edge": "strong boundaries and contrast edges between objects",
291
+ "annotation_depth": "distance and perspective information for spatial understanding",
292
+ "annotation_normal": "surface orientation and geometric curvature cues",
293
+ "annotation_albedo": "pure surface color without lighting or shading effects",
294
+ "annotation_seg_12colors": "semantic regions and object categories",
295
+ "annotation_openpose": "human body keypoints, joints, and orientation",
296
+ }
297
+ return desc_map.get(name, "complementary visual evidence")
298
+
299
+
300
+
301
+
302
+ # ------------------------------
303
+ # Argument Parser
304
+ # ------------------------------
305
+ def get_parser():
306
+ parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.")
307
+ parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
308
+ help="Path to model checkpoint.")
309
+ parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.")
310
+ parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth',
311
+ help="Path to model checkpoint.")
312
+ parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct',
313
+ help="Path to model checkpoint.")
314
+ parser.add_argument("--data_path", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/images",
315
+ help="Prompt text for generation.")
316
+ parser.add_argument("--json", type=str, default="/home/efs/mjw/mjw/dataset/dataset/realworldqa/annotations.json",
317
+ help="Optional negative prompt.")
318
+ parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp",
319
+ help="Prompt text for generation.")
320
+ parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.")
321
+ parser.add_argument("--question", type=str, default="how many cars in this image?",
322
+ help="Optional negative prompt.")
323
+ parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.")
324
+ parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.")
325
+ parser.add_argument("--guidance_scale", type=float, default=4.5)
326
+ parser.add_argument("--seed", type=int, default=42)
327
+ parser.add_argument("--output_dir", type=str, default="./vqa_realworld_outputs", help="Directory to save results.")
328
+ return parser
329
+
330
+
331
+ # ------------------------------
332
+ # Main Inference Function
333
+ # ------------------------------
334
+
335
+
336
+ @torch.inference_mode()
337
+ def vqa_i2t(model, processor, image_path, question, vqa_id, max_length=300):
338
+ messages = [
339
+ {
340
+ "role": "user",
341
+ "content": [
342
+ {
343
+ "type": "image",
344
+ "image": image_path,
345
+ },
346
+ {"type": "text", "text": f"Answer the follow question:{question} based on the <image>."},
347
+ ],
348
+ }
349
+ ]
350
+
351
+ print(messages)
352
+
353
+ inputs = processor.apply_chat_template(
354
+ messages,
355
+ tokenize=True,
356
+ add_generation_prompt=True,
357
+ return_dict=True,
358
+ return_tensors="pt"
359
+ )
360
+ inputs = inputs.to(model.device)
361
+
362
+ # Inference: Generation of the output
363
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
364
+ generated_ids_trimmed = [
365
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
366
+ ]
367
+ output_text = processor.batch_decode(
368
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
369
+ )
370
+ print(output_text)
371
+
372
+ os.makedirs(args.output_dir, exist_ok=True)
373
+ save_dir = Path(args.output_dir) / str(vqa_id)
374
+ save_dir.mkdir(parents=True, exist_ok=True)
375
+ caption_path = Path(save_dir) / f"caption.txt"
376
+ with open(caption_path, "w", encoding="utf-8") as f:
377
+ f.write(output_text[0].strip())
378
+
379
+ return output_text[0]
380
+
381
+
382
+ @torch.inference_mode()
383
+ def init_i2t(model, processor, image_path, iter_num, vqa_id, max_length=300):
384
+ messages = [
385
+ {
386
+ "role": "user",
387
+ "content": [
388
+ {
389
+ "type": "image",
390
+ "image": image_path,
391
+ },
392
+ {"type": "text", "text": f"Describe this image."},
393
+ ],
394
+ }
395
+ ]
396
+
397
+ inputs = processor.apply_chat_template(
398
+ messages,
399
+ tokenize=True,
400
+ add_generation_prompt=True, return_dict=True, return_tensors="pt"
401
+ )
402
+ inputs = inputs.to(model.device)
403
+
404
+ # Inference: Generation of the output
405
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
406
+ generated_ids_trimmed = [
407
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
408
+ ]
409
+ output_text = processor.batch_decode(
410
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
411
+ )
412
+ print(output_text)
413
+
414
+ os.makedirs(args.output_dir, exist_ok=True)
415
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
416
+ save_dir.mkdir(parents=True, exist_ok=True)
417
+ caption_path = Path(save_dir) / f"caption.txt"
418
+ with open(caption_path, "w", encoding="utf-8") as f:
419
+ f.write(output_text[0].strip())
420
+
421
+ return output_text[0]
422
+
423
+
424
+ @torch.inference_mode()
425
+ def evaluate_consistency(image_path, model, processor, caption, max_length=256):
426
+
427
+ # --- 构造 Qwen 输入 ---
428
+ eval_prompt = f"""
429
+ You are an image-text alignment evaluator.
430
+ Given one RGB image and a description, score how well the text matches
431
+ the visual evidence in the image. Then provide one short feedback
432
+ sentence suggesting how to make the description better aligned.
433
+
434
+ Return JSON strictly:
435
+ {{"Consistency": <float 0-1>, "Feedback": "<sentence>"}}
436
+
437
+ Description: "{caption}"
438
+ <image>
439
+ """
440
+
441
+ messages = [
442
+ {
443
+ "role": "user",
444
+ "content": [
445
+ {"type": "image", "image": image_path},
446
+ {"type": "text", "text": eval_prompt},
447
+ ],
448
+ }
449
+ ]
450
+
451
+ # --- 推理 ---
452
+ inputs = processor.apply_chat_template(
453
+ messages,
454
+ tokenize=True,
455
+ add_generation_prompt=True,
456
+ return_dict=True,
457
+ return_tensors="pt"
458
+ ).to(model.device)
459
+
460
+ out_ids = model.generate(**inputs, max_new_tokens=max_length)
461
+ out_trim = [o[len(i):] for i, o in zip(inputs.input_ids, out_ids)]
462
+ text = processor.batch_decode(out_trim, skip_special_tokens=True)[0]
463
+
464
+ # --- 解析输出 ---
465
+ try:
466
+ data = json.loads(re.search(r"\{.*\}", text, re.S).group(0))
467
+ score = float(data.get("Consistency", 0))
468
+ feedback = data.get("Feedback", "")
469
+ except Exception:
470
+ score, feedback = 0.0, text.strip()
471
+
472
+ print(f"🧮 [Image Consistency] {score:.3f} | Feedback: {feedback}")
473
+ return score, feedback
474
+
475
+
476
+ @torch.inference_mode()
477
+ def text_refine(root, model, processor, prompt, feedback, iter_num, vqa_id, max_length=300):
478
+ messages = build_multimodal_message(root, prompt, feedback)
479
+ inputs = processor.apply_chat_template(
480
+ messages,
481
+ tokenize=True,
482
+ add_generation_prompt=True,
483
+ return_dict=True,
484
+ return_tensors="pt"
485
+ )
486
+ inputs = inputs.to(model.device)
487
+
488
+ # Inference: Generation of the output
489
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
490
+ generated_ids_trimmed = [
491
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
492
+ ]
493
+ output_text = processor.batch_decode(
494
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
495
+ )
496
+ print(output_text)
497
+
498
+ os.makedirs(args.output_dir, exist_ok=True)
499
+ save_dir = Path(args.output_dir) / vqa_id / f"iteration_{iter_num}"
500
+ save_dir.mkdir(parents=True, exist_ok=True)
501
+ caption_path = Path(save_dir) / f"caption.txt"
502
+ with open(caption_path, "w", encoding="utf-8") as f:
503
+ f.write(output_text[0].strip())
504
+ return output_text[0]
505
+
506
+ @torch.inference_mode()
507
+ def vqa(root, model, processor, prompt, question, vqa_id, step, max_length=300):
508
+ messages = build_vqa_message(root, prompt, question)
509
+ print(messages)
510
+ inputs = processor.apply_chat_template(
511
+ messages,
512
+ tokenize=True,
513
+ add_generation_prompt=True,
514
+ return_dict=True,
515
+ return_tensors="pt"
516
+ )
517
+ inputs = inputs.to(model.device)
518
+ generated_ids = model.generate(**inputs, max_new_tokens=max_length)
519
+ generated_ids_trimmed = [
520
+ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
521
+ output_text = processor.batch_decode(
522
+ generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
523
+ )
524
+ print(output_text)
525
+ os.makedirs(args.output_dir, exist_ok=True)
526
+ save_dir = Path(args.output_dir) / vqa_id / f'iteration_{step}' /'vqa_answer'
527
+ save_dir.mkdir(parents=True, exist_ok=True)
528
+ caption_path = Path(save_dir) / f"caption.txt"
529
+ with open(caption_path, "w", encoding="utf-8") as f:
530
+ f.write(output_text[0].strip())
531
+ return output_text[0]
532
+
533
+ @torch.inference_mode()
534
+ def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, image_id):
535
+ # print(f"🚀 Generating with prompt: {prompt}")
536
+ outputs = pipe(
537
+ images=images,
538
+ role=role,
539
+ prompt=prompt,
540
+ negative_prompt=args.negative_prompt,
541
+ height=height,
542
+ width=width,
543
+ num_inference_steps=args.steps,
544
+ guidance_scale=args.guidance_scale,
545
+ num_images_per_prompt=1,
546
+ generator=generator,
547
+ task='t2i'
548
+ )
549
+
550
+ # Apply post-processing for each modality
551
+ results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)]
552
+ results = torch.stack(results, dim=1).reshape(-1, 3, height, width)
553
+ results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)]
554
+
555
+ # --------------------------
556
+ # Save results
557
+ # --------------------------
558
+ os.makedirs(args.output_dir, exist_ok=True)
559
+ save_dir = Path(args.output_dir) / image_id / f"iteration_{iter_num}"
560
+ save_dir.mkdir(parents=True, exist_ok=True)
561
+ for idx, img in enumerate(results):
562
+ name = modality_names[idx]
563
+ save_path = save_dir / f"{name}.png"
564
+ img.save(save_path)
565
+ print(f"💾 Saved {name} → {save_path}")
566
+
567
+
568
+ merged_path = save_dir / f"merged_iteration_{iter_num}.png"
569
+ concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path)
570
+ print(f"\n✅ All results saved in: {save_dir}\n")
571
+ return save_dir
572
+
573
+ if __name__ == "__main__":
574
+ args = get_parser().parse_args()
575
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
576
+ print(f"✅ Using device: {device}")
577
+
578
+ processor = AutoProcessor.from_pretrained(
579
+ args.model_name_or_path,
580
+ )
581
+
582
+ model = Qwen3VLForConditionalGeneration.from_pretrained(
583
+ args.text_model_path,
584
+ attn_implementation="flash_attention_2",
585
+ dtype=(torch.bfloat16),
586
+ ).to(device)
587
+
588
+ pipe = JodiPipeline(args.config)
589
+ pipe.from_pretrained(args.model_path)
590
+
591
+ modality_names = [
592
+ "image",
593
+ "annotation_lineart",
594
+ "annotation_edge",
595
+ "annotation_depth",
596
+ "annotation_normal",
597
+ "annotation_albedo",
598
+ "annotation_seg_12colors",
599
+ "annotation_openpose",
600
+ ]
601
+
602
+ # Build post-processors
603
+ post_processors: list[Any] = [ImagePostProcessor()]
604
+ for condition in pipe.config.conditions: # type: ignore
605
+ if condition == "lineart":
606
+ post_processors.append(LineartPostProcessor())
607
+ elif condition == "edge":
608
+ post_processors.append(EdgePostProcessor())
609
+ elif condition == "depth":
610
+ post_processors.append(DepthPostProcessor())
611
+ elif condition == "normal":
612
+ post_processors.append(NormalPostProcessor())
613
+ elif condition == "albedo":
614
+ post_processors.append(AlbedoPostProcessor())
615
+ elif condition == "segmentation":
616
+ post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
617
+ elif condition == "openpose":
618
+ post_processors.append(OpenposePostProcessor())
619
+ else:
620
+ print(f"⚠️ Warning: Unknown condition: {condition}")
621
+ post_processors.append(ImagePostProcessor())
622
+
623
+ torch.manual_seed(args.seed)
624
+ generator = torch.Generator(device=device).manual_seed(args.seed)
625
+
626
+ with open(args.json, "r", encoding="utf-8") as f:
627
+ annotations = json.load(f)
628
+
629
+ for sample in annotations[153:306]:
630
+ image_path = os.path.join(args.data_path, sample["image"])
631
+ image_id = sample["image"].split('.')[0]
632
+ image = Image.open(image_path)
633
+ question = sample["question"]
634
+
635
+ control_images = [image.convert('RGB')] + [None] * pipe.num_conditions
636
+
637
+ role = [1] + [0] * pipe.num_conditions
638
+ print(role)
639
+
640
+ best_dir, best_caption, best_score = '', '', 0.0
641
+ max_length = 1024
642
+
643
+ # input_img = Image.open(image_path).convert("RGB")
644
+ width, height = image.size
645
+ print(f'ori width:{width}', f'ori height:{height}')
646
+
647
+ prompt = init_i2t(model, processor, image_path, 0, image_id, max_length)
648
+ _ = vqa_i2t(model, processor, image_path, question, 100, max_length)
649
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
650
+
651
+ if score >= best_score:
652
+ best_caption, best_score = prompt, score
653
+ best_dir = image_path
654
+
655
+ for step in range(1, args.iters):
656
+ save_dir = image_refine(prompt, control_images, role, pipe, step, modality_names, generator, height, width,
657
+ image_id)
658
+ max_length += 100
659
+ prompt = text_refine(save_dir, model, processor, prompt, feedback, step, image_id, max_length)
660
+ result = vqa(save_dir, model, processor, prompt, question, image_id, step, max_length)
661
+ score, feedback = evaluate_consistency(image_path, model, processor, prompt)
662
+
663
+ if score >= best_score:
664
+ best_caption, best_score = prompt, score
665
+ best_dir = save_dir
666
+
667
+ result = vqa(best_dir, model, processor, best_caption, question, image_id, 'best', max_length)
668
+ print(f'result:{result}')