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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
#!/usr/bin/env python3
"""
SAM3 推理脚本 - 用于3D医学图像分割 (BraTS)
基于SAM3的视频分割功能处理3D医学数据
"""

import os
import sys
import argparse
import numpy as np
import torch
import cv2
from pathlib import Path
from PIL import Image
from tqdm import tqdm
import glob
import json

# 添加SAM3路径
sys.path.insert(0, '/root/githubs/sam3')

from sam3.model_builder import build_sam3_video_model
from sam3.visualization_utils import show_mask, show_points, show_box


def setup_device():
    """设置计算设备"""
    if torch.cuda.is_available():
        device = torch.device("cuda")
        torch.autocast("cuda", dtype=torch.bfloat16).__enter__()
        if torch.cuda.get_device_properties(0).major >= 8:
            torch.backends.cuda.matmul.allow_tf32 = True
            torch.backends.cudnn.allow_tf32 = True
    else:
        device = torch.device("cpu")
    
    print(f"Using device: {device}")
    return device


def load_frames_from_directory(frames_dir):
    """
    从目录加载帧图像
    
    Returns:
        frames: list of numpy arrays (H, W, 3)
        frame_paths: list of paths
    """
    frame_paths = sorted(glob.glob(str(Path(frames_dir) / "*.jpg")))
    if not frame_paths:
        frame_paths = sorted(glob.glob(str(Path(frames_dir) / "*.png")))
    
    frames = []
    for path in frame_paths:
        img = cv2.imread(path)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        frames.append(img)
    
    return frames, frame_paths


def load_prompt_info(case_dir):
    """加载提示信息"""
    prompt_path = Path(case_dir) / 'prompt_info.npy'
    if prompt_path.exists():
        return np.load(str(prompt_path), allow_pickle=True).item()
    return None


