File size: 8,017 Bytes
f22285b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3fc6c34
 
 
 
 
f22285b
 
3fc6c34
 
f22285b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import json
import glob
import random

# ============================================================
# 설정
# ============================================================
import os
import json
import glob
import random
from collections import defaultdict

# ============================================================
# 설정
# ============================================================
DATA_ROOT = "/data/dataset/vlm_direction/direction_benchmarks/E2E_real_object"
OUTPUT_DIR = "./"

DIRECTION_CLASSES = ["up", "down", "left", "right"]
DIRECTION_OPTIONS = ["Up", "Down", "Left", "Right"]
DIR_TO_LETTER = {"up": "A", "down": "B", "left": "C", "right": "D"}
DIR_TO_LABEL = {"up": "Up", "down": "Down", "left": "Left", "right": "Right"}

random.seed(42)

# ============================================================
# 데이터 수집
# ============================================================
all_samples = []
all_objects = set()

for cls in DIRECTION_CLASSES:
    cls_dir = os.path.join(DATA_ROOT, cls)
    if not os.path.isdir(cls_dir):
        print(f"[WARN] Directory not found: {cls_dir}")
        continue

    videos = sorted(glob.glob(os.path.join(cls_dir, "*.mp4")))
    print(f"{cls}: {len(videos)} videos")

    # 고유명사 → 일반명사 매핑
    OBJ_NAME_MAP = {
        "sophia": "person",
    }

    for video_path in videos:
        filename = os.path.basename(video_path)
        raw_name = os.path.splitext(filename)[0]  # car.mp4 → car
        obj_name = OBJ_NAME_MAP.get(raw_name, raw_name)  # sophia → person
        video_rel = f"{cls}/{filename}"

        all_samples.append({
            "video": video_rel,
            "category": cls,
            "object": obj_name,
        })
        all_objects.add(obj_name)

all_objects = sorted(list(all_objects))
print(f"\nTotal: {len(all_samples)} samples, {len(all_objects)} unique objects")
print(f"Objects: {all_objects}")


# ============================================================
# JSON 생성 함수
# ============================================================
def make_direction_only(samples):
    """조건1: 기본 - object 언급 없이 방향만"""
    question = "In which direction is the object moving in this video?"
    close, open_ = [], []

    for s in samples:
        close.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "options": DIRECTION_OPTIONS,
            "answer": DIR_TO_LETTER[s["category"]],
        })
        open_.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "answer": DIR_TO_LABEL[s["category"]],
        })
    return close, open_


def make_direction_obj_in_q(samples):
    """조건2: 질문에 object 이름 포함"""
    close, open_ = [], []

    for s in samples:
        obj = s["object"]
        question = f"In which direction is the {obj} moving in this video?"
        close.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "options": DIRECTION_OPTIONS,
            "answer": DIR_TO_LETTER[s["category"]],
        })
        open_.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "answer": DIR_TO_LABEL[s["category"]],
        })
    return close, open_


def make_direction_obj_in_a(samples):
    """조건3: 답변에 object 이름 포함"""
    question = "In which direction is the object moving in this video?"
    close, open_ = [], []

    for s in samples:
        obj = s["object"]
        direction = DIR_TO_LABEL[s["category"]]

        # close-ended: 선택지에 object 포함
        options = [f"The {obj} is moving {d.lower()}" for d in DIRECTION_OPTIONS]
        answer_idx = DIRECTION_CLASSES.index(s["category"])
        answer_letter = chr(ord("A") + answer_idx)

        close.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "options": options,
            "answer": answer_letter,
        })
        open_.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "answer": f"The {obj} is moving {direction.lower()}",
        })
    return close, open_


def make_direction_obj_in_qa(samples):
    """조건4: 질문+답변 모두 object 이름 포함"""
    close, open_ = [], []

    for s in samples:
        obj = s["object"]
        direction = DIR_TO_LABEL[s["category"]]
        question = f"In which direction is the {obj} moving in this video?"

        options = [f"The {obj} is moving {d.lower()}" for d in DIRECTION_OPTIONS]
        answer_idx = DIRECTION_CLASSES.index(s["category"])
        answer_letter = chr(ord("A") + answer_idx)

        close.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "options": options,
            "answer": answer_letter,
        })
        open_.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "answer": f"The {obj} is moving {direction.lower()}",
        })
    return close, open_


def make_object_recognition(samples, all_objects):
    """조건5: object 종류 맞추기"""
    question = "What is the object moving in this video?"
    close, open_ = [], []

    for s in samples:
        obj = s["object"]
        obj_cap = obj.capitalize()

        # close-ended: 정답 + 랜덤 3개 오답 (중복 없이)
        distractors = [o for o in all_objects if o != obj]
        chosen = random.sample(distractors, min(3, len(distractors)))
        options_raw = [obj] + chosen
        random.shuffle(options_raw)
        options = [o.capitalize() for o in options_raw]
        answer_letter = chr(ord("A") + options_raw.index(obj))

        close.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "options": options,
            "answer": answer_letter,
        })
        open_.append({
            "video": s["video"], "category": s["category"],
            "question": question,
            "answer": obj_cap,
        })
    return close, open_


# ============================================================
# 생성 & 저장
# ============================================================
CONDITIONS = {
    "direction_only":     lambda s: make_direction_only(s),
    "direction_obj_in_q": lambda s: make_direction_obj_in_q(s),
    "direction_obj_in_a": lambda s: make_direction_obj_in_a(s),
    "direction_obj_in_qa": lambda s: make_direction_obj_in_qa(s),
    "object_recognition": lambda s: make_object_recognition(s, all_objects),
}

for cond_name, gen_fn in CONDITIONS.items():
    # 셔플된 복사본 사용
    shuffled = all_samples.copy()
    random.shuffle(shuffled)

    close_data, open_data = gen_fn(shuffled)

    # ID 부여
    for i, d in enumerate(close_data):
        d["id"] = i
    for i, d in enumerate(open_data):
        d["id"] = i

    # 저장
    close_path = os.path.join(OUTPUT_DIR, f"{cond_name}_close_ended.json")
    open_path = os.path.join(OUTPUT_DIR, f"{cond_name}_open_ended.json")

    with open(close_path, "w") as f:
        json.dump(close_data, f, indent=2, ensure_ascii=False)
    with open(open_path, "w") as f:
        json.dump(open_data, f, indent=2, ensure_ascii=False)

    print(f"\n[{cond_name}]")
    print(f"  close: {len(close_data)}{close_path}")
    print(f"  open:  {len(open_data)}{open_path}")
    # 샘플 출력
    print(f"  sample close: Q={close_data[0]['question']}")
    print(f"                options={close_data[0].get('options', 'N/A')}")
    print(f"                answer={close_data[0]['answer']}")
    print(f"  sample open:  Q={open_data[0]['question']}")
    print(f"                answer={open_data[0]['answer']}")

print(f"\n=== All done! {len(CONDITIONS) * 2} JSON files saved to {OUTPUT_DIR} ===")