File size: 12,337 Bytes
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150050
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150050
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150050
 
 
 
 
 
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1150050
 
 
 
 
 
db613b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Command-line entry point: `kitti-c2l generate|verify|stats`."""

from __future__ import annotations

import argparse
import sys
from collections.abc import Iterator
from pathlib import Path

import pyarrow.parquet as pq

from kitti_c2l.assets import AssetRow, generate_sequence_assets
from kitti_c2l.generate import DEFAULT_BASE_SEED, DEFAULT_CAMERA_ID, generate_sequence_rows
from kitti_c2l.sequence_mapping import AVAILABLE_SEQUENCES, SequenceInfo, load_sequence_mapping
from kitti_c2l.stages import STAGES
from kitti_c2l.windows import (
    DEFAULT_WINDOW_LENGTH,
    DEFAULT_WINDOWS_BASE_SEED,
    generate_sequence_windows,
)
from kitti_c2l.writer import write_assets_sharded, write_split, write_windows


def _cmd_generate(args: argparse.Namespace) -> int:
    seq_map = load_sequence_mapping()
    user_specified = args.sequences is not None
    sequences = args.sequences.split(",") if user_specified else list(AVAILABLE_SEQUENCES)

    by_split: dict[str, list] = {}
    for seq_id in sequences:
        if seq_id not in seq_map:
            print(f"Unknown sequence {seq_id!r}, skipping.", file=sys.stderr)
            continue
        seq_info = seq_map[seq_id]
        if not seq_info.available and not user_specified:
            print(
                f"sequence {seq_id}: SKIPPED -- raw drive not publicly available "
                f"(see configs/sequence_mapping.yaml). Pass --sequences {seq_id} explicitly to force.",
                file=sys.stderr,
            )
            continue
        frame_indices = list(range(args.max_frames)) if args.max_frames else None
        rows = list(
            generate_sequence_rows(
                seq_info,
                args.kitti_calib_root,
                frame_indices=frame_indices,
                stages=STAGES,
                camera_id=args.camera_id,
                base_seed=args.base_seed,
                camera_model=args.camera_model,
            )
        )
        by_split.setdefault(seq_info.split, []).extend(rows)
        print(f"sequence {seq_id}: generated {len(rows)} rows ({seq_info.split})")

    total = 0
    for split, rows in by_split.items():
        output_path = Path(args.output_dir) / f"{split}.parquet"
        count = write_split(rows, output_path)
        total += count
        print(f"wrote {count} rows -> {output_path}")
    print(f"total: {total} rows")
    return 0


def _cmd_generate_assets(args: argparse.Namespace) -> int:
    seq_map = load_sequence_mapping()
    user_specified = args.sequences is not None
    sequences = args.sequences.split(",") if user_specified else list(AVAILABLE_SEQUENCES)

    by_split: dict[str, list] = {}
    for seq_id in sequences:
        if seq_id not in seq_map:
            print(f"Unknown sequence {seq_id!r}, skipping.", file=sys.stderr)
            continue
        seq_info = seq_map[seq_id]
        if not seq_info.available and not user_specified:
            print(
                f"sequence {seq_id}: SKIPPED -- raw drive not publicly available "
                f"(see configs/sequence_mapping.yaml). Pass --sequences {seq_id} explicitly to force.",
                file=sys.stderr,
            )
            continue
        by_split.setdefault(seq_info.split, []).append(seq_info)

    def _rows_for_split(seq_infos: list[SequenceInfo]) -> Iterator[AssetRow]:
        frame_indices = list(range(args.max_frames)) if args.max_frames else None
        for seq_info in seq_infos:
            count = 0
            for row in generate_sequence_assets(
                seq_info, args.kitti_raw_root, frame_indices=frame_indices, camera_id=args.camera_id
            ):
                count += 1
                yield row
            print(
                f"sequence {seq_info.sequence}: materialized {count} frame assets ({seq_info.split})"
            )

    total = 0
    for split, seq_infos in by_split.items():
        shard_paths = write_assets_sharded(_rows_for_split(seq_infos), args.output_dir, split)
        total_split_rows = sum(pq.read_metadata(p).num_rows for p in shard_paths)
        total += total_split_rows
        print(f"wrote {total_split_rows} rows across {len(shard_paths)} shard(s) for split={split}")
    print(f"total: {total} frame assets")
    return 0


def _cmd_generate_windows(args: argparse.Namespace) -> int:
    seq_map = load_sequence_mapping()
    user_specified = args.sequences is not None
    sequences = args.sequences.split(",") if user_specified else list(AVAILABLE_SEQUENCES)

    by_split: dict[str, list] = {}
    for seq_id in sequences:
        if seq_id not in seq_map:
            print(f"Unknown sequence {seq_id!r}, skipping.", file=sys.stderr)
            continue
        seq_info = seq_map[seq_id]
        if not seq_info.available and not user_specified:
            print(
                f"sequence {seq_id}: SKIPPED -- raw drive not publicly available "
                f"(see configs/sequence_mapping.yaml). Pass --sequences {seq_id} explicitly to force.",
                file=sys.stderr,
            )
            continue
        rows = list(
            generate_sequence_windows(
                seq_info,
                args.kitti_calib_root,
                window_length=args.window_length,
                stages=STAGES,
                camera_id=args.camera_id,
                base_seed=args.base_seed,
                max_windows=args.max_windows,
                camera_model=args.camera_model,
            )
        )
        num_windows = len(rows) // len(STAGES)
        by_split.setdefault(seq_info.split, []).extend(rows)
        print(
            f"sequence {seq_id}: generated {num_windows} windows ({len(rows)} rows, {seq_info.split})"
        )

    total = 0
    for split, rows in by_split.items():
        output_path = Path(args.output_dir) / f"windows_{split}.parquet"
        count = write_windows(rows, output_path)
        total += count
        print(f"wrote {count} rows -> {output_path}")
    print(f"total: {total} rows")
    return 0


def _cmd_stats(args: argparse.Namespace) -> int:
    seq_map = load_sequence_mapping()
    total_frames = 0
    available_frames = 0
    for seq_id, seq_info in seq_map.items():
        tag = "" if seq_info.available else "  [NOT PUBLICLY AVAILABLE -- excluded by default]"
        print(
            f"{seq_id}: {seq_info.date}/drive_{seq_info.drive} split={seq_info.split} "
            f"frames={seq_info.frame_count}{tag}"
        )
        total_frames += seq_info.frame_count
        if seq_info.available:
            available_frames += seq_info.frame_count
    print(
        f"total frames (11 sequences): {total_frames}, total rows at {len(STAGES)} stages: {total_frames * len(STAGES)}"
    )
    print(
        f"available frames (10 sequences, default `generate`): {available_frames}, "
        f"total rows at {len(STAGES)} stages: {available_frames * len(STAGES)}"
    )
    return 0


def _cmd_validate(args: argparse.Namespace) -> int:
    import json

    from kitti_c2l.release import validate_release

    report = validate_release(
        args.root, kitti_calib_root=args.kitti_calib_root, check_manifest=not args.write_manifest
    )
    if args.write_manifest:
        destination = args.root / "release/v1/manifest.json"
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps(report, indent=2))
    return 0


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="kitti-c2l")
    subparsers = parser.add_subparsers(dest="command", required=True)

    generate_parser = subparsers.add_parser(
        "generate", help="Generate parquet metadata for one or more sequences."
    )
    generate_parser.add_argument(
        "--kitti-calib-root",
        required=True,
        help="Directory containing per-date KITTI raw calibration subdirectories (e.g. .../2011_09_30/calib_*.txt).",
    )
    generate_parser.add_argument(
        "--output-dir", default="data", help="Directory to write {split}.parquet into."
    )
    generate_parser.add_argument(
        "--sequences",
        default=None,
        help="Comma-separated sequence IDs, default: all publicly-available ones (excludes 03; pass "
        "--sequences 03 explicitly to force an attempt).",
    )
    generate_parser.add_argument("--camera-id", type=int, default=DEFAULT_CAMERA_ID)
    generate_parser.add_argument(
        "--camera-model",
        choices=("legacy_v1", "full_projection_v1_1"),
        default="legacy_v1",
        help="Calibration conversion: frozen v1 x-only or source-consistent full projection (v1.1).",
    )
    generate_parser.add_argument("--base-seed", type=int, default=DEFAULT_BASE_SEED)
    generate_parser.add_argument(
        "--max-frames",
        type=int,
        default=None,
        help="Cap frames per sequence (for quick test slices).",
    )
    generate_parser.set_defaults(func=_cmd_generate)

    assets_parser = subparsers.add_parser(
        "generate-assets",
        help="Materialize the fully self-contained release: image + raw LiDAR bytes, once per unique frame.",
    )
    assets_parser.add_argument(
        "--kitti-raw-root",
        required=True,
        help="Directory containing per-date KITTI raw subdirectories (calib files + <date>_drive_<drive>_sync/).",
    )
    assets_parser.add_argument(
        "--output-dir", default="data", help="Directory to write frames_{split}.parquet into."
    )
    assets_parser.add_argument(
        "--sequences", default=None, help="Same semantics as `generate --sequences`."
    )
    assets_parser.add_argument("--camera-id", type=int, default=DEFAULT_CAMERA_ID)
    assets_parser.add_argument(
        "--max-frames",
        type=int,
        default=None,
        help="Cap frames per sequence (for quick test slices).",
    )
    assets_parser.set_defaults(func=_cmd_generate_assets)

    windows_parser = subparsers.add_parser(
        "generate-windows",
        help="Generate sequence-window metadata: one decalibration held constant across each window's frames.",
    )
    windows_parser.add_argument(
        "--kitti-calib-root",
        required=True,
        help="Directory containing per-date KITTI raw calibration subdirectories (e.g. .../2011_09_30/calib_*.txt).",
    )
    windows_parser.add_argument(
        "--output-dir", default="data", help="Directory to write windows_{split}.parquet into."
    )
    windows_parser.add_argument(
        "--sequences", default=None, help="Same semantics as `generate --sequences`."
    )
    windows_parser.add_argument("--camera-id", type=int, default=DEFAULT_CAMERA_ID)
    windows_parser.add_argument(
        "--camera-model",
        choices=("legacy_v1", "full_projection_v1_1"),
        default="legacy_v1",
        help="Calibration conversion; use the same model for frame and window metadata.",
    )
    windows_parser.add_argument("--base-seed", type=int, default=DEFAULT_WINDOWS_BASE_SEED)
    windows_parser.add_argument(
        "--window-length",
        type=int,
        default=DEFAULT_WINDOW_LENGTH,
        help=f"Frames per non-overlapping window (default: {DEFAULT_WINDOW_LENGTH}, ~3s at KITTI's 10Hz).",
    )
    windows_parser.add_argument(
        "--max-windows",
        type=int,
        default=None,
        help="Cap windows per sequence (for quick test slices).",
    )
    windows_parser.set_defaults(func=_cmd_generate_windows)

    validate_parser = subparsers.add_parser(
        "validate", help="Audit the frozen metadata release and its checksums."
    )
    validate_parser.add_argument("--root", type=Path, default=Path("."))
    validate_parser.add_argument("--kitti-calib-root", type=Path)
    validate_parser.add_argument(
        "--write-manifest",
        action="store_true",
        help="Write a manifest after a complete successful audit.",
    )
    validate_parser.set_defaults(func=_cmd_validate)

    stats_parser = subparsers.add_parser(
        "stats", help="Print sequence mapping stats without touching any KITTI data."
    )
    stats_parser.set_defaults(func=_cmd_stats)

    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    args = parser.parse_args(argv)
    return args.func(args)


if __name__ == "__main__":
    sys.exit(main())