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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
"""SAM 3 text-prompted segmentation helpers (model loading and per-prompt segmentation), used by the render
worker, the SAM 3 audit and the mask export. The command line segments a folder of images per class.
"""

import argparse
import json
import os
import random
import re
import tempfile
from pathlib import Path
from typing import Optional


def _atomic_write_json(path: Path, data) -> None:
    """Write JSON to ``path`` atomically.

    On some shared filesystems, ``open('w')`` doesn't truncate cleanly —
    if the new content is shorter than the old, NULL bytes can appear
    between new EOF and old EOF, leaving a corrupt mixed file. This
    helper writes to a sibling tempfile then ``os.replace``s it onto
    the target path; ``os.replace`` is atomic, so readers always see
    either the old complete file or the new complete file.
    """
    fd, tmp = tempfile.mkstemp(prefix=path.name + '.', suffix='.tmp',
                               dir=str(path.parent))
    try:
        with os.fdopen(fd, 'w') as f:
            json.dump(data, f, indent=2)
        os.replace(tmp, path)
    except Exception:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise

import cv2
import numpy as np
import torch
from PIL import Image


def load_sam3_processor(bpe_path: str,
                        confidence_threshold: float = 0.5,
                        device: str = 'cuda',
                        checkpoint_path: Optional[str] = None):
    """Build SAM3 image model + processor."""
    from sam3 import build_sam3_image_model
    from sam3.model.sam3_image_processor import Sam3Processor

    if checkpoint_path is not None:
        model = build_sam3_image_model(
            bpe_path=bpe_path,
            checkpoint_path=checkpoint_path,
            load_from_HF=False,
        )
    else:
        model = build_sam3_image_model(bpe_path=bpe_path)
    model = model.to(device).eval()
    processor = Sam3Processor(
        model, confidence_threshold=confidence_threshold)
    return processor


def load_clip_scorer(device: str = 'cuda', model_name: str = 'ViT-L/14'):
    """OpenAI CLIP for the optional white-bg re-score (paper metric)."""
    import clip
    model, preprocess = clip.load(model_name, device=device)
    model = model.eval()
    return model, preprocess, clip.tokenize


def category_name_for_prompt(cat_dir_name: str) -> str:
    """Reverse-clean directory name into a natural phrase.

    Mirrors ``segment_sam.py`` so dir-name conventions stay shared.
    """
    name = cat_dir_name.replace('_', ' ')
    name = re.sub(r'\s+', ' ', name).strip()
    return name


def get_largest_connect_component(mask: np.ndarray) -> np.ndarray:
    """Keep only the largest connected blob of a binary mask."""
    contours, _ = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if not contours:
        return mask
    areas = [cv2.contourArea(c) for c in contours]
    max_idx = int(np.argmax(areas))
    out = np.zeros_like(mask)
    cv2.fillPoly(out, [contours[max_idx]], 1)
    return out


@torch.no_grad()
def clip_rescore(
    image_rgb: np.ndarray,
    mask: np.ndarray,
    category_phrase: str,
    clip_model,
    clip_preprocess,
    clip_tokenizer,
    device: str = 'cuda',
) -> float:

    mask_bin = (mask > 128).astype(np.float32)[:, :, None]
    white = np.full_like(image_rgb, 255)
    composite = (image_rgb * mask_bin + white * (1.0 - mask_bin)).astype(
        np.uint8)
    img_tensor = clip_preprocess(Image.fromarray(composite)).unsqueeze(0)
    img_tensor = img_tensor.to(device)
    text_tokens = clip_tokenizer(
        [f"a photo of a {category_phrase}"]).to(device)
    image_features = clip_model.encode_image(img_tensor)
    text_features = clip_model.encode_text(text_tokens)
    image_features = image_features / image_features.norm(
        dim=-1, keepdim=True)
    text_features = text_features / text_features.norm(
        dim=-1, keepdim=True)
    similarity = (100.0 * text_features @ image_features.T).squeeze()
    return float(similarity.cpu())


def _to_numpy_mask(m) -> np.ndarray:
    """Coerce a SAM3 mask output (torch/np, bool/uint8/float) to HxW uint8."""
    if isinstance(m, torch.Tensor):
        if m.dtype not in (torch.bool, torch.uint8, torch.float32):
            m = m.float()
        m = m.detach().cpu().numpy()
    m = np.asarray(m)
    while m.ndim > 2:
        m = m[0]
    if m.dtype == np.bool_:
        return m.astype(np.uint8) * 255
    if np.issubdtype(m.dtype, np.floating):
        return ((m > 0.5).astype(np.uint8)) * 255
    return ((m > 0).astype(np.uint8)) * 255


