leeibo commited on
Commit
7cc0a4e
·
verified ·
1 Parent(s): 47652a2

Support chunk-level conversion with 24 workers by default

Browse files
Files changed (3) hide show
  1. scripts/USAGE.md +110 -107
  2. scripts/convert_dataset.py +354 -296
  3. scripts/test_pipeline.py +72 -72
scripts/USAGE.md CHANGED
@@ -1,108 +1,111 @@
1
- # TraceSpatial-Trace 转换与上传
2
-
3
- 这套脚本把已有 RGB + QA 数据转换为 HF Dataset Viewer 可直接浏览的 Parquet。它不是 RoboTracer 上游数据生成或训练代码。
4
-
5
- ## 环境
6
-
7
- 本机已安装环境 `tracespatial-hf`。在 Miniforge Prompt 中执行:
8
-
9
- ```powershell
10
- conda activate tracespatial-hf
11
- cd C:\Users\lee\Desktop\TraceSpatial-release-work\release\scripts
12
- ```
13
-
14
- 其他机器在本目录运行:
15
-
16
- ```powershell
17
- conda env create -f environment.yml
18
- conda activate tracespatial-hf
19
- ```
20
-
21
- 已有 Python 3.11 环境也可用 `python -m pip install -r requirements.txt`。不需要 CUDA/GPU。
22
-
23
- ## 小样本验证
24
-
25
- ```powershell
26
- python convert_dataset.py --input "C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace" --output "C:\Users\lee\Desktop\TraceSpatial-preview-build" --workers 5 --limit-records 8 --verify-images
27
- ```
28
-
29
- 每个来源取前 8 条原始记录,然后拆出全部 QA。`preview` 仅是演示子集,不是统计随机样本或测试集。
30
-
31
- ## 全量多进程转换
32
-
33
- ```powershell
34
- python convert_dataset.py --input "C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace" --output "C:\Users\lee\Desktop\TraceSpatial-full-release" --workers 5 --shard-mib 512 --row-group-mib 32
35
- ```
36
-
37
- - 原始 `images/` 和 `metadata/` 不修改。只读取被 QA 引用的 RGB 图像。
38
- - 一个来源一个进程,本数据包最多 5 个并发进程。增加到 8 不会超过 5 个来源的并行度。
39
- - 每行独立包含 RGB、问题、答案、type、source、task、id、qa_index、record_index。
40
- - `record_index` 是原始 JSON 数组中的位置。重复 id 不去重,也不丢失问答。
41
- - 保留原始图像字节,不重编码;保留原始 QA 字符串;缺失 type 留 null。
42
- - 严格检查单图引用、配对角色与文本类型;遇到缺图或格式错误会报错,不静默跳过。
43
- - `--verify-images` 可额外对所有引用图像解码校验,代价是更长运行时间。
44
- - 512 MiB 指近似未压缩内容阈值,实际 Parquet 大小取决于压缩;分片在整条原始记录结束后切分,单条超大记录可能超过阈值。
45
- - 每个 row group 约 32 MiB,最多 128 行,单张图片上限 64 MiB。Arrow 的编码缓冲会额外占内存,建议从 3–5 个进程开始。
46
- - 每行嵌入图像,逻辑内容量会因重复图像超过原始包;字典编码与 Zstd 减少行组内重复。不要把 189.6 GB 原始大小当作发布文件大小。
47
-
48
- ## 中断与续跑
49
-
50
- 原命令再次执行即可。每个完整分片写入 `.state/<source>.json` 后才算完成;已完成分片会校验 SHA-256 并跳过,不完整分片重新写入。恢复时仍需流式跳过 JSON 前面的记录。
51
-
52
- 保持原始图片不变。恢复身份会检查 JSON 路径、大小、mtime、脚本哈希和转换参数,但不会给 50 多万张原始图片逐一建立内容快照。原图或元数据、转换参数、代码发生变化时,应使用新的输出目录。改变 `--workers` 不改变数据,可以用于调整并发。
53
-
54
- `.state/conversion.log` 保存来源级进度;终端显示逐分片进度。Windows 后台启动示例:
55
-
56
- ```powershell
57
- Start-Process -FilePath "$env:CONDA_PREFIX\python.exe" -ArgumentList @('convert_dataset.py', '--input', '"C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace"', '--output', '"C:\Users\lee\Desktop\TraceSpatial-full-release"', '--workers', '5') -WorkingDirectory (Get-Location).Path -WindowStyle Hidden -RedirectStandardOutput '..\conversion.stdout.log' -RedirectStandardError '..\conversion.stderr.log'
58
- ```
59
-
60
- 只在没有其他转换进程使用同一输出目录时启动;脚本还会通过文件锁阻止并发写入。
61
-
62
- ## 上传
63
-
64
- 先登录,不要将 token 写入脚本:
65
-
66
- ```powershell
67
- hf auth login
68
- hf auth whoami
69
- ```
70
-
71
- 先校验文件和展示计划(无网络写入):
72
-
73
- ```powershell
74
- python upload_dataset.py --folder "C:\Users\lee\Desktop\TraceSpatial-full-release" --repo-id leeibo/TraceSpatial-Trace --workers 4
75
- ```
76
-
77
- 正式上传:
78
-
79
- ```powershell
80
- python upload_dataset.py --folder "C:\Users\lee\Desktop\TraceSpatial-full-release" --repo-id leeibo/TraceSpatial-Trace --workers 4 --execute
81
- ```
82
-
83
- 默认使用当前 `upload_folder` + `hf_xet` 的并发、分批提交与续传实现。`--workers` 默认控制本地 SHA-256 并行验证;现代上传路径的网络并发由 SDK/Xet 管理。必须安装 requirements 中的 hf-xet。
84
-
85
- 如需明确控制 SDK 上传 worker 数,可以额外指定 `--legacy-workers`:它使用当前仍可用但上游已弃用的 `upload_large_folder(num_workers=...)`。默认不采用该兼容模式。
86
-
87
- 重复上传命令可恢复未完成上传,不要启动多个上传进程。`.state/upload.log` 保存状态,HF 的缓存用于恢复。不会删除远端文件;不会更改现有仓库的公开/私有状态;不存在的仓库以私有方式创建。上传前需要完整 manifest,并校验全部分片;上传后检查远端大小以及可用的 LFS SHA-256。
88
-
89
- **注意:当 SDK 分批���交时,中途失败可能已提交部分文件。完成并通过末尾验证后才算整次上传成功。** 此时再重新运行即可。脚本不会自动付费升级存储或切换仓库可见性。
90
-
91
- ## 输出结构
92
-
93
- ```text
94
- release/
95
- README.md
96
- manifest.json
97
- data/agibot/train-00000.parquet
98
- data/ca1m/...
99
- data/droid/...
100
- data/robotwin/...
101
- data/scannet/...
102
- scripts/
103
- .state/ # 本地检查点与日志,不上传
104
- ```
105
-
106
- README 由 `README.template.md` 加上实际转换规模和 HF configs 生成。完整转换提供 `all` 和五个来源配置;小样本转换提供 `preview` 和各来源配置。
107
-
 
 
 
108
  全量完成不等于立即公开。许可证仍需维护者确定。私有仓库的 Viewer 能否显示取决于 HF 账户能力;原始上传和已授权用户的下载不等同于在线 Viewer 支持。
 
