import os import sys import argparse from pathlib import Path from PIL import Image from typing import Any import torch import torchvision.transforms as T from datasets import load_dataset sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ["GRADIO_TEMP_DIR"] = "./tmp" from jodi_pipeline import JodiPipeline from model.postprocess import ( ImagePostProcessor, LineartPostProcessor, EdgePostProcessor, DepthPostProcessor, NormalPostProcessor, AlbedoPostProcessor, SegADE20KPostProcessor, OpenposePostProcessor, ) from transformers import ( Qwen2VLForConditionalGeneration, Qwen2_5_VLForConditionalGeneration, Qwen3VLForConditionalGeneration, Qwen3VLMoeForConditionalGeneration ) from transformers import AutoProcessor, Trainer from pathlib import Path import itertools import ast import re def clean_question(q: str) -> str: if not isinstance(q, str): q = str(q) # 删除 等占位符 q = re.sub(r"<\s*image\s*\d+\s*>", "", q, flags=re.IGNORECASE) # 再清理多余空白 q = re.sub(r"\s+", " ", q).strip() return q def dump_image(image, save_root): os.makedirs(save_root, exist_ok=True) save_path = os.path.join(save_root, "input.jpg") image.convert("RGB").save(save_path, format="JPEG", quality=95) return save_path def concatenate_images(image_paths, save_path, images_per_row=None, image_format="png"): """ 将多个图像拼接成一张大图并保存。 Args: image_paths: List[str] 图像路径列表 save_path: 保存路径(包括文件名) images_per_row: 每行图像数量(默认为全部在一行) image_format: 保存格式 """ from PIL import Image import io # 读取图像 images = [Image.open(p).convert("RGB") for p in image_paths] if images_per_row is None: images_per_row = len(images) # 调整尺寸(可选) target_size = min(1024, images[0].size[0]) images = [img.resize((target_size, target_size)) for img in images] # 拼接 widths, heights = zip(*(img.size for img in images)) max_width = max(widths) rows = (len(images) + images_per_row - 1) // images_per_row total_height = sum(heights[:images_per_row]) * rows new_im = Image.new("RGB", (max_width * images_per_row, total_height)) y_offset = 0 for i in range(0, len(images), images_per_row): row_imgs = images[i:i+images_per_row] x_offset = 0 for img in row_imgs: new_im.paste(img, (x_offset, y_offset)) x_offset += max_width y_offset += heights[0] os.makedirs(os.path.dirname(save_path), exist_ok=True) new_im.save(save_path, format=image_format.upper()) print(f"🧩 Saved merged image → {save_path}") return save_path def build_vqa_message(root, prompt, question, options, subfield): """ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root. """ modality_names = [ "image", "annotation_lineart", "annotation_edge", "annotation_depth", "annotation_normal", "annotation_albedo", "annotation_seg_12colors", "annotation_openpose", ] # --- 检查存在的模态 --- available = [] for name in modality_names: # 优先匹配 .png 或 .jpg for ext in [".png", ".jpg", ".jpeg"]: path = Path(root) / f"{name}{ext}" if path.exists(): available.append(str(path)) break # --- 构建模态说明 --- readable_map = { "image": "RGB image", "annotation_lineart": "line drawing", "annotation_edge": "edge map", "annotation_depth": "depth map", "annotation_normal": "normal map", "annotation_albedo": "albedo map", "annotation_seg_12colors": "segmentation map", "annotation_openpose": "human pose map", } options_list = ast.literal_eval(options) option_text = "\n".join([f"{chr(65+i)}. {opt}" for i, opt in enumerate(options_list)]) 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"])] # --- 构造文本指令 --- text_prompt = ( f"You are given multiple visual modalities of the same scene, including: {', '.join(present_modalities)}. " f"Each modality provides complementary information about the same visual content: " f"- The RGB image conveys color, texture, lighting, and the overall visual appearance. " f"- The line drawing highlights object outlines, shapes, and fine structures. " f"- The edge map emphasizes boundaries and contours. " f"- The depth map reveals spatial distances, perspective, and 3D relationships. " f"- The normal map shows surface orientation and geometric curvature. " f"- The albedo map presents true surface color without illumination or shadows. " f"- The segmentation map divides the scene into semantic regions and object categories. " f"- The human pose map indicates body orientation, structure, and articulation. " f"Together, these modalities offer a unified, rich understanding of the scene, covering its appearance, structure, and spatial layout. " f"Scene description: \"{prompt}\" " f"Scientific Subfield: \"{subfield}\" " f"Now, based on both the multimodal visual information and the given scene description, " f"analyze the scene carefully to answer a question. " f"Your analysis should proceed in two stages:\n\n" f"**Stage 1 — Modality-wise Observation:**\n" f"For each provided modality image, analyze what specific visual information it contributes " f"based on the above definitions. Describe what can be directly observed from each modality, " f"such as color, shape, structure, spatial depth, or object positions. " f"Then use visual reasoning grounded in the image evidence and contextual understanding from the description answer the follow multiple-choice question: " f"Question: \"{question}\" " f"Options: \"{option_text}\" " + " ".join([""] * len(available)) ) # --- 构建 Qwen3-VL 消息格式 --- messages = [ { "role": "user", "content": [{"type": "image", "image": path} for path in available] + [{"type": "text", "text": text_prompt}], } ] return messages def build_multimodal_message(root, coarse_caption="a generic scene"): """ Build Qwen3-VL message for multi-modal caption refinement. Automatically detects available modalities under root. """ modality_names = [ "image", "annotation_lineart", "annotation_edge", "annotation_depth", "annotation_normal", "annotation_albedo", "annotation_seg_12colors", "annotation_openpose", ] # --- 检查存在的模态 --- available = [] for name in modality_names: # 优先匹配 .png 或 .jpg for ext in [".png", ".jpg", ".jpeg"]: path = Path(root) / f"{name}{ext}" if path.exists(): available.append(str(path)) break # --- 构建模态说明 --- readable_map = { "image": "RGB image", "annotation_lineart": "line drawing", "annotation_edge": "edge map", "annotation_depth": "depth map", "annotation_normal": "normal map", "annotation_albedo": "albedo map", "annotation_seg_12colors": "segmentation map", "annotation_openpose": "human pose map", } 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"])] # --- 构造文本指令 --- text_prompt = ( f"You are given multiple modalities of the same scene, including: {', '.join(present_modalities)}. " f"Each modality provides distinct types of visual information that together describe the same subject: " f"- The RGB image provides color, texture, lighting, and the overall visual appearance. " f"- The line drawing reveals detailed structural outlines, shapes, and proportions. " f"- The edge map highlights object boundaries and contours. " f"- The depth map shows spatial distance, perspective, and 3D depth relationships. " f"- The normal map captures fine surface orientation, curvature, and geometric details. " f"- The albedo map shows true surface colors without lighting or shadow effects. " f"- The segmentation map provides semantic regions and object boundaries for scene composition. " f"- The human pose map shows body structure, orientation, and posture of subjects. " f"For each provided modality image, analyze it according to the above definitions and describe " f"the specific visual information it contributes in this particular case. " f"Use all available information together to produce one unified, richly detailed, and realistic description of the scene. " f"Do NOT describe each modality separately or mention modality names. " f"Focus on merging their information into a single coherent image description. " #f"the subject’s appearance, lighting, form, and spatial depth. " f"Refine the coarse caption into a more detailed and accurate image description. " f"Coarse caption: '{coarse_caption}' " + " ".join([""] * len(available)) ) # --- 构建 Qwen3-VL 消息格式 --- messages = [ { "role": "user", "content": [{"type": "image", "image": path} for path in available] + [{"type": "text", "text": text_prompt}], } ] return messages # ------------------------------ # Argument Parser # ------------------------------ def get_parser(): parser = argparse.ArgumentParser(description="Run JODI inference without Gradio UI.") parser.add_argument("--text_model_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.") parser.add_argument("--config", type=str, default="./configs/inference.yaml", help="Path to config file.") parser.add_argument("--model_path", type=str, default='hf://VIPL-GENUN/Jodi/Jodi.pth', help="Path to model checkpoint.") parser.add_argument("--model_name_or_path", type=str, default='Qwen/Qwen3-VL-8B-Instruct', help="Path to model checkpoint.") 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.") parser.add_argument("--temp_dir", type=str, default="/home/efs/mjw/mjw/dataset/dataset/tmp", help="Prompt text for generation.") parser.add_argument("--negative_prompt", type=str, default="", help="Optional negative prompt.") parser.add_argument("--question", type=str, default="how many cars in this image?", help="Optional negative prompt.") parser.add_argument("--steps", type=int, default=20, help="Number of inference steps.") parser.add_argument("--iters", type=int, default=10, help="Number of inference steps.") parser.add_argument("--guidance_scale", type=float, default=4.5) parser.add_argument("--seed", type=int, default=1234) parser.add_argument("--output_dir", type=str, default="./qwen_Design_outputs", help="Directory to save results.") return parser # ------------------------------ # Main Inference Function # ------------------------------ @torch.inference_mode() def init_i2t(model, processor, image_path, vqa_id, question, option, max_length=300): options_list = ast.literal_eval(option) option_text="\n".join([f"{chr(65+i)}.{opt}" for i, opt in enumerate(options_list)]) question = clean_question(question) text_prompt = ( f"Analyze the given image and answer the following question." f"Question: \"{question}\" \n" f"Options: \"{option_text}\" " ) messages = [ { "role": "user", "content": [ { "type": "image", "image": image_path, }, {"type": "text", "text": text_prompt}, ], } ] print(messages) inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) inputs = inputs.to(model.device) # Inference: Generation of the output generated_ids = model.generate(**inputs, max_new_tokens=max_length) generated_ids_trimmed = [ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) print(output_text) os.makedirs(args.output_dir, exist_ok=True) save_dir = Path(args.output_dir) / vqa_id save_dir.mkdir(parents=True, exist_ok=True) caption_path = Path(save_dir) / f"caption.txt" with open(caption_path, "w", encoding="utf-8") as f: f.write(output_text[0].strip()) return output_text[0] @torch.inference_mode() def text_refine(root, model, processor, prompt, iter_num, max_length=300): messages = build_multimodal_message(root, prompt) inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) inputs = inputs.to(model.device) # Inference: Generation of the output generated_ids = model.generate(**inputs, max_new_tokens=max_length) generated_ids_trimmed = [ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids) ] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) print(output_text) os.makedirs(args.output_dir, exist_ok=True) save_dir = Path(args.output_dir) / f"iteration_{iter_num}" save_dir.mkdir(parents=True, exist_ok=True) caption_path = Path(save_dir) / f"caption.txt" with open(caption_path, "w", encoding="utf-8") as f: f.write(output_text[0].strip()) return output_text[0] @torch.inference_mode() def vqa(root, model, processor, prompt, question, options, subfield, vqa_id, max_length=300): messages = build_vqa_message(root, prompt, question, options, subfield) print(messages) inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt" ) inputs = inputs.to(model.device) generated_ids = model.generate(**inputs, max_new_tokens=max_length) generated_ids_trimmed = [ out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)] output_text = processor.batch_decode( generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False ) print(output_text) os.makedirs(args.output_dir, exist_ok=True) save_dir = Path(args.output_dir) / vqa_id save_dir.mkdir(parents=True, exist_ok=True) caption_path = Path(save_dir) / f"caption.txt" with open(caption_path, "w", encoding="utf-8") as f: f.write(output_text[0].strip()) return output_text[0] @torch.inference_mode() def image_refine(prompt, images, role, pipe, iter_num, modality_names, generator, height, width, subfield): print(f"🚀 Generating with prompt: {prompt}") prompt = f'{subfield} image,' + ' ' + prompt outputs = pipe( images=images, role=role, prompt=prompt, negative_prompt=args.negative_prompt, height=height, width=width, num_inference_steps=args.steps, guidance_scale=args.guidance_scale, num_images_per_prompt=1, generator=generator, task='t2i' ) # Apply post-processing for each modality results = [post_processors[i](outputs[i]) for i in range(1 + pipe.num_conditions)] results = torch.stack(results, dim=1).reshape(-1, 3, height, width) results = [T.ToPILImage()(res).convert("RGB") for res in results.unbind(0)] # -------------------------- # Save results # -------------------------- os.makedirs(args.output_dir, exist_ok=True) save_dir = Path(args.output_dir) / f"iteration_{iter_num}" save_dir.mkdir(parents=True, exist_ok=True) for idx, img in enumerate(results): name = modality_names[idx] save_path = save_dir / f"{name}.png" img.save(save_path) print(f"💾 Saved {name} → {save_path}") merged_path = save_dir / f"merged_iteration_{iter_num}.png" concatenate_images([save_dir / f"{name}.png" for name in modality_names], merged_path) print(f"\n✅ All results saved in: {save_dir}\n") return save_dir # ------------------------------ # Entry Point # ------------------------------ if __name__ == "__main__": args = get_parser().parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print(f"✅ Using device: {device}") processor = AutoProcessor.from_pretrained( args.model_name_or_path, ) model = Qwen3VLForConditionalGeneration.from_pretrained( args.text_model_path, attn_implementation="flash_attention_2", dtype=(torch.bfloat16), ).to(device) torch.manual_seed(args.seed) generator = torch.Generator(device=device).manual_seed(args.seed) dataset = load_dataset( "parquet", data_files=args.data_path, split="train") for sample in dataset: image_keys = [f"image_{i}" for i in range(1, 8)] 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) if num_images > 1: continue image = sample["image_1"] image_path = dump_image(image, args.temp_dir) question = clean_question(sample["question"]) image_id = sample["id"] options = sample["options"] field = sample["subfield"] max_length = 1024 #input_img = Image.open(image_path).convert("RGB") width, height = image.size print(f'ori width:{width}', f'ori height:{height}') prompt = init_i2t(model, processor, image_path, image_id, question, options, max_length)