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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
#!/usr/bin/env python3
"""InstantMesh 渲染器批处理脚本

用于批量渲染标准化后的 OBJ 文件,生成 InstantMesh 所需的多视角拼接图。
支持 Contact/HO3D 和 HOI4D 两种数据集格式,支持单 GPU / 多 GPU。

使用示例:
    # 批量渲染 Contact 数据集 (默认 mode=contact,单 GPU)
    python batch_instantmesh_render.py \
        --input_root /path/to/contact_processed/normalized \
        --output_root /path/to/contact_processed/renders_6view \
        --test --frames 3

    # 批量渲染 HOI4D 数据集 (mode=hoi4d,单 GPU)
    python batch_instantmesh_render.py \
        --input_root /path/to/hoi4d_right_hand_grasps_v1_processed \
        --output_root /path/to/hoi4d_right_hand_grasps_v1_renders \
        --mode hoi4d \
        --full \
        --batch_size 8 \
        --workers 8

    # 两张 GPU 并行(内部多进程 + 自动分片,一条命令统一调度)
    CUDA_VISIBLE_DEVICES=0,1 python batch_instantmesh_render.py \
        --input_root /path/to/hoi4d_right_hand_grasps_v1_processed \
        --output_root /path/to/hoi4d_right_hand_grasps_v1_renders \
        --mode hoi4d \
        --full \
        --batch_size 8 \
        --workers 12 \
        --num_gpus 2
"""

import os
import sys
import argparse
from pathlib import Path
from typing import List, Dict, Optional
from tqdm import tqdm

import torch
import torch.multiprocessing as mp
from torch.utils.data import Dataset, DataLoader

# 为了能从任意工作目录运行脚本,这里把当前脚本目录加入 sys.path,
# 确保可以导入同目录下的 instantmesh_renderer_v4.py
SCRIPT_DIR = Path(__file__).resolve().parent
if str(SCRIPT_DIR) not in sys.path:
    sys.path.insert(0, str(SCRIPT_DIR))

from instantmesh_renderer_v4 import InstantMeshRendererV4


def find_normalized_objs_contact(input_root: str, sequence_name: Optional[str] = None) -> List[Dict]:
    """查找 Contact/HO3D 格式的标准化 OBJ 文件

    兼容两种常见命名方式:

    1) 旧版/clean_combined 管线:
        input_root/
        ├── SiS1/
        │   ├── 0000/
        │   │   └── normalized_hand_object_combined.obj
        │   └── ...
        └── ABF11/
            └── ...

    2) 新版 normalized_*.obj 管线(当前 /contact_processed/normalized 的结构):
        input_root/
        ├── SiS1/
        │   ├── 0000/
        │   │   └── normalized_0000.obj
        │   └── ...
        └── ABF11/
            └── ...

    输出结构统一为: output_root/seq/frame.png
    """
    input_root = Path(input_root)
    obj_files: List[Dict] = []

    if sequence_name:
        sequences = [sequence_name]
    else:
        sequences = [d.name for d in input_root.iterdir() if d.is_dir()]

    for seq in sorted(sequences):
        seq_dir = input_root / seq
        if not seq_dir.exists():
            print(f"⚠️  序列目录不存在: {seq_dir}")
            continue

        for frame_dir in sorted(seq_dir.iterdir()):
            if not frame_dir.is_dir():
                continue

            # 优先使用旧版 normalized_hand_object_combined.obj
            obj_path = frame_dir / "normalized_hand_object_combined.obj"
            if not obj_path.exists():
                # 兼容新版 normalized_*.obj(例如 normalized_0656.obj)
                candidates = sorted(frame_dir.glob("normalized_*.obj"))
                if not candidates:
                    continue
                if len(candidates) > 1:
                    print(
                        f"⚠️  帧目录中找到多个 normalized_*.obj,只使用第一个: {frame_dir}"
                    )
                obj_path = candidates[0]

            obj_files.append(
                {
                    "sequence": seq,
                    "frame": frame_dir.name,
                    "obj_path": str(obj_path),
                    # 直接在序列目录下生成 PNG,例如: ABF11/0071.png
                    "output_subpath": f"{seq}/{frame_dir.name}.png",
                }
            )

    return obj_files