1
+ # TraceSpatial-Trace 转换与上传
2
+
3
+ 这套脚本把已有 RGB + QA 数据转换为 HF Dataset Viewer 可直接浏览的 Parquet。它不是 RoboTracer 上游数据生成或训练代码。
4
+
5
+ ## 环境
6
+
7
+ 本机已安装环境 `tracespatial-hf`。在 Miniforge Prompt 中执行:
8
+
9
+ ```powershell
10
+ conda activate tracespatial-hf
11
+ cd C:\Users\lee\Desktop\TraceSpatial-release-work\release\scripts
12
+ ```
13
+
14
+ 其他机器在本目录运行:
15
+
16
+ ```powershell
17
+ conda env create -f environment.yml
18
+ conda activate tracespatial-hf
19
+ ```
20
+
21
+ 已有 Python 3.11 环境也可用 `python -m pip install -r requirements.txt`。不需要 CUDA/GPU。
22
+
23
+ ## 小样本验证
24
+
25
+ ```powershell
26
+ python convert_dataset.py --input "C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace" --output "C:\Users\lee\Desktop\TraceSpatial-parallel-preview-v2" --workers 24 --chunk-records 4 --limit-records 64 --verify-images
27
+ ```
28
+
29
+ 每个来源取前 64 条原始记录,然后拆出全部 QA。`preview` 仅是演示子集,不是统计随机样本或测试集。
30
+
31
+ ## 全量多进程转换(v2)
32
+
33
+ v2 的工作块/检查点与旧版不兼容,请使用新的输出目录,不要把旧版 v1 输出作为 v2 续跑目录。`--chunk-records` 控制任务粒度,默认 2048 条原始记录;小样本测试可设为 4,让多个进程也能同时处理同一来源。
34
+
35
+
36
+ ```powershell
37
+ python convert_dataset.py --input "C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace" --output "C:\Users\lee\Desktop\TraceSpatial-full-release-v2" --workers 24 --chunk-records 2048 --shard-mib 512 --row-group-mib 32
38
+ ```
39
+
40
+ - 原始 `images/` 和 `metadata/` 不修改。只读取被 QA 引用的 RGB 图像。
41
+ - 先将各来源 JSON 流式拆为 JSONL 工作块,再由共享进程池动态领取;同一来源可以同时由多个进程转换,不再有五进程上限。默认最多 24 个进程,也可指定 `--workers 32`。本机 32 个逻辑处理器、约 128 GB 内存,已实测 24 个进程参与处理。
42
+ - 每行独立包含 RGB、问题、答案、type、source、task、id、qa_index、record_index。
43
+ - `record_index` 是原始 JSON 数组中的位置。重复 id 不去重,也不丢失问答。
44
+ - 保留原始图像字节,不重编码;保留原始 QA 字符串;缺失 type 留 null。
45
+ - 严格检查单图引用、配对角色与文本类型;遇到缺图或格式错误会报错,不静默跳过。
46
+ - `--verify-images` 可额外对所有引用图像解码校验,代价是更长运行时间。
47
+ - 512 MiB 指近似未压缩内容阈值,实际 Parquet 大小取决于压缩;分片在整条原始记录结束后切分,单条超大记录可能超过阈值。
48
+ - 每个 row group 约 32 MiB,最多 128 行,单张图片上限 64 MiB。Arrow 的编码缓冲会额外占内存,24 进程时行组缓冲会成倍增加;磁盘吞吐也会影响加速比。
49
+ - 每行嵌入图像,逻辑内容量会因重复图像超过原始包;字典编码与 Zstd 减少行组内重复。不要把 189.6 GB 原始大小当作发布文件大小。
50
+
51
+ ## 中断与续跑
52
+
53
+ 原命令再次执行即可。每个完整分片写入 `.state/<source>-<chunk_id>.json` 后才算完成;已完成分片会校验 SHA-256 并跳过,不完整分片重新写入。拆块结果保存在 `.state/chunks/`,首次准备阶段按来源顺序流式读取 JSON,只保存标注、不复制图片。后续恢复复用工作块,仅在未完成块内跳过已经处理的记录;JSONL 块会额外占用数 GB 磁盘空间。
54
+
55
+ 保持原始图片不变。恢复身份会检查 JSON 路径、大小、mtime、脚本哈希和转换参数,但不会给 50 多万张原始图片逐一建立内容快照。原图或元数据、转换参数、代码发生变化时,应使用新的输出目录。改变 `--workers` 不改变数据,可以用于调整并发。
56
+
57
+ `.state/conversion.log` 保存块级进度;终端显示逐分片进度。Windows 后台启动示例:
58
+
59
+ ```powershell
60
+ Start-Process -FilePath "$env:CONDA_PREFIX\python.exe" -ArgumentList @('convert_dataset.py', '--input', '"C:\Users\lee\Desktop\TraceSpatial-Trace\TraceSpatial-Trace"', '--output', '"C:\Users\lee\Desktop\TraceSpatial-full-release-v2"', '--workers', '24') -WorkingDirectory (Get-Location).Path -WindowStyle Hidden -RedirectStandardOutput '..\conversion.stdout.log' -RedirectStandardError '..\conversion.stderr.log'
61
+ ```
62
+
63
+ 只在没有其他转换进程使用同一输出目录时启动;脚本还会通过文件锁阻止并发写入。
64
+
65
+ ## 上传
66
+
67
+ 先登录,不要将 token 写入脚本:
68
+
69
+ ```powershell
70
+ hf auth login
71
+ hf auth whoami
72
+ ```
73
+
74
+ 先校验文件和展示计划(无网络写入):
75
+
76
+ ```powershell
77
+ python upload_dataset.py --folder "C:\Users\lee\Desktop\TraceSpatial-full-release-v2" --repo-id leeibo/TraceSpatial-Trace --workers 4
78
+ ```
79
+
80
+ 正式上传:
81
+
82
+ ```powershell
83
+ python upload_dataset.py --folder "C:\Users\lee\Desktop\TraceSpatial-full-release-v2" --repo-id leeibo/TraceSpatial-Trace --workers 4 --execute
84
+ ```
85
+
86
+ 默认使用当前 `upload_folder` + `hf_xet` 的并发、分批提交与续传实现。`--workers` 默认控制本地 SHA-256 并行验证;现代上传路径的网络并发由 SDK/Xet 管理。必须安装 requirements 中的 hf-xet。
87
+
88
+ 如需明确控制 SDK 上传 worker 数,可以额外指定 `--legacy-workers`:它使用当前仍可用但上游已弃用的 `upload_large_folder(num_workers=...)`。默认不采用该兼容模式。
89
+
90
+ 重复上传命令可恢复未完成上传,不要启动多个上传进程。`.state/upload.log` 保存状态,HF 的缓存用于恢复。不会删除远端文件;不会更改现有仓库的公开/私有状态;不存在的仓库以私有方式创建。上传前需要完整 manifest,并校验全部分片;上传后检查远端大小以及可用的 LFS SHA-256。
91
+
92
+ **注意:当 SDK 分批提交时,中途失败可能已提交部分文件。完成并通过末尾验证后才算整次上传成功。** 此时再重新运行即可。脚本不会自动付费升级存储或切换仓库可见性。
93
+
94
+ ## 输出结构
95
+
96
+ ```text
97
+ release/
98
+ README.md
99
+ manifest.json
100
+ data/agibot/train-00000-000.parquet
101
+ data/ca1m/...
102
+ data/droid/...
103
+ data/robotwin/...
104
+ data/scannet/...
105
+ scripts/
106
+ .state/ # 本地检查点与日志,不上传
107
+ ```
108
+
109
+ README 由 `README.template.md` 加上实际转换规模和 HF configs 生成。完整转换提供 `all` 和五个来源配置;小样本转换提供 `preview` 和各来源配置。
110
+
111
  全量完成不等于立即公开。许可证仍需维护者确定。私有仓库的 Viewer 能否显示取决于 HF 账户能力;原始上传和已授权用户的下载不等同于在线 Viewer 支持。