class MedSAM3VideoInference:
    """
    使用SAM3视频模式进行3D医学图像分割
    """
    
    def __init__(
        self,
        checkpoint_path=None,
        device="cuda",
        lora_weights: str = "",
        lora_rank: int = 8,
        lora_alpha: float = 16.0,
        lora_dropout: float = 0.0,
        lora_target_modules: str = "q_proj,k_proj,v_proj,out_proj,qkv,proj",
    ):
        """
        初始化SAM3视频模型
        
        Args:
            checkpoint_path: 模型检查点路径
            device: 计算设备
        """
        self.device = device
        print("Loading SAM3 video model...")
        
        # 构建模型
        self.sam3_model = build_sam3_video_model(
            checkpoint_path=checkpoint_path,
            load_from_HF=False if checkpoint_path else True,
            device=device,
            apply_temporal_disambiguation=True
        )

        # Optional: load LoRA adapters into the detector module
        if lora_weights:
            from lora import apply_lora_to_model, load_lora_weights

            target_modules = [s.strip() for s in str(lora_target_modules).split(",") if s.strip()]
            print(
                f"Loading LoRA into SAM3 detector: weights={lora_weights}, "
                f"rank={lora_rank}, alpha={lora_alpha}, targets={target_modules}"
            )
            apply_lora_to_model(
                self.sam3_model.detector,
                rank=int(lora_rank),
                alpha=float(lora_alpha),
                dropout=float(lora_dropout),
                target_modules=target_modules,
                exclude_modules=[],
            )
            load_lora_weights(self.sam3_model.detector, lora_weights)
        
        # 获取tracker predictor
        self.predictor = self.sam3_model.tracker
        self.predictor.backbone = self.sam3_model.detector.backbone
        
        print("SAM3 video model loaded successfully!")
    
    def segment_3d_volume(self, frames_dir, prompt_slice_idx, prompt_type='point',
                          points=None, labels=None, bbox=None,
                          propagate_forward=True, propagate_backward=True):
        """
        对3D体积进行分割
        
        Args:
            frames_dir: 帧目录路径
            prompt_slice_idx: 提示所在的切片索引
            prompt_type: 'point' 或 'box'
            points: 点坐标 [[x, y], ...]
            labels: 点标签 [1, 0, ...],1为正点,0为负点
            bbox: 边界框 [x_min, y_min, x_max, y_max]
            propagate_forward: 是否向前传播
            propagate_backward: 是否向后传播
        
        Returns:
            masks_3d: 3D分割结果 (D, H, W)
        """
        # 加载帧
        frames, frame_paths = load_frames_from_directory(frames_dir)
        num_frames = len(frames)
        
        if num_frames == 0:
            raise ValueError(f"No frames found in {frames_dir}")
        
        height, width = frames[0].shape[:2]
        print(f"Loaded {num_frames} frames with size {width}x{height}")
        
        # 初始化inference state
        # SAM3需要视频路径,我们创建临时视频或使用帧目录
        inference_state = self.predictor.init_state(video_path=str(frames_dir))
        
        # 清除之前的tracking
        self.predictor.clear_all_points_in_video(inference_state)
        
        # 添加提示
        ann_obj_id = 1  # 对象ID
        
        if prompt_type == 'point' and points is not None:
            # 转换点坐标为相对坐标
            rel_points = [[x / width, y / height] for x, y in points]
            points_tensor = torch.tensor(rel_points, dtype=torch.float32)
            labels_tensor = torch.tensor(labels, dtype=torch.int32)
            
            _, out_obj_ids, _, video_res_masks = self.predictor.add_new_points(
                inference_state=inference_state,
                frame_idx=prompt_slice_idx,
                obj_id=ann_obj_id,
                points=points_tensor,
                labels=labels_tensor,
                clear_old_points=True
            )
            
        elif prompt_type == 'box' and bbox is not None:
            # 转换bbox为相对坐标
            x_min, y_min, x_max, y_max = bbox
            rel_box = np.array([[
                x_min / width, y_min / height,
                x_max / width, y_max / height
            ]], dtype=np.float32)
            
            _, out_obj_ids, _, video_res_masks = self.predictor.add_new_points_or_box(
                inference_state=inference_state,
                frame_idx=prompt_slice_idx,
                obj_id=ann_obj_id,
                box=rel_box
            )
        else:
            raise ValueError("Must provide points or bbox for prompting")
        
        # 传播分割
        video_segments = {}
        
        # 从提示帧开始向前传播
        if propagate_forward:
            for frame_idx, obj_ids, _, video_res_masks, _ in self.predictor.propagate_in_video(
                inference_state, 
                start_frame_idx=prompt_slice_idx,
                max_frame_num_to_track=num_frames,
                reverse=False,
                propagate_preflight=True
            ):
                for i, obj_id in enumerate(obj_ids):
                    if frame_idx not in video_segments:
                        video_segments[frame_idx] = {}
                    video_segments[frame_idx][obj_id] = (video_res_masks[i] > 0.0).cpu().numpy()
        
        # 从提示帧开始向后传播
        if propagate_backward and prompt_slice_idx > 0:
            # 重新初始化state并添加提示
            inference_state = self.predictor.init_state(video_path=str(frames_dir))
            self.predictor.clear_all_points_in_video(inference_state)
            
            if prompt_type == 'point':
                self.predictor.add_new_points(
                    inference_state=inference_state,
                    frame_idx=prompt_slice_idx,
                    obj_id=ann_obj_id,
                    points=points_tensor,
                    labels=labels_tensor,
                    clear_old_points=True
                )
            elif prompt_type == 'box':
                self.predictor.add_new_points_or_box(
                    inference_state=inference_state,
                    frame_idx=prompt_slice_idx,
                    obj_id=ann_obj_id,
                    box=rel_box
                )
            
            for frame_idx, obj_ids, _, video_res_masks, _ in self.predictor.propagate_in_video(
                inference_state,
                start_frame_idx=prompt_slice_idx,
                max_frame_num_to_track=prompt_slice_idx + 1,
                reverse=True,
                propagate_preflight=True
            ):
                for i, obj_id in enumerate(obj_ids):
                    if frame_idx not in video_segments:
                        video_segments[frame_idx] = {}
                    video_segments[frame_idx][obj_id] = (video_res_masks[i] > 0.0).cpu().numpy()
        
        # 组装3D mask
        masks_3d = np.zeros((num_frames, height, width), dtype=np.uint8)
        
        for frame_idx in range(num_frames):
            if frame_idx in video_segments and ann_obj_id in video_segments[frame_idx]:
                mask = video_segments[frame_idx][ann_obj_id]
                # 确保mask是2D的
                if mask.ndim > 2:
                    mask = mask.squeeze()
                masks_3d[frame_idx] = mask.astype(np.uint8)
        
        return masks_3d


