yunfengwang commited on
Commit
0f0f196
·
verified ·
1 Parent(s): 7bbdfc0

Upload scripts/prepare_all_data.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/prepare_all_data.py +474 -0
scripts/prepare_all_data.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 一站式数据准备脚本。
3
+
4
+ 自动完成:
5
+ 1. 下载 COCO 2017 检测数据(val 子集,约 5K 图,~1GB)
6
+ 2. 生成预训练 grounding 数据(JSONL)
7
+ 3. 生成 Counting 冷启动数据(基于 COCO)
8
+ 4. 生成 Spatial Reasoning 数据(CLEVR 风格,纯程序生成)
9
+ 5. 调用 maze / path 生成脚本
10
+
11
+ 用法:
12
+ python scripts/prepare_all_data.py --output_dir data --coco_split val
13
+ """
14
+
15
+ import os
16
+ import sys
17
+ import json
18
+ import argparse
19
+ import random
20
+ import math
21
+ from pathlib import Path
22
+ from typing import List, Tuple
23
+ from collections import defaultdict
24
+
25
+ from PIL import Image, ImageDraw, ImageFont
26
+ from tqdm import tqdm
27
+
28
+ PROJECT_ROOT = Path(__file__).resolve().parent.parent
29
+ sys.path.insert(0, str(PROJECT_ROOT))
30
+
31
+
32
+ IRREGULAR_PLURALS = {
33
+ "person": "people",
34
+ "mouse": "mice",
35
+ "sheep": "sheep",
36
+ "knife": "knives",
37
+ "child": "children",
38
+ }
39
+
40
+
41
+ def pluralize(word: str) -> str:
42
+ """Simple English pluralization for COCO category names."""
43
+ low = word.lower()
44
+ if low in IRREGULAR_PLURALS:
45
+ return IRREGULAR_PLURALS[low]
46
+ if " " in word:
47
+ parts = word.rsplit(" ", 1)
48
+ return parts[0] + " " + pluralize(parts[1])
49
+ if word.endswith(("s", "sh", "ch", "x", "z")):
50
+ return word + "es"
51
+ if word.endswith("y") and word[-2] not in "aeiou":
52
+ return word[:-1] + "ies"
53
+ return word + "s"
54
+
55
+ from model.special_tokens import normalize_coordinate
56
+
57
+
58
+ def parse_args():
59
+ parser = argparse.ArgumentParser()
60
+ parser.add_argument("--output_dir", type=str, default="data")
61
+ parser.add_argument("--coco_split", type=str, default="val", choices=["train", "val"])
62
+ parser.add_argument("--coco_subset", type=int, default=5000, help="最多使用多少张 COCO 图片")
63
+ parser.add_argument("--num_counting", type=int, default=2000, help="生成 counting 样本数")
64
+ parser.add_argument("--num_spatial", type=int, default=2000, help="生成 spatial 样本数")
65
+ parser.add_argument("--num_maze", type=int, default=5000, help="生成 maze 样本数")
66
+ parser.add_argument("--num_path", type=int, default=3000, help="生成 path tracing 样本数")
67
+ parser.add_argument("--seed", type=int, default=42)
68
+ return parser.parse_args()
69
+
70
+
71
+ # ---------------------------------------------------------------------------
72
+ # 1. COCO 下载 & 导出
73
+ # ---------------------------------------------------------------------------
74
+
75
+ def download_coco(output_dir: Path, split: str = "val", max_images: int = 5000):
76
+ """使用 datasets 库下载 COCO,导出为图片+标注文件。"""
77
+ try:
78
+ from datasets import load_dataset
79
+ except ImportError:
80
+ print("请先安装 datasets: pip install datasets")
81
+ sys.exit(1)
82
+
83
+ print(f"正在下载 COCO 2017 {split} ...")
84
+ ds = load_dataset("detection-datasets/coco", split=split, streaming=True)
85
+
86
+ img_dir = output_dir / "coco" / split / "images"
87
+ img_dir.mkdir(parents=True, exist_ok=True)
88
+ ann_path = output_dir / "coco" / split / "annotations.json"
89
+
90
+ annotations = {"images": [], "annotations": [], "categories": []}
91
+ category_map = {}
92
+ cat_counter = 1
93
+
94
+ count = 0
95
+ for sample in tqdm(ds, desc="COCO download"):
96
+ if count >= max_images:
97
+ break
98
+ # sample keys: image, image_id, width, height, objects
99
+ img = sample["image"]
100
+ img_id = sample.get("image_id", count)
101
+ w, h = sample.get("width", img.width), sample.get("height", img.height)
102
+
103
+ img_path = img_dir / f"{img_id:012d}.jpg"
104
+ img.save(img_path)
105
+
106
+ annotations["images"].append({
107
+ "id": img_id,
108
+ "file_name": img_path.name,
109
+ "width": w,
110
+ "height": h,
111
+ })
112
+
113
+ objects = sample.get("objects", {})
114
+ bboxes = objects.get("bbox", [])
115
+ labels = objects.get("category", [])
116
+ for bbox, label in zip(bboxes, labels):
117
+ if label not in category_map:
118
+ category_map[label] = cat_counter
119
+ annotations["categories"].append({
120
+ "id": cat_counter,
121
+ "name": str(label),
122
+ })
123
+ cat_counter += 1
124
+ annotations["annotations"].append({
125
+ "id": len(annotations["annotations"]) + 1,
126
+ "image_id": img_id,
127
+ "category_id": category_map[label],
128
+ "bbox": bbox, # [x1, y1, x2, y2]
129
+ })
130
+ count += 1
131
+
132
+ with open(ann_path, "w") as f:
133
+ json.dump(annotations, f)
134
+ print(f"COCO 导出完成: {img_dir} ({count} 张图), 标注: {ann_path}")
135
+ return img_dir, ann_path, annotations
136
+
137
+
138
+ # ---------------------------------------------------------------------------
139
+ # 2. 预训练 Grounding 数据
140
+ # ---------------------------------------------------------------------------
141
+
142
+ def generate_pretrain_data(annotations: dict, output_path: Path):
143
+ """从 COCO 标注生成 grounding JSONL。"""
144
+ output_path.parent.mkdir(parents=True, exist_ok=True)
145
+ # 按图分组
146
+ img_anns = defaultdict(list)
147
+ for ann in annotations["annotations"]:
148
+ img_anns[ann["image_id"]].append(ann)
149
+
150
+ cats = {c["id"]: c["name"] for c in annotations["categories"]}
151
+
152
+ records = []
153
+ for img_info in annotations["images"]:
154
+ img_id = img_info["id"]
155
+ W, H = img_info["width"], img_info["height"]
156
+ anns = img_anns.get(img_id, [])
157
+ if not anns:
158
+ continue
159
+ # 按类别分组
160
+ by_cat = defaultdict(list)
161
+ for ann in anns:
162
+ cat_name = cats[ann["category_id"]]
163
+ x1, y1, x2, y2 = ann["bbox"] # HuggingFace COCO: [x1,y1,x2,y2]
164
+ x1 = max(0.0, min(x1, W))
165
+ y1 = max(0.0, min(y1, H))
166
+ x2 = max(0.0, min(x2, W))
167
+ y2 = max(0.0, min(y2, H))
168
+ box = (
169
+ normalize_coordinate(x1, W),
170
+ normalize_coordinate(y1, H),
171
+ normalize_coordinate(x2, W),
172
+ normalize_coordinate(y2, H),
173
+ )
174
+ by_cat[cat_name].append(box)
175
+
176
+ for cat_name, boxes in by_cat.items():
177
+ records.append({
178
+ "image": str(Path("images") / img_info["file_name"]),
179
+ "label": cat_name,
180
+ "boxes": boxes,
181
+ "points": [],
182
+ "normalized": True,
183
+ })
184
+
185
+ with open(output_path, "w", encoding="utf-8") as f:
186
+ for rec in records:
187
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
188
+ print(f"预训练 grounding 数据: {len(records)} 条 -> {output_path}")
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # 3. Counting 冷启动数据(基于 COCO)
193
+ # ---------------------------------------------------------------------------
194
+
195
+ def generate_counting_thinking(category: str, boxes: List[Tuple[int, int, int, int]], count: int) -> str:
196
+ """程序生成 Counting 的 thinking 内容(统一模板:与 grounding 格式一致)。"""
197
+ lines = []
198
+ lines.append("1. **Analyzing the request**")
199
+ lines.append(f"The user asks me to count the {category} in this image.")
200
+ lines.append("2. **Object grounding**")
201
+ box_strs = []
202
+ for x1, y1, x2, y2 in boxes:
203
+ box_strs.append(f"[{x1},{y1},{x2},{y2}]")
204
+ lines.append(f"I see {count} instance(s) of <|ref|>{category}<|/ref|><|box|>[{','.join(box_strs)}]<|/box|>.")
205
+ lines.append("3. **Conclusion**")
206
+ lines.append(f"There are {count} {category} in this image.")
207
+ return "\n".join(lines)
208
+
209
+
210
+ def generate_counting_data(annotations: dict, output_path: Path, num_samples: int):
211
+ """从 COCO 生成 counting 数据。"""
212
+ from utils.coco_categories import COCO_CATS, get_category_name
213
+
214
+ output_path.parent.mkdir(parents=True, exist_ok=True)
215
+ img_anns = defaultdict(list)
216
+ for ann in annotations["annotations"]:
217
+ img_anns[ann["image_id"]].append(ann)
218
+ cats = {c["id"]: c["name"] for c in annotations["categories"]}
219
+
220
+ # 筛选出实例数 >=2 的图
221
+ candidates = []
222
+ for img_info in annotations["images"]:
223
+ img_id = img_info["id"]
224
+ W, H = img_info["width"], img_info["height"]
225
+ anns = img_anns.get(img_id, [])
226
+ by_cat = defaultdict(list)
227
+ for ann in anns:
228
+ raw_name = cats[ann["category_id"]]
229
+ cat_name = get_category_name(raw_name)
230
+ x1, y1, x2, y2 = ann["bbox"] # HuggingFace COCO: [x1,y1,x2,y2]
231
+ x1 = max(0.0, min(x1, W))
232
+ y1 = max(0.0, min(y1, H))
233
+ x2 = max(0.0, min(x2, W))
234
+ y2 = max(0.0, min(y2, H))
235
+ box = (
236
+ normalize_coordinate(x1, W),
237
+ normalize_coordinate(y1, H),
238
+ normalize_coordinate(x2, W),
239
+ normalize_coordinate(y2, H),
240
+ )
241
+ by_cat[cat_name].append(box)
242
+ for cat_name, boxes in by_cat.items():
243
+ if len(boxes) >= 2:
244
+ candidates.append((img_info, cat_name, boxes))
245
+
246
+ random.shuffle(candidates)
247
+ candidates = candidates[:num_samples]
248
+
249
+ records = []
250
+ templates = [
251
+ "How many {category} are in this image?",
252
+ "How many {category} are in the image?",
253
+ "How many {plural} are in this image?",
254
+ "How many {plural} are in the image?",
255
+ "Count the number of {category}.",
256
+ "Count the number of {plural}.",
257
+ "Count the {plural} in the image.",
258
+ "Count all {plural} in this image.",
259
+ "What is the total count of {category}?",
260
+ "What is the total count of {plural}?",
261
+ "How many {plural} can you see?",
262
+ "How many {plural} are there in the image?",
263
+ ]
264
+ for img_info, cat_name, boxes in candidates:
265
+ plural_name = pluralize(cat_name)
266
+ question = random.choice(templates).format(category=cat_name, plural=plural_name)
267
+ thinking = generate_counting_thinking(cat_name, boxes, len(boxes))
268
+ records.append({
269
+ "image": str(Path("images") / img_info["file_name"]),
270
+ "question": question,
271
+ "thinking": thinking,
272
+ "count": len(boxes),
273
+ "boxes": boxes,
274
+ })
275
+
276
+ with open(output_path, "w", encoding="utf-8") as f:
277
+ for rec in records:
278
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
279
+ print(f"Counting 数据: {len(records)} 条 -> {output_path}")
280
+
281
+
282
+ # ---------------------------------------------------------------------------
283
+ # 4. Spatial Reasoning 数据(CLEVR 风格,程序生成)
284
+ # ---------------------------------------------------------------------------
285
+
286
+ def generate_clevr_image(size: int = 400) -> Image.Image:
287
+ """生成一张 CLEVR 风格的简单几何体图片。"""
288
+ img = Image.new("RGB", (size, size), "lightgray")
289
+ draw = ImageDraw.Draw(img)
290
+ colors = ["red", "blue", "green", "yellow", "purple", "cyan", "brown", "gray"]
291
+ shapes = ["circle", "rectangle", "triangle"]
292
+ materials = ["metal", "rubber"]
293
+ objects = []
294
+
295
+ num_objs = random.randint(3, 6)
296
+ for _ in range(num_objs):
297
+ obj_w = random.randint(30, 80)
298
+ obj_h = random.randint(30, 80)
299
+ x = random.randint(10, size - obj_w - 10)
300
+ y = random.randint(10, size - obj_h - 10)
301
+ color = random.choice(colors)
302
+ shape = random.choice(shapes)
303
+ material = random.choice(materials)
304
+
305
+ if shape == "circle":
306
+ draw.ellipse([x, y, x + obj_w, y + obj_h], fill=color, outline="black")
307
+ elif shape == "rectangle":
308
+ draw.rectangle([x, y, x + obj_w, y + obj_h], fill=color, outline="black")
309
+ else:
310
+ # triangle
311
+ draw.polygon([(x + obj_w // 2, y), (x, y + obj_h), (x + obj_w, y + obj_h)], fill=color, outline="black")
312
+
313
+ # normalized bbox
314
+ nx1 = normalize_coordinate(x, size)
315
+ ny1 = normalize_coordinate(y, size)
316
+ nx2 = normalize_coordinate(x + obj_w, size)
317
+ ny2 = normalize_coordinate(y + obj_h, size)
318
+ objects.append({
319
+ "shape": shape,
320
+ "color": color,
321
+ "material": material,
322
+ "bbox": [nx1, ny1, nx2, ny2],
323
+ })
324
+ return img, objects
325
+
326
+
327
+ def generate_spatial_question(objects: List[dict], img_path: Path) -> dict:
328
+ """基于生成物体生成空间推理问题和答案。"""
329
+ if len(objects) < 2:
330
+ return None
331
+
332
+ # 简化: 只使用 attribute 问题类型
333
+ q_type = "attribute"
334
+
335
+ # 选一个目标物体
336
+ target = random.choice(objects)
337
+ target_color = target["color"]
338
+ target_shape = target["shape"]
339
+ target_mat = target["material"]
340
+
341
+ question = f"Is there a {target_color} {target_mat} {target_shape}?"
342
+ answer = "Yes"
343
+
344
+ # 构建 thinking
345
+ lines = []
346
+ lines.append("1. **Analyzing the request**")
347
+ lines.append(f"The user asks if there is a {target_color} {target_mat} {target_shape}.")
348
+ lines.append("2. **Object grounding**")
349
+ for obj in objects:
350
+ c = obj["color"]
351
+ s = obj["shape"]
352
+ m = obj["material"]
353
+ b = obj["bbox"]
354
+ lines.append(f"I see a <|ref|>{c} {m} {s}<|/ref|><|box|>[[{b[0]},{b[1]},{b[2]},{b[3]}]]<|/box|>.")
355
+ lines.append("3. **Conclusion**")
356
+ lines.append(f"Since there is a {target_color} {target_mat} {target_shape}, the answer is Yes.")
357
+ thinking = "\n".join(lines)
358
+
359
+ return {
360
+ "image": str(img_path),
361
+ "question": question,
362
+ "thinking": thinking,
363
+ "answer": answer,
364
+ "boxes": [target["bbox"]],
365
+ "points": [],
366
+ }
367
+
368
+
369
+ def generate_spatial_data(output_dir: Path, num_samples: int):
370
+ output_dir.mkdir(parents=True, exist_ok=True)
371
+ img_dir = output_dir / "images"
372
+ img_dir.mkdir(exist_ok=True)
373
+
374
+ records = []
375
+ for i in range(num_samples):
376
+ img, objects = generate_clevr_image(size=400)
377
+ img_path = img_dir / f"spatial_{i:06d}.png"
378
+ img.save(img_path)
379
+
380
+ rec = generate_spatial_question(objects, img_path.relative_to(output_dir))
381
+ if rec:
382
+ records.append(rec)
383
+
384
+ with open(output_dir / "spatial_data.jsonl", "w", encoding="utf-8") as f:
385
+ for rec in records:
386
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
387
+ print(f"Spatial 数据: {len(records)} 条 -> {output_dir}")
388
+
389
+
390
+ # ---------------------------------------------------------------------------
391
+ # 5. 调用 maze / path 生成
392
+ # ---------------------------------------------------------------------------
393
+
394
+ def call_maze_generation(output_dir: Path, num_samples: int):
395
+ import subprocess
396
+ cmd = [
397
+ sys.executable, str(PROJECT_ROOT / "scripts" / "generate_maze_data.py"),
398
+ "--output_dir", str(output_dir),
399
+ "--num_samples", str(num_samples),
400
+ ]
401
+ print(f"运行: {' '.join(cmd)}")
402
+ subprocess.run(cmd, check=True)
403
+
404
+
405
+ def call_path_generation(output_dir: Path, num_samples: int):
406
+ import subprocess
407
+ cmd = [
408
+ sys.executable, str(PROJECT_ROOT / "scripts" / "generate_path_data.py"),
409
+ "--output_dir", str(output_dir),
410
+ "--num_samples", str(num_samples),
411
+ ]
412
+ print(f"运行: {' '.join(cmd)}")
413
+ subprocess.run(cmd, check=True)
414
+
415
+
416
+ # ---------------------------------------------------------------------------
417
+ # Main
418
+ # ---------------------------------------------------------------------------
419
+
420
+ def main():
421
+ args = parse_args()
422
+ random.seed(args.seed)
423
+
424
+ output_dir = Path(args.output_dir)
425
+ output_dir.mkdir(parents=True, exist_ok=True)
426
+
427
+ # 1. COCO
428
+ coco_img_dir, coco_ann_path, annotations = download_coco(
429
+ output_dir / "coco" / args.coco_split,
430
+ split=args.coco_split,
431
+ max_images=args.coco_subset,
432
+ )
433
+
434
+ # 2. 预训练 grounding
435
+ generate_pretrain_data(
436
+ annotations,
437
+ output_dir / "pretrain" / "grounding.jsonl",
438
+ )
439
+ # 创建符号链接或复制 images
440
+ pretrain_img_dir = output_dir / "pretrain" / "images"
441
+ pretrain_img_dir.mkdir(parents=True, exist_ok=True)
442
+ # 这里直接写入相对路径,训练时 image_root 指向 coco/val/images
443
+
444
+ # 3. Counting
445
+ generate_counting_data(
446
+ annotations,
447
+ output_dir / "sft" / "counting" / "counting_data.jsonl",
448
+ num_samples=args.num_counting,
449
+ )
450
+
451
+ # 4. Spatial
452
+ generate_spatial_data(
453
+ output_dir / "sft" / "spatial",
454
+ num_samples=args.num_spatial,
455
+ )
456
+
457
+ # 5. Maze
458
+ call_maze_generation(output_dir / "sft" / "maze", args.num_maze)
459
+
460
+ # 6. Path
461
+ call_path_generation(output_dir / "sft" / "path", args.num_path)
462
+
463
+ print("\n========================================")
464
+ print("所有数据准备完成!")
465
+ print(f"预训练数据: {output_dir / 'pretrain' / 'grounding.jsonl'}")
466
+ print(f"Counting: {output_dir / 'sft' / 'counting'}")
467
+ print(f"Spatial: {output_dir / 'sft' / 'spatial'}")
468
+ print(f"Maze: {output_dir / 'sft' / 'maze'}")
469
+ print(f"Path: {output_dir / 'sft' / 'path'}")
470
+ print("========================================")
471
+
472
+
473
+ if __name__ == "__main__":
474
+ main()