Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Sync from huggingface/lerobot-dataset-visualizer via hub-sync
Browse filesFiles changed (4)
192 unmodified lines193194195196197198199111 unmodified lines311312313314315316317318319320321322323324192 unmodified linesimport { buildVersionedUrl } from "@/utils/versionUtils";import { formatStringWithVars } from "@/utils/parquetUtils";import { buildV3EpisodesMetadataPath } from "@/utils/stringFormatting";import { formatPathTemplate } from "@huggingface/lerobot";const V3_DATA_TEMPLATE =111 unmodified linesconst repoId = "lerobot-data-collection/level12_rac_2_2026-02-07";const version = "v3.0";test("episode metadata path for first file", () => {const path = buildV3EpisodesMetadataPath(0, 0);const url = buildVersionedUrl(repoId, version, path);expect(url).toBe(`${DATASET_BASE}/${repoId}/resolve/main/meta/episodes/chunk-000/file-000.parquet`,);});test("data path from episode metadata (chunk 0, file 2)", () => {const path = formatPathTemplate(V3_DATA_TEMPLATE, {chunk_index: 0,192 unmodified lines193194195196197198111 unmodified lines310311312313314315192 unmodified linesimport { buildVersionedUrl } from "@/utils/versionUtils";import { formatStringWithVars } from "@/utils/parquetUtils";import { formatPathTemplate } from "@huggingface/lerobot";const V3_DATA_TEMPLATE =111 unmodified linesconst repoId = "lerobot-data-collection/level12_rac_2_2026-02-07";const version = "v3.0";test("data path from episode metadata (chunk 0, file 2)", () => {const path = formatPathTemplate(V3_DATA_TEMPLATE, {chunk_index: 0,
14 unmodified lines1516171819202142 unmodified lines6465666768691241 unmodified lines1311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146850 unmodified lines15191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547115 unmodified lines16631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697127 unmodified lines1825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185326 unmodified lines18801881188218831884188518861 unmodified line188818891890189118921893189418951896189718981899190014 unmodified linesprocessChartDataGroups,groupRowBySuffix,} from "@/utils/dataProcessing";import { buildV3EpisodesMetadataPath } from "@/utils/stringFormatting";import { bigIntToNumber } from "@/utils/typeGuards";import {isGrayscaleShape,42 unmodified lines* v3.0 concatenates episodes into shared files, so each camera carries a time range; v2.x gives every* episode its own file and the range simply spans it.*/function toVideosInfo(episode: LeRobotEpisode,info: DatasetMetadata,1241 unmodified linesreturn { chartDataGroups, flatChartData: chartData, ignoredColumns };}// Walks v3.0 episode-metadata parquet files across chunks/files. A new chunk// begins when the current chunk's files run out (404 or empty); iteration ends// when file-000 of the next chunk 404s. `chunks_size` caps files per chunk, so// large datasets can spill past chunk-000.async function* iterateEpisodeMetadataFilesV3(repoId: string,version: string,): AsyncGenerator<Record<string, unknown>[], void, unknown> {let chunkIndex = 0;let fileIndex = 0;while (true) {const path = buildV3EpisodesMetadataPath(chunkIndex, fileIndex);const url = buildVersionedUrl(repoId, version, path);let rows: Record<string, unknown>[];try {const buf = await fetchParquetFile(url);rows = await readParquetAsObjects(buf, []);} catch {if (fileIndex === 0) return;chunkIndex++;fileIndex = 0;continue;}if (rows.length === 0) {if (fileIndex === 0) return;chunkIndex++;fileIndex = 0;continue;}yield rows;fileIndex++;}}// Metadata loading for v3.0 episodes// Simple parser for episode row - focuses on key fields for episodesfunction parseEpisodeRowSimple(row: Record<string, unknown>,): EpisodeMetadataV3 {// v3.0 uses named keys in the episode metadataif (row && typeof row === "object") {// Check if this is v3.0 format with named keysif ("episode_index" in row) {// v3.0 format - use named keys// Convert BigInt values to numbersconst toBigIntSafe = (value: unknown): number => {if (typeof value === "bigint") return Number(value);if (typeof value === "number") return value;if (typeof value === "string") return parseInt(value) || 0;return 0;};const toNumSafe = (value: unknown): number => {if (typeof value === "number") return value;if (typeof value === "bigint") return Number(value);if (typeof value === "string") return parseFloat(value) || 0;return 0;};// Handle video metadata - look for video-specific keysconst videoKeys = Object.keys(row).filter((key) => key.includes("videos/") && key.includes("/chunk_index"),);let videoChunkIndex = 0,videoFileIndex = 0,videoFromTs = 0,videoToTs = 30;if (videoKeys.length > 0) {const videoBaseName = videoKeys[0].replace("/chunk_index", "");videoChunkIndex = toBigIntSafe(row[`${videoBaseName}/chunk_index`]);videoFileIndex = toBigIntSafe(row[`${videoBaseName}/file_index`]);videoFromTs = toNumSafe(row[`${videoBaseName}/from_timestamp`]);videoToTs = toNumSafe(row[`${videoBaseName}/to_timestamp`]) || 30;}// lerobot writes episode.tasks as list[str] (v3.0 multi-task support).const rawTasks = row["tasks"];const tasks = Array.isArray(rawTasks)? rawTasks.filter((t): t is string => typeof t === "string"): undefined;const episodeData: EpisodeMetadataV3 = {episode_index: toBigIntSafe(row["episode_index"]),data_chunk_index: toBigIntSafe(row["data/chunk_index"]),data_file_index: toBigIntSafe(row["data/file_index"]),dataset_from_index: toBigIntSafe(row["dataset_from_index"]),dataset_to_index: toBigIntSafe(row["dataset_to_index"]),length: toBigIntSafe(row["length"]),video_chunk_index: videoChunkIndex,video_file_index: videoFileIndex,video_from_timestamp: videoFromTs,video_to_timestamp: videoToTs,...(tasks && tasks.length > 0 ? { tasks } : {}),};// Store per-camera metadata for extractVideoInfoV3WithSegmentationObject.keys(row).forEach((key) => {if (key.startsWith("videos/")) {const val = row[key];episodeData[key] =typeof val === "bigint"? Number(val): typeof val === "number" || typeof val === "string"? val: 0;}});return episodeData as EpisodeMetadataV3;} else {// Fallback to numeric keys for compatibilityconst toNum = (v: unknown, fallback = 0): number =>typeof v === "number"? v: typeof v === "bigint"? Number(v): fallback;return {episode_index: toNum(row["0"]),data_chunk_index: toNum(row["1"]),data_file_index: toNum(row["2"]),dataset_from_index: toNum(row["3"]),dataset_to_index: toNum(row["4"]),video_chunk_index: toNum(row["5"]),video_file_index: toNum(row["6"]),video_from_timestamp: toNum(row["7"]),video_to_timestamp: toNum(row["8"], 30),length: toNum(row["9"], 30),};}}// Fallback if parsing failsconst fallback = {episode_index: 0,data_chunk_index: 0,data_file_index: 0,dataset_from_index: 0,dataset_to_index: 0,video_chunk_index: 0,video_file_index: 0,video_from_timestamp: 0,video_to_timestamp: 30,length: 30,};return fallback;}// βββ Stats computation βββββββββββββββββββββββββββββββββββββββββββ/**50 unmodified linesfps: number,): Promise<EpisodeLengthStats | null> {try {const allEpisodes: { index: number; length: number }[] = [];let fileIndex = 0;const chunkIndex = 0;while (true) {const path = `meta/episodes/chunk-${chunkIndex.toString().padStart(3, "0")}/file-${fileIndex.toString().padStart(3, "0")}.parquet`;const url = buildVersionedUrl(repoId, version, path);try {const buf = await fetchParquetFile(url);const rows = await readParquetAsObjects(buf, []);if (rows.length === 0 && fileIndex > 0) break;for (const row of rows) {const parsed = parseEpisodeRowSimple(row);allEpisodes.push({index: parsed.episode_index,length: parsed.length,});}fileIndex++;} catch {break;}}if (allEpisodes.length === 0) return null;115 unmodified lines);if (version === "v3.0") {for await (const rows of iterateEpisodeMetadataFilesV3(repoId, version)) {for (const row of rows) {const epIdx = Number(row["episode_index"] ?? 0);if (sampledEpisodeSet && !sampledEpisodeSet.has(epIdx)) continue;for (const cam of cameras) {const cIdx = Number(row[`videos/${cam}/chunk_index`] ?? row["video_chunk_index"] ?? 0,);const fIdx = Number(row[`videos/${cam}/file_index`] ?? row["video_file_index"] ?? 0,);const fromTs = Number(row[`videos/${cam}/from_timestamp`] ??row["video_from_timestamp"] ??0,);const toTs = Number(row[`videos/${cam}/to_timestamp`] ??row["video_to_timestamp"] ??30,);const videoPath = `videos/${cam}/chunk-${cIdx.toString().padStart(3, "0")}/file-${fIdx.toString().padStart(3, "0")}.mp4`;framesByCamera[cam].push({episodeIndex: epIdx,videoUrl: buildVersionedUrl(repoId, version, videoPath),firstFrameTime: fromTs,lastFrameTime: Math.max(0, toTs - 0.05),});}}}return { cameras, framesByCamera };127 unmodified lines// Collect episode metadatatype EpMeta = {index: number;chunkIdx: number;fileIdx: number;from: number;to: number;};const allEps: EpMeta[] = [];if (version === "v3.0") {for await (const rows of iterateEpisodeMetadataFilesV3(repoId, version)) {for (const row of rows) {const parsed = parseEpisodeRowSimple(row);allEps.push({index: parsed.episode_index,chunkIdx: parsed.data_chunk_index,fileIdx: parsed.data_file_index,from: parsed.dataset_from_index,to: parsed.dataset_to_index,});}}} else {for (let i = 0; i < info.total_episodes; i++) {allEps.push({ index: i, chunkIdx: 0, fileIdx: 0, from: 0, to: 0 });}}26 unmodified linesif (version === "v3.0") {const byFile = new Map<string, EpMeta[]>();for (const ep of sampled) {const key = `${ep.chunkIdx}-${ep.fileIdx}`;if (!byFile.has(key)) byFile.set(key, []);byFile.get(key)!.push(ep);}1 unmodified lineconst fileResults = await Promise.all([...byFile.values()].map(async (eps) => {const ep0 = eps[0];const dataPath = `data/chunk-${ep0.chunkIdx.toString().padStart(3, "0")}/file-${ep0.fileIdx.toString().padStart(3, "0")}.parquet`;const fileEpActions: { index: number; actions: number[][] }[] = [];const fileEpStates: (number[][] | null)[] = [];try {const buf = await fetchParquetFile(buildVersionedUrl(repoId, version, dataPath),);const rows = await readParquetAsObjects(buf,stateKey ? ["index", actionKey, stateKey] : ["index", actionKey],14 unmodified lines15161718192042 unmodified lines63646566676869707172737475761241 unmodified lines13181319132013211322132350 unmodified lines13741375137613771378137913801381138213831384115 unmodified lines150015011502150315041505150615071508150915101511151215131514151515161517127 unmodified lines164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167226 unmodified lines16991700170117021703170417051 unmodified line170717081709171017111712171317141715171614 unmodified linesprocessChartDataGroups,groupRowBySuffix,} from "@/utils/dataProcessing";import { bigIntToNumber } from "@/utils/typeGuards";import {isGrayscaleShape,42 unmodified lines* v3.0 concatenates episodes into shared files, so each camera carries a time range; v2.x gives every* episode its own file and the range simply spans it.*//** Every episode, normalized. v3 only: v2 needs no index read to locate an episode. */async function loadLeRobotEpisodes(repoId: string,totalEpisodes: number,): Promise<LeRobotEpisode[]> {return leRobotDataset(repoId).episodes({ offset: 0, limit: totalEpisodes });}function toVideosInfo(episode: LeRobotEpisode,info: DatasetMetadata,1241 unmodified linesreturn { chartDataGroups, flatChartData: chartData, ignoredColumns };}// βββ Stats computation βββββββββββββββββββββββββββββββββββββββββββ/**50 unmodified linesfps: number,): Promise<EpisodeLengthStats | null> {try {const dataset = leRobotDataset(repoId);const { totalEpisodes } = await dataset.info();const allEpisodes = (await dataset.episodes({ offset: 0, limit: totalEpisodes })).map((episode) => ({ index: episode.index, length: episode.length }));if (allEpisodes.length === 0) return null;115 unmodified lines);if (version === "v3.0") {for (const episode of await loadLeRobotEpisodes(repoId,info.total_episodes,)) {if (sampledEpisodeSet && !sampledEpisodeSet.has(episode.index)) continue;for (const video of episode.videos) {framesByCamera[video.cameraKey]?.push({episodeIndex: episode.index,videoUrl: video.url,firstFrameTime: video.fromSec,lastFrameTime: Math.max(0, video.toSec - 0.05),});}}return { cameras, framesByCamera };127 unmodified lines// Collect episode metadatatype EpMeta = {index: number;/** v3 only; v2 derives its per-episode path from the index. */dataUrl?: string;from: number;to: number;};const allEps: EpMeta[] = [];if (version === "v3.0") {for (const episode of await loadLeRobotEpisodes(repoId,info.total_episodes,)) {allEps.push({index: episode.index,dataUrl: episode.data.url,from: episode.data.fromRow,to: episode.data.toRow,});}} else {for (let i = 0; i < info.total_episodes; i++) {allEps.push({ index: i, from: 0, to: 0 });}}26 unmodified linesif (version === "v3.0") {const byFile = new Map<string, EpMeta[]>();for (const ep of sampled) {const key = ep.dataUrl ?? "";if (!byFile.has(key)) byFile.set(key, []);byFile.get(key)!.push(ep);}1 unmodified lineconst fileResults = await Promise.all([...byFile.values()].map(async (eps) => {const ep0 = eps[0];const fileEpActions: { index: number; actions: number[][] }[] = [];const fileEpStates: (number[][] | null)[] = [];try {const buf = await fetchParquetFile(ep0.dataUrl ?? "");const rows = await readParquetAsObjects(buf,stateKey ? ["index", actionKey, stateKey] : ["index", actionKey],
4 unmodified lines56789101163 unmodified lines7576777879808182838485868788894 unmodified linesformatEpisodeIndex,formatFileIndex,formatChunkIndex,buildV3EpisodesMetadataPath,} from "@/utils/stringFormatting";// These utilities are the foundation of v3.0 path construction.63 unmodified lines});// v3.0 specific path buildersdescribe("buildV3EpisodesMetadataPath", () => {test("chunk 0, file 0 (default for most datasets)", () => {expect(buildV3EpisodesMetadataPath(0, 0)).toBe("meta/episodes/chunk-000/file-000.parquet",);});test("chunk 0, file 2 (multiple metadata files)", () => {expect(buildV3EpisodesMetadataPath(0, 2)).toBe("meta/episodes/chunk-000/file-002.parquet",);});});4 unmodified lines567891063 unmodified lines7475764 unmodified linesformatEpisodeIndex,formatFileIndex,formatChunkIndex,} from "@/utils/stringFormatting";// These utilities are the foundation of v3.0 path construction.63 unmodified lines});// v3.0 specific path builders
54 unmodified lines555657585960616263646566676869707154 unmodified linesexport function formatChunkIndex(chunkIndex: number): string {return padNumber(chunkIndex, PADDING.CHUNK_INDEX);}/*** Build episodes metadata path for v3 datasets** @param chunkIndex - Episode chunk index* @param fileIndex - File index within chunk* @returns Formatted episodes metadata path (e.g., "meta/episodes/chunk-001/file-000.parquet")*/export function buildV3EpisodesMetadataPath(chunkIndex: number,fileIndex: number,): string {return `meta/episodes/chunk-${formatChunkIndex(chunkIndex)}/file-${formatFileIndex(fileIndex)}.parquet`;}54 unmodified lines55565754 unmodified linesexport function formatChunkIndex(chunkIndex: number): string {return padNumber(chunkIndex, PADDING.CHUNK_INDEX);}
src/app/[org]/[dataset]/[episode]/__tests__/fetch-data.test.ts-9
src/app/[org]/[dataset]/[episode]/fetch-data.ts+40-224
src/utils/__tests__/stringFormatting.test.ts-13
src/utils/stringFormatting.ts-14