def find_normalized_objs_hoi4d(input_root: str, sequence_name: Optional[str] = None) -> List[Dict]:
    """查找 HOI4D 格式的标准化 OBJ 文件

    预期目录结构:
        input_root/
        ├── C12_N11_S154_s03_T1/
        │   ├── normalized_frame_00074.obj
        │   ├── normalized_frame_00075.obj
        │   └── ...
        └── C12_N18_S154_s05_T1/
            └── ...

    输出结构(固定): output_root/seq/normalized_frame_00074.png
    """
    input_root = Path(input_root)
    obj_files = []

    if sequence_name:
        sequences = [sequence_name]
    else:
        sequences = [d.name for d in input_root.iterdir() if d.is_dir()]

    for seq in sorted(sequences):
        seq_dir = input_root / seq
        if not seq_dir.exists():
            print(f"⚠️  序列目录不存在: {seq_dir}")
            continue

        # 直接在序列目录下查找 normalized_frame_*.obj
        for obj_file in sorted(seq_dir.glob("normalized_frame_*.obj")):
            # 从 normalized_frame_00074.obj 提取帧名
            frame_name = obj_file.stem  # normalized_frame_00074
            obj_files.append({
                'sequence': seq,
                'frame': frame_name,
                'obj_path': str(obj_file),
                # 固定输出结构: output_root/seq/normalized_frame_00074.png
                'output_subpath': f"{seq}/{frame_name}.png",
            })

    return obj_files


def find_normalized_objs(input_root: str, mode: str = "contact", sequence_name: Optional[str] = None) -> List[Dict]:
    """根据 mode 选择对应的扫描函数"""
    if mode == "hoi4d":
        return find_normalized_objs_hoi4d(input_root, sequence_name)
    else:
        return find_normalized_objs_contact(input_root, sequence_name)


class RenderTaskDataset(Dataset):
	"""用于 DataLoader 的渲染任务数据集"""

	def __init__(self, tasks: List[Dict], output_root: str):
		"""保存任务列表和输出根目录"""
		self.tasks = tasks
		self.output_root = Path(output_root)

	def __len__(self) -> int:
		return len(self.tasks)

	def __getitem__(self, idx: int) -> Dict:
		"""返回单个渲染任务的信息"""
		task = self.tasks[idx]
		output_path = str(self.output_root / task['output_subpath'])
		return {
		    'idx': idx,
		    'obj_path': task['obj_path'],
		    'output_path': output_path,
		    'sequence': task['sequence'],
		    'frame': task['frame'],
		}


def collate_fn_identity(batch):
	"""DataLoader 的简单 collate_fn:直接返回 list[dict]

	需要是模块级函数,方便在多进程(spawn)模式下被 pickle。
	"""

	return batch