scripts/convert_dataset.py CHANGED
@@ -1,297 +1,355 @@
1
- """Stream original JSON into image-embedded QA Parquet, one process per source."""
2
- import argparse
3
- import ast
4
- from collections import Counter
5
- from concurrent.futures import ProcessPoolExecutor, as_completed
6
- import hashlib
7
- import io
8
- import json
9
- import logging
10
- import multiprocessing
11
- import os
12
- from pathlib import Path
13
- import re
14
- import shutil
15
- import sys
16
-
17
- import ijson
18
- import pyarrow as pa
19
- import pyarrow.parquet as pq
20
- from datasets import Features, Image, Value
21
- from filelock import FileLock
22
- from PIL import Image as PILImage
23
- import yaml
24
-
25
- VERSION = 1
26
- FIELDS = Features({'image': Image(), 'question': Value('string'), 'answer': Value('string'),
27
- 'type': Value('string'), 'source': Value('string'), 'task': Value('string'),
28
- 'id': Value('string'), 'qa_index': Value('int32'), 'record_index': Value('int64')})
29
- SCHEMA = FIELDS.arrow_schema
30
-
31
-
32
- def sha256(path):
33
- h = hashlib.sha256()
34
- with Path(path).open('rb') as f:
35
- for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
36
- h.update(block)
37
- return h.hexdigest()
38
-
39
-
40
- def save_json(path, value):
41
- path = Path(path)
42
- tmp = path.with_suffix(path.suffix + '.tmp')
43
- tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
44
- os.replace(tmp, path)
45
-
46
-
47
- def infer_task(question, answer):
48
- """Conservative derived label; never rewrite or execute answer text."""
49
- if len(answer) > 100000:
50
- return None
51
- try:
52
- points = ast.literal_eval(answer)
53
- if not isinstance(points, (list, tuple)) or not points:
54
- return None
55
- if any(not isinstance(p, (list, tuple)) or len(p) not in (2, 3) for p in points):
56
- return None
57
- dims = {len(p) for p in points}
58
- if len(dims) != 1 or any(not isinstance(v, (int, float)) or isinstance(v, bool) for p in points for v in p):
59
- return None
60
- except (ValueError, SyntaxError, TypeError, RecursionError):
61
- return None
62
- q = re.sub(r'\b([23])\s+d\b', r'\1d', question.lower())
63
- if re.search(r'\blift(?:ing)?\b', q) and '2d' in q and '3d' in q and dims == {3}:
64
- return '2d_to_3d'
65
- if dims == {2} and '2d' in q:
66
- return '2d_trace'
67
- if dims == {3} and '3d' in q and '2d' not in q:
68
- return '3d_trace'
69
- return None
70
-
71
-
72
- def resolve_image(root, name):
73
- # Input release uses flat image names. Do not accept traversal or absolute paths.
74
- if not isinstance(name, str) or '/' in name or '\\' in name or name in ('', '.', '..'):
75
- raise ValueError(f'Expected flat image filename: {name!r}')
76
- candidates = [name] if ':' not in name else [name.replace(':', '_')]
77
- for candidate in candidates:
78
- path = (root / candidate).resolve()
79
- if path.parent == root and path.is_file():
80
- return path
81
- raise FileNotFoundError(f'RGB image missing: {name}')
82
-
83
-
84
- def convert_source(job):
85
- source, metadata, images, out, opts = job
86
- metadata, images, out = Path(metadata), Path(images), Path(out)
87
- pa.set_cpu_count(1) # prevent each process spawning another CPU-sized thread pool
88
- dest = out / 'data' / source
89
- dest.mkdir(parents=True, exist_ok=True)
90
- state_path = out / '.state' / f'{source}.json'
91
- stat = metadata.stat()
92
- identity = {'version': VERSION, 'script_sha256': sha256(__file__), 'metadata': str(metadata),
93
- 'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns,
94
- 'images': str(images), 'options': opts}
95
- if state_path.exists():
96
- state = json.loads(state_path.read_text(encoding='utf-8'))
97
- if state['identity'] != identity:
98
- raise RuntimeError(f'{source}: input/options/code changed; use a new output directory')
99
- for item in state['files']:
100
- path = out / item['path']
101
- if not path.is_file() or path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']:
102
- raise RuntimeError(f'{source}: completed shard changed: {path}')
103
- if state['complete']:
104
- print(f'{source}: resume verified, already complete', flush=True)
105
- return state
106
- else:
107
- state = {'identity': identity, 'source': source, 'complete': False, 'next_record': 0,
108
- 'qa_rows': 0, 'mapped_image_records': 0, 'task_counts': {}, 'type_counts': {}, 'files': []}
109
- save_json(state_path, state)
110
- writer = None
111
- pending, pending_size, shard_size, shard_rows = [], 0, 0, 0
112
- tasks, types = Counter(state['task_counts']), Counter(state['type_counts'])
113
- processed, total_rows = state['next_record'], state['qa_rows']
114
- mapped = state['mapped_image_records']
115
- target = opts['shard_mib'] * 1024**2
116
- group_target = opts['row_group_mib'] * 1024**2
117
- shard_path = None
118
- tmp = None
119
-
120
- def flush_group():
121
- nonlocal pending, pending_size, writer, shard_path, tmp
122
- if not pending:
123
- return
124
- if writer is None:
125
- shard_path = dest / f'train-{len(state["files"]):05d}.parquet'
126
- tmp = shard_path.with_suffix('.parquet.incomplete')
127
- writer = pq.ParquetWriter(tmp, SCHEMA, compression='zstd', compression_level=3,
128
- use_dictionary=True, dictionary_pagesize_limit=16*1024**2)
129
- writer.write_table(pa.Table.from_pylist(pending, schema=SCHEMA), row_group_size=len(pending))
130
- pending, pending_size = [], 0
131
-
132
- def finish_shard():
133
- nonlocal writer, shard_rows, shard_size
134
- flush_group()
135
- if writer is None:
136
- return
137
- writer.close()
138
- writer = None
139
- assert pq.ParquetFile(tmp).metadata.num_rows == shard_rows
140
- os.replace(tmp, shard_path)
141
- state['files'].append({'path': shard_path.relative_to(out).as_posix(),
142
- 'rows': shard_rows, 'bytes': shard_path.stat().st_size,
143
- 'sha256': sha256(shard_path)})
144
- state.update(next_record=processed, qa_rows=total_rows, mapped_image_records=mapped,
145
- task_counts=dict(tasks), type_counts=dict(types))
146
- save_json(state_path, state)
147
- print(f'{source}: {processed:,} records / {total_rows:,} QA; committed {shard_path.name}', flush=True)
148
- shard_rows, shard_size = 0, 0
149
-
150
- try:
151
- with metadata.open('rb') as fp:
152
- for record_index, record in enumerate(ijson.items(fp, 'item')):
153
- if opts['limit_records'] and record_index >= opts['limit_records']:
154
- break
155
- if record_index < state['next_record']:
156
- continue
157
- refs = record.get('image')
158
- conv = record.get('conversations')
159
- if not isinstance(refs, list) or len(refs) != 1:
160
- raise ValueError(f'{source}[{record_index}]: expected exactly one RGB reference')
161
- if not isinstance(conv, list) or not conv or len(conv) % 2:
162
- raise ValueError(f'{source}[{record_index}]: invalid conversation length')
163
- path = resolve_image(images, refs[0])
164
- blob = path.read_bytes()
165
- if len(blob) > 64 * 1024**2:
166
- raise ValueError(f'Image exceeds 64 MiB memory guard: {path}')
167
- if opts['verify_images']:
168
- with PILImage.open(io.BytesIO(blob)) as im:
169
- im.verify()
170
- mapped += path.name != refs[0]
171
- kind = record.get('type')
172
- if kind is not None and not isinstance(kind, str):
173
- raise ValueError(f'{source}[{record_index}]: non-string type')
174
- if not isinstance(record.get('id'), str):
175
- raise ValueError(f'{source}[{record_index}]: non-string id')
176
- types[kind if kind is not None else '(missing)'] += 1
177
- for offset in range(0, len(conv), 2):
178
- q, a = conv[offset:offset+2]
179
- if q.get('from') != 'human' or a.get('from') != 'gpt':
180
- raise ValueError(f'{source}[{record_index}]: nonalternating roles')
181
- question, answer = q['value'], a['value']
182
- if not isinstance(question, str) or not isinstance(answer, str):
183
- raise ValueError('QA text must be strings')
184
- task = infer_task(question, answer)
185
- tasks[task or '(unknown)'] += 1
186
- row = {'image': {'bytes': blob, 'path': path.name}, 'question': question,
187
- 'answer': answer, 'type': kind, 'source': source, 'task': task,
188
- 'id': record['id'], 'qa_index': offset//2, 'record_index': record_index}
189
- size = len(blob) + len(question.encode('utf-8')) + len(answer.encode('utf-8')) + 256
190
- if pending and (pending_size + size > group_target or len(pending) >= 128):
191
- flush_group()
192
- pending.append(row)
193
- pending_size += size
194
- shard_size += size
195
- shard_rows += 1
196
- total_rows += 1
197
- processed = record_index + 1
198
- # Checkpoint only at whole-record boundaries, preserving conversation groups.
199
- if shard_size >= target:
200
- finish_shard()
201
- finish_shard()
202
- state.update(complete=True, next_record=processed, qa_rows=total_rows,
203
- mapped_image_records=mapped, task_counts=dict(tasks), type_counts=dict(types))
204
- save_json(state_path, state)
205
- return state
206
- except BaseException:
207
- if writer is not None:
208
- writer.close()
209
- raise
210
-
211
-
212
- def write_card(out, manifest):
213
- template = Path(__file__).with_name('README.template.md').read_text(encoding='utf-8')
214
- configs = []
215
- if manifest['limited']:
216
- configs.append({'config_name': 'preview', 'default': True,
217
- 'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
218
- else:
219
- configs.append({'config_name': 'all', 'default': True,
220
- 'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
221
- for source in manifest['sources']:
222
- configs.append({'config_name': source, 'data_files': [{'split': 'train', 'path': f'data/{source}/*.parquet'}]})
223
- metadata = {'language': ['en'], 'pretty_name': 'TraceSpatial-Trace',
224
- 'task_categories': ['visual-question-answering'],
225
- 'tags': ['robotics', 'spatial-reasoning', 'trajectory', 'arxiv:2512.13660'], 'configs': configs}
226
- if manifest['limited']:
227
- status = f"This is a **preview** containing {manifest['qa_rows']:,} QA rows from {manifest['records']:,} original records. Full local-corpus counts are shown below; those are not the size of this preview."
228
- else:
229
- status = f"This conversion contains **{manifest['qa_rows']:,} QA rows** from **{manifest['records']:,} original records** across {len(manifest['sources'])} sources."
230
- text = template.replace('@@STATUS@@', status).replace('@@CONFIG@@', 'preview' if manifest['limited'] else 'all')
231
- (out/'README.md').write_text('---\n'+yaml.safe_dump(metadata, sort_keys=False)+'---\n\n'+text, encoding='utf-8')
232
-
233
-
234
- def main():
235
- p = argparse.ArgumentParser(description=__doc__)
236
- p.add_argument('--input', type=Path, required=True, help='Directory containing images/ and metadata/')
237
- p.add_argument('--output', type=Path, required=True, help='New release directory; repeat to resume')
238
- p.add_argument('--workers', type=int, default=min(5, os.cpu_count() or 1))
239
- p.add_argument('--shard-mib', type=int, default=512, help='Approximate uncompressed bytes; finish whole record before splitting')
240
- p.add_argument('--row-group-mib', type=int, default=32)
241
- p.add_argument('--limit-records', type=int, default=0, help='Per-source record limit; 0 means all')
242
- p.add_argument('--verify-images', action='store_true', help='Decode/verify every referenced image; slower')
243
- args = p.parse_args()
244
- if min(args.workers, args.shard_mib, args.row_group_mib) < 1 or args.limit_records < 0:
245
- p.error('worker/size arguments must be positive and limit nonnegative')
246
- root, out = args.input.resolve(), args.output.resolve()
247
- if out == root or root in out.parents:
248
- p.error('Output must be separate from the input dataset')
249
- files = sorted((root/'metadata').glob('*.json'))
250
- if not files or not (root/'images').is_dir():
251
- p.error('Input needs metadata/*.json and images/')
252
- sources = [f.name.split('_')[0] for f in files]
253
- if len(sources) != len(set(sources)):
254
- p.error('Multiple metadata files share a source label')
255
- out.mkdir(parents=True, exist_ok=True)
256
- (out/'.state').mkdir(exist_ok=True)
257
- logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s',
258
- handlers=[logging.StreamHandler(), logging.FileHandler(out/'.state'/'conversion.log', encoding='utf-8')])
259
- opts = {k: getattr(args, k) for k in ('shard_mib','row_group_mib','limit_records','verify_images')}
260
- with FileLock(out/'.state'/'convert.lock', timeout=0):
261
- plan = {'sources': sources, 'input': str(root), 'options': opts, 'script_sha256':sha256(__file__)}
262
- plan_path = out/'.state'/'plan.json'
263
- if plan_path.exists() and json.loads(plan_path.read_text(encoding='utf-8')) != plan:
264
- raise RuntimeError('Output belongs to another conversion; use a fresh directory')
265
- save_json(plan_path, plan)
266
- jobs = [(s, str(f), str((root/'images').resolve()), str(out), opts) for s,f in zip(sources,files)]
267
- results = {}
268
- with ProcessPoolExecutor(max_workers=min(args.workers,len(jobs)), mp_context=multiprocessing.get_context('spawn')) as pool:
269
- futures = {pool.submit(convert_source,j):j[0] for j in jobs}
270
- for future in as_completed(futures):
271
- source = futures[future]
272
- try:
273
- results[source] = future.result()
274
- logging.info('%s complete: %s QA rows', source, results[source]['qa_rows'])
275
- except BaseException:
276
- for f in futures: f.cancel()
277
- logging.exception('%s failed; completed shards remain resumable', source)
278
- raise
279
- results = {s:results[s] for s in sorted(results)}
280
- manifest = {'version':VERSION, 'complete':True, 'limited':bool(args.limit_records),
281
- 'sources':list(results), 'records':sum(r['next_record'] for r in results.values()),
282
- 'qa_rows':sum(r['qa_rows'] for r in results.values()),
283
- 'files':[item for r in results.values() for item in r['files']],
284
- 'source_statistics': {s:{k:r[k] for k in ('next_record','qa_rows','mapped_image_records','task_counts','type_counts')} for s,r in results.items()}}
285
- write_card(out,manifest)
286
- script_dest = out/'scripts'
287
- script_dest.mkdir(exist_ok=True)
288
- for f in Path(__file__).parent.iterdir():
289
- if f.is_file() and f.suffix in ('.py','.md','.txt','.yml') and f.resolve() != (script_dest/f.name).resolve():
290
- shutil.copy2(f,script_dest/f.name)
291
- save_json(out/'manifest.json', manifest) # publish only after all sources succeed
292
- logging.info('COMPLETE: %s QA rows, %s shards',manifest['qa_rows'],len(manifest['files']))
293
-
294
-
295
- if __name__ == '__main__':
296
- multiprocessing.freeze_support()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  main()
 
1
+ """Stream original JSON into image-embedded QA Parquet, many dynamically scheduled record chunks per source."""
2
+ import argparse
3
+ import ast
4
+ from collections import Counter
5
+ from concurrent.futures import ProcessPoolExecutor, as_completed
6
+ import hashlib
7
+ import io
8
+ import json
9
+ import logging
10
+ import multiprocessing
11
+ import os
12
+ from pathlib import Path
13
+ import re
14
+ import shutil
15
+ import sys
16
+
17
+ import ijson
18
+ import pyarrow as pa
19
+ import pyarrow.parquet as pq
20
+ from datasets import Features, Image, Value
21
+ from filelock import FileLock
22
+ from PIL import Image as PILImage
23
+ import yaml
24
+
25
+ VERSION = 2
26
+ FIELDS = Features({'image': Image(), 'question': Value('string'), 'answer': Value('string'),
27
+ 'type': Value('string'), 'source': Value('string'), 'task': Value('string'),
28
+ 'id': Value('string'), 'qa_index': Value('int32'), 'record_index': Value('int64')})
29
+ SCHEMA = FIELDS.arrow_schema
30
+
31
+
32
+ def sha256(path):
33
+ h = hashlib.sha256()
34
+ with Path(path).open('rb') as f:
35
+ for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
36
+ h.update(block)
37
+ return h.hexdigest()
38
+
39
+
40
+ def save_json(path, value):
41
+ path = Path(path)
42
+ tmp = path.with_suffix(path.suffix + '.tmp')
43
+ tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
44
+ os.replace(tmp, path)
45
+
46
+
47
+ def infer_task(question, answer):
48
+ """Conservative derived label; never rewrite or execute answer text."""
49
+ if len(answer) > 100000:
50
+ return None
51
+ try:
52
+ points = ast.literal_eval(answer)
53
+ if not isinstance(points, (list, tuple)) or not points:
54
+ return None
55
+ if any(not isinstance(p, (list, tuple)) or len(p) not in (2, 3) for p in points):
56
+ return None
57
+ dims = {len(p) for p in points}
58
+ if len(dims) != 1 or any(not isinstance(v, (int, float)) or isinstance(v, bool) for p in points for v in p):
59
+ return None
60
+ except (ValueError, SyntaxError, TypeError, RecursionError):
61
+ return None
62
+ q = re.sub(r'\b([23])\s+d\b', r'\1d', question.lower())
63
+ if re.search(r'\blift(?:ing)?\b', q) and '2d' in q and '3d' in q and dims == {3}:
64
+ return '2d_to_3d'
65
+ if dims == {2} and '2d' in q:
66
+ return '2d_trace'
67
+ if dims == {3} and '3d' in q and '2d' not in q:
68
+ return '3d_trace'
69
+ return None
70
+
71
+
72
+ def resolve_image(root, name):
73
+ # Input release uses flat image names. Do not accept traversal or absolute paths.
74
+ if not isinstance(name, str) or '/' in name or '\\' in name or name in ('', '.', '..'):
75
+ raise ValueError(f'Expected flat image filename: {name!r}')
76
+ candidates = [name] if ':' not in name else [name.replace(':', '_')]
77
+ for candidate in candidates:
78
+ path = (root / candidate).resolve()
79
+ if path.parent == root and path.is_file():
80
+ return path
81
+ raise FileNotFoundError(f'RGB image missing: {name}')
82
+
83
+
84
+ def convert_source(job):
85
+ source, metadata, images, out, opts, chunk_id, start_index = job
86
+ metadata, images, out = Path(metadata), Path(images), Path(out)
87
+ pa.set_cpu_count(1) # prevent each process spawning another CPU-sized thread pool
88
+ dest = out / 'data' / source
89
+ dest.mkdir(parents=True, exist_ok=True)
90
+ state_path = out / '.state' / f'{source}-{chunk_id:05d}.json'
91
+ stat = metadata.stat()
92
+ identity = {'version': VERSION, 'script_sha256': sha256(__file__), 'metadata': str(metadata),
93
+ 'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns,
94
+ 'images': str(images), 'options': opts, 'chunk_id': chunk_id, 'start_index': start_index}
95
+ if state_path.exists():
96
+ state = json.loads(state_path.read_text(encoding='utf-8'))
97
+ if state['identity'] != identity:
98
+ raise RuntimeError(f'{source}: input/options/code changed; use a new output directory')
99
+ for item in state['files']:
100
+ path = out / item['path']
101
+ if not path.is_file() or path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']:
102
+ raise RuntimeError(f'{source}: completed shard changed: {path}')
103
+ if state['complete']:
104
+ print(f'{source}: resume verified, already complete', flush=True)
105
+ return state
106
+ else:
107
+ state = {'identity': identity, 'source': source, 'complete': False, 'next_record': 0,
108
+ 'worker_pid': os.getpid(), 'chunk_id': chunk_id, 'qa_rows': 0, 'mapped_image_records': 0, 'task_counts': {}, 'type_counts': {}, 'files': []}
109
+ save_json(state_path, state)
110
+ writer = None
111
+ pending, pending_size, shard_size, shard_rows = [], 0, 0, 0
112
+ tasks, types = Counter(state['task_counts']), Counter(state['type_counts'])
113
+ processed, total_rows = state['next_record'], state['qa_rows']
114
+ mapped = state['mapped_image_records']
115
+ target = opts['shard_mib'] * 1024**2
116
+ group_target = opts['row_group_mib'] * 1024**2
117
+ shard_path = None
118
+ tmp = None
119
+
120
+ def flush_group():
121
+ nonlocal pending, pending_size, writer, shard_path, tmp
122
+ if not pending:
123
+ return
124
+ if writer is None:
125
+ shard_path = dest / f'train-{chunk_id:05d}-{len(state["files"]):03d}.parquet'
126
+ tmp = shard_path.with_suffix('.parquet.incomplete')
127
+ writer = pq.ParquetWriter(tmp, SCHEMA, compression='zstd', compression_level=3,
128
+ use_dictionary=True, dictionary_pagesize_limit=16*1024**2)
129
+ writer.write_table(pa.Table.from_pylist(pending, schema=SCHEMA), row_group_size=len(pending))
130
+ pending, pending_size = [], 0
131
+
132
+ def finish_shard():
133
+ nonlocal writer, shard_rows, shard_size
134
+ flush_group()
135
+ if writer is None:
136
+ return
137
+ writer.close()
138
+ writer = None
139
+ assert pq.ParquetFile(tmp).metadata.num_rows == shard_rows
140
+ os.replace(tmp, shard_path)
141
+ state['files'].append({'path': shard_path.relative_to(out).as_posix(),
142
+ 'rows': shard_rows, 'bytes': shard_path.stat().st_size,
143
+ 'sha256': sha256(shard_path)})
144
+ state.update(next_record=processed, qa_rows=total_rows, mapped_image_records=mapped,
145
+ task_counts=dict(tasks), type_counts=dict(types))
146
+ save_json(state_path, state)
147
+ print(f'{source}: {processed:,} records / {total_rows:,} QA; committed {shard_path.name}', flush=True)
148
+ shard_rows, shard_size = 0, 0
149
+
150
+ try:
151
+ with metadata.open('r', encoding='utf-8') as fp:
152
+ for local_index, line in enumerate(fp):
153
+ if local_index < state['next_record']:
154
+ continue
155
+ record = json.loads(line)
156
+ record_index = start_index + local_index
157
+ refs = record.get('image')
158
+ conv = record.get('conversations')
159
+ if not isinstance(refs, list) or len(refs) != 1:
160
+ raise ValueError(f'{source}[{record_index}]: expected exactly one RGB reference')
161
+ if not isinstance(conv, list) or not conv or len(conv) % 2:
162
+ raise ValueError(f'{source}[{record_index}]: invalid conversation length')
163
+ path = resolve_image(images, refs[0])
164
+ blob = path.read_bytes()
165
+ if len(blob) > 64 * 1024**2:
166
+ raise ValueError(f'Image exceeds 64 MiB memory guard: {path}')
167
+ if opts['verify_images']:
168
+ with PILImage.open(io.BytesIO(blob)) as im:
169
+ im.verify()
170
+ mapped += path.name != refs[0]
171
+ kind = record.get('type')
172
+ if kind is not None and not isinstance(kind, str):
173
+ raise ValueError(f'{source}[{record_index}]: non-string type')
174
+ if not isinstance(record.get('id'), str):
175
+ raise ValueError(f'{source}[{record_index}]: non-string id')
176
+ types[kind if kind is not None else '(missing)'] += 1
177
+ for offset in range(0, len(conv), 2):
178
+ q, a = conv[offset:offset+2]
179
+ if q.get('from') != 'human' or a.get('from') != 'gpt':
180
+ raise ValueError(f'{source}[{record_index}]: nonalternating roles')
181
+ question, answer = q['value'], a['value']
182
+ if not isinstance(question, str) or not isinstance(answer, str):
183
+ raise ValueError('QA text must be strings')
184
+ task = infer_task(question, answer)
185
+ tasks[task or '(unknown)'] += 1
186
+ row = {'image': {'bytes': blob, 'path': path.name}, 'question': question,
187
+ 'answer': answer, 'type': kind, 'source': source, 'task': task,
188
+ 'id': record['id'], 'qa_index': offset//2, 'record_index': record_index}
189
+ size = len(blob) + len(question.encode('utf-8')) + len(answer.encode('utf-8')) + 256
190
+ if pending and (pending_size + size > group_target or len(pending) >= 128):
191
+ flush_group()
192
+ pending.append(row)
193
+ pending_size += size
194
+ shard_size += size
195
+ shard_rows += 1
196
+ total_rows += 1
197
+ processed = local_index + 1
198
+ # Checkpoint only at whole-record boundaries, preserving conversation groups.
199
+ if shard_size >= target:
200
+ finish_shard()
201
+ finish_shard()
202
+ state.update(complete=True, next_record=processed, qa_rows=total_rows,
203
+ mapped_image_records=mapped, task_counts=dict(tasks), type_counts=dict(types))
204
+ save_json(state_path, state)
205
+ return state
206
+ except BaseException:
207
+ if writer is not None:
208
+ writer.close()
209
+ raise
210
+
211
+
212
+ def write_card(out, manifest):
213
+ template = Path(__file__).with_name('README.template.md').read_text(encoding='utf-8')
214
+ configs = []
215
+ if manifest['limited']:
216
+ configs.append({'config_name': 'preview', 'default': True,
217
+ 'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
218
+ else:
219
+ configs.append({'config_name': 'all', 'default': True,
220
+ 'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
221
+ for source in manifest['sources']:
222
+ configs.append({'config_name': source, 'data_files': [{'split': 'train', 'path': f'data/{source}/*.parquet'}]})
223
+ metadata = {'language': ['en'], 'pretty_name': 'TraceSpatial-Trace',
224
+ 'task_categories': ['visual-question-answering'],
225
+ 'tags': ['robotics', 'spatial-reasoning', 'trajectory', 'arxiv:2512.13660'], 'configs': configs}
226
+ if manifest['limited']:
227
+ status = f"This is a **preview** containing {manifest['qa_rows']:,} QA rows from {manifest['records']:,} original records. Full local-corpus counts are shown below; those are not the size of this preview."
228
+ else:
229
+ status = f"This conversion contains **{manifest['qa_rows']:,} QA rows** from **{manifest['records']:,} original records** across {len(manifest['sources'])} sources."
230
+ text = template.replace('@@STATUS@@', status).replace('@@CONFIG@@', 'preview' if manifest['limited'] else 'all')
231
+ (out/'README.md').write_text('---\n'+yaml.safe_dump(metadata, sort_keys=False)+'---\n\n'+text, encoding='utf-8')
232
+
233
+
234
+ def prepare_chunks(files, sources, out, options):
235
+ """One streaming pass creates immutable, reusable work chunks (no RGB copy)."""
236
+ index_path = out/'.state'/'chunks'/'index.json'
237
+ if index_path.exists():
238
+ chunks = json.loads(index_path.read_text(encoding='utf-8'))
239
+ for c in chunks:
240
+ path = Path(c['path'])
241
+ if not path.is_file() or sha256(path) != c['sha256']:
242
+ raise RuntimeError(f'Prepared JSONL chunk changed: {path}')
243
+ return chunks
244
+ chunks = []
245
+ for source, metadata in zip(sources, files):
246
+ directory = index_path.parent/source
247
+ directory.mkdir(parents=True, exist_ok=True)
248
+ batch, start, chunk_id = [], 0, 0
249
+ def emit():
250
+ nonlocal batch, start, chunk_id
251
+ path = directory/f'chunk-{chunk_id:05d}.jsonl'
252
+ tmp = path.with_suffix('.jsonl.tmp')
253
+ with tmp.open('w', encoding='utf-8', newline='\n') as fp:
254
+ for record in batch:
255
+ fp.write(json.dumps(record, ensure_ascii=False)+'\n')
256
+ os.replace(tmp, path)
257
+ chunks.append({'source':source, 'path':str(path), 'chunk_id':chunk_id,
258
+ 'start_index':start, 'records':len(batch), 'sha256':sha256(path)})
259
+ start += len(batch)
260
+ chunk_id += 1
261
+ batch = []
262
+ with metadata.open('rb') as fp:
263
+ for index, row in enumerate(ijson.items(fp, 'item')):
264
+ if options['limit_records'] and index >= options['limit_records']:
265
+ break
266
+ batch.append({key:row.get(key) for key in ('id','image','conversations','type')})
267
+ if len(batch) >= options['chunk_records']:
268
+ emit()
269
+ if (index+1) % 50000 == 0:
270
+ logging.info('%s: prepared %s original records',source,index+1)
271
+ if batch: emit()
272
+ if start == 0: raise ValueError(f'Empty metadata: {metadata}')
273
+ logging.info('%s: prepared %s chunks / %s records',source,chunk_id,start)
274
+ save_json(index_path,chunks)
275
+ return chunks
276
+
277
+
278
+ def main():
279
+ p = argparse.ArgumentParser(description=__doc__)
280
+ p.add_argument('--input', type=Path, required=True, help='Directory containing images/ and metadata/')
281
+ p.add_argument('--output', type=Path, required=True, help='New release directory; repeat to resume')
282
+ p.add_argument('--workers', type=int, default=min(24, os.cpu_count() or 1))
283
+ p.add_argument('--chunk-records', type=int, default=2048, help='Original records per independent work chunk; shared across all workers')
284
+ p.add_argument('--shard-mib', type=int, default=512, help='Approximate uncompressed bytes; finish whole record before splitting')
285
+ p.add_argument('--row-group-mib', type=int, default=32)
286
+ p.add_argument('--limit-records', type=int, default=0, help='Per-source record limit; 0 means all')
287
+ p.add_argument('--verify-images', action='store_true', help='Decode/verify every referenced image; slower')
288
+ args = p.parse_args()
289
+ if min(args.workers, args.shard_mib, args.row_group_mib, args.chunk_records) < 1 or args.limit_records < 0:
290
+ p.error('worker/size arguments must be positive and limit nonnegative')
291
+ root, out = args.input.resolve(), args.output.resolve()
292
+ if out == root or root in out.parents:
293
+ p.error('Output must be separate from the input dataset')
294
+ files = sorted((root/'metadata').glob('*.json'))
295
+ if not files or not (root/'images').is_dir():
296
+ p.error('Input needs metadata/*.json and images/')
297
+ sources = [f.name.split('_')[0] for f in files]
298
+ if len(sources) != len(set(sources)):
299
+ p.error('Multiple metadata files share a source label')
300
+ out.mkdir(parents=True, exist_ok=True)
301
+ (out/'.state').mkdir(exist_ok=True)
302
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s',
303
+ handlers=[logging.StreamHandler(), logging.FileHandler(out/'.state'/'conversion.log', encoding='utf-8')])
304
+ opts = {k: getattr(args, k) for k in ('shard_mib','row_group_mib','limit_records','verify_images','chunk_records')}
305
+ with FileLock(out/'.state'/'convert.lock', timeout=0):
306
+ plan = {'sources': sources, 'input': str(root), 'options': opts, 'script_sha256':sha256(__file__), 'metadata':[{ 'path':str(f), 'size':f.stat().st_size, 'mtime_ns':f.stat().st_mtime_ns} for f in files]}
307
+ plan_path = out/'.state'/'plan.json'
308
+ if plan_path.exists() and json.loads(plan_path.read_text(encoding='utf-8')) != plan:
309
+ raise RuntimeError('Output belongs to another conversion; use a fresh directory')
310
+ save_json(plan_path, plan)
311
+ chunks = prepare_chunks(files, sources, out, opts)
312
+ jobs = [(c['source'],c['path'],str((root/'images').resolve()),str(out),opts,c['chunk_id'],c['start_index']) for c in chunks]
313
+ logging.info('Starting %s conversion processes for %s independent chunks',min(args.workers,len(jobs)),len(jobs))
314
+ results = {}
315
+ with ProcessPoolExecutor(max_workers=min(args.workers,len(jobs)), mp_context=multiprocessing.get_context('spawn')) as pool:
316
+ futures = {pool.submit(convert_source,j):(j[0],j[5]) for j in jobs}
317
+ for future in as_completed(futures):
318
+ key = futures[future]
319
+ try:
320
+ results[key] = future.result()
321
+ logging.info('%s chunk %s complete: %s QA rows (%s/%s chunks)',key[0],key[1],results[key]['qa_rows'],len(results),len(jobs))
322
+ except BaseException:
323
+ for f in futures: f.cancel()
324
+ logging.exception('%s failed; completed shards remain resumable',key)
325
+ raise
326
+ ordered = [results[key] for key in sorted(results)]
327
+ aggregate = {}
328
+ for source in sources:
329
+ group = [r for r in ordered if r['source']==source]
330
+ summary = {k:sum(r[k] for r in group) for k in ('next_record','qa_rows','mapped_image_records')}
331
+ for key in ('task_counts','type_counts'):
332
+ counter=Counter()
333
+ for r in group: counter.update(r[key])
334
+ summary[key]=dict(counter)
335
+ aggregate[source]=summary
336
+ manifest = {'version':VERSION, 'complete':True, 'limited':bool(args.limit_records),
337
+ 'sources':sources, 'records':sum(r['next_record'] for r in ordered),
338
+ 'qa_rows':sum(r['qa_rows'] for r in ordered),
339
+ 'files':[item for r in ordered for item in r['files']],
340
+ 'source_statistics':aggregate,
341
+ 'conversion':{'requested_workers':args.workers, 'chunks':len(jobs),
342
+ 'worker_pids':sorted({r['worker_pid'] for r in ordered})}}
343
+ write_card(out,manifest)
344
+ script_dest = out/'scripts'
345
+ script_dest.mkdir(exist_ok=True)
346
+ for f in Path(__file__).parent.iterdir():
347
+ if f.is_file() and f.suffix in ('.py','.md','.txt','.yml') and f.resolve() != (script_dest/f.name).resolve():
348
+ shutil.copy2(f,script_dest/f.name)
349
+ save_json(out/'manifest.json', manifest) # publish only after all sources succeed
350
+ logging.info('COMPLETE: %s QA rows, %s shards',manifest['qa_rows'],len(manifest['files']))
351
+
352
+
353
+ if __name__ == '__main__':
354
+ multiprocessing.freeze_support()
355
  main()
scripts/test_pipeline.py CHANGED
@@ -1,73 +1,73 @@
1
- """Integration checks: real-source fidelity and recovery after a missing-image failure."""
2
- import json
3
- import os
4
- from pathlib import Path
5
- import subprocess
6
- import sys
7
- import tempfile
8
- import unittest
9
-
10
- import pyarrow.parquet as pq
11
- from PIL import Image
12
- from convert_dataset import infer_task, sha256
13
-
14
- SCRIPT = Path(__file__).with_name('convert_dataset.py')
15
-
16
-
17
- class PipelineTests(unittest.TestCase):
18
- def test_task_labels_and_ambiguity(self):
19
- self.assertEqual(infer_task('Predict 2D waypoints', '[(1, 2)]'), '2d_trace')
20
- self.assertEqual(infer_task('Predict 3D waypoints', '[(1, 2, 0.4)]'), '3d_trace')
21
- self.assertEqual(infer_task('Lift the 2 D waypoints to 3 D', '[(1, 2, 0.4)]'), '2d_to_3d')
22
- self.assertIsNone(infer_task('Predict 2D waypoints', '[(1, 2, 3)]'))
23
- self.assertIsNone(infer_task('Predict 3D waypoints', '__import__("os").getcwd()'))
24
- self.assertIsNone(infer_task('Predict 3D waypoints', '[("a", 2, 3)]'))
25
-
26
- def test_checkpoint_resume_after_missing_image(self):
27
- with tempfile.TemporaryDirectory(prefix='tracespatial-test-') as directory:
28
- base = Path(directory)
29
- root, output = base/'input', base/'output'
30
- (root/'images').mkdir(parents=True)
31
- (root/'metadata').mkdir()
32
- image1 = root/'images'/'frame_01.png'
33
- image2 = root/'images'/'frame_02.png'
34
- Image.frombytes('RGB',(700,700),os.urandom(700*700*3)).save(image1)
35
- records = []
36
- for n in (1,2):
37
- records.append({'id':'duplicate-id','image':[f'frame:0{n}.png'],
38
- 'conversations':[{'from':'human','value':'Predict 2D waypoints'},
39
- {'from':'gpt','value':'[(10, 20), (30, 40)]'}]})
40
- (root/'metadata'/'droid_test.json').write_text(json.dumps(records),encoding='utf-8')
41
- command = [sys.executable,str(SCRIPT),'--input',str(root),'--output',str(output),
42
- '--workers','2','--shard-mib','1','--row-group-mib','1']
43
- failed = subprocess.run(command,capture_output=True,text=True)
44
- self.assertNotEqual(failed.returncode,0)
45
- self.assertIn('RGB image missing',failed.stderr)
46
- self.assertFalse((output/'manifest.json').exists())
47
- state = json.loads((output/'.state'/'droid.json').read_text())
48
- self.assertEqual(state['next_record'],1)
49
- first = output/state['files'][0]['path']
50
- original_sha, original_mtime = sha256(first), first.stat().st_mtime_ns
51
- image2.write_bytes(image1.read_bytes())
52
- resumed = subprocess.run(command,capture_output=True,text=True)
53
- self.assertEqual(resumed.returncode,0,resumed.stderr)
54
- self.assertEqual(sha256(first),original_sha)
55
- self.assertEqual(first.stat().st_mtime_ns,original_mtime)
56
- manifest = json.loads((output/'manifest.json').read_text())
57
- self.assertEqual(manifest['qa_rows'],2)
58
- rows = [row for item in manifest['files'] for row in pq.read_table(output/item['path']).to_pylist()]
59
- self.assertEqual([r['record_index'] for r in rows],[0,1])
60
- self.assertEqual([r['id'] for r in rows],['duplicate-id','duplicate-id'])
61
- self.assertTrue(all(r['type'] is None for r in rows))
62
- self.assertEqual(manifest['source_statistics']['droid']['mapped_image_records'],2)
63
- uploader = Path(__file__).with_name('upload_dataset.py')
64
- plan = subprocess.run([sys.executable,str(uploader),'--folder',str(output)],capture_output=True,text=True)
65
- self.assertEqual(plan.returncode,0,plan.stderr)
66
- with first.open('ab') as f: f.write(b'corruption')
67
- bad = subprocess.run([sys.executable,str(uploader),'--folder',str(output)],capture_output=True,text=True)
68
- self.assertNotEqual(bad.returncode,0)
69
- self.assertIn('checksum mismatch',bad.stderr)
70
-
71
-
72
- if __name__ == '__main__':
73
  unittest.main(verbosity=2)
 
1
+ """Integration checks: real-source fidelity and recovery after a missing-image failure."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import subprocess
6
+ import sys
7
+ import tempfile
8
+ import unittest
9
+
10
+ import pyarrow.parquet as pq
11
+ from PIL import Image
12
+ from convert_dataset import infer_task, sha256
13
+
14
+ SCRIPT = Path(__file__).with_name('convert_dataset.py')
15
+
16
+
17
+ class PipelineTests(unittest.TestCase):
18
+ def test_task_labels_and_ambiguity(self):
19
+ self.assertEqual(infer_task('Predict 2D waypoints', '[(1, 2)]'), '2d_trace')
20
+ self.assertEqual(infer_task('Predict 3D waypoints', '[(1, 2, 0.4)]'), '3d_trace')
21
+ self.assertEqual(infer_task('Lift the 2 D waypoints to 3 D', '[(1, 2, 0.4)]'), '2d_to_3d')
22
+ self.assertIsNone(infer_task('Predict 2D waypoints', '[(1, 2, 3)]'))
23
+ self.assertIsNone(infer_task('Predict 3D waypoints', '__import__("os").getcwd()'))
24
+ self.assertIsNone(infer_task('Predict 3D waypoints', '[("a", 2, 3)]'))
25
+
26
+ def test_checkpoint_resume_after_missing_image(self):
27
+ with tempfile.TemporaryDirectory(prefix='tracespatial-test-') as directory:
28
+ base = Path(directory)
29
+ root, output = base/'input', base/'output'
30
+ (root/'images').mkdir(parents=True)
31
+ (root/'metadata').mkdir()
32
+ image1 = root/'images'/'frame_01.png'
33
+ image2 = root/'images'/'frame_02.png'
34
+ Image.frombytes('RGB',(700,700),os.urandom(700*700*3)).save(image1)
35
+ records = []
36
+ for n in (1,2):
37
+ records.append({'id':'duplicate-id','image':[f'frame:0{n}.png'],
38
+ 'conversations':[{'from':'human','value':'Predict 2D waypoints'},
39
+ {'from':'gpt','value':'[(10, 20), (30, 40)]'}]})
40
+ (root/'metadata'/'droid_test.json').write_text(json.dumps(records),encoding='utf-8')
41
+ command = [sys.executable,str(SCRIPT),'--input',str(root),'--output',str(output),
42
+ '--workers','2','--shard-mib','1','--row-group-mib','1']
43
+ failed = subprocess.run(command,capture_output=True,text=True)
44
+ self.assertNotEqual(failed.returncode,0)
45
+ self.assertIn('RGB image missing',failed.stderr)
46
+ self.assertFalse((output/'manifest.json').exists())
47
+ state = json.loads((output/'.state'/'droid-00000.json').read_text())
48
+ self.assertEqual(state['next_record'],1)
49
+ first = output/state['files'][0]['path']
50
+ original_sha, original_mtime = sha256(first), first.stat().st_mtime_ns
51
+ image2.write_bytes(image1.read_bytes())
52
+ resumed = subprocess.run(command,capture_output=True,text=True)
53
+ self.assertEqual(resumed.returncode,0,resumed.stderr)
54
+ self.assertEqual(sha256(first),original_sha)
55
+ self.assertEqual(first.stat().st_mtime_ns,original_mtime)
56
+ manifest = json.loads((output/'manifest.json').read_text())
57
+ self.assertEqual(manifest['qa_rows'],2)
58
+ rows = [row for item in manifest['files'] for row in pq.read_table(output/item['path']).to_pylist()]
59
+ self.assertEqual([r['record_index'] for r in rows],[0,1])
60
+ self.assertEqual([r['id'] for r in rows],['duplicate-id','duplicate-id'])
61
+ self.assertTrue(all(r['type'] is None for r in rows))
62
+ self.assertEqual(manifest['source_statistics']['droid']['mapped_image_records'],2)
63
+ uploader = Path(__file__).with_name('upload_dataset.py')
64
+ plan = subprocess.run([sys.executable,str(uploader),'--folder',str(output)],capture_output=True,text=True)
65
+ self.assertEqual(plan.returncode,0,plan.stderr)
66
+ with first.open('ab') as f: f.write(b'corruption')
67
+ bad = subprocess.run([sys.executable,str(uploader),'--folder',str(output)],capture_output=True,text=True)
68
+ self.assertNotEqual(bad.returncode,0)
69
+ self.assertIn('checksum mismatch',bad.stderr)
70
+
71
+
72
+ if __name__ == '__main__':
73
  unittest.main(verbosity=2)