Caesarrr commited on
Commit
b73b7d0
·
1 Parent(s): a104ac4

feat: gen_task1 v3

Browse files
Files changed (1) hide show
  1. src/action_state/gen_task1.py +121 -95
src/action_state/gen_task1.py CHANGED
@@ -4,9 +4,9 @@
4
  注:{angle}就是 xx degrees, {direction} 就是 clockwise / anticlockwise
5
 
6
  1.
7
- The object in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this object. The direction of rotation is defined from a **top-down bird's-eye view**.
8
 
9
- Please identify the view of the object after the camera rotates {angle} {direction} based on this top-down perspective, and select the correct answer.
10
 
11
  A. <image_start>[image_A]<image_end>
12
  B. <image_start>[image_B]<image_end>
@@ -15,11 +15,11 @@ D. <image_start>[image_D]<image_end>
15
 
16
 
17
  2.
18
- Given the initial view of a static object: <image_start>[image_1]<image_end>.
19
 
20
- Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle} {direction} around the object.
21
 
22
- Which of the following images shows what the object looks like from this new position?
23
 
24
  A. <image_start>[image_A]<image_end>
25
  B. <image_start>[image_B]<image_end>
@@ -36,6 +36,7 @@ import argparse
36
  import numpy as np
37
  from scipy.spatial.transform import Rotation as SciRotation
38
  from tqdm import tqdm
 
39
 
40
  # --- 1. Utils 函数 ---
41
 
@@ -43,29 +44,27 @@ def get_relative_horizontal_rotation_matrix(R1, R2):
43
  """
44
  输入两个旋转矩阵,输出相对 Yaw 角度 (Degree)。
45
  """
46
- # R_rel = R2 @ R1.T
47
  R_rel = R2 @ R1.T
48
-
49
- # 转换为欧拉角提取水平分量 (Y轴)
50
  r = SciRotation.from_matrix(R_rel)
51
  euler_angles = r.as_euler('xyz', degrees=True)
52
  horizontal_rotation = euler_angles[1]
53
-
54
  return horizontal_rotation
55
 
56
  # --- 2. 核心生成类 ---
57
 
58
  class CO3DQuestionGenerator:
59
- def __init__(self, root_path, category):
60
  self.root_path = root_path
61
- # 移除末尾斜杠
62
  if self.root_path.endswith('/'):
63
  self.root_path = self.root_path[:-1]
64
 
65
  self.category = category
 
 
 
 
66
 
67
  # 预加载 annotations
68
- # 假设结构是 root/data/original/category/frame_annotations.json
69
  json_path = os.path.join(root_path, 'data', 'original', category, 'frame_annotations.json')
70
 
71
  if not os.path.exists(json_path):
@@ -76,9 +75,8 @@ class CO3DQuestionGenerator:
76
  with open(json_path, 'r') as f:
77
  self.annotations = json.load(f)
78
 
79
- # 整理数据结构:Sequence -> Frame Dict
80
  self.seq_data = {}
81
-
82
  for item in self.annotations:
83
  seq_name = item['sequence_name']
84
  frame_idx = item['frame_number']
@@ -92,12 +90,6 @@ class CO3DQuestionGenerator:
92
  }
93
 
94
  def format_path(self, raw_path):
95
- """
96
- 处理图片路径:
97
- 1. 移除 root_path 前缀(如果是绝对路径)。
98
- 2. 确保路径以 'data/' 开头。
99
- """
100
- # 1. 处理绝对路径转相对
101
  if raw_path.startswith(self.root_path):
102
  rel_path = raw_path[len(self.root_path):]
103
  if rel_path.startswith('/'):
@@ -105,21 +97,12 @@ class CO3DQuestionGenerator:
105
  else:
106
  rel_path = raw_path
107
 
