AGT / code /agt /dataset /build_scenes.py
MRBSTUDIO's picture
Update code and model card
fb3460f verified
Raw History Blame Contribute Delete
5.68 kB
from __future__ import annotations
import collections
import concurrent.futures
import json
import time
import traceback
from pathlib import Path
from . import scene_store as store
from . import waymo
from .video import VideoConfig
SOURCE_ID = waymo.SOURCE_ID
CRF = 14
MERGE_EVERY = 10
def video_config(pixel_format: str = "yuv420p") -> VideoConfig:
return VideoConfig(crf=CRF, pixel_format=pixel_format)
def current_identity(ffmpeg: str, ffprobe: str) -> dict:
return store.transcode_identity(ffmpeg=ffmpeg, ffprobe=ffprobe, config=video_config(),
native_size=waymo.NATIVE_SIZE, size=waymo.SIZE, decoder=waymo.decoder_identity(),
crop=waymo.crop_identity())
def split_segments(data_root: Path, split: str) -> list[tuple[str, str]]:
rows = [json.loads(line) for line in (Path(data_root) / "eval_sets/v2" / f"{split}.jsonl").read_text().splitlines()
if line.strip()]
return [(r["origin_split"], r["scene_id"]) for r in rows if r["source_id"] == SOURCE_ID]
def convert_segment(task: dict) -> dict:
started = time.time()
segment, split = task["segment"], task["split"]
try:
out, raw = Path(task["out"]), Path(task["raw"])
if store.scene_complete(out, task.get("row"), identity=task["identity"]):
return {"status": "skipped", "scene_id": segment, "row": task["row"], "seconds": time.time() - started}
data = waymo.read_segment(raw, split, segment, images=True)
records, world_from_local = waymo.frame_records(data)
timing = waymo.timing_summary(r["timestamp_start_us"] for r in records)
camera = waymo.camera_json(data, world_from_local)
destination = out / "scenes" / SOURCE_ID / segment
frames = waymo.clean_frames(f["image"] for f in data.frames)
written = store.write_scene(destination, frames, size=waymo.SIZE, fps=timing["fps"], frame_count=len(records),
metadata={"frames.jsonl": waymo.frames_jsonl_bytes(records), "camera.json": waymo.json_bytes(camera)},
ffmpeg=task["ffmpeg"], ffprobe=task["ffprobe"], config=video_config())
stats = store.scene_statistics_from_video(destination / store.VIDEO_NAME, len(records))
written["files"]["scene_stats.json"] = store.write_metadata(destination, "scene_stats.json", waymo.json_bytes(stats))
provenance = {"split": split, "segment": segment,
"source_files": {c: str(Path(p).relative_to(raw)) for c, p in data.paths.items()},
"time_of_day_source": data.stats["time_of_day"], "stats_rows": data.stats["rows"],
"front_rows": len(data.frames), "other_camera_rows": data.other_cameras,
"rolling_shutter_direction": int(data.calibration["rolling_shutter_direction"]),
"timing": timing}
row = store.scene_row(data_root=out, destination=destination, written=written, source_id=SOURCE_ID, scene_id=segment,
dataset_id=waymo.DATASET_ID, camera_id=waymo.CAMERA_ID, fps=waymo.NOMINAL_FPS,
video_fps=timing["fps"], frame_count=len(records), time_of_day=data.time_of_day,
size=waymo.SIZE, native_size=waymo.NATIVE_SIZE, transcode=task["identity"], provenance=provenance,
extra={"official_split": split, "location": data.stats["location"], "weather": data.stats["weather"]})
return {"status": "converted", "scene_id": segment, "row": row, "seconds": time.time() - started}
except Exception:
return {"status": "failed", "scene_id": segment, "error": traceback.format_exc(), "seconds": time.time() - started}
def build(out: Path, raw: Path, segments: list[tuple[str, str]], *, ffmpeg: str = "ffmpeg", ffprobe: str = "ffprobe",
workers: int = 3) -> int:
started = time.time()
out, raw = Path(out).resolve(), Path(raw).resolve()
identity = current_identity(ffmpeg, ffprobe)
manifest = out / "scenes" / store.MANIFEST_NAME
existing = {r["scene_id"]: r for r in store.read_manifest(manifest) if r["source_id"] == SOURCE_ID}
tasks = [{"out": str(out), "raw": str(raw), "identity": identity, "ffmpeg": ffmpeg, "ffprobe": ffprobe,
"split": split, "segment": segment, "row": existing.get(segment)} for split, segment in segments]
print(f"{len(tasks)} segments, {len(existing)} existing waymo rows, workers {workers}", flush=True)
results, pending = {}, []
with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(convert_segment, task) for task in tasks]
for done, future in enumerate(concurrent.futures.as_completed(futures), 1):
result = future.result()
results[result["scene_id"]] = result
if result["status"] == "converted":
pending.append(result["row"])
if len(pending) >= MERGE_EVERY:
store.merge_manifest(manifest, pending)
pending = []
tally = collections.Counter(r["status"] for r in results.values())
elapsed = time.time() - started
print(f"[{done}/{len(tasks)}] {result['status']:9s} {result['scene_id']} {result['seconds']:.1f}s | {dict(tally)} | "
f"{elapsed / 60:.1f} min", flush=True)
if result["status"] == "failed":
print(result["error"], flush=True)
if pending:
store.merge_manifest(manifest, pending)
return sum(1 for r in results.values() if r["status"] == "failed")