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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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#!/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())


@functools.lru_cache(maxsize=8)
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 []


@functools.lru_cache(maxsize=2)
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


@functools.lru_cache(maxsize=8)
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))