108
- # 2. 确保以 data/ 开头
109
- # 如果原始 path 是 "motorcycle/...",拼接成 "data/motorcycle/..."
110
- # 如果原始 path 已经是 "data/original/...",则保持不变
111
- if not rel_path.startswith('data/'):
112
- # 这里假设如果不是 data 开头,就需要补全 data/ 前缀
113
- # 注意:这里根据你的需求,如果原始是 motorcycle/xxx,变成 data/motorcycle/xxx
114
- # 如果原始是 original/motorcycle/xxx (比较少见),也会变成 data/original/...
115
- rel_path = os.path.join('data', rel_path)
116
 
117
- return rel_path
118
 
119
  def format_angle_direction(self, angle):
120
- """
121
- 将带符号的角度转换为绝对值角度和方向字符串。
122
- """
123
  angle = (angle + 180) % 360 - 180
124
  direction = "clockwise" if angle > 0 else "anticlockwise"
125
  abs_angle = abs(angle)
@@ -127,35 +110,44 @@ class CO3DQuestionGenerator:
127
 
128
  def verify_angles(self, start_R, target_R, distractor_Rs, min_angle, max_angle, min_interval):
129
  """
130
- 验证生成题目是否符合约束条件
131
  """
132
- # 1. 计算目标角度
133
  target_yaw = get_relative_horizontal_rotation_matrix(start_R, target_R)
134
- abs_target_yaw = abs(target_yaw)
135
 
136
- # 检查目标角度范围
137
- if not (min_angle <= abs_target_yaw <= max_angle):
138
  return False, target_yaw, []
139
 
140
- # 2. 检查干扰项
141
  distractor_yaws = []
142
  for d_R in distractor_Rs:
143
  d_yaw = get_relative_horizontal_rotation_matrix(start_R, d_R)
144
  distractor_yaws.append(d_yaw)
145
-
146
- # 计算干扰项和目标项的角度差 (考虑圆周)
147
- diff = abs(d_yaw - target_yaw)
148
- diff = min(diff, 360 - diff)
149
-
150
- if diff < min_interval:
151
- return False, target_yaw, []
 
 
 
 
 
152
 
 
 
 
 
 
 
 
 
153
  return True, target_yaw, distractor_yaws
154
 
155
  def generate_samples_for_sequence(self, sequence_name, num_samples, min_angle, max_angle, min_interval):
156
- """
157
- 为一个 Sequence 生成指定数量的样本。
158
- """
159
  if sequence_name not in self.seq_data:
160
  return []
161
 
@@ -167,28 +159,25 @@ class CO3DQuestionGenerator:
167
 
168
  generated_samples = []
169
  attempts = 0
170
- max_attempts = num_samples * 20 # 避免死循环
 
171
 
172
  while len(generated_samples) < num_samples and attempts < max_attempts:
173
  attempts += 1
174
 
175
- # 1. 随机选择起始帧
176
  start_idx = random.choice(frame_indices)
177
  start_R = frames_dict[start_idx]['R']
178
 
179
- # 2. 随机选择目标帧
180
  possible_targets = [f for f in frame_indices if f != start_idx]
181
  target_idx = random.choice(possible_targets)
182
  target_R = frames_dict[target_idx]['R']
183
 
184
- # 3. 随机选择干扰项
185
  remaining = [f for f in frame_indices if f != start_idx and f != target_idx]
186
  if len(remaining) < 3: continue
187
 
188
  distractor_indices = random.sample(remaining, 3)
189
  distractor_Rs = [frames_dict[d]['R'] for d in distractor_indices]
190
 