def segment_with_text(processor, image_rgb: np.ndarray,
                      prompt: str, top_k: int = 1) -> Optional[tuple]:
    """Run SAM3 with a text prompt; return (mask, score) or None."""
    pil = Image.fromarray(image_rgb)
    with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
        state = processor.set_image(pil)
        out = processor.set_text_prompt(state=state, prompt=prompt)
    masks = out.get('masks')
    scores = out.get('scores')
    if masks is None or scores is None:
        return None
    if isinstance(scores, torch.Tensor):
        scores_np = scores.detach().float().cpu().numpy()
    else:
        scores_np = np.asarray(scores)
    if scores_np.size == 0:
        return None
    order = np.argsort(-scores_np)[:max(1, int(top_k))]
    union_u8 = None
    for idx in order:
        m_raw = masks[idx] if isinstance(masks, (list, tuple)) else masks[idx]
        m_u8 = _to_numpy_mask(m_raw)
        union_u8 = m_u8 if union_u8 is None else np.maximum(union_u8, m_u8)
    best_score = float(scores_np[order[0]])
    return union_u8, best_score


def crop_to_mask_bbox(image: np.ndarray, mask: np.ndarray,
                      padding: int = 5) -> tuple:
    """Crop image+mask to mask bbox and stack to RGBA. Same as segment_sam."""
    coords = np.where(mask > 0)
    if len(coords[0]) == 0:
        return None, None
    y1, y2 = coords[0].min(), coords[0].max()
    x1, x2 = coords[1].min(), coords[1].max()
    h, w = image.shape[:2]
    y1 = max(0, y1 - padding)
    x1 = max(0, x1 - padding)
    y2 = min(h, y2 + padding + 1)
    x2 = min(w, x2 + padding + 1)
    cropped_img = image[y1:y2, x1:x2]
    cropped_mask = mask[y1:y2, x1:x2]
    if cropped_img.shape[2] == 3:
        rgba = np.concatenate(
            [cropped_img, cropped_mask[:, :, None]], axis=2)
    else:
        rgba = cropped_img.copy()
        rgba[:, :, 3] = cropped_mask
    return rgba, (x1, y1, x2, y2)


def process_category_dir(
    processor,
    cat_dir: Path,
    output_dir: Path,
    crop: bool = True,
    clip_components: tuple = None,
    device: str = 'cuda',
    max_per_class: int = None,
    min_area_ratio: float = 0.02,
    max_area_ratio: float = 0.85,
    prompt_template: str = 'a {category}',
    min_score: float = 0.2,
    per_class_min_score: Optional[dict] = None,
    per_class_prompt: Optional[dict] = None,
    per_class_confidence_threshold: Optional[dict] = None,
    per_class_top_k: Optional[dict] = None,
    sample_seed: Optional[int] = 42,
) -> list:
    """Segment every img_*.png in cat_dir using SAM3 text prompts."""
    cat_name = cat_dir.name
    category_phrase = category_name_for_prompt(cat_name)
    cls_template = (per_class_prompt or {}).get(cat_name, prompt_template)
    prompt = cls_template.format(category=category_phrase)
    out_cat_dir = output_dir / cat_name
    out_cat_dir.mkdir(parents=True, exist_ok=True)
    cls_min_score = (per_class_min_score or {}).get(cat_name, min_score)

    pcct = per_class_confidence_threshold or {}
    saved_proc_thr = None
    if cat_name in pcct:
        saved_proc_thr = getattr(processor, 'confidence_threshold', None)
        processor.confidence_threshold = float(pcct[cat_name])

    cls_top_k = int((per_class_top_k or {}).get(cat_name, 1))

    meta_path = out_cat_dir / 'metadata.json'
    if meta_path.exists():
        with open(meta_path) as f:
            existing = json.load(f)
        existing_names = {m['image'] for m in existing}
    else:
        existing = []
        existing_names = set()

    src_meta_path = cat_dir / 'metadata.json'
    src_meta = {}
    if src_meta_path.exists():
        with open(src_meta_path) as f:
            src_meta_list = json.load(f)
            src_meta = {m['image']: m for m in src_meta_list}

    image_files = sorted(cat_dir.glob('img_*.png'))
    if max_per_class is not None:
        if sample_seed is None:
            image_files = image_files[:max_per_class]
        else:
            rng = random.Random(f"{sample_seed}:{cat_name}")
            k = min(max_per_class, len(image_files))
            image_files = rng.sample(image_files, k)
            image_files.sort()
    results = list(existing)

    flush_every = 500
    n_processed_this_run = 0

    for img_path in image_files:
        out_name = img_path.stem + '.png'
        if out_name in existing_names:
            continue

        try:
            image = np.array(Image.open(img_path).convert('RGB'))
        except Exception as e:
            print(f"  [WARN] skipping {img_path.name}: {type(e).__name__}: {e}")
            continue

        try:
            seg = segment_with_text(processor, image, prompt, top_k=cls_top_k)
        except Exception as e:
            print(f"  [WARN] segment failed on {img_path.name}: "
                  f"{type(e).__name__}: {e}")
            continue
        if seg is None:
            continue
        mask, sam3_score = seg

        if sam3_score < cls_min_score:
            continue

        if cls_top_k <= 1:
            mask01 = (mask > 0).astype(np.uint8)
            mask01 = get_largest_connect_component(mask01)
            mask = mask01 * 255

        mask_area = mask.sum() / 255.0
        total_area = mask.shape[0] * mask.shape[1]
        area_ratio = mask_area / total_area
        if area_ratio < min_area_ratio or area_ratio > max_area_ratio:
            continue

        seg_clip_score = None
        if clip_components is not None:
            cm, cp, ct = clip_components
            seg_clip_score = clip_rescore(
                image, mask, category_phrase, cm, cp, ct, device=device)

        if crop:
            rgba, bbox = crop_to_mask_bbox(image, mask)
            if rgba is None:
                continue
        else:
            rgba = np.concatenate([image, mask[:, :, None]], axis=2)
            bbox = (0, 0, image.shape[1], image.shape[0])

        out_path = out_cat_dir / out_name
        Image.fromarray(rgba).save(out_path)

        meta = {
            'image': out_name,
            'source_image': img_path.name,
            'width': int(rgba.shape[1]),
            'height': int(rgba.shape[0]),
            'mask_area_ratio': float(area_ratio),
            'bbox': [int(x) for x in bbox],
            'sam3_score': float(sam3_score),
            'prompt': prompt,
        }
        raw_score = src_meta.get(img_path.name, {}).get('clip_score')
        if raw_score is not None:
            meta['raw_clip_score'] = raw_score
        if seg_clip_score is not None:
            meta['clip_score'] = seg_clip_score
        elif raw_score is not None:
            meta['clip_score'] = raw_score
        results.append(meta)
        n_processed_this_run += 1

        if n_processed_this_run % flush_every == 0:
            _atomic_write_json(meta_path, results)

    _atomic_write_json(meta_path, results)

    if saved_proc_thr is not None:
        processor.confidence_threshold = saved_proc_thr

    return results


