File size: 3,946 Bytes
4bc78fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Stratified sampling of SenseBench dataset (1000 instances).

Sampling strategy:
- Preserve the original distribution of task types
- Preserve the original distribution of image_count (single/paired)
- Fixed random seed for reproducibility
- Output structure: Perception/{single,paired}, Description/{single,paired}
"""

import json
import random
import shutil
from pathlib import Path
from collections import Counter

SEED = 42
N_SAMPLE = 1000
SRC_DIR = Path("/home/anxiao/zhongchen/Sensebench/data_hf")
DST_DIR = Path("/home/anxiao/zhongchen/Sensebench/codex_code/seleted")


def main():
    random.seed(SEED)

    records = []
    with open(SRC_DIR / "questions.jsonl", encoding="utf-8") as f:
        for line in f:
            records.append(json.loads(line))

    total = len(records)
    print(f"Total records: {total}")

    # Stratify by (task_category, image_count)
    groups = {}
    for r in records:
        meta = r["meta"]
        cat = "Description" if meta["task"] == "description" else "Perception"
        sub = "paired" if meta["image_count"] == "multi" else "single"
        key = (cat, sub)
        groups.setdefault(key, []).append(r)

    print("\nOriginal distribution:")
    for key in sorted(groups):
        print(f"  {key}: {len(groups[key])} ({len(groups[key])/total*100:.1f}%)")

    # Proportional sampling
    sampled = []
    for key in sorted(groups):
        group = groups[key]
        n = max(1, round(len(group) / total * N_SAMPLE))
        sampled.extend(random.sample(group, min(n, len(group))))

    if len(sampled) > N_SAMPLE:
        sampled = random.sample(sampled, N_SAMPLE)
    elif len(sampled) < N_SAMPLE:
        remaining = [r for r in records if r not in sampled]
        sampled.extend(random.sample(remaining, N_SAMPLE - len(sampled)))

    random.shuffle(sampled)

    # Print sampled distribution
    sampled_counter = Counter()
    for r in sampled:
        meta = r["meta"]
        cat = "Description" if meta["task"] == "description" else "Perception"
        sub = "paired" if meta["image_count"] == "multi" else "single"
        sampled_counter[(cat, sub)] += 1

    print(f"\nSampled: {len(sampled)}")
    print("Sampled distribution:")
    for key in sorted(sampled_counter):
        n = sampled_counter[key]
        print(f"  {key}: {n} ({n/len(sampled)*100:.1f}%)")

    # Create subdirs and copy images
    for cat in ["Perception", "Description"]:
        for sub in ["single", "paired"]:
            (DST_DIR / cat / sub).mkdir(parents=True, exist_ok=True)

    copied = set()
    with open(DST_DIR / "questions.jsonl", "w", encoding="utf-8") as f:
        for r in sampled:
            meta = r["meta"]
            cat = "Description" if meta["task"] == "description" else "Perception"
            sub = "paired" if meta["image_count"] == "multi" else "single"

            new_images = []
            for img_rel in r["images"]:
                img_name = Path(img_rel).name
                new_images.append(f"{cat}/{sub}/{img_name}")

                if img_name not in copied:
                    src_img = SRC_DIR / img_rel
                    dst_img = DST_DIR / cat / sub / img_name
                    if src_img.exists() and not dst_img.exists():
                        shutil.copy2(src_img, dst_img)
                    copied.add(img_name)

            r["images"] = new_images
            f.write(json.dumps(r, ensure_ascii=False) + "\n")

    # Stats
    print("\nOutput:")
    total_size = 0
    for cat in ["Perception", "Description"]:
        for sub in ["single", "paired"]:
            d = DST_DIR / cat / sub
            n = len(list(d.iterdir()))
            s = sum(f.stat().st_size for f in d.iterdir()) / (1024**2)
            total_size += s
            print(f"  {cat}/{sub}: {n} images, {s:.1f} MB")
    print(f"  Total: {total_size:.1f} MB")
    print(f"  Seed: {SEED}")
    print(f"\nOutput: {DST_DIR}")


if __name__ == "__main__":
    main()