191
- # 4. 验证
192
  is_valid, target_yaw, distractor_yaws = self.verify_angles(
193
  start_R, target_R, distractor_Rs,
194
  min_angle, max_angle, min_interval
@@ -208,18 +197,14 @@ class CO3DQuestionGenerator:
208
 
209
  angle_deg, direction_str = self.format_angle_direction(target_yaw)
210
 
211
- # 获取并格式化路径
212
  img_start = self.format_path(frames_dict[start_idx]['path'])
213
 
214
- # 准备选项数据:(路径, 角度, 是否正确)
215
- # 正确选项
216
  options_data = [{
217
  "path": self.format_path(frames_dict[target_idx]['path']),
218
  "angle": target_yaw,
219
  "is_correct": True
220
  }]
221
 
222
- # 干扰选项
223
  for idx, yaw in zip(distractor_indices, distractor_yaws):
224
  options_data.append({
225
  "path": self.format_path(frames_dict[idx]['path']),
@@ -227,10 +212,8 @@ class CO3DQuestionGenerator:
227
  "is_correct": False
228
  })
229
 
230
- # 打乱选项
231
  random.shuffle(options_data)
232
 
233
- # 构建选项字典和元数据
234
  images_dict = {"image_1": img_start}
235
  option_labels = ['A', 'B', 'C', 'D']
236
  option_angles_meta = {}
@@ -244,24 +227,27 @@ class CO3DQuestionGenerator:
244
  if opt["is_correct"]:
245
  correct_answer_label = label
246
 
247
- # 构建 Question
 
 
 
248
  template_id = random.choice([1, 2])
249
  question = ""
250
  if template_id == 1:
251
- question = f"""The object in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this object. The direction of rotation is defined from a **top-down bird's-eye view**.
252
 
253
- Please identify the view of the object after the camera rotates {angle_deg} degrees {direction_str} based on this top-down perspective, and select the correct answer.
254
 
255
  A. <image_start>[image_A]<image_end>
256
  B. <image_start>[image_B]<image_end>
257
  C. <image_start>[image_C]<image_end>
258
  D. <image_start>[image_D]<image_end>"""
259
  else:
260
- question = f"""Given the initial view of a static object: <image_start>[image_1]<image_end>.
261
 
262
- Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle_deg} degrees {direction_str} around the object.
263
 
264
- Which of the following images shows what the object looks like from this new position?
265
 
266
  A. <image_start>[image_A]<image_end>
267
  B. <image_start>[image_B]<image_end>
@@ -280,69 +266,96 @@ D. <image_start>[image_D]<image_end>"""
280
  "angle_degrees": angle_deg,
281
  "direction": direction_str,
282
  "raw_yaw": target_yaw,
283
- "option_angles": option_angles_meta # 新增:记录每个选项的角度
284
  },
285
  "gt_answer": correct_answer_label
286
  }
287
 
288
- # --- 3. 主程序 ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
 
290
  def main():
291
- parser = argparse.ArgumentParser(description="Generate CO3D Rotation Questions")
292
 
293
- # 路径参数
294
  parser.add_argument("--root_path", type=str, required=True, help="Dataset root path")
295
- parser.add_argument("--output_file", type=str, default="co3d_questions.json", help="Output JSON file path")
 
296
 
297
- # 筛选参数
298
- parser.add_argument("--category", type=str, default=None, help="Specific category (e.g., motorcycle). If None, iterate all.")
299
  parser.add_argument("--num_samples", type=int, default=1, help="Number of samples per sequence")
300
 
301
- # 角度约束参数
302
- parser.add_argument("--min_angle", type=float, default=40.0, help="Minimum rotation angle for correct answer")
303
- parser.add_argument("--max_angle", type=float, default=140.0, help="Maximum rotation angle for correct answer")
304
- parser.add_argument("--min_interval", type=float, default=25.0, help="Minimum angle difference between correct answer and distractors")
305
 
306
- # 随机种子
307
- parser.add_argument("--seed", type=int, default=42, help="Random seed")
 
 
 
 
308
 
309
  args = parser.parse_args()
310
 
311
- # 1. 设置随机种子
 
 
 
 
 
 
312
  random.seed(args.seed)
313
  np.random.seed(args.seed)
314
 
315
- # 2. 确定要处理的 Categories
316
  categories = []
317
  if args.category:
318
  categories = [args.category]