def main():
    parser = argparse.ArgumentParser(
        description='SAM 3 text-prompt segmentation of a folder of images, per class.')
    parser.add_argument('--input_dir', required=True)
    parser.add_argument('--output_dir', required=True)
    parser.add_argument('--sam3_bpe_path', required=True,
                        help='Path to assets/bpe_simple_vocab_16e6.txt.gz '
                             'from the cloned sam3 repo.')
    parser.add_argument('--sam3_checkpoint_path', type=str, default=None,
                        help='Optional local path to sam3.pt; when set, the Hugging Face Hub is not used.')
    parser.add_argument('--confidence_threshold', type=float, default=0.05,
                        help='Score threshold inside the SAM 3 processor; --min_score makes the final decision.')
    parser.add_argument('--min_score', type=float, default=0.2,
                        help='Minimum SAM 3 score of the kept mask.')
    parser.add_argument('--per_class_min_score_json', type=str, default=None,
                        help="Optional JSON file with per-class min_score "
                             "overrides, e.g. {\"person\": 0.1, "
                             "\"banana\": 0.1}. Falls back to --min_score "
                             "for any class not in the file.")
    parser.add_argument('--prompt_template', type=str,
                        default='a {category}',
                        help="Global text-prompt template; {category} is "
                             "replaced with the cleaned class name. "
                             "Default 'a {category}' — empirically the "
                             "old 'a photo of a {category}' wrapper "
                             "tanks SAM3 grounding for many classes "
                             "(e.g. bed/donut: 0.04 / 0.01 vs. 0.90 / "
                             "0.97 with 'a {category}').")
    parser.add_argument('--per_class_prompt_json', type=str, default=None,
                        help="Optional JSON file with per-class prompt "
                             "templates, e.g. "
                             '{"bed": "a picture of a {category}"}. '
                             "Falls back to --prompt_template otherwise.")
    parser.add_argument('--per_class_confidence_threshold_json',
                        type=str, default=None,
                        help='Optional JSON file with per-class processor score thresholds, e.g. {"bed": 0.0}.')
    parser.add_argument('--per_class_top_k_json', type=str, default=None,
                        help='Optional JSON file with per-class top-K: the top-K masks of a class are merged (for plural-noun classes).')
    parser.add_argument('--no_crop', action='store_true')

    parser.add_argument('--no_clip_rescore', action='store_true',
                        help='Skip optional white-bg CLIP re-score. Faster; '
                             'clean_pool.py will fall back to text2im.py '
                             'raw-image CLIP scores.')
    parser.add_argument('--clip_model', type=str, default='ViT-L/14')

    parser.add_argument('--min_area_ratio', type=float, default=0.02)
    parser.add_argument('--max_area_ratio', type=float, default=0.85)

    parser.add_argument('--classes', type=str, default=None,
                        help='Optional comma-separated class allowlist '
                             '(e.g. "person,banana,broccoli"). When set, '
                             'only those subdirs of --input_dir are '
                             'processed; useful for threshold sweeps over '
                             'a subset of problem classes.')
    parser.add_argument('--shard_id', type=int, default=0)
    parser.add_argument('--num_shards', type=int, default=1)
    parser.add_argument('--max_per_class', type=int, default=None,
                        help='Cap to N images per class (smoke / sweep). '
                             'Sampling is seeded random (see --sample_seed) '
                             'so the same N are picked across threshold '
                             'sweeps, but the sample is representative '
                             'instead of head-take img_0000..img_000N-1.')
    parser.add_argument('--sample_seed', type=int, default=42,
                        help='Seed for per-class random sampling under '
                             '--max_per_class. Set to -1 to fall back to '
                             'deterministic head-take.')
    parser.add_argument('--device', type=str, default='cuda')

    args = parser.parse_args()

    input_dir = Path(args.input_dir)
    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    cat_dirs = sorted([d for d in input_dir.iterdir() if d.is_dir()])
    print(f"Found {len(cat_dirs)} category directories")
    if args.classes:
        wanted = {c.strip() for c in args.classes.split(',') if c.strip()}
        cat_dirs = [d for d in cat_dirs if d.name in wanted]
        missing = wanted - {d.name for d in cat_dirs}
        if missing:
            print(f"  WARNING: requested classes not found: "
                  f"{sorted(missing)}")
        print(f"Class allowlist applied: {len(cat_dirs)} categories")
    cat_dirs = [d for i, d in enumerate(cat_dirs)
                if i % args.num_shards == args.shard_id]
    print(f"This shard: {len(cat_dirs)} categories")

    print(f"Loading SAM3 (bpe={args.sam3_bpe_path}, "
          f"conf_thr={args.confidence_threshold})...")
    processor = load_sam3_processor(
        args.sam3_bpe_path,
        confidence_threshold=args.confidence_threshold,
        device=args.device,
        checkpoint_path=args.sam3_checkpoint_path,
    )

    clip_components = None
    if not args.no_clip_rescore:
        print(f"Loading CLIP {args.clip_model} for white-bg re-score...")
        clip_components = load_clip_scorer(
            device=args.device, model_name=args.clip_model)

    per_class_min_score = None
    if args.per_class_min_score_json:
        with open(args.per_class_min_score_json) as f:
            per_class_min_score = json.load(f)
        print(f"Loaded per-class min_score overrides for "
              f"{len(per_class_min_score)} classes from "
              f"{args.per_class_min_score_json}")

    per_class_prompt = None
    if args.per_class_prompt_json:
        with open(args.per_class_prompt_json) as f:
            per_class_prompt = json.load(f)
        print(f"Loaded per-class prompt overrides for "
              f"{len(per_class_prompt)} classes from "
              f"{args.per_class_prompt_json}")

    per_class_conf_thr = None
    if args.per_class_confidence_threshold_json:
        with open(args.per_class_confidence_threshold_json) as f:
            per_class_conf_thr = json.load(f)
        print(f"Loaded per-class confidence_threshold overrides for "
              f"{len(per_class_conf_thr)} classes from "
              f"{args.per_class_confidence_threshold_json}")

    per_class_top_k = None
    if args.per_class_top_k_json:
        with open(args.per_class_top_k_json) as f:
            per_class_top_k = json.load(f)
        print(f"Loaded per-class top-K overrides for "
              f"{len(per_class_top_k)} classes from "
              f"{args.per_class_top_k_json}")

    total_instances = 0
    for idx, cat_dir in enumerate(cat_dirs):
        print(f"[{idx+1}/{len(cat_dirs)}] {cat_dir.name}...")
        results = process_category_dir(
            processor, cat_dir, output_dir,
            crop=not args.no_crop,
            clip_components=clip_components,
            device=args.device,
            max_per_class=args.max_per_class,
            min_area_ratio=args.min_area_ratio,
            max_area_ratio=args.max_area_ratio,
            prompt_template=args.prompt_template,
            min_score=args.min_score,
            per_class_min_score=per_class_min_score,
            per_class_prompt=per_class_prompt,
            per_class_confidence_threshold=per_class_conf_thr,
            per_class_top_k=per_class_top_k,
            sample_seed=(None if args.sample_seed == -1 else args.sample_seed),
        )
        total_instances += len(results)
        print(f"  {len(results)} instances segmented")

    print(f"\nDone. Total instances: {total_instances}")


if __name__ == '__main__':
    main()