Instructions to use NoesisLab/LITOperator with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- LeRobot
How to use NoesisLab/LITOperator with LeRobot:
# No code snippets available yet for this library. # To use this model, check the repository files and the library's documentation. # Want to help? PRs adding snippets are welcome at: # https://github.com/huggingface/huggingface.js
- Notebooks
- Google Colab
- Kaggle
Download sandbox/lerobot_host/lit_stream.py from NoesisLab/LITOperator: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/NoesisLab/LITOperator/resolve/main/sandbox/lerobot_host/lit_stream.py
- Command line
-
hf download hf://NoesisLab/LITOperator/sandbox/lerobot_host/lit_stream.py
-
curl -L -o lit_stream.py https://huggingface.co/NoesisLab/LITOperator/resolve/main/sandbox/lerobot_host/lit_stream.py
16.1 kB
| #!/usr/bin/env python3 | |
| """lit_stream.py — stream LeRobot datasets over HTTPS; nothing hits disk. | |
| The menu is the Hugging Face `lerobot` org. A dataset is read as | |
| Parquet row batches through HfFileSystem; the LeRobot `features` dict is | |
| handed to `lit_codec.FeatureCodec`, which translates every feature | |
| (state, action, camera/video, text/task, peripherals) into 64 u64 slots | |
| plus one packed action code. A video is an MP4 sample table read with | |
| HTTP Range requests; each frame is hashed from its compressed sample | |
| bytes. No decoder, no whole-file download, never stored. | |
| """ | |
| import functools | |
| import hashlib | |
| import json | |
| import sys | |
| import threading | |
| from collections import OrderedDict | |
| from concurrent.futures import ThreadPoolExecutor | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi, HfFileSystem | |
| import lit_codec | |
| FS = HfFileSystem() | |
| API = HfApi() | |
| def _join(root, path): | |
| return "%s/%s" % (root, path) if root else path | |
| def read_json(repo, path, root=""): | |
| with FS.open("datasets/%s/%s" % (repo, _join(root, path)), "rb") as f: | |
| return json.loads(f.read().decode()) | |
| def repo_files(repo): | |
| """One listing per repo; both data and meta walk the same list.""" | |
| return API.list_repo_files(repo, repo_type="dataset") | |
| def data_files(repo, root=""): | |
| pref = _join(root, "data/") | |
| return sorted(f for f in repo_files(repo) | |
| if f.startswith(pref) and f.endswith(".parquet")) | |
| def community_roots(repo): | |
| """Every subdataset root: the directory holding meta/info.json.""" | |
| suf = "/meta/info.json" | |
| return sorted(p[:-len(suf)] for p in repo_files(repo) | |
| if p.endswith(suf)) | |
| def read_tasks(repo, root=""): | |
| """meta/tasks.parquet -> the task strings, in task_index order.""" | |
| try: | |
| with FS.open("datasets/%s/%s" | |
| % (repo, _join(root, "meta/tasks.parquet")), "rb") as f: | |
| d = pq.read_table(f).to_pydict() | |
| except Exception: | |
| return [] | |
| if "task" in d: | |
| return [str(x) for x in d["task"]] | |
| if "tasks" in d: | |
| return [str(x) for x in d["tasks"]] | |
| if "task_index" in d and "__index_level_0__" in d: | |
| out = [""] * len(d["task_index"]) | |
| for i, ti in enumerate(d["task_index"]): | |
| out[int(ti)] = str(d["__index_level_0__"][i]) | |
| return out | |
| return [] | |
| def _read_episodes_cached(repo, root, cams, fps): | |
| eps = {} | |
| pref = _join(root, "meta/episodes/") | |
| for path in repo_files(repo): | |
| if not path.startswith(pref) or not path.endswith(".parquet"): | |
| continue | |
| with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: | |
| names = set(pq.ParquetFile(f).schema_arrow.names) | |
| wanted = ["episode_index"] | |
| for cam in cams: | |
| for suf in ("chunk_index", "file_index", "from_timestamp"): | |
| c = "videos/%s/%s" % (cam, suf) | |
| if c in names: | |
| wanted.append(c) | |
| d = pq.read_table( | |
| f, columns=[c for c in wanted if c in names]).to_pydict() | |
| n = len(d.get("episode_index", [])) | |
| for i in range(n): | |
| ep = d["episode_index"][i] | |
| camsd = {} | |
| for cam in cams: | |
| ck = "videos/%s/chunk_index" % cam | |
| fk = "videos/%s/file_index" % cam | |
| tk = "videos/%s/from_timestamp" % cam | |
| if ck not in d or fk not in d: | |
| continue | |
| off = 0 | |
| if fps and tk in d: | |
| off = int(round(float(d[tk][i]) * fps)) | |
| camsd[cam] = (d[ck][i], d[fk][i], off) | |
| if camsd: | |
| eps[ep] = camsd | |
| return eps | |
| def read_episodes(repo, cams=(), fps=0, root=""): | |
| """episode -> {camera: (chunk, file, sample_offset)} from meta/episodes. | |
| ``from_timestamp`` is relative to the video file, so the first frame | |
| of the episode is sample ``round(from_timestamp * fps)``. Only the | |
| needed columns are read; per-episode stats blobs stay on the Hub. | |
| """ | |
| return _read_episodes_cached(repo, root, tuple(cams), float(fps)) | |
| def _mp4_box(data, start, end, typ): | |
| p = start | |
| while p + 8 <= end: | |
| size = int.from_bytes(data[p:p + 4], "big") | |
| t = data[p + 4:p + 8] | |
| hdr = 8 | |
| if size == 1 and p + 16 <= end: | |
| size = int.from_bytes(data[p + 8:p + 16], "big") | |
| hdr = 16 | |
| if size < hdr or p + size > end: | |
| break | |
| if t == typ: | |
| return p + hdr, p + size | |
| p += size | |
| return None | |
| def _mp4_samples(data): | |
| """Sample table: [(byte_offset, byte_size)] for every video frame. | |
| No decoder; the MP4 stbl (stsz/stco/stsc) is the 4D volume's address | |
| map. Each sample is the compressed frame, ready to hash. | |
| """ | |
| moov = _mp4_box(data, 0, len(data), b"moov") | |
| if not moov: | |
| return [] | |
| trak = _mp4_box(data, moov[0], moov[1], b"trak") | |
| if not trak: | |
| return [] | |
| mdia = _mp4_box(data, trak[0], trak[1], b"mdia") | |
| if not mdia: | |
| return [] | |
| minf = _mp4_box(data, mdia[0], mdia[1], b"minf") | |
| if not minf: | |
| return [] | |
| stbl = _mp4_box(data, minf[0], minf[1], b"stbl") | |
| if not stbl: | |
| return [] | |
| stsz = _mp4_box(data, stbl[0], stbl[1], b"stsz") | |
| stco = _mp4_box(data, stbl[0], stbl[1], b"stco") | |
| stsc = _mp4_box(data, stbl[0], stbl[1], b"stsc") | |
| if not stsz or not stco or not stsc: | |
| return [] | |
| p = stsz[0] + 4 | |
| sample_size = int.from_bytes(data[p:p + 4], "big") | |
| p += 4 | |
| count = int.from_bytes(data[p:p + 4], "big") | |
| p += 4 | |
| if sample_size: | |
| sizes = [sample_size] * count | |
| else: | |
| sizes = [] | |
| for _ in range(count): | |
| sizes.append(int.from_bytes(data[p:p + 4], "big")) | |
| p += 4 | |
| p = stco[0] + 4 | |
| n = int.from_bytes(data[p:p + 4], "big") | |
| p += 4 | |
| chunks = [int.from_bytes(data[p + 4 * i:p + 4 * i + 4], "big") | |
| for i in range(n)] | |
| p = stsc[0] + 4 | |
| n = int.from_bytes(data[p:p + 4], "big") | |
| p += 4 | |
| entries = [] | |
| for _ in range(n): | |
| first = int.from_bytes(data[p:p + 4], "big") | |
| spc = int.from_bytes(data[p + 4:p + 8], "big") | |
| entries.append((first, spc)) | |
| p += 12 | |
| out = [] | |
| si = 0 | |
| for ci, off in enumerate(chunks, 1): | |
| spc = 0 | |
| for first, n in entries: | |
| if ci >= first: | |
| spc = n | |
| else: | |
| break | |
| for _ in range(spc): | |
| if si >= len(sizes): | |
| break | |
| out.append((off, sizes[si])) | |
| off += sizes[si] | |
| si += 1 | |
| return out | |
| def video_hash_block(repo, path, per_frame=True): | |
| """Offline: the whole video volume -> (top, per-sample hashes). | |
| This reads the entire file; the streaming path below never calls it. | |
| """ | |
| with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: | |
| data = f.read() | |
| top = int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), | |
| "little") | |
| if not per_frame: | |
| return top, [] | |
| try: | |
| samples = _mp4_samples(data) | |
| except Exception: | |
| return top, [] | |
| hashes = [] | |
| for off, size in samples: | |
| hashes.append(int.from_bytes( | |
| hashlib.blake2b(data[off:off + size], digest_size=8).digest(), | |
| "little")) | |
| return top, hashes | |
| def make_codec(repo, root=""): | |
| """LeRobot features + stats + tasks -> the universal FeatureCodec.""" | |
| info = read_json(repo, "meta/info.json", root) | |
| stats = read_json(repo, "meta/stats.json", root) | |
| tasks = read_tasks(repo, root) | |
| name = repo if not root else repo + "/" + root | |
| return lit_codec.FeatureCodec.from_dataset( | |
| name, info["features"], stats, tasks), info | |
| _VCOUNT = 0 | |
| class VideoReader: | |
| """One MP4 volume, read by Range: moov once, then one block at a time. | |
| The sample table (stsz/stco/stsc) is the address map; ``sample(i)`` | |
| seeks to frame i's compressed bytes and hashes them. A block cache | |
| (1 MiB) makes a run of consecutive frames one request, so a frame | |
| costs a slice of an already-fetched block, not a whole-file read. | |
| """ | |
| def __init__(self, repo, path, block=1 << 20): | |
| self.repo = repo | |
| self.path = path | |
| self.block = block | |
| self.f = FS.open("datasets/%s/%s" % (repo, path), "rb") | |
| self._buf = b"" | |
| self._buf_off = -1 | |
| self._lock = threading.Lock() | |
| self.samples = [] | |
| self.top = 0 | |
| self._open_table() | |
| global _VCOUNT | |
| _VCOUNT += 1 | |
| if _VCOUNT <= 12 or _VCOUNT % 200 == 0: | |
| print("video #%d %s samples=%d top=%016x" | |
| % (_VCOUNT, path, len(self.samples), self.top), flush=True) | |
| def _size(self): | |
| size = getattr(self.f, "size", None) | |
| if size: | |
| return int(size) | |
| try: | |
| return int(FS.info("datasets/%s/%s" | |
| % (self.repo, self.path))["size"]) | |
| except Exception: | |
| return 0 | |
| def _open_table(self): | |
| """Walk top-level boxes to moov, then parse the sample table.""" | |
| size = self._size() | |
| p = 0 | |
| moov = None | |
| while size and p + 8 <= size: | |
| self.f.seek(p) | |
| hdr = self.f.read(16) | |
| if len(hdr) < 8: | |
| break | |
| sz = int.from_bytes(hdr[0:4], "big") | |
| typ = hdr[4:8] | |
| hdrlen = 8 | |
| if sz == 1 and len(hdr) >= 16: | |
| sz = int.from_bytes(hdr[8:16], "big") | |
| hdrlen = 16 | |
| elif sz == 0: | |
| sz = size - p | |
| if sz < hdrlen: | |
| break | |
| if typ == b"moov": | |
| moov = p | |
| break | |
| p += sz | |
| if moov is None: | |
| return | |
| self.f.seek(moov) | |
| blob = self.f.read(sz) | |
| if not blob: | |
| return | |
| self.top = int.from_bytes( | |
| hashlib.blake2b(blob, digest_size=8).digest(), "little") | |
| try: | |
| self.samples = _mp4_samples(blob) | |
| except Exception: | |
| self.samples = [] | |
| def _read(self, off, size): | |
| if self._buf_off >= 0 and \ | |
| self._buf_off <= off and off + size <= self._buf_off + len(self._buf): | |
| s = off - self._buf_off | |
| return self._buf[s:s + size] | |
| self.f.seek(off) | |
| self._buf = self.f.read(max(self.block, size)) or b"" | |
| self._buf_off = off | |
| return self._buf[:size] | |
| def sample(self, i): | |
| """Frame i's compressed bytes -> one u64 (16 hex digits).""" | |
| if not self.samples: | |
| return self.top | |
| i = int(i) | |
| if i < 0 or i >= len(self.samples): | |
| return self.top | |
| off, size = self.samples[i] | |
| if size <= 0: | |
| return self.top | |
| with self._lock: | |
| data = self._read(off, size) | |
| return int.from_bytes(hashlib.blake2b(data, digest_size=8).digest(), | |
| "little") | |
| def close(self): | |
| try: | |
| self.f.close() | |
| except Exception: | |
| pass | |
| def _get_reader(readers, repo, path, key, cap=16): | |
| r = readers.get(key) | |
| if r is not None: | |
| readers.move_to_end(key) | |
| return r | |
| r = VideoReader(repo, path) | |
| readers[key] = r | |
| while len(readers) > cap: | |
| _, old = readers.popitem(last=False) | |
| old.close() | |
| return r | |
| def _grab_off(job): | |
| cam, r, i = job | |
| return cam, (r.sample(i) if r is not None else 0) | |
| def iter_frames(repo, no_video=False, root=""): | |
| """Every frame: all data columns + one hash per camera (Range reads).""" | |
| codec, info = make_codec(repo, root) | |
| cams = [] if no_video else list(codec.cameras) | |
| episodes = (read_episodes(repo, cams, info.get("fps") or 0, root) | |
| if cams else {}) | |
| readers = OrderedDict() | |
| pool = (ThreadPoolExecutor(max_workers=max(1, min(8, len(cams)))) | |
| if cams else None) | |
| try: | |
| for path in data_files(repo, root): | |
| with FS.open("datasets/%s/%s" % (repo, path), "rb") as f: | |
| pf = pq.ParquetFile(f) | |
| for batch in pf.iter_batches(batch_size=128): | |
| d = batch.to_pydict() | |
| n = len(d.get("frame_index", [])) | |
| for i in range(n): | |
| fr = {k: d[k][i] for k in d} | |
| ep = fr.get("episode_index") | |
| fi = int(fr.get("frame_index", 0)) | |
| if cams: | |
| jobs = [] | |
| for cam in cams: | |
| cf = episodes.get(ep, {}).get(cam) | |
| off = cf[2] if cf else 0 | |
| r = None | |
| if cf: | |
| key = (int(cf[0]), int(cf[1]), cam) | |
| r = readers.get(key) | |
| if r is None: | |
| vpath = ("%svideos/%s/chunk-%03d/" | |
| "file-%03d.mp4" | |
| % (_root_prefix(root), cam, | |
| int(cf[0]), int(cf[1]))) | |
| r = _get_reader(readers, repo, vpath, | |
| key) | |
| else: | |
| readers.move_to_end(key) | |
| jobs.append((cam, r, fi + off)) | |
| for cam, h in pool.map(_grab_off, jobs): | |
| fr[cam] = h | |
| yield fr | |
| finally: | |
| if pool is not None: | |
| pool.shutdown(wait=True) | |
| for r in readers.values(): | |
| r.close() | |
| def _root_prefix(root): | |
| return (root + "/") if root else "" | |
| def iter_transitions(repo, no_video=False, root=""): | |
| """Yield (episode, frame, state_frame, action, next_frame, done, | |
| codec, task_index). The next frame is the causal edge; the episode | |
| end is the one-line judge.""" | |
| codec, _info = make_codec(repo, root) | |
| prev = None | |
| prev_action = None | |
| for fr in iter_frames(repo, no_video, root): | |
| cur = (fr["episode_index"], fr["frame_index"], fr) | |
| if prev is not None: | |
| ep, fi, frame = prev | |
| if cur[0] == ep and cur[1] == fi + 1: | |
| yield (ep, fi, frame, prev_action, cur[2], 0, codec, | |
| fr.get("task_index", 0)) | |
| else: | |
| yield (ep, fi, frame, prev_action, frame, 1, codec, | |
| fr.get("task_index", 0)) | |
| prev = cur | |
| prev_action = fr[codec.action_feature] | |
| if prev is not None: | |
| yield (prev[0], prev[1], prev[2], prev_action, prev[2], 1, | |
| codec, 0) | |
| def main(argv): | |
| repo = argv[1] if len(argv) > 1 else "lerobot/svla_so101_pickplace" | |
| limit = int(argv[2]) if len(argv) > 2 else 5 | |
| codec, info = make_codec(repo) | |
| print("repo", repo, "robot", info.get("robot_type"), "eps", | |
| info.get("total_episodes"), "fps", info.get("fps")) | |
| print("features", list(codec.features.keys())) | |
| print("state slots", len(codec.state_slots), | |
| "cameras", codec.cameras, "texts", codec.texts, | |
| "extras", len(codec.extras), | |
| "action dims", len(codec.action_dims)) | |
| n = 0 | |
| for ep, fi, frame, ac, nframe, done, sch, task in iter_transitions(repo): | |
| sh = lit_codec.hex16(sch.state_key(sch.state_words(frame))) | |
| ah = lit_codec.hex16(sch.action_code(ac)) | |
| print("ep=%d f=%d task=%s state=%s action=%s done=%d" | |
| % (ep, fi, task, sh, ah, done)) | |
| n += 1 | |
| if n >= limit: | |
| break | |
| print("edges", n) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main(sys.argv)) | |