319
  else:
320
- # 自动遍历 root/data/original 下的所有文件夹
321
  data_dir = os.path.join(args.root_path, 'data', 'original')
322
  if os.path.exists(data_dir):
323
  categories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
324
- categories.sort() # 排序保证顺序一致
325
- print(f"Found {len(categories)} categories: {categories}")
326
  else:
327
  print(f"Error: Data directory not found: {data_dir}")
328
  return
329
 
330
  all_results = []
331
 
332
- # 3. 遍历 Category
333
  for cat in categories:
334
- print(f"\nProcessing category: {cat}")
335
- generator = CO3DQuestionGenerator(args.root_path, cat)
336
 
337
  if not hasattr(generator, 'seq_data') or not generator.seq_data:
338
  continue
339
 
340
  sequences = list(generator.seq_data.keys())
341
- sequences.sort() # 排序保证顺序一致
342
 
343
- # 4. 遍历 Sequence
344
- # 使用 tqdm 显示进度
345
- for seq in tqdm(sequences, desc=f"Sequences in {cat}"):
346
  samples = generator.generate_samples_for_sequence(
347
  seq,
348
  args.num_samples,
@@ -352,12 +365,25 @@ def main():
352
  )
353
  all_results.extend(samples)
354
 
355
- # 5. 保存结果
356
  print(f"\nTotal samples generated: {len(all_results)}")
357
- print(f"Saving to {args.output_file}...")
358
- with open(args.output_file, 'w') as f:
359
- json.dump(all_results, f, indent=4)
360
- print("Done.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
  if __name__ == "__main__":
363
  main()
 
4
  注:{angle}就是 xx degrees, {direction} 就是 clockwise / anticlockwise
5
 
6
  1.
7
+ The {object} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {object}. The direction of rotation is defined from a **top-down bird's-eye view**.
8
 
9
+ Please identify the view of the {object} after the camera rotates {angle} {direction} based on this top-down perspective, and select the correct answer.
10
 
11
  A. <image_start>[image_A]<image_end>
12
  B. <image_start>[image_B]<image_end>
 
15
 
16
 
17
  2.
18
+ Given the initial view of a **static** {object}: <image_start>[image_1]<image_end>.
19
 
20
+ Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle} {direction} around the {object}.
21
 
22
+ Which of the following images shows what the {object} looks like from this new position?
23
 
24
  A. <image_start>[image_A]<image_end>
25
  B. <image_start>[image_B]<image_end>
 
36
  import numpy as np
37
  from scipy.spatial.transform import Rotation as SciRotation
38
  from tqdm import tqdm
39
+ import math
40
 
41
  # --- 1. Utils 函数 ---
42
 
 
44
  """
45
  输入两个旋转矩阵,输出相对 Yaw 角度 (Degree)。
46
  """
 
47
  R_rel = R2 @ R1.T
 
 
48
  r = SciRotation.from_matrix(R_rel)
49
  euler_angles = r.as_euler('xyz', degrees=True)
50
  horizontal_rotation = euler_angles[1]
 
51
  return horizontal_rotation
52
 
53
  # --- 2. 核心生成类 ---
54
 
55
  class CO3DQuestionGenerator:
56
+ def __init__(self, root_path, category, image_prefix="data/"):
57
  self.root_path = root_path
 
58
  if self.root_path.endswith('/'):
59
  self.root_path = self.root_path[:-1]
60
 
61
  self.category = category
62
+ self.image_prefix = image_prefix
63
+
64
+ if self.image_prefix and not self.image_prefix.endswith('/'):
65
+ self.image_prefix += '/'
66
 
67
  # 预加载 annotations
 
68
  json_path = os.path.join(root_path, 'data', 'original', category, 'frame_annotations.json')
69
 
70
  if not os.path.exists(json_path):
 
75
  with open(json_path, 'r') as f:
76
  self.annotations = json.load(f)
77
 
