Datasets:
CarolinePascal commited on
chore(clean): cleaning up python files
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Renumber episode_index so every recording becomes a unique, contiguous episode.
See README / chat context. Operates in-place on ./data, ./meta, ./meta/info.json.Run from the dataset root. Backup is made under ./.backup."""
from __future__ import annotations
import globimport jsonimport osfrom pathlib import Path
import pyarrow as paimport pyarrow.parquet as pq
ROOT = Path(__file__).resolve().parentDATA_DIR = ROOT / "data"META_EP_DIR = ROOT / "meta" / "episodes"INFO_PATH = ROOT / "meta" / "info.json"
def read_all_episode_meta(): """Return list of dict rows across every meta/episodes file (small number of columns).""" cols = [ "episode_index", "length", "data/chunk_index", "data/file_index", "dataset_from_index", "dataset_to_index", ] rows = [] for f in sorted(glob.glob(str(META_EP_DIR / "chunk-*" / "*.parquet"))): t = pq.read_table(f, columns=cols) d = t.to_pydict() for i in range(t.num_rows): rows.append({ "episode_index": d["episode_index"][i], "length": d["length"][i], "chunk_index": d["data/chunk_index"][i], "file_index": d["data/file_index"][i], "dataset_from_index": d["dataset_from_index"][i], "dataset_to_index": d["dataset_to_index"][i], "meta_file": f, }) return rows
def build_mapping(rows): """Sort rows by (chunk_index, file_index, dataset_from_index) and assign new ids 0..N-1.
Also compute the new compact `index` range per (chunk, file, old_ep) so we can update the data parquet `index` column. The meta's dataset_from/to_index already lives in the compact space and matches this ordering, so we use it directly. """ rows_sorted = sorted( rows, key=lambda r: (r["chunk_index"], r["file_index"], r["dataset_from_index"]), ) mapping = {} # (chunk, file, old_ep) -> dict(new_ep, new_from, new_to, old_from, old_to) for new_ep, r in enumerate(rows_sorted): key = (r["chunk_index"], r["file_index"], r["episode_index"]) assert key not in mapping, f"duplicate key {key}" mapping[key] = { "new_ep": new_ep, "new_from": r["dataset_from_index"], "new_to": r["dataset_to_index"], "old_from": r["dataset_from_index"], # placeholder; we fill real old_from below "old_to": r["dataset_to_index"], "length": r["length"], } return mapping, rows_sorted
def fix_data_files(mapping): """Rewrite every data parquet: remap episode_index and re-number index column.
`index` for each data file starts at `cumulative_frames` seen so far (chronological, numeric file order), matching the meta's compact `dataset_from_index` space. """ data_files = sorted(glob.glob(str(DATA_DIR / "chunk-*" / "*.parquet"))) cum = 0 for df in data_files: # Parse chunk/file from path chunk = int(Path(df).parent.name.split("-")[1]) file_idx = int(Path(df).stem.split("-")[1])
table = pq.read_table(df) schema = table.schema d = table.to_pydict() n = table.num_rows
# New index column: cum .. cum + n - 1 new_index = list(range(cum, cum + n))
# New episode_index: map each row's old ep -> new ep using (chunk, file, old_ep) old_eps = d["episode_index"] new_eps = [] for old_ep in old_eps: key = (chunk, file_idx, old_ep) m = mapping[key] new_eps.append(m["new_ep"])
d["index"] = new_index d["episode_index"] = new_eps
new_table = pa.Table.from_pydict(d, schema=schema) pq.write_table(new_table, df, compression="snappy") print( f"data/chunk-{chunk:03d}/file-{file_idx:03d}.parquet: " f"rows={n} index={cum}..{cum + n - 1} eps={sorted(set(new_eps))[0]}..{sorted(set(new_eps))[-1]}" ) cum += n
return cum
def fix_meta_files(mapping): """For each meta/episodes parquet file, update episode_index and index-related stats.""" meta_files = sorted(glob.glob(str(META_EP_DIR / "chunk-*" / "*.parquet"))) index_stat_cols = [ "stats/index/min", "stats/index/max", "stats/index/mean", "stats/index/q01", "stats/index/q10", "stats/index/q50", "stats/index/q90", "stats/index/q99", # std is invariant to translation, count is invariant ]
for mf in meta_files: chunk = int(Path(mf).parent.name.split("-")[1]) # meta file index: derive file_index from the data/file_index column of the first row table = pq.read_table(mf) schema = table.schema d = table.to_pydict() n = table.num_rows
new_ep_col = [] # Stats: translate index stats by (new_from - old_from). All rows in this file # may correspond to different data files in theory, but in practice each meta file # maps 1:1 to a data file. Regardless, we translate per-row. for i in range(n): old_ep = d["episode_index"][i] ch = d["data/chunk_index"][i] fi = d["data/file_index"][i] key = (ch, fi, old_ep) m = mapping[key] new_ep_col.append(m["new_ep"])
# Translate index-based stats # old_start = stats/index/min[i][0] # new_start = m["new_from"] old_start = d["stats/index/min"][i][0] new_start = m["new_from"] delta = new_start - old_start if delta != 0: for col in index_stat_cols: v = d[col][i] # v is a list with one element (or possibly a scalar inside) d[col][i] = [v[0] + delta]
# Replace episode_index stats with the single new value for col, val in [ ("stats/episode_index/min", [new_ep_col[-1]]), ("stats/episode_index/max", [new_ep_col[-1]]), ("stats/episode_index/mean", [float(new_ep_col[-1])]), ("stats/episode_index/q01", [float(new_ep_col[-1])]), ("stats/episode_index/q10", [float(new_ep_col[-1])]), ("stats/episode_index/q50", [float(new_ep_col[-1])]), ("stats/episode_index/q90", [float(new_ep_col[-1])]), ("stats/episode_index/q99", [float(new_ep_col[-1])]), ]: if col in d: d[col][i] = val # std=0 and count=length are already correct (single-valued per episode)
d["episode_index"] = new_ep_col
# Sort rows within the meta file by new episode_index for cleanliness order = sorted(range(n), key=lambda k: new_ep_col[k]) for col in list(d.keys()): d[col] = [d[col][k] for k in order]
new_table = pa.Table.from_pydict(d, schema=schema) pq.write_table(new_table, mf, compression="snappy") print( f"meta/episodes/chunk-{chunk:03d}/{Path(mf).name}: " f"rows={n} new_eps={d['episode_index'][0]}..{d['episode_index'][-1]}" )
def update_info_json(total_episodes: int, total_frames: int): with open(INFO_PATH) as f: info = json.load(f) info["total_episodes"] = total_episodes info["total_frames"] = total_frames info["splits"] = {"train": f"0:{total_episodes}"} with open(INFO_PATH, "w") as f: json.dump(info, f, indent=4) print(f"info.json updated: total_episodes={total_episodes} total_frames={total_frames}")
def main(): os.chdir(ROOT) rows = read_all_episode_meta() print(f"Loaded {len(rows)} episode metadata rows")
mapping, rows_sorted = build_mapping(rows) print(f"Built mapping for {len(mapping)} unique (chunk, file, old_ep) triples")
# Sanity preview preview = [(r["chunk_index"], r["file_index"], r["episode_index"], mapping[(r["chunk_index"], r["file_index"], r["episode_index"])]["new_ep"]) for r in rows_sorted[:5]] print("First 5 (chunk, file, old_ep, new_ep):", preview) preview_end = [(r["chunk_index"], r["file_index"], r["episode_index"], mapping[(r["chunk_index"], r["file_index"], r["episode_index"])]["new_ep"]) for r in rows_sorted[-5:]] print("Last 5 (chunk, file, old_ep, new_ep):", preview_end)
total_frames = fix_data_files(mapping) fix_meta_files(mapping) update_info_json(total_episodes=len(mapping), total_frames=total_frames)
if __name__ == "__main__": main()fix_episode_indices.pyDeleted-227