File size: 13,975 Bytes
b3035f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
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

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

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_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(["<image>"] * 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("--prompt", type=str, default="cat.", help="Prompt text for generation.")
    parser.add_argument("--negative_prompt", type=str, default="", 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("--height", type=int, default=1024)
    parser.add_argument("--width", type=int, default=1024)
    parser.add_argument("--seed", type=int, default=1234)
    parser.add_argument("--output_dir", type=str, default="./demo_t2i_outputs", help="Directory to save results.")
    return parser


# ------------------------------
# Main Inference Function
# ------------------------------
@torch.inference_mode()
def init_t2i(args, pipe, iter_num, post_processors, modality_names, generator):

    # --------------------------
    # Inference
    # --------------------------

    print(f"🚀 Generating with prompt: {args.prompt}")
    outputs = pipe(
        images=[None] * (1 + pipe.num_conditions),
        role=[0] * (1 + pipe.num_conditions),
        prompt=args.prompt,
        negative_prompt=args.negative_prompt,
        height=args.height,
        width=args.width,
        num_inference_steps=args.steps,
        guidance_scale=args.guidance_scale,
        num_images_per_prompt=1,
        generator=generator
    )

    # 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, args.height, args.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

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]

def image_refine(prompt, root, iter_num, modality_names, generator):

    control_images = []
    for name in modality_names:
        control_images.append(Image.open(os.path.join(root, name+'.png')).convert("RGB"))

    print(f"🚀 Generating with prompt: {args.prompt}")
    prompt = args.prompt + ' ' + prompt
    outputs = pipe(
        images=control_images,
        role=[0] * (1 + pipe.num_conditions),
        prompt=prompt,
        negative_prompt=args.negative_prompt,
        height=args.height,
        width=args.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, args.height, args.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)

    pipe = JodiPipeline(args.config)
    pipe.from_pretrained(args.model_path)

    modality_names = [
        "image",
        "annotation_lineart",
        "annotation_edge",
        "annotation_depth",
        "annotation_normal",
        "annotation_albedo",
        "annotation_seg_12colors",
        "annotation_openpose",
    ]

    # Build post-processors
    post_processors: list[Any] = [ImagePostProcessor()]
    for condition in pipe.config.conditions:  # type: ignore
        if condition == "lineart":
            post_processors.append(LineartPostProcessor())
        elif condition == "edge":
            post_processors.append(EdgePostProcessor())
        elif condition == "depth":
            post_processors.append(DepthPostProcessor())
        elif condition == "normal":
            post_processors.append(NormalPostProcessor())
        elif condition == "albedo":
            post_processors.append(AlbedoPostProcessor())
        elif condition == "segmentation":
            post_processors.append(SegADE20KPostProcessor(color_scheme="colors12", only_return_image=True))
        elif condition == "openpose":
            post_processors.append(OpenposePostProcessor())
        else:
            print(f"⚠️ Warning: Unknown condition: {condition}")
            post_processors.append(ImagePostProcessor())

    torch.manual_seed(args.seed)
    generator = torch.Generator(device=device).manual_seed(args.seed)
    
    init_dir = init_t2i(args, pipe, 0, post_processors, modality_names, generator)

    save_dir = init_dir
    prompt = args.prompt
    max_length  = 1024
    for step in range(1, args.iters):
        prompt = text_refine(save_dir,model, processor, prompt, step, max_length)
        max_length += 100
        save_dir = image_refine(prompt, save_dir, step, modality_names, generator)