Spaces:
Running

HDF5_Visualizer / index.html
ns69956's picture
Update index.html
3669ef3 verified
Raw History Blame Contribute Delete
19.6 kB
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>UR5e GELLO Dataset Viewer</title>
<style>
:root {
--bg:#f5f7fb;
--card:#fff;
--ink:#1c2940;
--muted:#66758c;
--line:#dfe5ef;
--blue:#2757bb;
}
* {box-sizing:border-box}
body {margin:0;background:var(--bg);color:var(--ink);font:15px/1.5 system-ui,sans-serif}
header {background:#162f59;color:white;padding:20px max(18px,calc((100vw - 1160px)/2))}
h1 {font-size:23px;margin:0 0 4px}
header p {color:#d8e3f5;margin:0}
main {max-width:1160px;margin:22px auto 45px;padding:0 16px;display:grid;gap:16px}
.card {background:var(--card);border:1px solid var(--line);border-radius:12px;padding:20px}
h2 {font-size:17px;margin:0 0 13px}
label {display:block;color:var(--muted);font-size:12px;font-weight:700;margin-bottom:5px}
input[type=url],select,button {font:inherit;padding:10px;border:1px solid var(--line);border-radius:8px;min-height:44px}
input[type=url],select {width:100%;background:white;min-width:0}
button {cursor:pointer;background:white;font-weight:600}
button:disabled,select:disabled {opacity:.45;cursor:not-allowed}
.row {display:flex;gap:10px;align-items:end;flex-wrap:wrap}
.grow {flex:1;min-width:200px}
.note {font-size:12px;color:var(--muted);margin:10px 0 0}
.status {font-size:13px;color:#20613f;margin:10px 0 0;overflow-wrap:anywhere}
.status.error {color:#ad3039}
[hidden] {display:none !important}
/* Download progress */
.download-progress {margin-top:12px}
.progress-head {display:flex;justify-content:space-between;gap:12px;font-size:13px;font-weight:600}
#downloadBar {display:block;width:100%;height:16px;margin-top:6px;accent-color:var(--blue)}
/* Camera views */
.views {display:grid;grid-template-columns:1fr 1fr;gap:12px}
.view {border:1px solid var(--line);border-radius:9px;overflow:hidden;background:#101a2b}
.view-title {background:white;padding:10px 12px;font-weight:600;font-size:13px}
.image-wrap {min-height:240px;padding:10px;display:grid;place-items:center}
canvas {display:block;max-width:100%;max-height:420px;object-fit:contain}
.placeholder {color:#cbd6e8;font-size:13px}
/* Timeline */
.controls {display:flex;align-items:center;gap:10px;margin-top:15px}
#frame {width:100%;accent-color:var(--blue)}
#frameLabel {white-space:nowrap;font-size:13px;color:var(--muted)}
/* Robot observations */
.fields {display:grid;grid-template-columns:1fr 1fr;gap:10px}
.field {background:#fafbff;border:1px solid var(--line);padding:11px;border-radius:8px;min-width:0}
.field b {display:block;color:var(--muted);font-size:12px;margin-bottom:6px}
.field pre {white-space:pre-wrap;overflow-wrap:anywhere;margin:0;font-size:12px}
@media(max-width:700px){
.views,.fields {grid-template-columns:1fr}
.image-wrap {min-height:170px}
}
</style>
</head>
<body>
<header>
<h1>UR5e GELLO · HDF5 Demonstration Viewer</h1>
<p>Peg-in-hole insertion dataset · Browser-based, read-only</p>
</header>
<main>
<!-- Dataset loading -->
<section class="card">
<h2>1. Load dataset from Hugging Face</h2>
<div class="row">
<div class="grow">
<label for="url">Hugging Face file URL (paste the usual /blob/ link)</label>
<input id="url" type="url" value="https://huggingface.co/datasets/ns69956/UR5e-PegInsertion/blob/main/square_hole_box.hdf5">
</div>
<button id="load" type="button" disabled>Load dataset</button>
</div>
<p class="note">
The viewer automatically changes /blob/ into /resolve/.
It requires a public HDF5 file and browser-permitted cross-origin access.
</p>
<!-- Download progress -->
<div id="downloadBox" class="download-progress" hidden>
<div class="progress-head">
<span id="downloadTitle">Downloading…</span>
<span id="downloadPercent">0%</span>
</div>
<progress id="downloadBar" max="100" value="0"></progress>
<p id="downloadDetail" class="note">0 MB downloaded</p>
</div>
<p id="status" class="status" role="status">
Initializing HDF5 reader…
</p>
</section>
<!-- Demonstration selector -->
<section class="card">
<h2>2. Select demonstration and cameras</h2>
<div class="row">
<div class="grow">
<label for="demo">Demonstration</label>
<select id="demo" disabled></select>
</div>
<div class="grow">
<label for="cam1">Camera 1</label>
<select id="cam1" disabled></select>
</div>
<div class="grow">
<label for="cam2">Camera 2</label>
<select id="cam2" disabled></select>
</div>
</div>
<p id="meta" class="note">No dataset loaded</p>
</section>
<!-- Camera observations -->
<section class="card">
<h2>3. Camera observations</h2>
<div class="views">
<div class="view">
<div id="name1" class="view-title">Camera 1</div>
<div class="image-wrap">
<canvas id="image1" hidden></canvas>
<span id="empty1" class="placeholder">No image loaded</span>
</div>
</div>
<div class="view">
<div id="name2" class="view-title">Camera 2</div>
<div class="image-wrap">
<canvas id="image2" hidden></canvas>
<span id="empty2" class="placeholder">No image loaded</span>
</div>
</div>
</div>
<!-- Frame navigation -->
<div class="controls">
<button id="prev" disabled aria-label="Previous frame">←</button>
<button id="play" disabled>Play</button>
<input id="frame" type="range" min="0" max="0" value="0" step="1" disabled aria-label="Frame">
<button id="next" disabled aria-label="Next frame">→</button>
<output id="frameLabel">0 / 0</output>
</div>
<p class="note">
Playback is for browsing only (4 frames/second), not the original recording rate.
</p>
</section>
<!-- Robot observations -->
<section class="card">
<h2>4. Robot states and actions</h2>
<div id="fields" class="fields">
<div class="field">Load a dataset to view observations.</div>
</div>
</section>
</main>
<script type="module">
import h5wasm from 'https://cdn.jsdelivr.net/npm/h5wasm@0.10.3/dist/esm/hdf5_hl.js';
const $ = id => document.getElementById(id);
const obsFields = ['tcp_pos', 'tcp_quat', 'joints', 'gripper_position', 'wrench'];
let FS, h5, demos = [], currentDemo = '', lastFrame = 0, playback = null;
// ----------------------------------------
// Status
// ----------------------------------------
function status(message, error = false) {
$('status').textContent = message;
$('status').classList.toggle('error', error);
}
// ----------------------------------------
// Hugging Face URL
// ----------------------------------------
function normalizeUrl(input) {
const url = new URL(input.trim());
if (url.protocol !== 'https:' || url.hostname !== 'huggingface.co') {
throw new Error('Paste an HTTPS link from huggingface.co.');
}
if (!url.pathname.startsWith('/datasets/')) {
throw new Error('This must be a Hugging Face dataset file link.');
}
url.pathname = url.pathname.replace('/blob/', '/resolve/');
if (!url.pathname.includes('/resolve/')) {
throw new Error('Copy a link to a specific HDF5 file, not the dataset homepage.');
}
url.hash = '';
return url.toString();
}
// ----------------------------------------
// HDF5 Validation
// ----------------------------------------
function validHdf5(bytes) {
const magic = [137, 72, 68, 70, 13, 10, 26, 10];
for (
let offset = 0;
offset + 8 <= bytes.length && offset <= 65536;
offset = offset === 0 ? 512 : offset * 2
) {
if (magic.every((v, i) => bytes[offset + i] === v)) return true;
}
return false;
}
// ----------------------------------------
// HDF5 Utilities
// ----------------------------------------
function keys(path) {
try {
return h5.get(path).keys();
} catch {
return [];
}
}
function getDataset(path) {
try {
const item = h5.get(path);
return Array.isArray(item.shape) ? item : null;
} catch {
return null;
}
}
function getFrame(path, t) {
const ds = getDataset(path);
if (!ds || !ds.shape.length || t >= ds.shape[0]) return null;
return {
values: ds.slice([
[t, t + 1],
...ds.shape.slice(1).map(() => [])
]),
shape: ds.shape.slice(1)
};
}
function displayValue(path, t) {
const result = getFrame(path, t);
if (!result) return 'N/A';
const values = Array.from(result.values);
const shown = values.slice(0, 80).map(v =>
typeof v === 'number' && Number.isFinite(v)
? Number(v.toFixed(5))
: String(v)
);
return `[${shown.join(', ')}${values.length > 80 ? ', …' : ''}]`;
}
// ----------------------------------------
// Dropdowns
// ----------------------------------------
function selectOptions(id, options) {
const element = $(id);
element.replaceChildren();
options.forEach(value => {
const option = document.createElement('option');
option.value = value;
option.textContent = value || 'None';
element.append(option);
});
element.disabled = !options.length;
}
// ----------------------------------------
// Image Rendering
// ----------------------------------------
function drawImage(canvasId, emptyId, titleId, key, t) {
const canvas = $(canvasId);
const empty = $(emptyId);
$(titleId).textContent = key || 'No camera';
canvas.hidden = true;
empty.hidden = false;
empty.textContent = key ? 'Image unavailable' : 'No camera selected';
if (!key) return;
try {
const result = getFrame(`data/${currentDemo}/obs/${key}`, t);
if (!result) return;
const [height, width, channels = 1] = result.shape;
if (
![2, 3].includes(result.shape.length) ||
![1, 3, 4].includes(channels)
) {
throw new Error(`Unsupported shape: [${result.shape.join(', ')}]`);
}
const raw = result.values;
if (raw.length !== width * height * channels) {
throw new Error('Invalid image data shape');
}
let scale = 1, shift = 0;
if (!(raw instanceof Uint8Array || raw instanceof Uint8ClampedArray)) {
let min = Infinity, max = -Infinity;
for (const v of raw) {
if (Number.isFinite(v)) {
min = Math.min(min, v);
max = Math.max(max, v);
}
}
if (min >= 0 && max <= 1) {
scale = 255;
} else if (min < 0 || max > 255) {
scale = max > min ? 255 / (max - min) : 1;
shift = -min * scale;
}
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
const img = ctx.createImageData(width, height);
for (let i = 0; i < width * height; i++) {
const s = i * channels;
const d = i * 4;
const r = raw[s] * scale + shift;
img.data[d] = r;
img.data[d + 1] = channels === 1 ? r : raw[s + 1] * scale + shift;
img.data[d + 2] = channels === 1 ? r : raw[s + 2] * scale + shift;
img.data[d + 3] = channels === 4 ? raw[s + 3] : 255;
}
ctx.putImageData(img, 0, 0);
canvas.hidden = false;
empty.hidden = true;
} catch (err) {
empty.textContent = `Unable to display image: ${err.message}`;
}
}
// ----------------------------------------
// Playback
// ----------------------------------------
function stopPlayback() {
if (playback) clearInterval(playback);
playback = null;
$('play').textContent = 'Play';
}
// ----------------------------------------
// Render Selected Frame
// ----------------------------------------
function render() {
if (!h5 || !currentDemo) return;
const t = Math.min(lastFrame, Number($('frame').value));
$('frameLabel').textContent = `${t} / ${lastFrame}`;
drawImage('image1', 'empty1', 'name1', $('cam1').value, t);
drawImage('image2', 'empty2', 'name2', $('cam2').value, t);
const fields = [
...obsFields.map(key => [key, `data/${currentDemo}/obs/${key}`]),
['actions', `data/${currentDemo}/actions`],
['rewards', `data/${currentDemo}/rewards`],
['dones', `data/${currentDemo}/dones`]
];
$('fields').replaceChildren();
fields.forEach(([name, path]) => {
const field = document.createElement('div');
field.className = 'field';
const title = document.createElement('b');
title.textContent = name;
const value = document.createElement('pre');
try {
value.textContent = displayValue(path, t);
} catch (err) {
value.textContent = `Error: ${err.message}`;
}
field.append(title, value);
$('fields').append(field);
});
}
// ----------------------------------------
// Demonstration Selection
// ----------------------------------------
function chooseDemo(name) {
stopPlayback();
currentDemo = name;
const obsPath = `data/${name}/obs`;
const actionCount = getDataset(`data/${name}/actions`)?.shape[0];
const firstObs = keys(obsPath)[0];
const count = actionCount ??
getDataset(`${obsPath}/${firstObs}`)?.shape[0] ?? 0;
lastFrame = Math.max(0, count - 1);
$('frame').max = lastFrame;
$('frame').value = 0;
const cameras = keys(obsPath).filter(key =>
key.toLowerCase().includes('image') &&
(getDataset(`${obsPath}/${key}`)?.shape.length ?? 0) >= 3
);
selectOptions('cam1', cameras);
selectOptions('cam2', ['', ...cameras]);
if (cameras.length > 1) $('cam2').value = cameras[1];
for (const id of ['frame', 'prev', 'next', 'play']) {
$(id).disabled = count < 2;
}
$('meta').textContent =
`${demos.length} demonstrations · ${count} transitions in ${name}`;
render();
}
// ----------------------------------------
// Download Progress Utilities
// ----------------------------------------
function mb(bytes) {
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function updateProgress(received, total, startTime) {
const bar = $('downloadBar');
const elapsed = Math.max((performance.now() - startTime) / 1000, 0.1);
const speed = mb(received / elapsed) + '/s';
if (total) {
const pct = Math.min(100, (received / total) * 100);
bar.value = pct;
$('downloadPercent').textContent = pct.toFixed(1) + '%';
$('downloadDetail').textContent =
`${mb(received)} / ${mb(total)} · ${speed}`;
} else {
// Unknown content length
bar.removeAttribute('value');
$('downloadPercent').textContent = 'Downloading…';
$('downloadDetail').textContent =
`${mb(received)} downloaded · ${speed}`;
}
}
// ----------------------------------------
// Stream Download With Progress
// ----------------------------------------
async function downloadWithProgress(url) {
$('downloadBox').hidden = false;
$('downloadTitle').textContent = 'Downloading HDF5 file';
$('downloadBar').value = 0;
$('downloadPercent').textContent = '0%';
$('downloadDetail').textContent = 'Connecting to Hugging Face…';
const response = await fetch(url, { redirect: 'follow' });
if (!response.ok) {
throw new Error(
`HTTP ${response.status}: verify that the dataset and file are public.`
);
}
const contentLength = Number(response.headers.get('content-length'));
const total = Number.isFinite(contentLength) && contentLength > 0
? contentLength
: null;
const startTime = performance.now();
let received = 0;
let bytes;
if (response.body && typeof response.body.getReader === 'function') {
const reader = response.body.getReader();
const chunks = [];
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value || !value.length) continue;
chunks.push(value);
received += value.length;
updateProgress(received, total, startTime);
}
bytes = new Uint8Array(received);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.length;
}
} else {
// Fallback if browser does not expose a readable stream
updateProgress(0, null, startTime);
bytes = new Uint8Array(await response.arrayBuffer());
received = bytes.length;
}
$('downloadBar').value = 100;
$('downloadPercent').textContent = '100%';
$('downloadTitle').textContent = 'Download complete';
$('downloadDetail').textContent = `${mb(received)} downloaded`;
return bytes;
}
// ----------------------------------------
// Load Dataset
// ----------------------------------------
async function loadDataset() {
stopPlayback();
$('load').disabled = true;
$('downloadBox').hidden = true;
try {
const url = normalizeUrl($('url').value);
status('Downloading HDF5 file from Hugging Face…');
const bytes = await downloadWithProgress(url);
if (!validHdf5(bytes)) {
throw new Error('The URL did not return valid HDF5 content.');
}
status('Download complete. Opening HDF5 dataset…');
if (h5) h5.close();
try {
FS.unlink('/dataset.hdf5');
} catch {}
FS.writeFile('/dataset.hdf5', bytes);
h5 = new h5wasm.File('/dataset.hdf5', 'r');
if (!h5.keys().includes('data')) {
throw new Error('Missing /data group in HDF5 file.');
}
demos = keys('data')
.filter(name => /^demo_\d+$/.test(name))
.sort((a, b) => Number(a.slice(5)) - Number(b.slice(5)));
if (!demos.length) {
throw new Error('No demo_* trajectories found under /data.');
}
selectOptions('demo', demos);
chooseDemo(demos[0]);
status(
`Loaded ${demos.length} demonstrations ` +
`(${(bytes.length / 1024 / 1024).toFixed(1)} MiB).`
);
} catch (err) {
const message = err instanceof TypeError
? 'Browser download failed. The file may be private, unavailable, or blocked by CORS on a Hugging Face storage redirect.'
: `Unable to load dataset: ${err.message}`;
$('downloadTitle').textContent = 'Download interrupted';
status(message, true);
} finally {
$('load').disabled = false;
}
}
// ----------------------------------------
// Event Listeners
// ----------------------------------------
$('load').addEventListener('click', loadDataset);
$('url').addEventListener('keydown', event => {
if (event.key === 'Enter') loadDataset();
});
$('demo').addEventListener('change', () => chooseDemo($('demo').value));
$('cam1').addEventListener('change', render);
$('cam2').addEventListener('change', render);
$('frame').addEventListener('input', render);
function step(delta) {
$('frame').value = Math.max(
0,
Math.min(lastFrame, Number($('frame').value) + delta)
);
render();
}
$('prev').addEventListener('click', () => step(-1));
$('next').addEventListener('click', () => step(1));
$('play').addEventListener('click', () => {
if (playback) return stopPlayback();
if (Number($('frame').value) >= lastFrame) {
$('frame').value = 0;
}
$('play').textContent = 'Pause';
playback = setInterval(() => {
if (Number($('frame').value) >= lastFrame) {
stopPlayback();
} else {
step(1);
}
}, 250);
});
// ----------------------------------------
// Initialize HDF5 Reader
// ----------------------------------------
try {
FS = (await h5wasm.ready).FS;
$('load').disabled = false;
status('Ready. Paste a dataset link and click Load dataset.');
} catch (err) {
status(`Unable to initialize HDF5 reader: ${err.message}`, true);
}
</script>
</body>
</html>