78
+ # 整理数据结构
79
  self.seq_data = {}
 
80
  for item in self.annotations:
81
  seq_name = item['sequence_name']
82
  frame_idx = item['frame_number']
 
90
  }
91
 
92
  def format_path(self, raw_path):
 
 
 
 
 
 
93
  if raw_path.startswith(self.root_path):
94
  rel_path = raw_path[len(self.root_path):]
95
  if rel_path.startswith('/'):
 
97
  else:
98
  rel_path = raw_path
99
 
100
+ if self.image_prefix and rel_path.startswith(self.image_prefix):
101
+ return rel_path
 
 
 
 
 
 
102
 
103
+ return os.path.join(self.image_prefix, rel_path)
104
 
105
  def format_angle_direction(self, angle):
 
 
 
106
  angle = (angle + 180) % 360 - 180
107
  direction = "clockwise" if angle > 0 else "anticlockwise"
108
  abs_angle = abs(angle)
 
110
 
111
  def verify_angles(self, start_R, target_R, distractor_Rs, min_angle, max_angle, min_interval):
112
  """
113
+ 验证所有选定帧之间角度互斥性
114
  """
115
+ # 1. 计算 Target 相对于 Start 的角度
116
  target_yaw = get_relative_horizontal_rotation_matrix(start_R, target_R)
 
117
 
118
+ # 检查 Target 是否在合法范围内 (绝对值)
119
+ if not (min_angle <= abs(target_yaw) <= max_angle):
120
  return False, target_yaw, []
121
 
122
+ # 2. 计算所有 Distractors 相对于 Start 的角度
123
  distractor_yaws = []
124
  for d_R in distractor_Rs:
125
  d_yaw = get_relative_horizontal_rotation_matrix(start_R, d_R)
126
  distractor_yaws.append(d_yaw)
127
+
128
+ # 3. 全局互斥检查 (Global Separation Check)
129
+ # 我们需要确保以下集合中任意两个角度之差都 >= min_interval:
130
+ # [Start(0度), Target, Distractor1, Distractor2, Distractor3]
131
+
132
+ all_angles = [0.0, target_yaw] + distractor_yaws
133
+
134
+ # 双重循环检查任意两两组合
135
+ for i in range(len(all_angles)):
136
+ for j in range(i + 1, len(all_angles)):
137
+ angle_a = all_angles[i]
138
+ angle_b = all_angles[j]
139
 
140
+ # 计算圆周上的最小差值
141
+ diff = abs(angle_a - angle_b)
142
+ diff = min(diff, 360 - diff)
143
+
144
+ if diff < min_interval:
145
+ # 只要有一对冲突,该组合即为无效
146
+ return False, target_yaw, []
147
+
148
  return True, target_yaw, distractor_yaws
149
 
150
  def generate_samples_for_sequence(self, sequence_name, num_samples, min_angle, max_angle, min_interval):
 
 
 
151
  if sequence_name not in self.seq_data:
152
  return []
153
 
 
159
 
160
  generated_samples = []
161
  attempts = 0
162
+ # 增加尝试次数,因为全互斥条件比较严格
163
+ max_attempts = num_samples * 5000
164
 
165
  while len(generated_samples) < num_samples and attempts < max_attempts:
166
  attempts += 1
167
 
 
168
  start_idx = random.choice(frame_indices)
169
  start_R = frames_dict[start_idx]['R']
170
 
 
171
  possible_targets = [f for f in frame_indices if f != start_idx]
172
  target_idx = random.choice(possible_targets)
173
  target_R = frames_dict[target_idx]['R']
174
 
 
175
  remaining = [f for f in frame_indices if f != start_idx and f != target_idx]
176
  if len(remaining) < 3: continue
177
 
178
  distractor_indices = random.sample(remaining, 3)
179
  distractor_Rs = [frames_dict[d]['R'] for d in distractor_indices]
