File size: 19,151 Bytes
7cc0a4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47652a2
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
"""Stream original JSON into image-embedded QA Parquet, many dynamically scheduled record chunks per source."""
import argparse
import ast
from collections import Counter
from concurrent.futures import ProcessPoolExecutor, as_completed
import hashlib
import io
import json
import logging
import multiprocessing
import os
from pathlib import Path
import re
import shutil
import sys

import ijson
import pyarrow as pa
import pyarrow.parquet as pq
from datasets import Features, Image, Value
from filelock import FileLock
from PIL import Image as PILImage
import yaml

VERSION = 2
FIELDS = Features({'image': Image(), 'question': Value('string'), 'answer': Value('string'),
                   'type': Value('string'), 'source': Value('string'), 'task': Value('string'),
                   'id': Value('string'), 'qa_index': Value('int32'), 'record_index': Value('int64')})
SCHEMA = FIELDS.arrow_schema


def sha256(path):
    h = hashlib.sha256()
    with Path(path).open('rb') as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def save_json(path, value):
    path = Path(path)
    tmp = path.with_suffix(path.suffix + '.tmp')
    tmp.write_text(json.dumps(value, ensure_ascii=False, indent=2), encoding='utf-8')
    os.replace(tmp, path)


def infer_task(question, answer):
    """Conservative derived label; never rewrite or execute answer text."""
    if len(answer) > 100000:
        return None
    try:
        points = ast.literal_eval(answer)
        if not isinstance(points, (list, tuple)) or not points:
            return None
        if any(not isinstance(p, (list, tuple)) or len(p) not in (2, 3) for p in points):
            return None
        dims = {len(p) for p in points}
        if len(dims) != 1 or any(not isinstance(v, (int, float)) or isinstance(v, bool) for p in points for v in p):
            return None
    except (ValueError, SyntaxError, TypeError, RecursionError):
        return None
    q = re.sub(r'\b([23])\s+d\b', r'\1d', question.lower())
    if re.search(r'\blift(?:ing)?\b', q) and '2d' in q and '3d' in q and dims == {3}:
        return '2d_to_3d'
    if dims == {2} and '2d' in q:
        return '2d_trace'
    if dims == {3} and '3d' in q and '2d' not in q:
        return '3d_trace'
    return None


def resolve_image(root, name):
    # Input release uses flat image names. Do not accept traversal or absolute paths.
    if not isinstance(name, str) or '/' in name or '\\' in name or name in ('', '.', '..'):
        raise ValueError(f'Expected flat image filename: {name!r}')
    candidates = [name] if ':' not in name else [name.replace(':', '_')]
    for candidate in candidates:
        path = (root / candidate).resolve()
        if path.parent == root and path.is_file():
            return path
    raise FileNotFoundError(f'RGB image missing: {name}')