def batch_render(
    input_root: str,
    output_root: str,
    mode: str = "contact",
    sequence: Optional[str] = None,
    test_mode: bool = False,
    max_frames: int = 3,
    device: Optional[str] = None,
    batch_size: int = 1,
    num_workers: int = 0,
    shard_id: int = 0,
    num_shards: int = 1,
    skip_existing: bool = True,
    input_coord: str = "z_up",
):
    """批量渲染(支持 batch、DataLoader、多卡分片)

    Args:
        input_root: 输入根目录
        output_root: 输出根目录
        mode: "contact" 或 "hoi4d"
        sequence: 只处理指定序列
        test_mode: 测试模式(每序列只处理少量帧)
        max_frames: 测试模式下每序列最大帧数
        device: 渲染设备
        batch_size: 批量渲染大小(多个 mesh 同时渲染)
        num_workers: DataLoader 的 worker 数量(CPU 预加载)
        shard_id: 当前分片 ID(用于多卡并行)
        num_shards: 总分片数
        skip_existing: 是否跳过已存在的输出文件
    """
    print("=" * 80)
    print("🎨 InstantMesh 渲染器批处理 (v2 - Batch + DataLoader)")
    print("=" * 80)
    print(f"📁 输入根目录: {input_root}")
    print(f"📁 输出根目录: {output_root}")
    print(f"📦 模式: {mode}")
    print(f"🔢 Batch Size: {batch_size}, Workers: {num_workers}")
    if num_shards > 1:
        print(f"🔀 分片: {shard_id + 1}/{num_shards}")
    if sequence:
        print(f"🎯 处理序列: {sequence}")
    if test_mode:
        print(f"🧪 测试模式: 每序列最多 {max_frames} 帧")
    print("=" * 80)

    # 1. 查找所有 OBJ 文件
    obj_files = find_normalized_objs(input_root, mode=mode, sequence_name=sequence)

    if not obj_files:
        print("❌ 未找到任何标准化的 OBJ 文件")
        return False

    print(f"\n📊 找到 {len(obj_files)} 个文件")

    # 2. 测试模式:限制每序列的帧数
    if test_mode:
        filtered_files = []
        seq_counts = {}
        for obj_info in obj_files:
            seq = obj_info['sequence']
            if seq not in seq_counts:
                seq_counts[seq] = 0
            if seq_counts[seq] < max_frames:
                filtered_files.append(obj_info)
                seq_counts[seq] += 1
        obj_files = filtered_files
        print(f"🧪 测试模式:处理 {len(obj_files)} 个文件")

    # 3. 分片:只处理属于当前 shard 的任务
    if num_shards > 1:
        obj_files = [f for i, f in enumerate(obj_files) if i % num_shards == shard_id]
        print(f"🔀 分片后:处理 {len(obj_files)} 个文件")

    # 4. 跳过已存在的文件
    if skip_existing:
        output_root_path = Path(output_root)
        filtered = []
        skipped = 0
        for obj_info in obj_files:
            output_path = output_root_path / obj_info['output_subpath']
            if output_path.exists():
                skipped += 1
            else:
                filtered.append(obj_info)
        obj_files = filtered
        if skipped > 0:
            print(f"⏭️  跳过已存在: {skipped} 个")

    if not obj_files:
        print("✅ 所有文件已处理完毕")
        return True

    print(f"📝 待处理: {len(obj_files)} 个文件")

    # 5. 创建 Dataset 和 DataLoader
    dataset = RenderTaskDataset(obj_files, output_root)

    dataloader = DataLoader(
        dataset,
        batch_size=batch_size,
        shuffle=False,
        num_workers=num_workers,
        collate_fn=collate_fn_identity,
        prefetch_factor=2 if num_workers > 0 else None,
        persistent_workers=num_workers > 0,
    )

    # 6. 创建渲染器
    # input_coord:
    #   - "z_up": 输入 mesh 已经是 Z-up(默认,适用于新的 normalized_*.obj / HOI4D 等)
    #   - "y_up": 输入 mesh 为 Y-up,这里会自动做一次 Y-up → Z-up 旋转
    renderer = InstantMeshRendererV4(device=device, image_size=320, input_coord=input_coord)

    # 7. 批量渲染
    success_count = 0
    fail_count = 0
    total_batches = len(dataloader)

    pbar = tqdm(dataloader, desc="渲染进度", total=total_batches)
    for batch_idx, batch in enumerate(pbar):
        obj_paths = [item['obj_path'] for item in batch]
        output_paths = [item['output_path'] for item in batch]

        # 使用 batch 渲染
        if batch_size > 1:
            batch_success, batch_fail = renderer.render_batch_for_instantmesh(
                obj_paths, output_paths, verbose=False
            )
            success_count += batch_success
            fail_count += batch_fail
        else:
            # 单个渲染(兼容旧逻辑)
            for item in batch:
                try:
                    os.makedirs(os.path.dirname(item['output_path']), exist_ok=True)
                    renderer.render_for_instantmesh(item['obj_path'], item['output_path'])
                    success_count += 1
                except Exception as e:
                    fail_count += 1

        pbar.set_postfix({'成功': success_count, '失败': fail_count})

    print("\n" + "=" * 80)
    print(f"📊 批量渲染完成")
    print(f"   ✅ 成功: {success_count} 个")
    print(f"   ❌ 失败: {fail_count} 个")
    print("=" * 80)

    return fail_count == 0


def _mp_worker(rank: int, world_size: int, args: argparse.Namespace) -> None:
    """多 GPU 模式下的子进程入口

    每个 rank 负责一个 shard,设备固定为 cuda:{rank}(若可用),否则回退到 CPU/指定设备。
    """

    if torch.cuda.is_available():
        device = f"cuda:{rank}"
    else:
        # 无 GPU 时,仍然可以多进程跑 CPU(一般用不到)
        device = args.device or "cpu"

    print(f"\n[Worker {rank}/{world_size}] 使用设备: {device}")

    ok = batch_render(
        input_root=args.input_root,
        output_root=args.output_root,
        mode=args.mode,
        sequence=args.sequence,
        test_mode=args.test_mode,
        max_frames=args.frames,
        device=device,
        batch_size=args.batch_size,
        num_workers=args.workers,
        shard_id=rank,
        num_shards=world_size,
        skip_existing=not args.no_skip,
        input_coord=args.input_coord,
    )

    if not ok:
        # 让 mp.spawn 感知失败,从而中止所有进程
        raise RuntimeError(f"Worker {rank} failed")