def compute_dice(pred, gt):
    """计算Dice系数"""
    pred = pred.astype(bool)
    gt = gt.astype(bool)
    
    intersection = np.sum(pred & gt)
    union = np.sum(pred) + np.sum(gt)
    
    if union == 0:
        return 1.0 if np.sum(pred) == 0 else 0.0
    
    return 2 * intersection / union


def compute_metrics(pred_mask, gt_mask):
    """计算评估指标"""
    dice = compute_dice(pred_mask, gt_mask)
    
    # IoU
    intersection = np.sum((pred_mask > 0) & (gt_mask > 0))
    union = np.sum((pred_mask > 0) | (gt_mask > 0))
    iou = intersection / (union + 1e-8)
    
    return {'dice': dice, 'iou': iou}


def load_gt_masks(masks_dir):
    """加载ground truth masks"""
    mask_paths = sorted(glob.glob(str(Path(masks_dir) / "*.png")))
    
    masks = []
    for path in mask_paths:
        mask = np.array(Image.open(path))
        masks.append((mask > 128).astype(np.uint8))  # 二值化
    
    return np.stack(masks, axis=0)


def save_predictions(pred_masks, output_dir, case_name):
    """保存预测结果"""
    save_dir = Path(output_dir) / case_name / "predictions"
    save_dir.mkdir(parents=True, exist_ok=True)
    
    for i, mask in enumerate(pred_masks):
        mask_img = (mask * 255).astype(np.uint8)
        Image.fromarray(mask_img).save(str(save_dir / f"{i:05d}.png"))
    
    # 保存为npz
    np.savez_compressed(
        str(Path(output_dir) / case_name / "pred_mask.npz"),
        masks=pred_masks
    )


def visualize_results(frames_dir, pred_masks, gt_masks, output_dir, case_name, 
                      num_vis=10, prompt_slice_idx=None, prompt_info=None):
    """可视化结果"""
    import matplotlib.pyplot as plt
    
    vis_dir = Path(output_dir) / case_name / "visualization"
    vis_dir.mkdir(parents=True, exist_ok=True)
    
    frames, _ = load_frames_from_directory(frames_dir)
    num_frames = len(frames)
    
    # 选择要可视化的帧
    vis_indices = np.linspace(0, num_frames - 1, num_vis, dtype=int)
    
    # 确保包含提示帧
    if prompt_slice_idx is not None and prompt_slice_idx not in vis_indices:
        vis_indices = np.append(vis_indices, prompt_slice_idx)
        vis_indices = np.sort(np.unique(vis_indices))
    
    for idx in vis_indices:
        fig, axes = plt.subplots(1, 3, figsize=(15, 5))
        
        # 原图
        axes[0].imshow(frames[idx])
        axes[0].set_title(f'Frame {idx}')
        axes[0].axis('off')
        
        # 预测
        axes[1].imshow(frames[idx])
        if pred_masks[idx].sum() > 0:
            show_mask(pred_masks[idx], axes[1], obj_id=1)
        axes[1].set_title('Prediction')
        axes[1].axis('off')
        
        # GT
        if gt_masks is not None:
            axes[2].imshow(frames[idx])
            if gt_masks[idx].sum() > 0:
                show_mask(gt_masks[idx], axes[2], obj_id=2)
            axes[2].set_title('Ground Truth')
        else:
            axes[2].imshow(frames[idx])
            axes[2].set_title('No GT')
        axes[2].axis('off')
        
        # 如果是提示帧,显示提示
        if idx == prompt_slice_idx and prompt_info is not None:
            if prompt_info.get('center'):
                center = prompt_info['center']
                axes[0].plot(center[0], center[1], 'r*', markersize=15)
            if prompt_info.get('bbox'):
                bbox = prompt_info['bbox']
                show_box(bbox, axes[0])
        
        plt.tight_layout()
        plt.savefig(str(vis_dir / f"frame_{idx:05d}.png"), dpi=150, bbox_inches='tight')
        plt.close()


