File size: 11,799 Bytes
d783907
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Relabel and merge reviewed LeRobot v3 episodes without transcoding videos.

No source checksums, value-range audit, or exhaustive video decoding are run.
Requires: numpy, pandas, pyarrow. Use --help for input paths.
"""
import argparse
import copy
import csv
import json
import shutil
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq

EPISODES_PATH = 'meta/episodes/chunk-000/file-000.parquet'
DATA_PATH = 'data/chunk-000/file-000.parquet'
QUANTILES = {'q01': .01, 'q10': .1, 'q50': .5, 'q90': .9, 'q99': .99}


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


def numeric_stats(column):
    values = np.asarray(column.to_pylist(), dtype=np.float64)
    if values.ndim == 1:
        values = values[:, None]
    result = {'min': values.min(axis=0).tolist(), 'max': values.max(axis=0).tolist(),
              'mean': values.mean(axis=0).tolist(), 'std': values.std(axis=0).tolist(),
              'count': [len(values)]}
    result.update({key: np.quantile(values, q, axis=0).tolist() for key, q in QUANTILES.items()})
    return result


def aggregate_image_stats(episodes, key):
    """Pool source episode stats using LeRobot's count-weighted formula.

    Image quantiles are weighted approximations, not recomputed pixel quantiles.
    Source image-stat quality is inherited; no new image audit is implied.
    """
    prefix = f'stats/{key}/'
    parts = [{k[len(prefix):]: np.asarray(v) for k, v in ep.items() if k.startswith(prefix)}
             for ep in episodes]
    means = np.stack([s['mean'] for s in parts])
    counts = np.stack([s['count'] for s in parts])
    total = counts.sum(axis=0)
    weights = counts.reshape(counts.shape + (1,) * (means.ndim - counts.ndim))
    mean = (means * weights).sum(axis=0) / total
    variance = ((np.stack([s['std'] ** 2 for s in parts]) + (means - mean) ** 2) * weights).sum(axis=0) / total
    result = {'min': np.min([s['min'] for s in parts], axis=0).tolist(),
              'max': np.max([s['max'] for s in parts], axis=0).tolist(),
              'mean': mean.tolist(), 'std': np.sqrt(variance).tolist(), 'count': total.tolist()}
    for key in QUANTILES:
        if all(key in s for s in parts):
            result[key] = (np.stack([s[key] for s in parts]) * weights).sum(axis=0).__truediv__(total).tolist()
    return result


def merge(source, labels_path, output):
    labels = json.loads(labels_path.read_text(encoding='utf-8'))
    catalog = labels['tasks']
    source_manifest = json.loads((source / 'dataset_manifest.json').read_text())
    session_names = [s['name'] for s in source_manifest['datasets']]
    episode_tables = {name: pq.read_table(source / name / EPISODES_PATH) for name in session_names}
    source_episodes = {(name, row['episode_index']): row for name, table in episode_tables.items()
                       for row in table.to_pylist()}
    assignments = labels['episodes']
    keys = [(a['source_session'], a['source_episode_index']) for a in assignments]
    if len(set(keys)) != len(keys) or set(keys) != set(source_episodes):
        raise ValueError('Labels must cover each source episode exactly once.')
    groups = {slug: [] for slug in catalog}
    for assignment in assignments:
        slug = assignment['task_slug']
        if slug not in catalog:
            raise ValueError(f'Unknown task assignment: {slug}')
        groups[slug].append(assignment)

    mapping, summary = [], []
    for slug, members in groups.items():
        if not members:
            raise ValueError(f'No episodes assigned to task: {slug}')
        relative_root = f'review/{slug}' if slug == 'needs_review' else f'tasks/{slug}'
        destination = output / relative_root
        if (destination / 'meta/info.json').exists():
            raise FileExistsError(f'Refusing to overwrite existing dataset: {destination}')
        instruction = catalog[slug]['instruction_en']
        first_session = members[0]['source_session']
        info = json.loads((source / first_session / 'meta/info.json').read_text())
        cameras = [k for k, v in info['features'].items() if v['dtype'] == 'video']
        video_files = {}
        cached_data = {}
        merged_data, merged_episodes = [], []
        cursor = 0
        for new_episode, assignment in enumerate(members):
            session = assignment['source_session']
            old_index = assignment['source_episode_index']
            original = source_episodes[(session, old_index)]
            original_info = json.loads((source / session / 'meta/info.json').read_text())
            for field in ['codebase_version', 'fps', 'robot_type', 'features']:
                if original_info[field] != info[field]:
                    raise ValueError(f'Incompatible source schema: {session}/{field}')
            original_data_path = original_info['data_path'].format(
                chunk_index=original['data/chunk_index'], file_index=original['data/file_index'])
            data_key = (session, original_data_path)
            if data_key not in cached_data:
                cached_data[data_key] = pq.read_table(source / session / original_data_path)
            source_table = cached_data[data_key]
            selected = source_table.filter(pa.compute.equal(source_table['episode_index'], old_index))
            if selected.num_rows != original['length']:
                raise ValueError(f'Episode slice mismatch: {session}/{old_index}')
            length = selected.num_rows
            for name, values in [('episode_index', np.full(length, new_episode, dtype=np.int64)),
                                 ('index', np.arange(cursor, cursor + length, dtype=np.int64)),
                                 ('task_index', np.zeros(length, dtype=np.int64))]:
                selected = selected.set_column(selected.schema.get_field_index(name), name,
                                               pa.array(values, type=pa.int64()))
            merged_data.append(selected)
            episode = copy.deepcopy(original)
            episode.update({'episode_index': new_episode, 'tasks': [instruction],
                            'data/chunk_index': 0, 'data/file_index': 0,
                            'dataset_from_index': cursor, 'dataset_to_index': cursor + length,
                            'meta/episodes/chunk_index': 0, 'meta/episodes/file_index': 0})
            for camera in cameras:
                old_chunk = original[f'videos/{camera}/chunk_index']
                old_file = original[f'videos/{camera}/file_index']
                key = (session, old_chunk, old_file)
                if key not in video_files:
                    video_files[key] = len(video_files)
                new_file = video_files[key]
                old_path = original_info['video_path'].format(video_key=camera, chunk_index=old_chunk, file_index=old_file)
                new_path = info['video_path'].format(video_key=camera, chunk_index=0, file_index=new_file)
                new_video = destination / new_path
                if not new_video.exists():
                    new_video.parent.mkdir(parents=True, exist_ok=True)
                    shutil.copy2(source / session / old_path, new_video)
                episode[f'videos/{camera}/chunk_index'] = 0
                episode[f'videos/{camera}/file_index'] = new_file
                # The original MP4 is copied intact, so video timestamps stay unchanged.
            for name in selected.column_names:
                for stat, value in numeric_stats(selected[name]).items():
                    episode[f'stats/{name}/{stat}'] = value
            merged_episodes.append(episode)
            mapping.append({**assignment, 'destination_root': relative_root,
                            'destination_episode_index': new_episode, 'destination_task_index': 0,
                            'name_en': catalog[slug]['name_en'],
                            'instruction': instruction, 'instruction_language': 'en',
                            'instruction_ko': catalog[slug]['instruction_ko'],
                            'instruction_en': instruction, 'length': length,
                            'dataset_from_index': cursor, 'dataset_to_index': cursor + length,
                            'source_revision': labels['source_revision']})
            cursor += length

        table = pa.concat_tables(merged_data)
        data_path = destination / DATA_PATH
        data_path.parent.mkdir(parents=True, exist_ok=True)
        pq.write_table(table, data_path)
        ep_path = destination / EPISODES_PATH
        ep_path.parent.mkdir(parents=True, exist_ok=True)
        ep_schema = episode_tables[first_session].schema
        pq.write_table(pa.Table.from_pylist(merged_episodes, schema=ep_schema), ep_path)
        tasks = pd.DataFrame({'task_index': [0]}, index=pd.Index([instruction], name='task'))
        tasks.to_parquet(destination / 'meta/tasks.parquet')
        info.update({'total_episodes': len(members), 'total_frames': table.num_rows,
                     'total_tasks': 1, 'splits': {'train': f'0:{len(members)}'}})
        write_json(destination / 'meta/info.json', info)
        stats = {name: numeric_stats(table[name]) for name in table.column_names}
        stats.update({camera: aggregate_image_stats(merged_episodes, camera) for camera in cameras})
        write_json(destination / 'meta/stats.json', stats)
        item = {'task_slug': slug, 'name_ko': catalog[slug]['name_ko'],
                'name_en': catalog[slug]['name_en'], 'instruction_en': instruction,
                'instruction_language': 'en', 'root': relative_root,
                'episodes': len(members), 'frames': table.num_rows, 'video_files': len(video_files) * len(cameras)}
        summary.append(item)
        print(json.dumps(item, ensure_ascii=False), flush=True)

    if sum(x['frames'] for x in summary) != source_manifest['total_frames']:
        raise ValueError('Output frame accounting differs from source manifest.')
    reports = output / 'reports'
    write_json(reports / 'task_labels.json', labels)
    write_json(reports / 'episode_mapping.json', mapping)
    write_json(reports / 'summary.json', {'source_repo': labels['source_repo'],
               'source_revision': labels['source_revision'], 'datasets': summary,
               'total_episodes': len(mapping), 'total_frames': sum(x['frames'] for x in summary),
               'checksum_audit': 'not performed, as requested',
               'exhaustive_data_video_integrity_audit': 'not performed, as requested',
               'review_method': labels['review_method'], 'instruction_language': 'en'})
    fields = ['source_session', 'source_episode_index', 'task_slug', 'status', 'name_ko', 'name_en',
              'instruction', 'instruction_language', 'instruction_ko', 'instruction_en',
              'destination_root', 'destination_episode_index', 'length', 'duration_seconds',
              'label_basis', 'confidence', 'secondary_review_status', 'needs_secondary_review', 'reason', 'source_revision']
    with (reports / 'episode_mapping.csv').open('w', encoding='utf-8-sig', newline='') as f:
        writer = csv.DictWriter(f, fieldnames=fields, extrasaction='ignore')
        writer.writeheader()
        writer.writerows(mapping)
    return summary


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, required=True)
    parser.add_argument('--labels', type=Path, required=True)
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    merge(args.source, args.labels, args.output)