def main():
    parser = argparse.ArgumentParser(
        description="InstantMesh 渲染器批处理脚本 (v2 - Batch + DataLoader + 多 GPU)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=__doc__,
    )

    # 基础参数
    parser.add_argument(
        "--input_root",
        type=str,
        required=True,
        help="输入根目录(标准化后的 OBJ 文件所在目录)",
    )
    parser.add_argument(
        "--output_root",
        type=str,
        required=True,
        help="输出根目录(将保存渲染 PNG 的目录)",
    )
    parser.add_argument(
        "--mode",
        type=str,
        default="contact",
        choices=["contact", "hoi4d"],
        help="数据集模式: contact (seq/frame/normalized_*.obj) 或 hoi4d (seq/normalized_frame_*.obj)",
    )
    parser.add_argument(
        "--sequence",
        type=str,
        default=None,
        help="只处理指定序列名称(例如 SiS1 或 C12_N11_S154_s03_T1),默认处理所有序列",
    )

    # 模式控制
    parser.add_argument(
        "--test",
        action="store_true",
        help="测试模式:每个序列只处理少量帧(由 --frames 控制)",
    )
    parser.add_argument(
        "--full",
        action="store_true",
        help="完整模式:处理所有帧(与 --test 互斥)",
    )
    parser.add_argument(
        "--frames",
        type=int,
        default=3,
        help="测试模式下每个序列处理的最大帧数(默认 3)",
    )

    # 性能参数
    parser.add_argument(
        "--device",
        type=str,
        default=None,
        help="渲染设备,例如 cuda:0;留空则自动检测 GPU/CPU(单 GPU 模式有效)",
    )
    parser.add_argument(
        "--batch_size",
        type=int,
        default=1,
        help="批量渲染大小:多个 mesh 同时在 GPU 渲染(默认 1,建议 4-16)",
    )
    parser.add_argument(
        "--workers",
        type=int,
        default=0,
        help="DataLoader worker 数量:CPU 预加载线程(默认 0,建议 4-8)",
    )

    parser.add_argument(
        "--input_coord",
        type=str,
        default="z_up",
        choices=["z_up", "y_up"],
        help=(
            "输入 mesh 的坐标系:z_up (默认,新的 normalized_*.obj / HOI4D);"
            "y_up 表示老数据集仍为 Y-up,会在渲染前自动旋转到 Z-up"
        ),
    )

    # 多 GPU / 分片
    parser.add_argument(
        "--num_gpus",
        type=int,
        default=1,
        help="使用的 GPU 数量:>1 时自动按 rank 分片并内部多进程调度",
    )
    parser.add_argument(
        "--shard_id",
        type=int,
        default=0,
        help="手动分片 ID(从 0 开始),仅在 num_gpus=1 时用于高级自定义",
    )
    parser.add_argument(
        "--num_shards",
        type=int,
        default=1,
        help="手动总分片数,仅在 num_gpus=1 时有效(默认 1 不分片)",
    )

    # 其他
    parser.add_argument(
        "--no_skip",
        action="store_true",
        help="不跳过已存在的输出文件(默认会跳过)",
    )

    args = parser.parse_args()

    # 参数校验
    if args.test and args.full:
        print("❌ 参数错误:--test 和 --full 不能同时使用")
        return 1

    if args.num_gpus < 1:
        print("❌ 参数错误:--num_gpus 必须 >= 1")
        return 1

    if args.num_gpus == 1 and args.shard_id >= args.num_shards:
        print(f"❌ 参数错误:shard_id ({args.shard_id}) 必须小于 num_shards ({args.num_shards})")
        return 1

    if args.num_gpus > 1 and (args.shard_id != 0 or args.num_shards != 1):
        print("⚠️ 检测到手动分片参数,但在多 GPU 模式下会被忽略,改用自动按 rank 分片")

    # 默认行为:如果既没有 --test 也没有 --full,则按测试模式处理
    test_mode = args.test or (not args.test and not args.full)
    if not args.test and not args.full:
        print("ℹ️ 未指定 --test/--full,默认使用测试模式 (--test),每序列仅处理少量帧")

    # 将 test_mode 挂到 args 上,便于子进程读取
    args.test_mode = test_mode

    # 多 GPU 模式:内部多进程 + 自动分片
    if args.num_gpus > 1:
        world_size = args.num_gpus
        print(f"🚀 多 GPU 模式:world_size={world_size}(需要提前设置 CUDA_VISIBLE_DEVICES)")

        try:
            mp.set_start_method("spawn", force=True)
        except RuntimeError:
            # 已经设置过 start method,忽略
            pass

        # mp.spawn 的 args 需为 tuple
        mp.spawn(_mp_worker, args=(world_size, args), nprocs=world_size, join=True)
        return 0

    # 单 GPU / CPU:直接在当前进程中运行,可选手动分片
    ok = batch_render(
        input_root=args.input_root,
        output_root=args.output_root,
        mode=args.mode,
        sequence=args.sequence,
        test_mode=test_mode,
        max_frames=args.frames,
        device=args.device,
        batch_size=args.batch_size,
        num_workers=args.workers,
        shard_id=args.shard_id,
        num_shards=args.num_shards,
        skip_existing=not args.no_skip,
        input_coord=args.input_coord,
    )

    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())