Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Sync from huggingface/lerobot-dataset-visualizer via hub-sync
Browse filesFiles changed (4)
4 unmodified lines567891011437 unmodified lines4494504514524534544554564574584594604 unmodified linesimport { postParentMessageWithParams } from "@/utils/postParentMessage";import { SimpleVideosPlayer } from "@/components/simple-videos-player";import PlaybackBar from "@/components/playback-bar";import { TimeProvider, useTime } from "@/context/time-context";import { FlaggedEpisodesProvider } from "@/context/flagged-episodes-context";import {AnnotationsProvider,437 unmodified lines}};// `currentTime` is intentionally NOT read here. Subscribing to it would// re-render this 700-line component every ~80ms during playback. The// <UrlTimeSync /> child handles its only consumer (the ?t= URL writer).// `seek` and `setIsPlaying` are stable references from useCallback /// useState — they don't drive renders.const { seek, setIsPlaying } = useTime();// URDFViewer episode changer and play toggle — populated by URDFViewer on mountconst urdfChangerRef = useRef<((ep: number) => void) | undefined>(undefined);4 unmodified lines567891011437 unmodified lines4494504514524534544554564574584 unmodified linesimport { postParentMessageWithParams } from "@/utils/postParentMessage";import { SimpleVideosPlayer } from "@/components/simple-videos-player";import PlaybackBar from "@/components/playback-bar";import { TimeProvider, useTime, useTimeControls } from "@/context/time-context";import { FlaggedEpisodesProvider } from "@/context/flagged-episodes-context";import {AnnotationsProvider,437 unmodified lines}};// Not `useTime()`: any consumer of it re-renders on every playback tick,// which would redraw this whole component ~12×/s. <UrlTimeSync /> handles// the one thing here that needs `currentTime` (the ?t= URL writer).const { seek, setIsPlaying } = useTimeControls();// URDFViewer episode changer and play toggle — populated by URDFViewer on mountconst urdfChangerRef = useRef<((ep: number) => void) | undefined>(undefined);
17 unmodified lines18192021222324401 unmodified lines42642742842943043143217 unmodified lines*/import React, { useMemo, useState } from "react";import { useTime } from "../context/time-context";import { useAnnotations } from "../context/annotations-context";import {buildSpeechAtom,401 unmodified lines];function useJump(): (ts: number) => void {const { seek, setIsPlaying } = useTime();return React.useCallback((ts: number) => {seek(ts, "external");17 unmodified lines18192021222324401 unmodified lines42642742842943043143217 unmodified lines*/import React, { useMemo, useState } from "react";import { useTime, useTimeControls } from "../context/time-context";import { useAnnotations } from "../context/annotations-context";import {buildSpeechAtom,401 unmodified lines];function useJump(): (ts: number) => void {const { seek, setIsPlaying } = useTimeControls();return React.useCallback((ts: number) => {seek(ts, "external");
5 unmodified lines6789101112132 unmodified lines1617181920212220 unmodified lines43444546474818 unmodified lines6768697071727352 unmodified lines1261271281291301311321331341351361371381391401411421431441451462 unmodified lines14915015115215315415515615715815916016116216316416516616777 unmodified lines2452462472482492502512522532542552562572582592602612622633 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239318 unmodified lines41241341441541641741841942042142242342442542642742842943043112 unmodified lines4444454464474484494504514524534544554563 unmodified lines46046146246346446546646746846947047147247347447547647747847948024 unmodified lines5055065075085095105115125 unmodified linesuseMemo,useRef,useState,} from "react";import { useTime } from "../context/time-context";import {LineChart,Line,2 unmodified linesCartesianGrid,ResponsiveContainer,Tooltip,ReferenceLine,} from "recharts";type ChartRow = Record<string, number | Record<string, number>>;20 unmodified lines"#84cc16",];function mergeGroups(data: ChartRow[][]): ChartRow[] {if (data.length <= 1) return data[0] ?? [];const maxLen = Math.max(...data.map((g) => g.length));18 unmodified linesexport const DataRecharts = React.memo(({ data, onChartsReady }: DataGraphProps) => {const [hoveredTime, setHoveredTime] = useState<number | null>(null);const [expanded, setExpanded] = useState(false);useEffect(() => {52 unmodified lines)}{expanded ? (<SingleDataGraphdata={combinedData}hoveredTime={hoveredTime}setHoveredTime={setHoveredTime}tall/>) : (<div className="grid md:grid-cols-2 grid-cols-1 gap-4">{data.map((group, idx) => (<SingleDataGraphkey={idx}data={group}hoveredTime={hoveredTime}setHoveredTime={setHoveredTime}/>))}</div>)}2 unmodified lines},);const SingleDataGraph = React.memo(({data,hoveredTime,setHoveredTime,tall,}: {data: ChartRow[];hoveredTime: number | null;setHoveredTime: (t: number | null) => void;tall?: boolean;}) => {const { currentTime, seek } = useTime();const flattenRow = useCallback((row: Record<string, number | Record<string, number>>, prefix = "") => {const result: Record<string, number> = {};77 unmodified linesreturn { groups: grouped, singles: singleList, groupColorMap: colorMap };}, [dataKeys]);// Find the closest data point to the current time for highlightingconst findClosestDataIndex = (time: number) => {if (!chartData.length) return 0;// Find the index of the first data point whose timestamp is >= time (ceiling)const idx = chartData.findIndex((point) => point.timestamp >= time);if (idx !== -1) return idx;// If all timestamps are less than time, return the last indexreturn chartData.length - 1;};const handleMouseLeave = () => {setHoveredTime(null);};const handleClick = (data: { activePayload?: { payload: { timestamp: number } }[] } | null,3 unmodified lines}};// Custom legend to show current value next to each seriesconst CustomLegend = () => {const closestIndex = findClosestDataIndex(hoveredTime != null ? hoveredTime : currentTime,);const currentData = chartData[closestIndex] || {};const isGroupChecked = (group: string) =>groups[group].every((k) => visibleKeys.includes(k));const isGroupIndeterminate = (group: string) =>groups[group].some((k) => visibleKeys.includes(k)) &&!isGroupChecked(group);const handleGroupCheckboxChange = (group: string) => {if (isGroupChecked(group)) {// Uncheck all childrensetVisibleKeys((prev) =>prev.filter((k) => !groups[group].includes(k)),);} else {// Check all childrensetVisibleKeys((prev) =>Array.from(new Set([...prev, ...groups[group]])),);}};const handleCheckboxChange = (key: string) => {setVisibleKeys((prev) =>prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],);};return (<div className="flex flex-wrap gap-x-5 gap-y-2 px-1 pt-2">{Object.entries(groups).map(([group, children]) => {const color = groupColorMap[group];return (<div key={group}><label className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={isGroupChecked(group)}ref={(el) => {if (el) el.indeterminate = isGroupIndeterminate(group);}}onChange={() => handleGroupCheckboxChange(group)}className="size-3"style={{ accentColor: color }}/><span className="text-xs font-semibold text-slate-200">{group}</span></label><div className="pl-5 flex flex-col gap-0.5 mt-0.5">{children.map((key) => {const label = key.split(SERIES_NAME_DELIMITER).pop() ?? key;return (<labelkey={key}className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={visibleKeys.includes(key)}onChange={() => handleCheckboxChange(key)}className="size-2.5"style={{ accentColor: color }}/><spanclassName={`text-xs ${visibleKeys.includes(key) ? "text-slate-300" : "text-slate-500"}`}>{label}</span><spanclassName={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}>{typeof currentData[key] === "number"? currentData[key].toFixed(2): "–"}</span></label>);})}</div></div>);})}{singles.map((key) => {const color = groupColorMap[key];return (<labelkey={key}className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={visibleKeys.includes(key)}onChange={() => handleCheckboxChange(key)}className="size-3"style={{ accentColor: color }}/><spanclassName={`text-xs ${visibleKeys.includes(key) ? "text-slate-200" : "text-slate-500"}`}>{key}</span><spanclassName={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}>{typeof currentData[key] === "number"? currentData[key].toFixed(2): "–"}</span></label>);})}</div>);};// Derive chart title from the grouped feature namesconst chartTitle = useMemo(() => {const featureNames = Object.keys(groups);18 unmodified lines</p>)}<divclassName={`w-full ${tall ? "h-[500px]" : "h-72"}`}onMouseLeave={handleMouseLeave}><ResponsiveContainer width="100%" height="100%"><LineChartdata={chartData}syncId="episode-sync"margin={{ top: 12, right: 12, left: -8, bottom: 8 }}onClick={handleClick}onMouseMove={(state) => {const payload = state?.activePayload?.[0]?.payload as| { timestamp?: number }| undefined;setHoveredTime(payload?.timestamp ?? null);}}onMouseLeave={handleMouseLeave}>12 unmodified linesstroke="#64748b"tick={{ fontSize: 12, fill: "#94a3b8" }}minTickGap={30}allowDataOverflow={true}/><YAxisdomain={["auto", "auto"]}stroke="#64748b"tick={{ fontSize: 12, fill: "#94a3b8" }}width={55}allowDataOverflow={true}tickFormatter={(v: number) => {if (v === 0) return "0";3 unmodified lines}}/><Tooltipcontent={() => null}active={true}isAnimationActive={false}defaultIndex={!hoveredTime ? findClosestDataIndex(currentTime) : undefined}/><ReferenceLinex={currentTime}stroke="#f97316"strokeWidth={1.5}strokeOpacity={0.7}/>{dataKeys.map((key) => {const group = key.includes(SERIES_NAME_DELIMITER)24 unmodified lines})}</LineChart></ResponsiveContainer></div><CustomLegend /></div>);},5 unmodified lines678910111213142 unmodified lines17181920212220 unmodified lines43444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810918 unmodified lines12812913013113213313452 unmodified lines1871881891901911921931941951961972 unmodified lines20020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735877 unmodified lines4364374384394404414423 unmodified lines44644744844945045118 unmodified lines47047147247347447547647747847948048148248348448548648748848912 unmodified lines5025035045055065075085095105115125135145153 unmodified lines51952052152252352452524 unmodified lines5505515525535545555565575585595605615625635645655665675685695 unmodified linesuseMemo,useRef,useState,useSyncExternalStore,} from "react";import { useTime, useTimeControls } from "../context/time-context";import {LineChart,Line,2 unmodified linesCartesianGrid,ResponsiveContainer,Tooltip,} from "recharts";type ChartRow = Record<string, number | Record<string, number>>;20 unmodified lines"#84cc16",];/// Plot-area geometry, shared by the chart and the playback cursor drawn over it.const CHART_MARGIN = { top: 12, right: 12, left: -8, bottom: 8 };const Y_AXIS_WIDTH = 55;const X_AXIS_HEIGHT = 30;/*** The time under the pointer, shared by every chart's legend. A store rather than state, so moving* the pointer re-renders the legends only, not every chart.*/type HoverStore = {get: () => number | null;set: (t: number | null) => void;subscribe: (cb: () => void) => () => void;};function createHoverStore(): HoverStore {let time: number | null = null;const listeners = new Set<() => void>();return {get: () => time,set: (t) => {if (t === time) return;time = t;listeners.forEach((cb) => cb());},subscribe: (cb) => {listeners.add(cb);return () => listeners.delete(cb);},};}/** Index of the first point at or after `time`, or the last point. */function closestDataIndex(chartData: Record<string, number>[], time: number) {if (!chartData.length) return 0;const idx = chartData.findIndex((point) => point.timestamp >= time);return idx !== -1 ? idx : chartData.length - 1;}/*** Drawn over the chart instead of as a Recharts ReferenceLine: a ReferenceLine* makes the whole chart re-render on every playback tick.*/function PlaybackCursor({ start, end }: { start: number; end: number }) {const { currentTime } = useTime();if (end <= start) return null;const fraction = (currentTime - start) / (end - start);if (fraction < 0 || fraction > 1) return null;const left = CHART_MARGIN.left + Y_AXIS_WIDTH;return (<divclassName="pointer-events-none absolute w-[1.5px] bg-orange-500/70"style={{top: CHART_MARGIN.top,bottom: CHART_MARGIN.bottom + X_AXIS_HEIGHT,left: `calc(${left}px + (100% - ${left + CHART_MARGIN.right}px) * ${fraction})`,}}/>);}function mergeGroups(data: ChartRow[][]): ChartRow[] {if (data.length <= 1) return data[0] ?? [];const maxLen = Math.max(...data.map((g) => g.length));18 unmodified linesexport const DataRecharts = React.memo(({ data, onChartsReady }: DataGraphProps) => {const [hoverStore] = useState(createHoverStore);const [expanded, setExpanded] = useState(false);useEffect(() => {52 unmodified lines)}{expanded ? (<SingleDataGraph data={combinedData} hoverStore={hoverStore} tall />) : (<div className="grid md:grid-cols-2 grid-cols-1 gap-4">{data.map((group, idx) => (<SingleDataGraph key={idx} data={group} hoverStore={hoverStore} />))}</div>)}2 unmodified lines},);/** Series toggles with each series' value at the hovered time, or the playback time. */function ChartLegend({chartData,groups,singles,groupColorMap,visibleKeys,setVisibleKeys,hoverStore,}: {chartData: Record<string, number>[];groups: Record<string, string[]>;singles: string[];groupColorMap: Record<string, string>;visibleKeys: string[];setVisibleKeys: React.Dispatch<React.SetStateAction<string[]>>;hoverStore: HoverStore;}) {const { currentTime } = useTime();const hoveredTime = useSyncExternalStore(hoverStore.subscribe,hoverStore.get,hoverStore.get,);const closestIndex = closestDataIndex(chartData,hoveredTime != null ? hoveredTime : currentTime,);const currentData = chartData[closestIndex] || {};const isGroupChecked = (group: string) =>groups[group].every((k) => visibleKeys.includes(k));const isGroupIndeterminate = (group: string) =>groups[group].some((k) => visibleKeys.includes(k)) &&!isGroupChecked(group);const handleGroupCheckboxChange = (group: string) => {if (isGroupChecked(group)) {// Uncheck all childrensetVisibleKeys((prev) => prev.filter((k) => !groups[group].includes(k)));} else {// Check all childrensetVisibleKeys((prev) =>Array.from(new Set([...prev, ...groups[group]])),);}};const handleCheckboxChange = (key: string) => {setVisibleKeys((prev) =>prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],);};return (<div className="flex flex-wrap gap-x-5 gap-y-2 px-1 pt-2">{Object.entries(groups).map(([group, children]) => {const color = groupColorMap[group];return (<div key={group}><label className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={isGroupChecked(group)}ref={(el) => {if (el) el.indeterminate = isGroupIndeterminate(group);}}onChange={() => handleGroupCheckboxChange(group)}className="size-3"style={{ accentColor: color }}/><span className="text-xs font-semibold text-slate-200">{group}</span></label><div className="pl-5 flex flex-col gap-0.5 mt-0.5">{children.map((key) => {const label = key.split(SERIES_NAME_DELIMITER).pop() ?? key;return (<labelkey={key}className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={visibleKeys.includes(key)}onChange={() => handleCheckboxChange(key)}className="size-2.5"style={{ accentColor: color }}/><spanclassName={`text-xs ${visibleKeys.includes(key) ? "text-slate-300" : "text-slate-500"}`}>{label}</span><spanclassName={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}>{typeof currentData[key] === "number"? currentData[key].toFixed(2): "–"}</span></label>);})}</div></div>);})}{singles.map((key) => {const color = groupColorMap[key];return (<labelkey={key}className="flex items-center gap-1.5 cursor-pointer select-none"><inputtype="checkbox"checked={visibleKeys.includes(key)}onChange={() => handleCheckboxChange(key)}className="size-3"style={{ accentColor: color }}/><spanclassName={`text-xs ${visibleKeys.includes(key) ? "text-slate-200" : "text-slate-500"}`}>{key}</span><spanclassName={`text-xs font-mono tabular-nums ml-1 ${visibleKeys.includes(key) ? "text-cyan-200/80" : "text-slate-600"}`}>{typeof currentData[key] === "number"? currentData[key].toFixed(2): "–"}</span></label>);})}</div>);}const SingleDataGraph = React.memo(({data,hoverStore,tall,}: {data: ChartRow[];hoverStore: HoverStore;tall?: boolean;}) => {const { seek } = useTimeControls();const flattenRow = useCallback((row: Record<string, number | Record<string, number>>, prefix = "") => {const result: Record<string, number> = {};77 unmodified linesreturn { groups: grouped, singles: singleList, groupColorMap: colorMap };}, [dataKeys]);const handleMouseLeave = () => hoverStore.set(null);const handleClick = (data: { activePayload?: { payload: { timestamp: number } }[] } | null,3 unmodified lines}};// Derive chart title from the grouped feature namesconst chartTitle = useMemo(() => {const featureNames = Object.keys(groups);18 unmodified lines</p>)}<divclassName={`relative w-full ${tall ? "h-[500px]" : "h-72"}`}onMouseLeave={handleMouseLeave}><ResponsiveContainer width="100%" height="100%"><LineChartdata={chartData}syncId="episode-sync"margin={CHART_MARGIN}onClick={handleClick}onMouseMove={(state) => {const payload = state?.activePayload?.[0]?.payload as| { timestamp?: number }| undefined;hoverStore.set(payload?.timestamp ?? null);}}onMouseLeave={handleMouseLeave}>12 unmodified linesstroke="#64748b"tick={{ fontSize: 12, fill: "#94a3b8" }}minTickGap={30}height={X_AXIS_HEIGHT}allowDataOverflow={true}/><YAxisdomain={["auto", "auto"]}stroke="#64748b"tick={{ fontSize: 12, fill: "#94a3b8" }}width={Y_AXIS_WIDTH}allowDataOverflow={true}tickFormatter={(v: number) => {if (v === 0) return "0";3 unmodified lines}}/><Tooltip content={() => null} isAnimationActive={false} />{dataKeys.map((key) => {const group = key.includes(SERIES_NAME_DELIMITER)24 unmodified lines})}</LineChart></ResponsiveContainer><PlaybackCursorstart={chartData.at(0)?.timestamp ?? 0}end={chartData.at(-1)?.timestamp ?? 0}/></div><ChartLegendchartData={chartData}groups={groups}singles={singles}groupColorMap={groupColorMap}visibleKeys={visibleKeys}setVisibleKeys={setVisibleKeys}hoverStore={hoverStore}/></div>);},
4 unmodified lines56789106 unmodified lines17181920212223242526272829301 unmodified line323334353637383940414243444560 unmodified lines1061071081091101111121131141151161171181191201211221231241254 unmodified linesuseState,useCallback,useEffect,} from "react";// `external` (default) — user-initiated seek (slider drag, chart click,6 unmodified lines// report, not a command.type TimeUpdateSource = "external" | "video";type TimeContextType = {currentTime: number;seek: (t: number, source?: TimeUpdateSource) => void;// Monotonically increasing counter that bumps on every `external` seek.// Sync effects compare the current value against a stored ref to detect// user-initiated seeks without relying on heuristics like "did the time// jump by more than 0.3s".externalSeekVersion: number;subscribe: (cb: (t: number) => void) => () => void;isPlaying: boolean;setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;1 unmodified linesetDuration: React.Dispatch<React.SetStateAction<number>>;};const TimeContext = createContext<TimeContextType | undefined>(undefined);export const useTime = () => {const ctx = useContext(TimeContext);if (!ctx) throw new Error("useTime must be used within a TimeProvider");return ctx;};const TIME_RENDER_THROTTLE_MS = 80;export const TimeProvider: React.FC<{60 unmodified linesreturn () => listeners.current.delete(cb);}, []);return (<TimeContext.Providervalue={{currentTime,seek: updateTime,externalSeekVersion,subscribe,isPlaying,setIsPlaying,duration,setDuration,}}>{children}</TimeContext.Provider>);};4 unmodified lines5678910116 unmodified lines18192021222324251 unmodified line2728293031323334353637383940414243444546474849505152535455565758596061626360 unmodified lines1241251261271281291301311321331341351361371381391401411421431441451461471484 unmodified linesuseState,useCallback,useEffect,useMemo,} from "react";// `external` (default) — user-initiated seek (slider drag, chart click,6 unmodified lines// report, not a command.type TimeUpdateSource = "external" | "video";type TimeControls = {seek: (t: number, source?: TimeUpdateSource) => void;subscribe: (cb: (t: number) => void) => () => void;isPlaying: boolean;setIsPlaying: React.Dispatch<React.SetStateAction<boolean>>;1 unmodified linesetDuration: React.Dispatch<React.SetStateAction<number>>;};type TimeContextType = TimeControls & {currentTime: number;// Monotonically increasing counter that bumps on every `external` seek.// Sync effects compare the current value against a stored ref to detect// user-initiated seeks without relying on heuristics like "did the time// jump by more than 0.3s".externalSeekVersion: number;};const TimeControlsContext = createContext<TimeControls | undefined>(undefined);const TimeContext = createContext<TimeContextType | undefined>(undefined);/** Everything, including `currentTime`: re-renders on every playback tick. */export const useTime = () => {const ctx = useContext(TimeContext);if (!ctx) throw new Error("useTime must be used within a TimeProvider");return ctx;};/*** Seeking and play state without `currentTime`. A component that only seeks or toggles playback* should use this: reading `useTime()` at all re-renders it on every playback tick, whichever* fields it destructures.*/export const useTimeControls = () => {const ctx = useContext(TimeControlsContext);if (!ctx)throw new Error("useTimeControls must be used within a TimeProvider");return ctx;};const TIME_RENDER_THROTTLE_MS = 80;export const TimeProvider: React.FC<{60 unmodified linesreturn () => listeners.current.delete(cb);}, []);const controls = useMemo(() => ({seek: updateTime,subscribe,isPlaying,setIsPlaying,duration,setDuration,}),[updateTime, subscribe, isPlaying, duration],);const value = useMemo(() => ({ ...controls, currentTime, externalSeekVersion }),[controls, currentTime, externalSeekVersion],);return (<TimeControlsContext.Provider value={controls}><TimeContext.Provider value={value}>{children}</TimeContext.Provider></TimeControlsContext.Provider>);};
src/app/[org]/[dataset]/[episode]/episode-viewer.tsx+5-7
src/components/annotations-panel.tsx+2-2
src/components/data-recharts.tsx+231-174
src/context/time-context.tsx+44-21