robolake 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- robolake/__init__.py +0 -0
- robolake/align/__init__.py +0 -0
- robolake/align/timeline.py +86 -0
- robolake/cli.py +122 -0
- robolake/ingest/__init__.py +0 -0
- robolake/ingest/mcap_reader.py +119 -0
- robolake/pipeline.py +45 -0
- robolake/schema.py +92 -0
- robolake/serve/__init__.py +0 -0
- robolake/sim.py +141 -0
- robolake/store/__init__.py +0 -0
- robolake/store/lerobot_v3.py +133 -0
- robolake/validate/__init__.py +0 -0
- robolake/validate/quality.py +187 -0
- robolake-0.1.0.dist-info/METADATA +96 -0
- robolake-0.1.0.dist-info/RECORD +19 -0
- robolake-0.1.0.dist-info/WHEEL +4 -0
- robolake-0.1.0.dist-info/entry_points.txt +3 -0
- robolake-0.1.0.dist-info/licenses/LICENSE +201 -0
robolake/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Align multi-rate streams onto one shared timeline (one row per training frame)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import polars as pl
|
|
6
|
+
|
|
7
|
+
from robolake.ingest.mcap_reader import IngestResult
|
|
8
|
+
from robolake.schema import RobotConfig, Role
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class AlignResult:
|
|
13
|
+
frames: pl.DataFrame
|
|
14
|
+
fps: float
|
|
15
|
+
tolerance_ms: float
|
|
16
|
+
coverage: dict[str, float]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def align(
|
|
20
|
+
result: IngestResult,
|
|
21
|
+
config: RobotConfig,
|
|
22
|
+
fps: float = 15.0,
|
|
23
|
+
tolerance_ms: float = 100.0,
|
|
24
|
+
reference: str | None = None,
|
|
25
|
+
) -> AlignResult:
|
|
26
|
+
"""Match every stream to a fixed-rate frame grid.
|
|
27
|
+
|
|
28
|
+
For each frame time t, each stream contributes its latest sample at or before t
|
|
29
|
+
(never a future one), as long as it is no older than `tolerance_ms`.
|
|
30
|
+
Otherwise the value is null and the frame is flagged by the coverage numbers.
|
|
31
|
+
|
|
32
|
+
Frame times come from a fixed `fps` grid, or, if `reference` names a stream,
|
|
33
|
+
from that stream's own timestamps (e.g. a camera, so its images are never stale).
|
|
34
|
+
"""
|
|
35
|
+
numeric = pl.from_arrow(result.numeric)
|
|
36
|
+
cameras = pl.from_arrow(result.cameras).drop("data") # keep pointers, not image bytes
|
|
37
|
+
|
|
38
|
+
sources: dict[str, pl.DataFrame] = {}
|
|
39
|
+
for spec in config.streams:
|
|
40
|
+
table = cameras if spec.role is Role.CAMERA else numeric
|
|
41
|
+
rows = table.filter(pl.col("stream") == spec.name).sort("t_ns")
|
|
42
|
+
if rows.is_empty():
|
|
43
|
+
raise ValueError(f"stream '{spec.name}' has no samples to align")
|
|
44
|
+
sources[spec.name] = rows
|
|
45
|
+
|
|
46
|
+
# Only the time window where every stream has started and none has ended.
|
|
47
|
+
start_ns = max(df["t_ns"].min() for df in sources.values())
|
|
48
|
+
end_ns = min(df["t_ns"].max() for df in sources.values())
|
|
49
|
+
if start_ns >= end_ns:
|
|
50
|
+
raise ValueError("streams do not overlap in time")
|
|
51
|
+
|
|
52
|
+
if reference is None:
|
|
53
|
+
step_ns = round(1e9 / fps)
|
|
54
|
+
grid = pl.int_range(start_ns, end_ns + 1, step_ns, dtype=pl.Int64, eager=True)
|
|
55
|
+
elif reference in sources:
|
|
56
|
+
ref = sources[reference]["t_ns"]
|
|
57
|
+
grid = ref.filter((ref >= start_ns) & (ref <= end_ns))
|
|
58
|
+
else:
|
|
59
|
+
raise ValueError(f"unknown reference stream '{reference}'")
|
|
60
|
+
|
|
61
|
+
frames = pl.DataFrame({"t_ns": grid})
|
|
62
|
+
frames = frames.with_row_index("frame_index").with_columns(
|
|
63
|
+
((pl.col("t_ns") - pl.col("t_ns").first()) / 1e9).alias("timestamp")
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
tolerance_ns = int(tolerance_ms * 1e6)
|
|
67
|
+
coverage: dict[str, float] = {}
|
|
68
|
+
for spec in config.streams:
|
|
69
|
+
name = spec.name
|
|
70
|
+
src = sources[name].select(pl.col("t_ns").alias(f"{name}.src_t_ns"), *_payload(spec.role, name))
|
|
71
|
+
frames = frames.join_asof(
|
|
72
|
+
src,
|
|
73
|
+
left_on="t_ns",
|
|
74
|
+
right_on=f"{name}.src_t_ns",
|
|
75
|
+
strategy="backward",
|
|
76
|
+
tolerance=tolerance_ns,
|
|
77
|
+
).with_columns(((pl.col("t_ns") - pl.col(f"{name}.src_t_ns")) / 1e6).alias(f"{name}.age_ms"))
|
|
78
|
+
coverage[name] = 1 - frames[f"{name}.src_t_ns"].null_count() / frames.height
|
|
79
|
+
|
|
80
|
+
return AlignResult(frames=frames, fps=fps, tolerance_ms=tolerance_ms, coverage=coverage)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _payload(role: Role, name: str) -> list[pl.Expr]:
|
|
84
|
+
if role is Role.CAMERA:
|
|
85
|
+
return [] # the matched src_t_ns is the pointer into the camera table
|
|
86
|
+
return [pl.col("values").alias(name)]
|
robolake/cli.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""robolake command-line interface."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
from mcap.reader import make_reader
|
|
8
|
+
|
|
9
|
+
from robolake.pipeline import run_pipeline
|
|
10
|
+
from robolake.schema import RobotConfig
|
|
11
|
+
from robolake.sim import SimConfig, simulate
|
|
12
|
+
from robolake.validate.quality import ICON, Status
|
|
13
|
+
|
|
14
|
+
app = typer.Typer(help="Ingest, align, validate and export multimodal robot data.", no_args_is_help=True)
|
|
15
|
+
|
|
16
|
+
ConfigOpt = Annotated[Path, typer.Option("--config", "-c", exists=True, dir_okay=False, help="Robot topic-map YAML")]
|
|
17
|
+
InputArg = Annotated[Path, typer.Argument(exists=True, dir_okay=False, help="ROS 2 MCAP recording")]
|
|
18
|
+
ReferenceOpt = Annotated[str | None, typer.Option(help="Stream whose timestamps define the frames (default: first camera)")]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@app.command()
|
|
22
|
+
def inspect(mcap: InputArg) -> None:
|
|
23
|
+
"""List the topics in a recording, with message counts and rates (use it to write a config)."""
|
|
24
|
+
with open(mcap, "rb") as f:
|
|
25
|
+
summary = make_reader(f).get_summary()
|
|
26
|
+
stats = summary.statistics
|
|
27
|
+
duration_s = (stats.message_end_time - stats.message_start_time) / 1e9
|
|
28
|
+
typer.echo(f"{mcap.name}: {stats.message_count} messages, {len(summary.channels)} topics, {duration_s:.2f} s\n")
|
|
29
|
+
typer.echo(f"{'topic':60s} {'type':40s} {'count':>7s} {'Hz':>7s}")
|
|
30
|
+
for channel_id, channel in sorted(summary.channels.items(), key=lambda kv: kv[1].topic):
|
|
31
|
+
count = stats.channel_message_counts.get(channel_id, 0)
|
|
32
|
+
hz = count / duration_s if duration_s else 0.0
|
|
33
|
+
schema = summary.schemas[channel.schema_id].name
|
|
34
|
+
typer.echo(f"{channel.topic:60s} {schema:40s} {count:7d} {hz:7.1f}")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@app.command()
|
|
38
|
+
def validate(
|
|
39
|
+
mcap: InputArg,
|
|
40
|
+
config: ConfigOpt,
|
|
41
|
+
report_dir: Annotated[Path | None, typer.Option(help="Write quality.json and quality.md here")] = None,
|
|
42
|
+
fps: float = 15.0,
|
|
43
|
+
tolerance_ms: float = 100.0,
|
|
44
|
+
reference: ReferenceOpt = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
"""Check a recording's quality. Exits with code 1 if any check fails (useful in CI)."""
|
|
47
|
+
result = run_pipeline(
|
|
48
|
+
mcap, RobotConfig.from_yaml(config), fps=fps, tolerance_ms=tolerance_ms, reference=reference, build=False
|
|
49
|
+
)
|
|
50
|
+
_print_report(result.report)
|
|
51
|
+
if report_dir:
|
|
52
|
+
paths = result.report.write(report_dir)
|
|
53
|
+
typer.echo(f"\nreport written to {paths['markdown']}")
|
|
54
|
+
if result.report.status is Status.FAIL:
|
|
55
|
+
raise typer.Exit(code=1)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@app.command()
|
|
59
|
+
def convert(
|
|
60
|
+
mcap: InputArg,
|
|
61
|
+
config: ConfigOpt,
|
|
62
|
+
out: Annotated[Path, typer.Option("--out", "-o", help="Output folder for the LeRobot dataset (must not exist)")],
|
|
63
|
+
repo_id: Annotated[str, typer.Option(help="Dataset id, e.g. your-name/my-robot-data")] = "local/robolake-dataset",
|
|
64
|
+
task: Annotated[str, typer.Option(help="Natural-language task description")] = "robot demonstration",
|
|
65
|
+
fps: float = 15.0,
|
|
66
|
+
tolerance_ms: float = 100.0,
|
|
67
|
+
reference: ReferenceOpt = None,
|
|
68
|
+
force: Annotated[bool, typer.Option(help="Export even if a quality check fails")] = False,
|
|
69
|
+
push: Annotated[bool, typer.Option(help="Upload the dataset to the Hugging Face Hub after export")] = False,
|
|
70
|
+
private: Annotated[bool, typer.Option(help="With --push: make the Hub dataset private")] = True,
|
|
71
|
+
dataset_license: Annotated[
|
|
72
|
+
str, typer.Option("--license", help="With --push: license of YOUR data, e.g. apache-2.0")
|
|
73
|
+
] = "other",
|
|
74
|
+
) -> None:
|
|
75
|
+
"""Convert a recording into a LeRobot v3 dataset (requires the 'lerobot' extra)."""
|
|
76
|
+
if push and repo_id.startswith("local/"):
|
|
77
|
+
typer.echo("error: --push needs a real --repo-id, e.g. your-hf-name/my-robot-data", err=True)
|
|
78
|
+
raise typer.Exit(code=2)
|
|
79
|
+
if out.exists():
|
|
80
|
+
typer.echo(f"error: {out} already exists", err=True)
|
|
81
|
+
raise typer.Exit(code=2)
|
|
82
|
+
|
|
83
|
+
robot = RobotConfig.from_yaml(config)
|
|
84
|
+
result = run_pipeline(mcap, robot, fps=fps, tolerance_ms=tolerance_ms, reference=reference)
|
|
85
|
+
_print_report(result.report)
|
|
86
|
+
if result.report.status is Status.FAIL and not force:
|
|
87
|
+
typer.echo("\nnot exported: fix the failing checks or pass --force", err=True)
|
|
88
|
+
raise typer.Exit(code=1)
|
|
89
|
+
|
|
90
|
+
from robolake.store.lerobot_v3 import export_lerobot
|
|
91
|
+
|
|
92
|
+
export_lerobot(result.episode, repo_id=repo_id, root=out, fps=round(fps), task=task, robot_type=robot.robot_type)
|
|
93
|
+
result.report.write(out) # the quality report travels with the dataset
|
|
94
|
+
typer.echo(f"\nexported {len(result.episode.frames)} frames to {out}")
|
|
95
|
+
|
|
96
|
+
if push:
|
|
97
|
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
|
98
|
+
|
|
99
|
+
LeRobotDataset(repo_id, root=out).push_to_hub(
|
|
100
|
+
private=private, license=dataset_license, tags=["robolake", "ros2", "mcap"]
|
|
101
|
+
)
|
|
102
|
+
typer.echo(f"pushed to https://huggingface.co/datasets/{repo_id}")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@app.command(name="simulate")
|
|
106
|
+
def simulate_cmd(
|
|
107
|
+
out: Annotated[Path, typer.Argument(help="Path of the .mcap file to write")],
|
|
108
|
+
seconds: float = 8.0,
|
|
109
|
+
seed: int = 0,
|
|
110
|
+
) -> None:
|
|
111
|
+
"""Write a simulated robot-arm recording (realistic problems included) for demos and tests."""
|
|
112
|
+
path = simulate(out, SimConfig(seconds=seconds, seed=seed))
|
|
113
|
+
typer.echo(f"wrote {path} ({path.stat().st_size / 1e6:.2f} MB)")
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _print_report(report) -> None:
|
|
117
|
+
typer.echo(f"Quality: {ICON[report.status]} {report.status.upper()} ({report.episode_id})")
|
|
118
|
+
for c in report.checks:
|
|
119
|
+
if c.status is not Status.PASS:
|
|
120
|
+
typer.echo(f" {ICON[c.status]} {c.check:17s} {c.stream:32s} {c.message}")
|
|
121
|
+
passed = sum(c.status is Status.PASS for c in report.checks)
|
|
122
|
+
typer.echo(f" {passed} of {len(report.checks)} checks passed")
|
|
File without changes
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Read a ROS 2 MCAP log into robolake's canonical tables."""
|
|
2
|
+
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pyarrow as pa
|
|
9
|
+
import pyarrow.parquet as pq
|
|
10
|
+
from mcap.reader import make_reader
|
|
11
|
+
from mcap_ros2.decoder import DecoderFactory
|
|
12
|
+
|
|
13
|
+
from robolake.schema import CAMERA_FRAMES, NUMERIC_SAMPLES, RobotConfig, Role
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class IngestResult:
|
|
18
|
+
"""The canonical tables plus counts of everything the reader fixed or skipped."""
|
|
19
|
+
|
|
20
|
+
numeric: pa.Table
|
|
21
|
+
cameras: pa.Table
|
|
22
|
+
messages_read: dict[str, int] = field(default_factory=dict)
|
|
23
|
+
duplicates_dropped: dict[str, int] = field(default_factory=dict)
|
|
24
|
+
stamp_fallbacks: dict[str, int] = field(default_factory=dict)
|
|
25
|
+
skipped_empty: dict[str, int] = field(default_factory=dict)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def read_mcap(path: str | Path, config: RobotConfig, episode_id: str | None = None) -> IngestResult:
|
|
29
|
+
path = Path(path)
|
|
30
|
+
episode_id = episode_id or path.stem
|
|
31
|
+
by_topic = {s.topic: s for s in config.streams}
|
|
32
|
+
|
|
33
|
+
numeric_rows: list[dict[str, Any]] = []
|
|
34
|
+
camera_rows: list[dict[str, Any]] = []
|
|
35
|
+
seen: set[tuple[str, int]] = set()
|
|
36
|
+
messages_read: dict[str, int] = defaultdict(int)
|
|
37
|
+
duplicates: dict[str, int] = defaultdict(int)
|
|
38
|
+
fallbacks: dict[str, int] = defaultdict(int)
|
|
39
|
+
skipped: dict[str, int] = defaultdict(int)
|
|
40
|
+
|
|
41
|
+
with open(path, "rb") as f:
|
|
42
|
+
reader = make_reader(f, decoder_factories=[DecoderFactory()])
|
|
43
|
+
for _schema, channel, message, ros_msg in reader.iter_decoded_messages(topics=list(by_topic)):
|
|
44
|
+
spec = by_topic[channel.topic]
|
|
45
|
+
messages_read[spec.name] += 1
|
|
46
|
+
|
|
47
|
+
# Sensor time first; fall back to recorder time if the stamp is missing or zero.
|
|
48
|
+
t_ns = _stamp_ns(ros_msg) if config.time_source == "header" else None
|
|
49
|
+
if not t_ns:
|
|
50
|
+
if config.time_source == "header":
|
|
51
|
+
fallbacks[spec.name] += 1
|
|
52
|
+
t_ns = message.log_time
|
|
53
|
+
|
|
54
|
+
# Same stream + same timestamp = duplicate (Step 1B: all were identical copies).
|
|
55
|
+
key = (spec.name, t_ns)
|
|
56
|
+
if key in seen:
|
|
57
|
+
duplicates[spec.name] += 1
|
|
58
|
+
continue
|
|
59
|
+
seen.add(key)
|
|
60
|
+
|
|
61
|
+
base = {"episode_id": episode_id, "stream": spec.name, "t_ns": t_ns, "log_ns": message.log_time}
|
|
62
|
+
if spec.role is Role.CAMERA:
|
|
63
|
+
camera_rows.append({**base, "format": _image_format(ros_msg.format), "data": bytes(ros_msg.data)})
|
|
64
|
+
else:
|
|
65
|
+
values = _resolve(ros_msg, spec.msg_field)
|
|
66
|
+
if values is None:
|
|
67
|
+
skipped[spec.name] += 1
|
|
68
|
+
continue
|
|
69
|
+
numeric_rows.append({**base, "values": [float(v) for v in values]})
|
|
70
|
+
|
|
71
|
+
return IngestResult(
|
|
72
|
+
numeric=pa.Table.from_pylist(numeric_rows, schema=NUMERIC_SAMPLES),
|
|
73
|
+
cameras=pa.Table.from_pylist(camera_rows, schema=CAMERA_FRAMES),
|
|
74
|
+
messages_read=dict(messages_read),
|
|
75
|
+
duplicates_dropped=dict(duplicates),
|
|
76
|
+
stamp_fallbacks=dict(fallbacks),
|
|
77
|
+
skipped_empty=dict(skipped),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def write_parquet(result: IngestResult, out_dir: str | Path) -> dict[str, Path]:
|
|
82
|
+
out = Path(out_dir)
|
|
83
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
84
|
+
paths = {"numeric": out / "numeric.parquet", "cameras": out / "cameras.parquet"}
|
|
85
|
+
pq.write_table(result.numeric, paths["numeric"], compression="zstd")
|
|
86
|
+
pq.write_table(result.cameras, paths["cameras"], compression="zstd")
|
|
87
|
+
return paths
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _stamp_ns(ros_msg: Any) -> int | None:
|
|
91
|
+
header = getattr(ros_msg, "header", None)
|
|
92
|
+
if header is None:
|
|
93
|
+
return None
|
|
94
|
+
return header.stamp.sec * 1_000_000_000 + header.stamp.nanosec
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _resolve(msg: Any, field_path: str | None) -> Any:
|
|
98
|
+
"""Follow a path like 'position' or 'points.0.positions' into a message."""
|
|
99
|
+
if field_path is None:
|
|
100
|
+
raise ValueError("numeric streams need msg_field in the config")
|
|
101
|
+
value = msg
|
|
102
|
+
for part in field_path.split("."):
|
|
103
|
+
if part.isdigit():
|
|
104
|
+
index = int(part)
|
|
105
|
+
if index >= len(value):
|
|
106
|
+
return None # e.g. a trajectory with no points
|
|
107
|
+
value = value[index]
|
|
108
|
+
else:
|
|
109
|
+
value = getattr(value, part)
|
|
110
|
+
return value
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _image_format(fmt: str) -> str:
|
|
114
|
+
fmt = fmt.lower()
|
|
115
|
+
if "jpeg" in fmt or "jpg" in fmt:
|
|
116
|
+
return "jpeg"
|
|
117
|
+
if "png" in fmt:
|
|
118
|
+
return "png"
|
|
119
|
+
return fmt or "unknown"
|
robolake/pipeline.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Run the whole robolake pipeline in one call: ingest -> align -> validate (-> build episode)."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from robolake.align.timeline import AlignResult, align
|
|
7
|
+
from robolake.ingest.mcap_reader import IngestResult, read_mcap
|
|
8
|
+
from robolake.schema import RobotConfig, Role
|
|
9
|
+
from robolake.store.lerobot_v3 import EpisodeData, build_episode
|
|
10
|
+
from robolake.validate.quality import QualityReport, Thresholds, validate
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class PipelineResult:
|
|
15
|
+
ingest: IngestResult
|
|
16
|
+
aligned: AlignResult
|
|
17
|
+
report: QualityReport
|
|
18
|
+
episode: EpisodeData | None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def run_pipeline(
|
|
22
|
+
mcap_path: str | Path,
|
|
23
|
+
config: RobotConfig,
|
|
24
|
+
*,
|
|
25
|
+
fps: float = 15.0,
|
|
26
|
+
tolerance_ms: float = 100.0,
|
|
27
|
+
reference: str | None = None,
|
|
28
|
+
thresholds: Thresholds | None = None,
|
|
29
|
+
build: bool = True,
|
|
30
|
+
trim_idle: bool = True,
|
|
31
|
+
) -> PipelineResult:
|
|
32
|
+
"""Read, align and validate one recording; optionally build the LeRobot episode.
|
|
33
|
+
|
|
34
|
+
By default frames follow the first camera's own timestamps (see docs/05-alignment.md),
|
|
35
|
+
so that camera's images are never stale.
|
|
36
|
+
"""
|
|
37
|
+
if reference is None:
|
|
38
|
+
cameras = config.by_role(Role.CAMERA)
|
|
39
|
+
reference = cameras[0].name if cameras else None
|
|
40
|
+
|
|
41
|
+
ingest = read_mcap(mcap_path, config)
|
|
42
|
+
aligned = align(ingest, config, fps=fps, tolerance_ms=tolerance_ms, reference=reference)
|
|
43
|
+
report = validate(ingest, aligned, config, thresholds)
|
|
44
|
+
episode = build_episode(ingest, aligned, config, trim_idle=trim_idle) if build else None
|
|
45
|
+
return PipelineResult(ingest=ingest, aligned=aligned, report=report, episode=episode)
|
robolake/schema.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""Canonical data model for robolake.
|
|
2
|
+
|
|
3
|
+
Every input format (MCAP, LeRobot, HDF5) is converted into these structures
|
|
4
|
+
before alignment, validation and export.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Literal, Self
|
|
10
|
+
|
|
11
|
+
import pyarrow as pa
|
|
12
|
+
import yaml
|
|
13
|
+
from pydantic import BaseModel, Field, model_validator
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Role(StrEnum):
|
|
17
|
+
"""What a stream represents for robot learning."""
|
|
18
|
+
|
|
19
|
+
STATE = "state" # what the robot measured (e.g. joint positions)
|
|
20
|
+
ACTION = "action" # what the robot was told to do
|
|
21
|
+
CAMERA = "camera" # image frames
|
|
22
|
+
OTHER = "other" # kept, but not used for training
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class StreamSpec(BaseModel):
|
|
26
|
+
"""One logical stream, e.g. the joint positions or a wrist camera."""
|
|
27
|
+
|
|
28
|
+
name: str = Field(description="Canonical name, e.g. 'observation.state'")
|
|
29
|
+
role: Role
|
|
30
|
+
topic: str = Field(description="Source topic in the raw log, e.g. '/joint_states'")
|
|
31
|
+
msg_field: str | None = Field(default=None, description="Message field to read, e.g. 'position'")
|
|
32
|
+
names: list[str] | None = Field(default=None, description="Per-dimension names, e.g. joint names")
|
|
33
|
+
unit: str | None = Field(default=None, description="Unit of numeric values, e.g. 'rad'")
|
|
34
|
+
nominal_hz: float | None = Field(default=None, gt=0, description="Expected rate")
|
|
35
|
+
|
|
36
|
+
@model_validator(mode="after")
|
|
37
|
+
def check_role_fields(self) -> Self:
|
|
38
|
+
if self.role is Role.CAMERA and (self.names or self.unit):
|
|
39
|
+
raise ValueError(f"camera stream '{self.name}' must not set names or unit")
|
|
40
|
+
if self.role in (Role.STATE, Role.ACTION) and self.unit is None:
|
|
41
|
+
raise ValueError(f"{self.role} stream '{self.name}' must declare a unit")
|
|
42
|
+
return self
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RobotConfig(BaseModel):
|
|
46
|
+
"""Maps a robot's raw topics to canonical streams."""
|
|
47
|
+
|
|
48
|
+
robot_type: str
|
|
49
|
+
time_source: Literal["header", "log"] = "header"
|
|
50
|
+
streams: list[StreamSpec]
|
|
51
|
+
|
|
52
|
+
@model_validator(mode="after")
|
|
53
|
+
def check_streams(self) -> Self:
|
|
54
|
+
names = [s.name for s in self.streams]
|
|
55
|
+
duplicates = {n for n in names if names.count(n) > 1}
|
|
56
|
+
if duplicates:
|
|
57
|
+
raise ValueError(f"duplicate stream names: {sorted(duplicates)}")
|
|
58
|
+
if not any(s.role is Role.STATE for s in self.streams):
|
|
59
|
+
raise ValueError("config needs at least one state stream")
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
def by_role(self, role: Role) -> list[StreamSpec]:
|
|
63
|
+
return [s for s in self.streams if s.role is role]
|
|
64
|
+
|
|
65
|
+
@classmethod
|
|
66
|
+
def from_yaml(cls, path: str | Path) -> Self:
|
|
67
|
+
with open(path) as f:
|
|
68
|
+
return cls.model_validate(yaml.safe_load(f))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# Numeric streams (state, action, other): one row per message.
|
|
72
|
+
NUMERIC_SAMPLES = pa.schema(
|
|
73
|
+
[
|
|
74
|
+
pa.field("episode_id", pa.string(), nullable=False),
|
|
75
|
+
pa.field("stream", pa.string(), nullable=False),
|
|
76
|
+
pa.field("t_ns", pa.int64(), nullable=False), # sensor time (header.stamp)
|
|
77
|
+
pa.field("log_ns", pa.int64(), nullable=False), # recorder time (log_time)
|
|
78
|
+
pa.field("values", pa.list_(pa.float64()), nullable=False),
|
|
79
|
+
]
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
# Camera streams: one row per frame, image kept in its original encoding.
|
|
83
|
+
CAMERA_FRAMES = pa.schema(
|
|
84
|
+
[
|
|
85
|
+
pa.field("episode_id", pa.string(), nullable=False),
|
|
86
|
+
pa.field("stream", pa.string(), nullable=False),
|
|
87
|
+
pa.field("t_ns", pa.int64(), nullable=False),
|
|
88
|
+
pa.field("log_ns", pa.int64(), nullable=False),
|
|
89
|
+
pa.field("format", pa.string(), nullable=False), # e.g. "jpeg", "png"
|
|
90
|
+
pa.field("data", pa.binary(), nullable=False),
|
|
91
|
+
]
|
|
92
|
+
)
|
|
File without changes
|
robolake/sim.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Generate a simulated robot-arm recording as a ROS 2 MCAP file.
|
|
2
|
+
|
|
3
|
+
The output looks like a real teleoperation log (joint states, operator commands and a camera)
|
|
4
|
+
and includes the same problems found in real data, so the whole pipeline can be demoed and
|
|
5
|
+
tested on data anyone can share.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from io import BytesIO
|
|
10
|
+
from math import cos, pi, sin
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
from mcap_ros2.writer import Writer
|
|
15
|
+
from PIL import Image, ImageDraw
|
|
16
|
+
|
|
17
|
+
JOINTS = ["shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper"]
|
|
18
|
+
|
|
19
|
+
_SEP = "=" * 80
|
|
20
|
+
_TIME = "MSG: builtin_interfaces/Time\nint32 sec\nuint32 nanosec"
|
|
21
|
+
_DURATION = "MSG: builtin_interfaces/Duration\nint32 sec\nuint32 nanosec"
|
|
22
|
+
_HEADER = "MSG: std_msgs/Header\nbuiltin_interfaces/Time stamp\nstring frame_id"
|
|
23
|
+
_POINT = (
|
|
24
|
+
"MSG: trajectory_msgs/JointTrajectoryPoint\nfloat64[] positions\nfloat64[] velocities\n"
|
|
25
|
+
"float64[] accelerations\nfloat64[] effort\nbuiltin_interfaces/Duration time_from_start"
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _msgdef(main: str, *deps: str) -> str:
|
|
30
|
+
parts = [main]
|
|
31
|
+
for dep in deps:
|
|
32
|
+
parts += [_SEP, dep]
|
|
33
|
+
return "\n".join(parts)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
JOINT_STATE_DEF = _msgdef(
|
|
37
|
+
"std_msgs/Header header\nstring[] name\nfloat64[] position\nfloat64[] velocity\nfloat64[] effort", _HEADER, _TIME
|
|
38
|
+
)
|
|
39
|
+
TRAJECTORY_DEF = _msgdef(
|
|
40
|
+
"std_msgs/Header header\nstring[] joint_names\nJointTrajectoryPoint[] points", _HEADER, _TIME, _POINT, _DURATION
|
|
41
|
+
)
|
|
42
|
+
IMAGE_DEF = _msgdef("std_msgs/Header header\nstring format\nuint8[] data", _HEADER, _TIME)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class SimConfig:
|
|
47
|
+
seconds: float = 8.0
|
|
48
|
+
idle_seconds: float = 1.0 # robot still at the start, like real recordings
|
|
49
|
+
state_hz: float = 100.0
|
|
50
|
+
command_hz: float = 50.0
|
|
51
|
+
camera_hz: float = 15.0
|
|
52
|
+
response_lag_s: float = 0.1 # how far the measured joints trail the commands
|
|
53
|
+
sensor_noise_rad: float = 0.0001 # encoder noise; must stay below the idle-detection threshold (1e-3)
|
|
54
|
+
duplicate_states: bool = True # every joint state published twice (seen in real data)
|
|
55
|
+
stamp_commands: bool = False # real operator commands had no sensor timestamp
|
|
56
|
+
dropped_camera_frames: tuple[int, ...] = (40,) # frame indexes that never arrive
|
|
57
|
+
image_size: tuple[int, int] = (320, 240)
|
|
58
|
+
seed: int = 0
|
|
59
|
+
start_ns: int = 1_767_225_600_000_000_000 # 2026-01-01 00:00:00 UTC
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def commanded_positions(t: float, cfg: SimConfig) -> np.ndarray:
|
|
63
|
+
"""Operator command at time t: still during the idle period, then a smooth reach-and-grasp loop."""
|
|
64
|
+
t = max(t, cfg.idle_seconds)
|
|
65
|
+
phase = 2 * pi * (t - cfg.idle_seconds) / 4.0 # one reach cycle every 4 s
|
|
66
|
+
return np.array(
|
|
67
|
+
[
|
|
68
|
+
0.6 * sin(phase / 2), # shoulder_pan
|
|
69
|
+
0.3 - 0.4 * (1 - cos(phase)) / 2, # shoulder_lift
|
|
70
|
+
0.8 + 0.5 * (1 - cos(phase)) / 2, # elbow_flex
|
|
71
|
+
-0.3 * sin(phase), # wrist_flex
|
|
72
|
+
0.2 * sin(phase / 2), # wrist_roll
|
|
73
|
+
1.0 if sin(phase) > 0 else 0.1, # gripper: open, then closed
|
|
74
|
+
]
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def simulate(path: str | Path, cfg: SimConfig | None = None) -> Path:
|
|
79
|
+
"""Write a simulated recording to `path` and return it."""
|
|
80
|
+
cfg = cfg or SimConfig()
|
|
81
|
+
path = Path(path)
|
|
82
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
83
|
+
rng = np.random.default_rng(cfg.seed)
|
|
84
|
+
|
|
85
|
+
with open(path, "wb") as f:
|
|
86
|
+
writer = Writer(f)
|
|
87
|
+
js = writer.register_msgdef("sensor_msgs/msg/JointState", JOINT_STATE_DEF)
|
|
88
|
+
traj = writer.register_msgdef("trajectory_msgs/msg/JointTrajectory", TRAJECTORY_DEF)
|
|
89
|
+
img = writer.register_msgdef("sensor_msgs/msg/CompressedImage", IMAGE_DEF)
|
|
90
|
+
|
|
91
|
+
events = [] # (log_time_ns, kind, t_seconds, index)
|
|
92
|
+
for kind, hz in (("state", cfg.state_hz), ("command", cfg.command_hz), ("camera", cfg.camera_hz)):
|
|
93
|
+
for i in range(int(cfg.seconds * hz)):
|
|
94
|
+
t = i / hz
|
|
95
|
+
events.append((cfg.start_ns + int((t + rng.uniform(0.001, 0.004)) * 1e9), kind, t, i))
|
|
96
|
+
events.sort()
|
|
97
|
+
|
|
98
|
+
for log_ns, kind, t, i in events:
|
|
99
|
+
stamp_ns = cfg.start_ns + int(t * 1e9)
|
|
100
|
+
if kind == "state":
|
|
101
|
+
measured = commanded_positions(t - cfg.response_lag_s, cfg) + rng.normal(0, cfg.sensor_noise_rad, len(JOINTS))
|
|
102
|
+
msg = {"header": _header(stamp_ns), "name": JOINTS, "position": measured.tolist(),
|
|
103
|
+
"velocity": [], "effort": []}
|
|
104
|
+
for _ in range(2 if cfg.duplicate_states else 1):
|
|
105
|
+
writer.write_message("/joint_states", js, msg, log_time=log_ns, publish_time=log_ns)
|
|
106
|
+
elif kind == "command":
|
|
107
|
+
point = {"positions": commanded_positions(t, cfg).tolist(), "velocities": [], "accelerations": [],
|
|
108
|
+
"effort": [], "time_from_start": {"sec": 0, "nanosec": 0}}
|
|
109
|
+
msg = {"header": _header(stamp_ns if cfg.stamp_commands else 0), "joint_names": JOINTS,
|
|
110
|
+
"points": [point]}
|
|
111
|
+
writer.write_message("/leader/joint_trajectory", traj, msg, log_time=log_ns, publish_time=log_ns)
|
|
112
|
+
elif i not in cfg.dropped_camera_frames:
|
|
113
|
+
measured = commanded_positions(t - cfg.response_lag_s, cfg)
|
|
114
|
+
msg = {"header": _header(stamp_ns), "format": "jpeg",
|
|
115
|
+
"data": _render(measured, cfg.image_size)}
|
|
116
|
+
writer.write_message("/camera/image/compressed", img, msg, log_time=log_ns, publish_time=log_ns)
|
|
117
|
+
writer.finish()
|
|
118
|
+
return path
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _header(t_ns: int) -> dict:
|
|
122
|
+
return {"stamp": {"sec": t_ns // 1_000_000_000, "nanosec": t_ns % 1_000_000_000}, "frame_id": ""}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _render(q: np.ndarray, size: tuple[int, int]) -> bytes:
|
|
126
|
+
"""Draw a simple 2-link arm seen from the side, so the video visibly matches the joint data."""
|
|
127
|
+
w, h = size
|
|
128
|
+
image = Image.new("RGB", size, (235, 235, 230))
|
|
129
|
+
draw = ImageDraw.Draw(image)
|
|
130
|
+
draw.rectangle([0, int(h * 0.85), w, h], fill=(120, 120, 120)) # table
|
|
131
|
+
base = (w / 2 + q[0] * w * 0.25, h * 0.85)
|
|
132
|
+
a1 = -pi / 2 + q[1]
|
|
133
|
+
elbow = (base[0] + 0.3 * h * cos(a1), base[1] + 0.3 * h * sin(a1))
|
|
134
|
+
a2 = a1 + q[2]
|
|
135
|
+
wrist = (elbow[0] + 0.25 * h * cos(a2), elbow[1] + 0.25 * h * sin(a2))
|
|
136
|
+
draw.line([base, elbow, wrist], fill=(40, 90, 200), width=8)
|
|
137
|
+
gap = 4 + 10 * q[5]
|
|
138
|
+
draw.ellipse([wrist[0] - gap, wrist[1] - gap, wrist[0] + gap, wrist[1] + gap], outline=(200, 60, 40), width=3)
|
|
139
|
+
buf = BytesIO()
|
|
140
|
+
image.save(buf, format="JPEG", quality=85)
|
|
141
|
+
return buf.getvalue()
|
|
File without changes
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Export an aligned episode in Hugging Face LeRobot v3 format."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterator
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from io import BytesIO
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import polars as pl
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from robolake.align.timeline import AlignResult
|
|
13
|
+
from robolake.ingest.mcap_reader import IngestResult
|
|
14
|
+
from robolake.schema import RobotConfig, Role, StreamSpec
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class EpisodeData:
|
|
19
|
+
features: dict
|
|
20
|
+
frames: list[dict]
|
|
21
|
+
idle_frames_trimmed: int
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def trim_idle_start(frames: pl.DataFrame, state: str, epsilon: float = 1e-3) -> tuple[pl.DataFrame, int]:
|
|
25
|
+
"""Drop leading frames where the robot state has not changed from the first frame."""
|
|
26
|
+
rows = frames[state].to_list()
|
|
27
|
+
first = rows[0]
|
|
28
|
+
idle = 0
|
|
29
|
+
for row in rows:
|
|
30
|
+
if row is None or max(abs(a - b) for a, b in zip(row, first)) > epsilon:
|
|
31
|
+
break
|
|
32
|
+
idle += 1
|
|
33
|
+
keep_from = max(idle - 1, 0) # keep the last still frame so the episode starts at rest
|
|
34
|
+
return frames.slice(keep_from), keep_from
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def build_episode(
|
|
38
|
+
ingest: IngestResult,
|
|
39
|
+
aligned: AlignResult,
|
|
40
|
+
config: RobotConfig,
|
|
41
|
+
trim_idle: bool = True,
|
|
42
|
+
) -> EpisodeData:
|
|
43
|
+
"""Turn aligned frames into LeRobot feature specs and per-frame dicts (numpy + PIL)."""
|
|
44
|
+
states = config.by_role(Role.STATE)
|
|
45
|
+
actions = config.by_role(Role.ACTION)
|
|
46
|
+
cameras = config.by_role(Role.CAMERA)
|
|
47
|
+
if len(states) != 1:
|
|
48
|
+
raise ValueError("LeRobot export needs exactly one state stream")
|
|
49
|
+
|
|
50
|
+
frames = aligned.frames.drop_nulls([s.name for s in states + actions] + [f"{c.name}.src_t_ns" for c in cameras])
|
|
51
|
+
trimmed = 0
|
|
52
|
+
if trim_idle:
|
|
53
|
+
frames, trimmed = trim_idle_start(frames, states[0].name)
|
|
54
|
+
|
|
55
|
+
images = _image_lookup(ingest)
|
|
56
|
+
first = frames.row(0, named=True)
|
|
57
|
+
features = {
|
|
58
|
+
"observation.state": _vector_feature(states[0], len(first[states[0].name])),
|
|
59
|
+
"action": {
|
|
60
|
+
"dtype": "float32",
|
|
61
|
+
"shape": (sum(len(first[a.name]) for a in actions),),
|
|
62
|
+
"names": [n for a in actions for n in _names(a, len(first[a.name]))],
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
for cam in cameras:
|
|
66
|
+
height, width = _decode(images[(cam.name, first[f"{cam.name}.src_t_ns"])]).shape[:2]
|
|
67
|
+
features[cam.name] = {"dtype": "video", "shape": (height, width, 3), "names": ["height", "width", "channels"]}
|
|
68
|
+
|
|
69
|
+
out = list(_frames(frames, states[0], actions, cameras, images))
|
|
70
|
+
return EpisodeData(features=features, frames=out, idle_frames_trimmed=trimmed)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def export_lerobot(
|
|
74
|
+
episode: EpisodeData,
|
|
75
|
+
repo_id: str,
|
|
76
|
+
root: str | Path,
|
|
77
|
+
fps: int,
|
|
78
|
+
task: str,
|
|
79
|
+
robot_type: str | None = None,
|
|
80
|
+
):
|
|
81
|
+
"""Write the episode with the official LeRobot writer (optional dependency)."""
|
|
82
|
+
try:
|
|
83
|
+
from lerobot.datasets.lerobot_dataset import LeRobotDataset
|
|
84
|
+
except ImportError as e:
|
|
85
|
+
raise ImportError("LeRobot export needs the optional extra: uv sync --extra lerobot") from e
|
|
86
|
+
|
|
87
|
+
dataset = LeRobotDataset.create(
|
|
88
|
+
repo_id=repo_id, fps=fps, features=episode.features, root=root, robot_type=robot_type, use_videos=True
|
|
89
|
+
)
|
|
90
|
+
for frame in episode.frames:
|
|
91
|
+
dataset.add_frame({**frame, "task": task})
|
|
92
|
+
dataset.save_episode(parallel_encoding=False)
|
|
93
|
+
dataset.finalize()
|
|
94
|
+
return dataset
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _frames(
|
|
98
|
+
frames: pl.DataFrame,
|
|
99
|
+
state: StreamSpec,
|
|
100
|
+
actions: list[StreamSpec],
|
|
101
|
+
cameras: list[StreamSpec],
|
|
102
|
+
images: dict[tuple[str, int], bytes],
|
|
103
|
+
) -> Iterator[dict]:
|
|
104
|
+
for row in frames.iter_rows(named=True):
|
|
105
|
+
frame = {
|
|
106
|
+
"observation.state": np.asarray(row[state.name], dtype=np.float32),
|
|
107
|
+
"action": np.concatenate([np.asarray(row[a.name], dtype=np.float32) for a in actions]),
|
|
108
|
+
}
|
|
109
|
+
for cam in cameras:
|
|
110
|
+
frame[cam.name] = _decode(images[(cam.name, row[f"{cam.name}.src_t_ns"])])
|
|
111
|
+
yield frame
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _image_lookup(ingest: IngestResult) -> dict[tuple[str, int], bytes]:
|
|
115
|
+
cams = ingest.cameras
|
|
116
|
+
return dict(
|
|
117
|
+
zip(
|
|
118
|
+
zip(cams.column("stream").to_pylist(), cams.column("t_ns").to_pylist()),
|
|
119
|
+
cams.column("data").to_pylist(),
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _decode(data: bytes) -> np.ndarray:
|
|
125
|
+
return np.asarray(Image.open(BytesIO(data)).convert("RGB"))
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _names(spec: StreamSpec, size: int) -> list[str]:
|
|
129
|
+
return spec.names or [f"{spec.name}.{i}" for i in range(size)]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _vector_feature(spec: StreamSpec, size: int) -> dict:
|
|
133
|
+
return {"dtype": "float32", "shape": (size,), "names": _names(spec, size)}
|
|
File without changes
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Quality checks and reports for an ingested, aligned episode."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import asdict, dataclass, field
|
|
5
|
+
from enum import StrEnum
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import polars as pl
|
|
9
|
+
from pydantic import BaseModel
|
|
10
|
+
|
|
11
|
+
from robolake.align.timeline import AlignResult
|
|
12
|
+
from robolake.ingest.mcap_reader import IngestResult
|
|
13
|
+
from robolake.schema import RobotConfig, Role, StreamSpec
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Status(StrEnum):
|
|
17
|
+
PASS = "pass"
|
|
18
|
+
WARN = "warn"
|
|
19
|
+
FAIL = "fail"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
SEVERITY = {Status.PASS: 0, Status.WARN: 1, Status.FAIL: 2}
|
|
23
|
+
ICON = {Status.PASS: "✅", Status.WARN: "⚠️", Status.FAIL: "❌"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Thresholds(BaseModel):
|
|
27
|
+
"""Limits for each check. Defaults suit a 15 fps camera robot; override per project."""
|
|
28
|
+
|
|
29
|
+
warn_coverage: float = 0.99
|
|
30
|
+
fail_coverage: float = 0.90
|
|
31
|
+
warn_camera_age_ms: float = 33.0
|
|
32
|
+
fail_camera_age_ms: float = 66.0
|
|
33
|
+
warn_duplicate_ratio: float = 0.05
|
|
34
|
+
warn_idle_fraction: float = 0.20
|
|
35
|
+
idle_epsilon: float = 1e-3
|
|
36
|
+
gap_factor: float = 1.5 # a gap longer than 1.5x the expected period counts as a dropped message
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class CheckResult:
|
|
41
|
+
check: str
|
|
42
|
+
stream: str
|
|
43
|
+
status: Status
|
|
44
|
+
value: float
|
|
45
|
+
message: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class QualityReport:
|
|
50
|
+
episode_id: str
|
|
51
|
+
checks: list[CheckResult] = field(default_factory=list)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def status(self) -> Status:
|
|
55
|
+
"""Overall status = the worst status of any check."""
|
|
56
|
+
return max((c.status for c in self.checks), key=SEVERITY.__getitem__, default=Status.PASS)
|
|
57
|
+
|
|
58
|
+
def to_dict(self) -> dict:
|
|
59
|
+
return {"episode_id": self.episode_id, "status": self.status, "checks": [asdict(c) for c in self.checks]}
|
|
60
|
+
|
|
61
|
+
def to_markdown(self) -> str:
|
|
62
|
+
lines = [
|
|
63
|
+
f"# Quality report — {self.episode_id}",
|
|
64
|
+
"",
|
|
65
|
+
f"**Overall: {ICON[self.status]} {self.status.upper()}**",
|
|
66
|
+
"",
|
|
67
|
+
"| Check | Stream | Status | Value | Details |",
|
|
68
|
+
"|---|---|---|---|---|",
|
|
69
|
+
]
|
|
70
|
+
for c in self.checks:
|
|
71
|
+
lines.append(f"| {c.check} | {c.stream} | {ICON[c.status]} {c.status} | {c.value:.3g} | {c.message} |")
|
|
72
|
+
return "\n".join(lines) + "\n"
|
|
73
|
+
|
|
74
|
+
def write(self, out_dir: str | Path) -> dict[str, Path]:
|
|
75
|
+
out = Path(out_dir)
|
|
76
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
paths = {"json": out / "quality.json", "markdown": out / "quality.md"}
|
|
78
|
+
paths["json"].write_text(json.dumps(self.to_dict(), indent=2))
|
|
79
|
+
paths["markdown"].write_text(self.to_markdown())
|
|
80
|
+
return paths
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def validate(
|
|
84
|
+
ingest: IngestResult,
|
|
85
|
+
aligned: AlignResult,
|
|
86
|
+
config: RobotConfig,
|
|
87
|
+
thresholds: Thresholds | None = None,
|
|
88
|
+
) -> QualityReport:
|
|
89
|
+
t = thresholds or Thresholds()
|
|
90
|
+
episode_ids = ingest.numeric.column("episode_id").to_pylist()
|
|
91
|
+
report = QualityReport(episode_id=episode_ids[0] if episode_ids else "unknown")
|
|
92
|
+
|
|
93
|
+
for spec in config.streams:
|
|
94
|
+
report.checks.append(_coverage(spec.name, aligned.coverage[spec.name], t))
|
|
95
|
+
if spec.role is Role.CAMERA:
|
|
96
|
+
report.checks.append(_camera_age(spec.name, aligned.frames, t))
|
|
97
|
+
report.checks.append(_duplicates(spec.name, ingest, t))
|
|
98
|
+
report.checks.append(_clock(spec.name, ingest))
|
|
99
|
+
if spec.nominal_hz:
|
|
100
|
+
report.checks.append(_frame_gaps(spec, ingest, t))
|
|
101
|
+
|
|
102
|
+
report.checks.extend(_non_finite(ingest, config))
|
|
103
|
+
report.checks.append(_idle_start(config.by_role(Role.STATE)[0].name, aligned.frames, t))
|
|
104
|
+
return report
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _grade(value: float, warn: float, fail: float = float("inf"), higher_is_bad: bool = True) -> Status:
|
|
108
|
+
if not higher_is_bad:
|
|
109
|
+
value, warn, fail = -value, -warn, -fail
|
|
110
|
+
if value > fail:
|
|
111
|
+
return Status.FAIL
|
|
112
|
+
if value > warn:
|
|
113
|
+
return Status.WARN
|
|
114
|
+
return Status.PASS
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _coverage(name: str, coverage: float, t: Thresholds) -> CheckResult:
|
|
118
|
+
status = _grade(coverage, t.warn_coverage, t.fail_coverage, higher_is_bad=False)
|
|
119
|
+
return CheckResult("coverage", name, status, coverage, f"{coverage:.1%} of frames have a recent sample")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _camera_age(name: str, frames: pl.DataFrame, t: Thresholds) -> CheckResult:
|
|
123
|
+
mean_age = frames[f"{name}.age_ms"].mean()
|
|
124
|
+
if mean_age is None:
|
|
125
|
+
return CheckResult("camera_staleness", name, Status.FAIL, float("nan"), "no camera frame matched any frame")
|
|
126
|
+
status = _grade(mean_age, t.warn_camera_age_ms, t.fail_camera_age_ms)
|
|
127
|
+
return CheckResult("camera_staleness", name, status, mean_age, f"images are {mean_age:.1f} ms old on average")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _duplicates(name: str, ingest: IngestResult, t: Thresholds) -> CheckResult:
|
|
131
|
+
read = ingest.messages_read.get(name, 0)
|
|
132
|
+
dropped = ingest.duplicates_dropped.get(name, 0)
|
|
133
|
+
ratio = dropped / read if read else 0.0
|
|
134
|
+
status = _grade(ratio, t.warn_duplicate_ratio)
|
|
135
|
+
return CheckResult("duplicates", name, status, ratio, f"{dropped} of {read} messages were duplicates (dropped)")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _clock(name: str, ingest: IngestResult) -> CheckResult:
|
|
139
|
+
read = ingest.messages_read.get(name, 0)
|
|
140
|
+
fallbacks = ingest.stamp_fallbacks.get(name, 0)
|
|
141
|
+
ratio = fallbacks / read if read else 0.0
|
|
142
|
+
status = Status.WARN if fallbacks else Status.PASS
|
|
143
|
+
return CheckResult("sensor_clock", name, status, ratio, f"{fallbacks} of {read} messages had no sensor timestamp")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _frame_gaps(spec: StreamSpec, ingest: IngestResult, t: Thresholds) -> CheckResult:
|
|
147
|
+
table = ingest.cameras if spec.role is Role.CAMERA else ingest.numeric
|
|
148
|
+
times = pl.from_arrow(table.select(["stream", "t_ns"])).filter(pl.col("stream") == spec.name)["t_ns"].sort()
|
|
149
|
+
gaps_ms = (times.diff().drop_nulls() / 1e6).to_list()
|
|
150
|
+
limit_ms = t.gap_factor * 1000 / spec.nominal_hz
|
|
151
|
+
big = [g for g in gaps_ms if g > limit_ms]
|
|
152
|
+
longest = max(gaps_ms, default=0.0)
|
|
153
|
+
status = Status.WARN if big else Status.PASS
|
|
154
|
+
message = f"{len(big)} gaps > {limit_ms:.0f} ms (expected {spec.nominal_hz:g} Hz); longest {longest:.0f} ms"
|
|
155
|
+
return CheckResult("frame_gaps", spec.name, status, len(big), message)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _non_finite(ingest: IngestResult, config: RobotConfig) -> list[CheckResult]:
|
|
159
|
+
bad = (
|
|
160
|
+
pl.from_arrow(ingest.numeric)
|
|
161
|
+
.explode("values")
|
|
162
|
+
.filter(~pl.col("values").is_finite())
|
|
163
|
+
.group_by("stream")
|
|
164
|
+
.len()
|
|
165
|
+
)
|
|
166
|
+
counts = dict(zip(bad["stream"].to_list(), bad["len"].to_list()))
|
|
167
|
+
results = []
|
|
168
|
+
for spec in config.streams:
|
|
169
|
+
if spec.role is Role.CAMERA:
|
|
170
|
+
continue
|
|
171
|
+
n = counts.get(spec.name, 0)
|
|
172
|
+
status = Status.FAIL if n else Status.PASS
|
|
173
|
+
results.append(CheckResult("finite_values", spec.name, status, n, f"{n} NaN/inf values"))
|
|
174
|
+
return results
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _idle_start(state: str, frames: pl.DataFrame, t: Thresholds) -> CheckResult:
|
|
178
|
+
rows = frames[state].to_list()
|
|
179
|
+
first = rows[0]
|
|
180
|
+
idle = 0
|
|
181
|
+
for row in rows:
|
|
182
|
+
if row is None or first is None or max(abs(a - b) for a, b in zip(row, first)) > t.idle_epsilon:
|
|
183
|
+
break
|
|
184
|
+
idle += 1
|
|
185
|
+
fraction = idle / len(rows)
|
|
186
|
+
status = _grade(fraction, t.warn_idle_fraction)
|
|
187
|
+
return CheckResult("idle_start", state, status, fraction, f"robot idle for the first {idle} of {len(rows)} frames")
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: robolake
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Ingest, time-align, validate and export multimodal robot data (ROS 2 / MCAP to LeRobot v3)
|
|
5
|
+
Keywords: robotics,physical-ai,lerobot,mcap,ros2,data-quality,robot-learning
|
|
6
|
+
Author: Harshith Raju
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Dist: mcap>=1.6.0
|
|
17
|
+
Requires-Dist: mcap-ros2-support>=0.6.0
|
|
18
|
+
Requires-Dist: numpy>=2.0,<3
|
|
19
|
+
Requires-Dist: pillow>=10.1
|
|
20
|
+
Requires-Dist: polars>=1.0
|
|
21
|
+
Requires-Dist: pyarrow>=16.0
|
|
22
|
+
Requires-Dist: pydantic>=2.5
|
|
23
|
+
Requires-Dist: pyyaml>=6.0.1
|
|
24
|
+
Requires-Dist: typer>=0.13
|
|
25
|
+
Requires-Dist: gradio>=6.33 ; extra == 'demo'
|
|
26
|
+
Requires-Dist: lerobot[dataset]>=0.7 ; extra == 'lerobot'
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Project-URL: Homepage, https://github.com/harshu-29-hr/robolake
|
|
29
|
+
Project-URL: Repository, https://github.com/harshu-29-hr/robolake
|
|
30
|
+
Project-URL: Issues, https://github.com/harshu-29-hr/robolake/issues
|
|
31
|
+
Project-URL: Showcase, https://huggingface.co/spaces/Harshith29hr/robolake
|
|
32
|
+
Provides-Extra: demo
|
|
33
|
+
Provides-Extra: lerobot
|
|
34
|
+
Description-Content-Type: text/markdown
|
|
35
|
+
|
|
36
|
+
# robolake
|
|
37
|
+
|
|
38
|
+
[](https://huggingface.co/spaces/Harshith29hr/robolake)
|
|
39
|
+
[](https://huggingface.co/datasets/Harshith29hr/robolake-sim-demo)
|
|
40
|
+
[](https://github.com/harshu-29-hr/robolake/actions/workflows/ci.yml)
|
|
41
|
+
|
|
42
|
+
**Open-source pipelines to ingest, time-align, validate and serve multimodal robot data for training and fleet operations.**
|
|
43
|
+
|
|
44
|
+
> 🚧 Under active development
|
|
45
|
+
|
|
46
|
+
## The problem
|
|
47
|
+
|
|
48
|
+
Robots log camera feeds, joint telemetry and action commands at different rates, on different clocks, in different formats (MCAP / ROS 2 bags, HDF5). Before any of it can train a policy, someone has to align it, catch bad episodes and convert it. `robolake` does that step.
|
|
49
|
+
|
|
50
|
+
## What it does
|
|
51
|
+
|
|
52
|
+
- **Ingest** ROS 2 / MCAP recordings: filters topics, de-duplicates messages, uses sensor timestamps *(HDF5 and LeRobot readers planned)*
|
|
53
|
+
- **Time-align** multi-rate streams onto one timeline, with no future-data leakage
|
|
54
|
+
- **Validate** episodes with robot-specific quality checks: duplicates, missing timestamps, dropped frames, coverage, camera staleness, NaN values, idle time *(joint limits and action-lag checks planned)*
|
|
55
|
+
- **Store** clean telemetry as compressed Parquet *(Apache Iceberg + DuckDB fleet store planned)*
|
|
56
|
+
- **Export** training-ready LeRobot v3 datasets and publish them to the Hugging Face Hub
|
|
57
|
+
- **Serve** through a CLI (`inspect`, `validate`, `convert`, `simulate`) and a local demo app *(REST API planned)*
|
|
58
|
+
|
|
59
|
+
## Quickstart
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
git clone https://github.com/harshu-29-hr/robolake.git
|
|
63
|
+
cd robolake
|
|
64
|
+
uv sync --extra lerobot
|
|
65
|
+
|
|
66
|
+
# make a simulated robot recording (no robot needed)
|
|
67
|
+
uv run robolake simulate data/raw/sim/demo.mcap
|
|
68
|
+
|
|
69
|
+
# see what's inside a recording
|
|
70
|
+
uv run robolake inspect data/raw/sim/demo.mcap
|
|
71
|
+
|
|
72
|
+
# check its quality (exit code 1 if any check fails — handy in CI)
|
|
73
|
+
uv run robolake validate data/raw/sim/demo.mcap -c examples/configs/sim_arm.yaml
|
|
74
|
+
|
|
75
|
+
# convert it into a LeRobot v3 dataset
|
|
76
|
+
uv run robolake convert data/raw/sim/demo.mcap -c examples/configs/sim_arm.yaml -o data/lerobot/sim-demo
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
For your own robot, run `robolake inspect` on a recording and write a topic-map config like [`examples/configs/robotis_ai_worker.yaml`](https://github.com/harshu-29-hr/robolake/blob/main/examples/configs/robotis_ai_worker.yaml)
|
|
80
|
+
|
|
81
|
+
## Roadmap
|
|
82
|
+
|
|
83
|
+
- [x] Project setup
|
|
84
|
+
- [x] Explore real robot data
|
|
85
|
+
- [x] Canonical data model
|
|
86
|
+
- [ ] Ingestion connectors (MCAP ✅ · HDF5 · LeRobot)
|
|
87
|
+
- [x] Time-alignment engine
|
|
88
|
+
- [x] Validation and quality reports
|
|
89
|
+
- [x] Storage and LeRobot export
|
|
90
|
+
- [x] CLI, API and Hugging Face Space demo (CLI ✅ · showcase Space ✅ · REST API later)
|
|
91
|
+
- [ ] Streaming fleet ingestion
|
|
92
|
+
- [ ] PyPI release and docs
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
Apache 2.0
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
robolake/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
2
|
+
robolake/align/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
robolake/align/timeline.py,sha256=HIwY4paceKstVyTkMqnJyEFL6v5BpWL3mZorOm3S9JI,3258
|
|
4
|
+
robolake/cli.py,sha256=CjCW7aPBgRS6S4dxODNaLkdgkgURxDQj_wwEQynZV3o,5602
|
|
5
|
+
robolake/ingest/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
6
|
+
robolake/ingest/mcap_reader.py,sha256=2pMywSWxe-mWrpXFuezs34ho1F_OM3Mrx1eG2_JHN0g,4475
|
|
7
|
+
robolake/pipeline.py,sha256=ItKb1lsRYG8yvOL9Heh1SbVjld9YHRUOGcwtt-93Boo,1627
|
|
8
|
+
robolake/schema.py,sha256=uKTJfkkQUP5mLBNhmypjBzJjK0pK3gLG3IWasXU36pI,3553
|
|
9
|
+
robolake/serve/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
robolake/sim.py,sha256=CAqdVS31k_lZyGNx_H99W6rTcPVK-gqUOLCpJTZoT6M,6493
|
|
11
|
+
robolake/store/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
12
|
+
robolake/store/lerobot_v3.py,sha256=s-VRmNxgbtyR2eBYHA1ja2FH8CygJyJ0glNTorDoS1w,4515
|
|
13
|
+
robolake/validate/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
robolake/validate/quality.py,sha256=ewEobN0TegbfFWR6-jzbyo_keyx53Vgi0E7adB-f3UA,7140
|
|
15
|
+
robolake-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
16
|
+
robolake-0.1.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
|
|
17
|
+
robolake-0.1.0.dist-info/entry_points.txt,sha256=JzC6EqjR5G2ovX0h0cwqVmxJsIFYRi5s4bd0INSkHVI,47
|
|
18
|
+
robolake-0.1.0.dist-info/METADATA,sha256=RmI5wclthiUVO15wY3weF-l_oZyjWhwhaYFv_ZabaHc,4297
|
|
19
|
+
robolake-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|