def main():
    parser = argparse.ArgumentParser(description='SAM3 inference for 3D medical images')
    parser.add_argument('--input_dir', type=str, required=True,
                        help='Input directory with processed cases')
    parser.add_argument('--output_dir', type=str, required=True,
                        help='Output directory for predictions')
    parser.add_argument('--checkpoint', type=str, default='/data/yty/sam3/sam3.pt',
                        help='SAM3 checkpoint path')
    parser.add_argument('--lora_weights', type=str, default='',
                        help='Optional LoRA weights (e.g. .../checkpoints/best_lora_weights.pt). Applied to SAM3 detector.')
    parser.add_argument('--lora_rank', type=int, default=8)
    parser.add_argument('--lora_alpha', type=float, default=16.0)
    parser.add_argument('--lora_dropout', type=float, default=0.0)
    parser.add_argument('--lora_target_modules', type=str, default='q_proj,k_proj,v_proj,out_proj,qkv,proj')
    parser.add_argument('--prompt_type', type=str, default='box', choices=['point', 'box'],
                        help='Prompt type: point or box')
    parser.add_argument('--split', type=str, default='all', choices=['all', 'train', 'val', 'test'],
                        help='Which split to run. If not "all", will filter cases by splits.json or ratio-based split.')
    parser.add_argument('--split_json', type=str, default='',
                        help='Optional split json (same format as preprocess_brats.py --write_splits). Defaults to input_dir/splits.json if present.')
    parser.add_argument('--train_ratio', type=float, default=0.7)
    parser.add_argument('--val_ratio', type=float, default=0.1)
    parser.add_argument('--test_ratio', type=float, default=0.2)
    parser.add_argument('--seed', type=int, default=42)
    parser.add_argument('--num_cases', type=int, default=None,
                        help='Number of cases to process')
    parser.add_argument('--visualize', action='store_true',
                        help='Generate visualization')
    parser.add_argument('--device', type=str, default='cuda',
                        help='Device to use')
    
    args = parser.parse_args()
    
    # 设置设备
    device = setup_device() if args.device == 'cuda' else torch.device(args.device)
    
    # 初始化模型
    model = MedSAM3VideoInference(
        checkpoint_path=args.checkpoint,
        device=str(device),
        lora_weights=args.lora_weights,
        lora_rank=args.lora_rank,
        lora_alpha=args.lora_alpha,
        lora_dropout=args.lora_dropout,
        lora_target_modules=args.lora_target_modules,
    )
    
    # 获取所有病例
    input_dir = Path(args.input_dir)
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    
    case_dirs = sorted([d for d in input_dir.iterdir() if d.is_dir()])

    # Filter by split if requested
    if args.split != 'all':
        split_json = args.split_json.strip()
        if split_json == "":
            default_split = input_dir / "splits.json"
            if default_split.exists():
                split_json = str(default_split)

        wanted_names = None
        if split_json:
            with open(split_json, "r") as f:
                cfg = json.load(f)
            splits = cfg.get("splits", cfg)
            if isinstance(splits, dict) and "splits" in splits and isinstance(splits["splits"], dict):
                splits = splits["splits"]
            wanted_names = splits.get(args.split)
            if wanted_names is None:
                raise KeyError(f"split '{args.split}' not found in split json: {split_json}")
        else:
            # deterministic ratio-based split
            ratios_sum = float(args.train_ratio) + float(args.val_ratio) + float(args.test_ratio)
            if abs(ratios_sum - 1.0) > 1e-6:
                raise ValueError(f"train/val/test ratios must sum to 1.0, got {ratios_sum}")
            names = [d.name for d in case_dirs]
            rng = np.random.RandomState(args.seed)
            rng.shuffle(names)
            n = len(names)
            n_train = int(round(n * float(args.train_ratio)))
            n_val = int(round(n * float(args.val_ratio)))
            n_train = min(max(n_train, 0), n)
            n_val = min(max(n_val, 0), n - n_train)
            train = names[:n_train]
            val = names[n_train : n_train + n_val]
            test = names[n_train + n_val :]
            wanted_names = {"train": train, "val": val, "test": test}[args.split]

        wanted_set = set(wanted_names)
        case_dirs = [d for d in case_dirs if d.name in wanted_set]
    
    if args.num_cases is not None:
        case_dirs = case_dirs[:args.num_cases]
    
    print(f"Found {len(case_dirs)} cases to process")
    
    all_metrics = []
    
    for case_dir in tqdm(case_dirs, desc="Processing cases"):
        case_name = case_dir.name
        frames_dir = case_dir / "frames"
        masks_dir = case_dir / "masks"
        
        if not frames_dir.exists():
            print(f"Skipping {case_name}: no frames directory")
            continue
        
        try:
            # 加载提示信息
            prompt_info = load_prompt_info(case_dir)
            
            if prompt_info is None:
                print(f"Skipping {case_name}: no prompt info")
                continue
            
            prompt_slice_idx = prompt_info['slice_idx']
            bbox = prompt_info.get('bbox')
            center = prompt_info.get('center')
            
            # 准备提示
            if args.prompt_type == 'box' and bbox is not None:
                pred_masks = model.segment_3d_volume(
                    frames_dir=str(frames_dir),
                    prompt_slice_idx=prompt_slice_idx,
                    prompt_type='box',
                    bbox=bbox
                )
            elif args.prompt_type == 'point' and center is not None:
                pred_masks = model.segment_3d_volume(
                    frames_dir=str(frames_dir),
                    prompt_slice_idx=prompt_slice_idx,
                    prompt_type='point',
                    points=[list(center)],
                    labels=[1]
                )
            else:
                print(f"Skipping {case_name}: invalid prompt")
                continue
            
            # 保存预测
            save_predictions(pred_masks, output_dir, case_name)
            
            # 计算指标
            gt_masks = None
            if masks_dir.exists():
                gt_masks = load_gt_masks(masks_dir)
                metrics = compute_metrics(pred_masks, gt_masks)
                metrics['case_name'] = case_name
                all_metrics.append(metrics)
                print(f"{case_name}: Dice={metrics['dice']:.4f}, IoU={metrics['iou']:.4f}")
            
            # 可视化
            if args.visualize:
                visualize_results(
                    frames_dir, pred_masks, gt_masks, output_dir, case_name,
                    prompt_slice_idx=prompt_slice_idx, prompt_info=prompt_info
                )
        
        except Exception as e:
            print(f"Error processing {case_name}: {e}")
            import traceback
            traceback.print_exc()
            continue
    
    # 汇总结果
    if all_metrics:
        avg_dice = np.mean([m['dice'] for m in all_metrics])
        avg_iou = np.mean([m['iou'] for m in all_metrics])
        
        print(f"\n{'='*50}")
        print(f"Results Summary ({len(all_metrics)} cases):")
        print(f"  Average Dice: {avg_dice:.4f}")
        print(f"  Average IoU: {avg_iou:.4f}")
        print(f"{'='*50}")
        
        # 保存结果
        np.save(str(output_dir / 'metrics.npy'), all_metrics, allow_pickle=True)


if __name__ == "__main__":
    main()