forked from alphaXiv/TinyRecursiveModels
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaze_visualizer.html
More file actions
395 lines (366 loc) · 18.7 KB
/
maze_visualizer.html
File metadata and controls
395 lines (366 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Maze Predictions Visualizer</title>
<style>
body { font-family: sans-serif; margin: 16px; }
.controls { margin-bottom: 12px; }
.grid-canvas { border: 1px solid #333; margin-top: 8px; }
#status { margin-top: 8px; }
button { padding: 8px 12px; margin-right: 8px; }
</style>
</head>
<body>
<h1>Maze Predictions Visualizer</h1>
<div class="controls">
<button id="loadPreds">Load Server Prediction</button>
<label for="predictUrl"> Predict URL:</label>
<input id="predictUrl" type="text" value="https://alphaxiv--tinyrecursive-eval-predict-dev.modal.run/" style="width:420px" />
<label for="exampleIndex">Example index:</label>
<input id="exampleIndex" type="number" value="0" min="0" style="width:60px" />
<label for="predFile">Preds file (optional):</label>
<input id="predFile" type="text" placeholder="step_32550_all_preds.0" style="width:220px" />
<button id="loadExample">Load Example (from uploaded .npy)</button>
<div style="margin-top:10px"></div>
<label>Paste input grid JSON (2D or flat):</label>
<textarea id="inputGridJson" rows="4" cols="60" placeholder="[[1,0,...], [0,1,...], ...]"></textarea>
<button id="sendInput">Predict from pasted grid (POST)</button>
<div style="margin-top:10px"></div>
<label for="listUrl">List URL (optional):</label>
<input id="listUrl" type="text" placeholder="derive from Predict URL" style="width:360px" />
<label for="getUrl">Get URL (optional):</label>
<input id="getUrl" type="text" placeholder="derive from Predict URL" style="width:360px" />
<button id="refreshSaved">Refresh Saved List</button>
<select id="savedSelect" style="min-width:240px"></select>
<button id="loadSaved">Load Selected Saved</button>
</div>
<div id="status">Status: idle</div>
<div id="canvasHolder"></div>
<script>
// Render a 2D grid to a canvas. grid is a 2D array of numbers.
function renderGridToCanvas(grid, scale=10) {
const rows = grid.length;
const cols = grid[0].length;
const canvas = document.createElement('canvas');
canvas.width = cols * scale;
canvas.height = rows * scale;
canvas.className = 'grid-canvas';
const ctx = canvas.getContext('2d');
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const v = grid[r][c];
ctx.fillStyle = valueToColor(v);
ctx.fillRect(c*scale, r*scale, scale, scale);
}
}
return canvas;
}
function valueToColor(v) {
// Generic palette for integer-labeled maze grids. The model outputs
// integer labels per cell; we map common values to intuitive colors.
// You can customize these if your dataset uses different encodings.
const palette = {
0: '#FFFFFF', // empty / pad
1: '#000000', // wall
2: '#EEEEEE', // open / floor
3: '#00AA00', // goal
4: '#FFFF00', // special marker (yellow)
5: '#1E90FF', // path / predicted fill (blue)
6: '#FF00FF', // extra
};
return palette.hasOwnProperty(v) ? palette[v] : '#CCCCCC';
}
async function loadServerPrediction() {
// No fallbacks: call the exact predict URL provided by the user and require a 'solved_maze' key.
const PREDICT_URL = document.getElementById('predictUrl').value.trim();
const idx = parseInt(document.getElementById('exampleIndex').value, 10);
const file = (document.getElementById('predFile')?.value || '').trim();
try {
if (!Number.isInteger(idx) || idx < 0) throw new Error('Example index must be a non-negative integer');
// Ensure the URL is absolute and non-empty
if (!PREDICT_URL) throw new Error('Predict URL is empty');
const url = new URL(PREDICT_URL);
url.searchParams.set('index', String(idx));
if (file) url.searchParams.set('file', file);
document.getElementById('status').textContent = 'Status: fetching prediction from ' + url.toString() + ' ...';
const resp = await fetch(url.toString(), { method: 'GET' });
if (!resp.ok) {
throw new Error('Server returned HTTP ' + resp.status);
}
const data = await resp.json();
// Strict: must contain 'solved_maze' as a 2D square array.
if (!data || !('solved_maze' in data)) {
throw new Error("Response JSON missing required 'solved_maze' field");
}
let grid = data.solved_maze;
// Normalize predicted grid to 2D and validate square
if (!Array.isArray(grid) || grid.length === 0) {
throw new Error('Predicted grid is empty or invalid');
}
if (!Array.isArray(grid[0])) {
const flat = grid;
const L = flat.length;
const side = Math.sqrt(L);
if (!Number.isInteger(side)) {
throw new Error(`Predicted grid length ${L} is not a perfect square`);
}
const newGrid = [];
for (let r = 0; r < side; r++) {
newGrid.push(flat.slice(r*side, (r+1)*side));
}
grid = newGrid;
}
const hPred = grid.length;
const wPred = Array.isArray(grid[0]) ? grid[0].length : 0;
if (hPred !== wPred) {
throw new Error(`Predicted grid is not square: ${hPred}x${wPred}`);
}
const holder = document.getElementById('canvasHolder');
holder.innerHTML = '';
// Make the canvas scale adaptively so large grids still fit the view.
const side = grid.length;
const maxPixels = Math.min(window.innerWidth - 40, 900);
const scale = Math.max(4, Math.floor(maxPixels / side));
// Side-by-side layout
const wrap = document.createElement('div');
wrap.style.display = 'grid';
wrap.style.gridTemplateColumns = '1fr 1fr 1fr';
wrap.style.gap = '16px';
const left = document.createElement('div');
const right = document.createElement('div');
const extra = document.createElement('div');
const headerIn = document.createElement('div');
headerIn.textContent = 'Input grid';
headerIn.style.fontWeight = 'bold';
headerIn.style.marginBottom = '4px';
left.appendChild(headerIn);
const inputGrid = data.input_maze;
if (!Array.isArray(inputGrid) || inputGrid.length === 0) {
throw new Error('Input grid unavailable in server response');
}
if (!Array.isArray(inputGrid[0])) {
const flat = inputGrid;
const L = flat.length;
const side = Math.sqrt(L);
if (!Number.isInteger(side)) {
throw new Error(`Input grid length ${L} is not a perfect square`);
}
const newGrid = [];
for (let r = 0; r < side; r++) {
newGrid.push(flat.slice(r*side, (r+1)*side));
}
inputGrid.length = 0; // replace contents
for (const row of newGrid) inputGrid.push(row);
}
const hIn = inputGrid.length;
const wIn = Array.isArray(inputGrid[0]) ? inputGrid[0].length : 0;
if (hIn !== wIn) {
throw new Error(`Input grid is not square: ${hIn}x${wIn}`);
}
const inScale = Math.max(4, Math.floor(maxPixels / hIn));
left.appendChild(renderGridToCanvas(inputGrid, inScale));
const headerOut = document.createElement('div');
headerOut.textContent = 'Predicted grid';
headerOut.style.fontWeight = 'bold';
headerOut.style.marginBottom = '4px';
right.appendChild(headerOut);
right.appendChild(renderGridToCanvas(grid, scale));
// Optional: ground truth labels if server returned target_maze
if (data.target_maze) {
const gtHeader = document.createElement('div');
gtHeader.textContent = 'Ground truth';
gtHeader.style.fontWeight = 'bold';
gtHeader.style.marginTop = '16px';
extra.appendChild(gtHeader);
let gt = data.target_maze;
if (!Array.isArray(gt[0])) {
const flat = gt;
const L = flat.length;
const side = Math.sqrt(L);
if (Number.isInteger(side)) {
const newGrid = [];
for (let r = 0; r < side; r++) newGrid.push(flat.slice(r*side, (r+1)*side));
gt = newGrid;
}
}
const gtScale = Math.max(4, Math.floor(maxPixels / gt.length));
extra.appendChild(renderGridToCanvas(gt, gtScale));
}
wrap.appendChild(left);
wrap.appendChild(right);
if (extra.childNodes.length > 0) wrap.appendChild(extra);
holder.appendChild(wrap);
const retIdx = Number.isInteger(data.index) ? data.index : idx;
document.getElementById('status').textContent = 'Status: rendered (index: ' + retIdx + ', source: ' + (data.source_file || 'unknown') + ')';
renderLegend();
} catch (err) {
// Per request: no fallbacks, surface the error to the user.
document.getElementById('status').textContent = 'Status: error - ' + err.message;
console.error(err);
}
}
function renderLegend() {
const legendId = 'vizLegend';
let legend = document.getElementById(legendId);
if (!legend) {
legend = document.createElement('div');
legend.id = legendId;
legend.style.marginTop = '8px';
document.getElementById('canvasHolder').appendChild(legend);
}
const items = [
{k:1, label:'Wall'},
{k:2, label:'Open'},
{k:5, label:'Predicted / path'},
{k:3, label:'Goal'},
{k:4, label:'Marker'}
];
legend.innerHTML = '<strong>Legend:</strong> ' + items.map(it => {
const color = valueToColor(it.k);
return `<span style="display:inline-block;margin-right:10px"><span style="display:inline-block;width:16px;height:16px;background:${color};border:1px solid #000;margin-right:6px"></span>${it.label}</span>`;
}).join('');
}
document.getElementById('loadPreds').addEventListener('click', loadServerPrediction);
async function postInputGrid() {
const PREDICT_URL = document.getElementById('predictUrl').value.trim();
const raw = document.getElementById('inputGridJson').value.trim();
try {
if (!PREDICT_URL) throw new Error('Predict URL is empty');
if (!raw) throw new Error('Paste an input grid JSON');
const body = { grid: JSON.parse(raw), task: 'maze' };
const resp = await fetch(PREDICT_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!resp.ok) throw new Error('Server returned HTTP ' + resp.status);
const data = await resp.json();
// Reuse render path: pretend this is what GET returned
if (!data || !('solved_maze' in data)) throw new Error("Response JSON missing 'solved_maze'");
// Minimal reuse: set status and let user click Load Server Prediction to compare
document.getElementById('status').textContent = 'Status: POST prediction ok. Rendering...';
// Build a fake URL-less render path: just draw input and prediction
const holder = document.getElementById('canvasHolder');
holder.innerHTML = '';
const wrap = document.createElement('div');
wrap.style.display = 'grid';
wrap.style.gridTemplateColumns = '1fr 1fr 1fr';
wrap.style.gap = '16px';
const left = document.createElement('div');
const right = document.createElement('div');
const extra = document.createElement('div');
const maxPixels = Math.min(window.innerWidth - 40, 900);
const inp = Array.isArray(data.input_maze) ? data.input_maze : body.grid;
if (!Array.isArray(inp[0])) {
const L = inp.length; const s = Math.sqrt(L); if (!Number.isInteger(s)) throw new Error('Input not square');
const g=[]; for (let r=0;r<s;r++) g.push(inp.slice(r*s,(r+1)*s));
data.input_maze = g;
}
const inScale = Math.max(4, Math.floor(maxPixels / data.input_maze.length));
const headerIn = document.createElement('div'); headerIn.textContent = 'Input grid'; headerIn.style.fontWeight='bold'; headerIn.style.marginBottom='4px'; left.appendChild(headerIn);
left.appendChild(renderGridToCanvas(data.input_maze, inScale));
let pred = data.solved_maze; if (!Array.isArray(pred[0])) { const L=pred.length; const s=Math.sqrt(L); if(!Number.isInteger(s)) throw new Error('Pred not square'); const g=[]; for(let r=0;r<s;r++) g.push(pred.slice(r*s,(r+1)*s)); pred=g; }
const scale = Math.max(4, Math.floor(maxPixels / pred.length));
const headerOut = document.createElement('div'); headerOut.textContent='Predicted grid'; headerOut.style.fontWeight='bold'; headerOut.style.marginBottom='4px'; right.appendChild(headerOut);
right.appendChild(renderGridToCanvas(pred, scale));
if (data.target_maze) { let gt=data.target_maze; if(!Array.isArray(gt[0])){ const L=gt.length; const s=Math.sqrt(L); if(Number.isInteger(s)){ const g=[]; for(let r=0;r<s;r++) g.push(gt.slice(r*s,(r+1)*s)); gt=g; }} const gtScale=Math.max(4, Math.floor(maxPixels/gt.length)); const gtHeader=document.createElement('div'); gtHeader.textContent='Ground truth'; gtHeader.style.fontWeight='bold'; gtHeader.style.marginTop='16px'; extra.appendChild(gtHeader); extra.appendChild(renderGridToCanvas(gt, gtScale)); }
wrap.appendChild(left); wrap.appendChild(right); if (extra.childNodes.length>0) wrap.appendChild(extra); holder.appendChild(wrap);
renderLegend();
} catch (err) {
document.getElementById('status').textContent = 'Status: error - ' + err.message;
console.error(err);
}
}
document.getElementById('sendInput').addEventListener('click', postInputGrid);
function deriveEndpoint(base, name) {
// Try to replace the function segment in the subdomain: --predict--> --name--
// Example: https://...--tinyrecursive-eval-predict....modal.run/
// becomes: https://...--tinyrecursive-eval-name....modal.run/
try {
if (!base) return '';
const url = new URL(base);
url.hostname = url.hostname.replace('--predict', `--${name}`);
return url.toString();
} catch (_) {
return '';
}
}
async function refreshSavedList() {
const predictUrl = document.getElementById('predictUrl').value.trim();
let listUrl = document.getElementById('listUrl').value.trim();
if (!listUrl) listUrl = deriveEndpoint(predictUrl, 'list_custom');
if (!listUrl) { document.getElementById('status').textContent = 'Status: provide List URL or a valid Predict URL'; return; }
try {
const url = new URL(listUrl);
url.searchParams.set('task', 'maze');
document.getElementById('status').textContent = 'Status: fetching saved list …';
const resp = await fetch(url.toString(), { method: 'GET' });
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const data = await resp.json();
const sel = document.getElementById('savedSelect');
sel.innerHTML = '';
(data.items || []).forEach(it => {
const opt = document.createElement('option');
const d = new Date((it.mtime || 0) * 1000);
opt.value = it.name;
opt.textContent = `${it.name} (${d.toLocaleString()})`;
sel.appendChild(opt);
});
document.getElementById('status').textContent = `Status: loaded ${ (data.items||[]).length } saved items`;
} catch (err) {
document.getElementById('status').textContent = 'Status: error - ' + err.message;
console.error(err);
}
}
async function loadSaved() {
const predictUrl = document.getElementById('predictUrl').value.trim();
let getUrl = document.getElementById('getUrl').value.trim();
if (!getUrl) getUrl = deriveEndpoint(predictUrl, 'get_custom');
const name = document.getElementById('savedSelect').value;
if (!getUrl || !name) { document.getElementById('status').textContent = 'Status: provide Get URL and select a saved item'; return; }
try {
const url = new URL(getUrl);
url.searchParams.set('task', 'maze');
url.searchParams.set('name', name);
document.getElementById('status').textContent = 'Status: fetching saved sample …';
const resp = await fetch(url.toString(), { method: 'GET' });
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const data = await resp.json();
// Render I/O→O/P
const holder = document.getElementById('canvasHolder');
holder.innerHTML = '';
const wrap = document.createElement('div');
wrap.style.display = 'grid';
wrap.style.gridTemplateColumns = '1fr 1fr 1fr';
wrap.style.gap = '16px';
const left = document.createElement('div');
const right = document.createElement('div');
const extra = document.createElement('div');
const maxPixels = Math.min(window.innerWidth - 40, 900);
let inp = data.input_maze; if (!Array.isArray(inp[0])) { const L=inp.length; const s=Math.sqrt(L); if (!Number.isInteger(s)) throw new Error('Input not square'); const g=[]; for(let r=0;r<s;r++) g.push(inp.slice(r*s,(r+1)*s)); inp=g; }
const inScale = Math.max(4, Math.floor(maxPixels / inp.length));
const headerIn = document.createElement('div'); headerIn.textContent = 'Input grid'; headerIn.style.fontWeight='bold'; headerIn.style.marginBottom='4px'; left.appendChild(headerIn);
left.appendChild(renderGridToCanvas(inp, inScale));
let pred = data.solved_maze; if (!Array.isArray(pred[0])) { const L=pred.length; const s=Math.sqrt(L); if (!Number.isInteger(s)) throw new Error('Pred not square'); const g=[]; for(let r=0;r<s;r++) g.push(pred.slice(r*s,(r+1)*s)); pred=g; }
const scale = Math.max(4, Math.floor(maxPixels / pred.length));
const headerOut = document.createElement('div'); headerOut.textContent='Predicted grid'; headerOut.style.fontWeight='bold'; headerOut.style.marginBottom='4px'; right.appendChild(headerOut);
right.appendChild(renderGridToCanvas(pred, scale));
if (data.target_maze) { let gt=data.target_maze; if(!Array.isArray(gt[0])){ const L=gt.length; const s=Math.sqrt(L); if(Number.isInteger(s)){ const g=[]; for(let r=0;r<s;r++) g.push(gt.slice(r*s,(r+1)*s)); gt=g; }} const gtScale=Math.max(4, Math.floor(maxPixels/gt.length)); const gtHeader=document.createElement('div'); gtHeader.textContent='Ground truth'; gtHeader.style.fontWeight='bold'; gtHeader.style.marginTop='16px'; extra.appendChild(gtHeader); extra.appendChild(renderGridToCanvas(gt, gtScale)); }
wrap.appendChild(left); wrap.appendChild(right); if (extra.childNodes.length>0) wrap.appendChild(extra); holder.appendChild(wrap);
renderLegend();
document.getElementById('status').textContent = 'Status: loaded saved sample ' + name;
} catch (err) {
document.getElementById('status').textContent = 'Status: error - ' + err.message;
console.error(err);
}
}
document.getElementById('refreshSaved').addEventListener('click', refreshSavedList);
document.getElementById('loadSaved').addEventListener('click', loadSaved);
// For future: support loading local examples (not required now). Hook placeholder.
document.getElementById('loadExample').addEventListener('click', ()=>{
alert('Local example load not implemented in this minimal maze visualizer. Use "Load Server Prediction" for now.');
});
</script>
</body>
</html>