def convert_source(job):
    source, metadata, images, out, opts, chunk_id, start_index = job
    metadata, images, out = Path(metadata), Path(images), Path(out)
    pa.set_cpu_count(1)  # prevent each process spawning another CPU-sized thread pool
    dest = out / 'data' / source
    dest.mkdir(parents=True, exist_ok=True)
    state_path = out / '.state' / f'{source}-{chunk_id:05d}.json'
    stat = metadata.stat()
    identity = {'version': VERSION, 'script_sha256': sha256(__file__), 'metadata': str(metadata),
                'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns,
                'images': str(images), 'options': opts, 'chunk_id': chunk_id, 'start_index': start_index}
    if state_path.exists():
        state = json.loads(state_path.read_text(encoding='utf-8'))
        if state['identity'] != identity:
            raise RuntimeError(f'{source}: input/options/code changed; use a new output directory')
        for item in state['files']:
            path = out / item['path']
            if not path.is_file() or path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']:
                raise RuntimeError(f'{source}: completed shard changed: {path}')
        if state['complete']:
            print(f'{source}: resume verified, already complete', flush=True)
            return state
    else:
        state = {'identity': identity, 'source': source, 'complete': False, 'next_record': 0,
                 'worker_pid': os.getpid(), 'chunk_id': chunk_id, 'qa_rows': 0, 'mapped_image_records': 0, 'task_counts': {}, 'type_counts': {}, 'files': []}
        save_json(state_path, state)
    writer = None
    pending, pending_size, shard_size, shard_rows = [], 0, 0, 0
    tasks, types = Counter(state['task_counts']), Counter(state['type_counts'])
    processed, total_rows = state['next_record'], state['qa_rows']
    mapped = state['mapped_image_records']
    target = opts['shard_mib'] * 1024**2
    group_target = opts['row_group_mib'] * 1024**2
    shard_path = None
    tmp = None

    def flush_group():
        nonlocal pending, pending_size, writer, shard_path, tmp
        if not pending:
            return
        if writer is None:
            shard_path = dest / f'train-{chunk_id:05d}-{len(state["files"]):03d}.parquet'
            tmp = shard_path.with_suffix('.parquet.incomplete')
            writer = pq.ParquetWriter(tmp, SCHEMA, compression='zstd', compression_level=3,
                                     use_dictionary=True, dictionary_pagesize_limit=16*1024**2)
        writer.write_table(pa.Table.from_pylist(pending, schema=SCHEMA), row_group_size=len(pending))
        pending, pending_size = [], 0

    def finish_shard():
        nonlocal writer, shard_rows, shard_size
        flush_group()
        if writer is None:
            return
        writer.close()
        writer = None
        assert pq.ParquetFile(tmp).metadata.num_rows == shard_rows
        os.replace(tmp, shard_path)
        state['files'].append({'path': shard_path.relative_to(out).as_posix(),
                               'rows': shard_rows, 'bytes': shard_path.stat().st_size,
                               'sha256': sha256(shard_path)})
        state.update(next_record=processed, qa_rows=total_rows, mapped_image_records=mapped,
                     task_counts=dict(tasks), type_counts=dict(types))
        save_json(state_path, state)
        print(f'{source}: {processed:,} records / {total_rows:,} QA; committed {shard_path.name}', flush=True)
        shard_rows, shard_size = 0, 0

    try:
        with metadata.open('r', encoding='utf-8') as fp:
            for local_index, line in enumerate(fp):
                if local_index < state['next_record']:
                    continue
                record = json.loads(line)
                record_index = start_index + local_index
                refs = record.get('image')
                conv = record.get('conversations')
                if not isinstance(refs, list) or len(refs) != 1:
                    raise ValueError(f'{source}[{record_index}]: expected exactly one RGB reference')
                if not isinstance(conv, list) or not conv or len(conv) % 2:
                    raise ValueError(f'{source}[{record_index}]: invalid conversation length')
                path = resolve_image(images, refs[0])
                blob = path.read_bytes()
                if len(blob) > 64 * 1024**2:
                    raise ValueError(f'Image exceeds 64 MiB memory guard: {path}')
                if opts['verify_images']:
                    with PILImage.open(io.BytesIO(blob)) as im:
                        im.verify()
                mapped += path.name != refs[0]
                kind = record.get('type')
                if kind is not None and not isinstance(kind, str):
                    raise ValueError(f'{source}[{record_index}]: non-string type')
                if not isinstance(record.get('id'), str):
                    raise ValueError(f'{source}[{record_index}]: non-string id')
                types[kind if kind is not None else '(missing)'] += 1
                for offset in range(0, len(conv), 2):
                    q, a = conv[offset:offset+2]
                    if q.get('from') != 'human' or a.get('from') != 'gpt':
                        raise ValueError(f'{source}[{record_index}]: nonalternating roles')
                    question, answer = q['value'], a['value']
                    if not isinstance(question, str) or not isinstance(answer, str):
                        raise ValueError('QA text must be strings')
                    task = infer_task(question, answer)
                    tasks[task or '(unknown)'] += 1
                    row = {'image': {'bytes': blob, 'path': path.name}, 'question': question,
                           'answer': answer, 'type': kind, 'source': source, 'task': task,
                           'id': record['id'], 'qa_index': offset//2, 'record_index': record_index}
                    size = len(blob) + len(question.encode('utf-8')) + len(answer.encode('utf-8')) + 256
                    if pending and (pending_size + size > group_target or len(pending) >= 128):
                        flush_group()
                    pending.append(row)
                    pending_size += size
                    shard_size += size
                    shard_rows += 1
                    total_rows += 1
                processed = local_index + 1
                # Checkpoint only at whole-record boundaries, preserving conversation groups.
                if shard_size >= target:
                    finish_shard()
        finish_shard()
        state.update(complete=True, next_record=processed, qa_rows=total_rows,
                     mapped_image_records=mapped, task_counts=dict(tasks), type_counts=dict(types))
        save_json(state_path, state)
        return state
    except BaseException:
        if writer is not None:
            writer.close()
        raise


def write_card(out, manifest):
    template = Path(__file__).with_name('README.template.md').read_text(encoding='utf-8')
    configs = []
    if manifest['limited']:
        configs.append({'config_name': 'preview', 'default': True,
                        'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
    else:
        configs.append({'config_name': 'all', 'default': True,
                        'data_files': [{'split': 'train', 'path': 'data/*/*.parquet'}]})
    for source in manifest['sources']:
        configs.append({'config_name': source, 'data_files': [{'split': 'train', 'path': f'data/{source}/*.parquet'}]})
    metadata = {'language': ['en'], 'pretty_name': 'TraceSpatial-Trace',
                'task_categories': ['visual-question-answering'],
                'tags': ['robotics', 'spatial-reasoning', 'trajectory', 'arxiv:2512.13660'], 'configs': configs}
    if manifest['limited']:
        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."
    else:
        status = f"This conversion contains **{manifest['qa_rows']:,} QA rows** from **{manifest['records']:,} original records** across {len(manifest['sources'])} sources."
    text = template.replace('@@STATUS@@', status).replace('@@CONFIG@@', 'preview' if manifest['limited'] else 'all')
    (out/'README.md').write_text('---\n'+yaml.safe_dump(metadata, sort_keys=False)+'---\n\n'+text, encoding='utf-8')


def prepare_chunks(files, sources, out, options):
    """One streaming pass creates immutable, reusable work chunks (no RGB copy)."""
    index_path = out/'.state'/'chunks'/'index.json'
    if index_path.exists():
        chunks = json.loads(index_path.read_text(encoding='utf-8'))
        for c in chunks:
            path = Path(c['path'])
            if not path.is_file() or sha256(path) != c['sha256']:
                raise RuntimeError(f'Prepared JSONL chunk changed: {path}')
        return chunks
    chunks = []
    for source, metadata in zip(sources, files):
        directory = index_path.parent/source
        directory.mkdir(parents=True, exist_ok=True)
        batch, start, chunk_id = [], 0, 0
        def emit():
            nonlocal batch, start, chunk_id
            path = directory/f'chunk-{chunk_id:05d}.jsonl'
            tmp = path.with_suffix('.jsonl.tmp')
            with tmp.open('w', encoding='utf-8', newline='\n') as fp:
                for record in batch:
                    fp.write(json.dumps(record, ensure_ascii=False)+'\n')
            os.replace(tmp, path)
            chunks.append({'source':source, 'path':str(path), 'chunk_id':chunk_id,
                           'start_index':start, 'records':len(batch), 'sha256':sha256(path)})
            start += len(batch)
            chunk_id += 1
            batch = []
        with metadata.open('rb') as fp:
            for index, row in enumerate(ijson.items(fp, 'item')):
                if options['limit_records'] and index >= options['limit_records']:
                    break
                batch.append({key:row.get(key) for key in ('id','image','conversations','type')})
                if len(batch) >= options['chunk_records']:
                    emit()
                if (index+1) % 50000 == 0:
                    logging.info('%s: prepared %s original records',source,index+1)
        if batch: emit()
        if start == 0: raise ValueError(f'Empty metadata: {metadata}')
        logging.info('%s: prepared %s chunks / %s records',source,chunk_id,start)
    save_json(index_path,chunks)
    return chunks


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--input', type=Path, required=True, help='Directory containing images/ and metadata/')
    p.add_argument('--output', type=Path, required=True, help='New release directory; repeat to resume')
    p.add_argument('--workers', type=int, default=min(24, os.cpu_count() or 1))
    p.add_argument('--chunk-records', type=int, default=2048, help='Original records per independent work chunk; shared across all workers')
    p.add_argument('--shard-mib', type=int, default=512, help='Approximate uncompressed bytes; finish whole record before splitting')
    p.add_argument('--row-group-mib', type=int, default=32)
    p.add_argument('--limit-records', type=int, default=0, help='Per-source record limit; 0 means all')
    p.add_argument('--verify-images', action='store_true', help='Decode/verify every referenced image; slower')
    args = p.parse_args()
    if min(args.workers, args.shard_mib, args.row_group_mib, args.chunk_records) < 1 or args.limit_records < 0:
        p.error('worker/size arguments must be positive and limit nonnegative')
    root, out = args.input.resolve(), args.output.resolve()
    if out == root or root in out.parents:
        p.error('Output must be separate from the input dataset')
    files = sorted((root/'metadata').glob('*.json'))
    if not files or not (root/'images').is_dir():
        p.error('Input needs metadata/*.json and images/')
    sources = [f.name.split('_')[0] for f in files]
    if len(sources) != len(set(sources)):
        p.error('Multiple metadata files share a source label')
    out.mkdir(parents=True, exist_ok=True)
    (out/'.state').mkdir(exist_ok=True)
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s',
                        handlers=[logging.StreamHandler(), logging.FileHandler(out/'.state'/'conversion.log', encoding='utf-8')])
    opts = {k: getattr(args, k) for k in ('shard_mib','row_group_mib','limit_records','verify_images','chunk_records')}
    with FileLock(out/'.state'/'convert.lock', timeout=0):
        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]}
        plan_path = out/'.state'/'plan.json'
        if plan_path.exists() and json.loads(plan_path.read_text(encoding='utf-8')) != plan:
            raise RuntimeError('Output belongs to another conversion; use a fresh directory')
        save_json(plan_path, plan)
        chunks = prepare_chunks(files, sources, out, opts)
        jobs = [(c['source'],c['path'],str((root/'images').resolve()),str(out),opts,c['chunk_id'],c['start_index']) for c in chunks]
        logging.info('Starting %s conversion processes for %s independent chunks',min(args.workers,len(jobs)),len(jobs))
        results = {}
        with ProcessPoolExecutor(max_workers=min(args.workers,len(jobs)), mp_context=multiprocessing.get_context('spawn')) as pool:
            futures = {pool.submit(convert_source,j):(j[0],j[5]) for j in jobs}
            for future in as_completed(futures):
                key = futures[future]
                try:
                    results[key] = future.result()
                    logging.info('%s chunk %s complete: %s QA rows (%s/%s chunks)',key[0],key[1],results[key]['qa_rows'],len(results),len(jobs))
                except BaseException:
                    for f in futures: f.cancel()
                    logging.exception('%s failed; completed shards remain resumable',key)
                    raise
        ordered = [results[key] for key in sorted(results)]
        aggregate = {}
        for source in sources:
            group = [r for r in ordered if r['source']==source]
            summary = {k:sum(r[k] for r in group) for k in ('next_record','qa_rows','mapped_image_records')}
            for key in ('task_counts','type_counts'):
                counter=Counter()
                for r in group: counter.update(r[key])
                summary[key]=dict(counter)
            aggregate[source]=summary
        manifest = {'version':VERSION, 'complete':True, 'limited':bool(args.limit_records),
                    'sources':sources, 'records':sum(r['next_record'] for r in ordered),
                    'qa_rows':sum(r['qa_rows'] for r in ordered),
                    'files':[item for r in ordered for item in r['files']],
                    'source_statistics':aggregate,
                    'conversion':{'requested_workers':args.workers, 'chunks':len(jobs),
                                  'worker_pids':sorted({r['worker_pid'] for r in ordered})}}
        write_card(out,manifest)
        script_dest = out/'scripts'
        script_dest.mkdir(exist_ok=True)
        for f in Path(__file__).parent.iterdir():
            if f.is_file() and f.suffix in ('.py','.md','.txt','.yml') and f.resolve() != (script_dest/f.name).resolve():
                shutil.copy2(f,script_dest/f.name)
        save_json(out/'manifest.json', manifest)  # publish only after all sources succeed
        logging.info('COMPLETE: %s QA rows, %s shards',manifest['qa_rows'],len(manifest['files']))


if __name__ == '__main__':
    multiprocessing.freeze_support()
    main()