180
 
 
181
  is_valid, target_yaw, distractor_yaws = self.verify_angles(
182
  start_R, target_R, distractor_Rs,
183
  min_angle, max_angle, min_interval
 
197
 
198
  angle_deg, direction_str = self.format_angle_direction(target_yaw)
199
 
 
200
  img_start = self.format_path(frames_dict[start_idx]['path'])
201
 
 
 
202
  options_data = [{
203
  "path": self.format_path(frames_dict[target_idx]['path']),
204
  "angle": target_yaw,
205
  "is_correct": True
206
  }]
207
 
 
208
  for idx, yaw in zip(distractor_indices, distractor_yaws):
209
  options_data.append({
210
  "path": self.format_path(frames_dict[idx]['path']),
 
212
  "is_correct": False
213
  })
214
 
 
215
  random.shuffle(options_data)
216
 
 
217
  images_dict = {"image_1": img_start}
218
  option_labels = ['A', 'B', 'C', 'D']
219
  option_angles_meta = {}
 
227
  if opt["is_correct"]:
228
  correct_answer_label = label
229
 
230
+ # --- 修改点:将 object 替换为 category ---
231
+ # 处理 category 名称,去掉下划线,使其更自然 (例如 tv_monitor -> tv monitor)
232
+ cat_name = self.category.replace('_', ' ')
233
+
234
  template_id = random.choice([1, 2])
235
  question = ""
236
  if template_id == 1:
237
+ question = f"""The {cat_name} in the image <image_start>[image_1]<image_end> remains **static**. Imagine a camera rotating around this {cat_name}. The direction of rotation is defined from a **top-down bird's-eye view**.
238
 
239
+ Please identify the view of the {cat_name} after the camera rotates {angle_deg} degrees {direction_str} based on this top-down perspective, and select the correct answer.
240
 
241
  A. <image_start>[image_A]<image_end>
242
  B. <image_start>[image_B]<image_end>
243
  C. <image_start>[image_C]<image_end>
244
  D. <image_start>[image_D]<image_end>"""
245
  else:
246
+ question = f"""Given the initial view of a **static** {cat_name}: <image_start>[image_1]<image_end>.
247
 
248
+ Imagine looking at the setup from a bird's-eye view (from directly above) to determine the direction. Now, move the camera {angle_deg} degrees {direction_str} around the {cat_name}.
249
 
250
+ Which of the following images shows what the {cat_name} looks like from this new position?
251
 
252
  A. <image_start>[image_A]<image_end>
253
  B. <image_start>[image_B]<image_end>
 
266
  "angle_degrees": angle_deg,
267
  "direction": direction_str,
268
  "raw_yaw": target_yaw,
269
+ "option_angles": option_angles_meta
270
  },
271
  "gt_answer": correct_answer_label
272
  }
273
 
274
+ # --- 3. 辅助函数:保存与切分 ---
275
+
276
+ def save_split_data(data_list, output_dir, split_name, max_items):
277
+ if not data_list:
278
+ return
279
+
280
+ split_dir = os.path.join(output_dir, split_name)
281
+ os.makedirs(split_dir, exist_ok=True)
282
+
283
+ num_files = math.ceil(len(data_list) / max_items)
284
+
285
+ print(f"Saving {len(data_list)} items to {split_name} (split into {num_files} files)...")
286
+
287
+ for i in range(num_files):
288
+ start_idx = i * max_items
289
+ end_idx = min((i + 1) * max_items, len(data_list))
290
+ chunk = data_list[start_idx:end_idx]
291
+
292
+ file_name = f"{split_name}_{i+1}.jsonl"
293
+ file_path = os.path.join(split_dir, file_name)
294
+
295
+ with open(file_path, 'w') as f:
296
+ for item in chunk:
297
+ f.write(json.dumps(item) + '\n')
298
+
299
+ # --- 4. 主程序 ---
300
 
301
  def main():
302
+ parser = argparse.ArgumentParser(description="Generate CO3D Rotation Questions (JSONL with Splits)")
303
 
 
304
  parser.add_argument("--root_path", type=str, required=True, help="Dataset root path")
305
+ parser.add_argument("--output_dir", type=str, default="output_dataset", help="Output directory")
306
+ parser.add_argument("--image_prefix", type=str, default="data/", help="Prefix for image paths")
307
 
308
+ parser.add_argument("--category", type=str, default=None, help="Specific category. If None, iterate all.")
 
309
  parser.add_argument("--num_samples", type=int, default=1, help="Number of samples per sequence")
310
 
311
+ parser.add_argument("--min_angle", type=float, default=40.0)
312
+ parser.add_argument("--max_angle", type=float, default=140.0)
313
+ parser.add_argument("--min_interval", type=float, default=25.0)
 
314
 
315
+ parser.add_argument("--train_ratio", type=float, default=0.8)
316
+ parser.add_argument("--val_ratio", type=float, default=0.1)
317
+ parser.add_argument("--test_ratio", type=float, default=0.1)
318
+ parser.add_argument("--max_items", type=int, default=10000)
319
+
320
+ parser.add_argument("--seed", type=int, default=42)
321
 
322
  args = parser.parse_args()
323
 
324
+ total_ratio = args.train_ratio + args.val_ratio + args.test_ratio
325
+ if abs(total_ratio - 1.0) > 1e-5:
326
+ print(f"Warning: Ratios sum to {total_ratio}, not 1.0. They will be normalized.")
327
+ args.train_ratio /= total_ratio
328
+ args.val_ratio /= total_ratio
329
+ args.test_ratio /= total_ratio
330
+
331
  random.seed(args.seed)
332
  np.random.seed(args.seed)
333
 
 
334
  categories = []
335
  if args.category:
336
  categories = [args.category]
337
  else:
 
338
  data_dir = os.path.join(args.root_path, 'data', 'original')
339
  if os.path.exists(data_dir):
340
  categories = [d for d in os.listdir(data_dir) if os.path.isdir(os.path.join(data_dir, d))]
341
+ categories.sort()
342
+ print(f"Found {len(categories)} categories.")
343
  else:
344
  print(f"Error: Data directory not found: {data_dir}")
345
  return
346
 
347
  all_results = []
348
 
 
349
  for cat in categories:
350
+ generator = CO3DQuestionGenerator(args.root_path, cat, args.image_prefix)
 
351
 
352
  if not hasattr(generator, 'seq_data') or not generator.seq_data:
353
  continue
354
 
355
  sequences = list(generator.seq_data.keys())
356
+ sequences.sort()
357
 
358
+ for seq in tqdm(sequences, desc=f"Processing {cat}", leave=False):
 
 
359
  samples = generator.generate_samples_for_sequence(
360
  seq,
361
  args.num_samples,
 
365
  )
366
  all_results.extend(samples)
367
 
 
368
  print(f"\nTotal samples generated: {len(all_results)}")
369
+
370
+ random.shuffle(all_results)
371
+
372
+ n_total = len(all_results)
373
+ n_train = int(n_total * args.train_ratio)
374
+ n_val = int(n_total * args.val_ratio)
375
+
376
+ train_data = all_results[:n_train]
377
+ val_data = all_results[n_train : n_train + n_val]
378
+ test_data = all_results[n_train + n_val :]
379
+
380
+ print(f"Split counts: Train={len(train_data)}, Val={len(val_data)}, Test={len(test_data)}")
381
+
382
+ save_split_data(train_data, args.output_dir, "train", args.max_items)
383
+ save_split_data(val_data, args.output_dir, "val", args.max_items)
384
+ save_split_data(test_data, args.output_dir, "test", args.max_items)
385
+
386
+ print(f"All done. Output saved to {args.output_dir}")
387
 
388
  if __name__ == "__main__":
389
  main()