-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
471 lines (411 loc) · 18.5 KB
/
index.html
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Datalab API WASM Plugin Template</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
#loading {
display: none;
margin-top: 20px;
}
.spinner-border {
width: 3rem;
height: 3rem;
}
#console {
font-family: monospace;
background-color: #f8f9fa;
color: #212529;
padding: 15px;
border-radius: 5px;
height: 300px;
overflow-y: auto;
margin-bottom: 20px;
white-space: pre-wrap;
}
.error {
color: #dc3545;
}
.success {
color: #198754;
}
.info {
color: #0d6efd;
}
.warning {
color: #ffc107;
}
#plot-container {
width: 100%;
min-height: 300px;
margin-top: 20px;
border: 1px solid #dee2e6;
border-radius: 5px;
display: flex;
align-items: center;
justify-content: center;
background-color: #f8f9fa;
}
.status-indicator {
display: inline-block;
width: 12px;
height: 12px;
border-radius: 50%;
margin-right: 8px;
}
.status-not-loaded {
background-color: #dc3545;
}
.status-loaded {
background-color: #198754;
}
</style>
</head>
<body>
<div class="container mt-5">
<h1 class="mb-4">Datalab API WASM Plugin Template</h1>
<div class="row mb-3">
<div class="col">
<div class="card">
<div class="card-header bg-primary text-white">
Pyodide Status
</div>
<div class="card-body">
<div class="d-flex justify-content-between">
<div>
<span class="status-indicator status-not-loaded" id="pyodide-status"></span>
<span id="pyodide-status-text">Pyodide: Not Loaded</span>
</div>
<div>
<span class="status-indicator status-not-loaded" id="package-status"></span>
<span id="package-status-text">Package: Not Loaded</span>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<ul class="nav nav-tabs card-header-tabs" id="myTab" role="tablist">
<li class="nav-item" role="presentation">
<button class="nav-link active" id="demo-tab" data-bs-toggle="tab" data-bs-target="#demo" type="button" role="tab" aria-controls="demo" aria-selected="true">Demo</button>
</li>
<li class="nav-item" role="presentation">
<button class="nav-link" id="code-tab" data-bs-toggle="tab" data-bs-target="#code" type="button" role="tab" aria-controls="code" aria-selected="false">Code Editor</button>
</li>
</ul>
</div>
<div class="card-body">
<div class="tab-content" id="myTabContent">
<div class="tab-pane fade show active" id="demo" role="tabpanel" aria-labelledby="demo-tab">
<p class="card-text">This template demonstrates using Pyodide to run the Datalab API directly in the browser.</p>
<div class="d-grid gap-2 d-md-block">
<button class="btn btn-primary" id="loadPyodideBtn">Load Pyodide</button>
<button class="btn btn-success" id="runExampleBtn" disabled>Run Example</button>
<button class="btn btn-danger" id="resetBtn" disabled>Reset</button>
</div>
<div id="loading" class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
<p class="mt-2" id="loading-text">Initializing Pyodide...</p>
</div>
<div id="plot-container" class="mt-4">
<p class="text-muted">Visualization will appear here</p>
</div>
</div>
<div class="tab-pane fade" id="code" role="tabpanel" aria-labelledby="code-tab">
<textarea id="code-editor" class="form-control" rows="15">
# Test importing the datalab-api package
try:
import datalab_api
print(f"Successfully imported datalab_api!")
# Try to get the version
try:
print(f"Package version: {datalab_api.__version__}")
except AttributeError:
print("Version information not available")
# List available functions/methods
print("\nAvailable attributes:")
attributes = [attr for attr in dir(datalab_api) if not attr.startswith('_')]
for attr in attributes:
print(f" - {attr}")
except ImportError as e:
print(f"Failed to import datalab_api: {str(e)}")
# Create sample data for visualization demo
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from js import document
# Create sample data
print("\nCreating sample data for demonstration...")
np.random.seed(42)
n = 50
x = np.linspace(0, 10, n)
y = 2 * x + 1 + np.random.normal(0, 2, n)
# Create DataFrame
data = pd.DataFrame({
'x': x,
'y': y,
'category': np.random.choice(['A', 'B', 'C'], n)
})
print(data.head())
# Create plot
plt.figure(figsize=(10, 6))
for category, group in data.groupby('category'):
plt.scatter(group['x'], group['y'], label=category, alpha=0.7)
plt.xlabel('X Value')
plt.ylabel('Y Value')
plt.title('Sample Data Plot')
plt.legend()
plt.grid(alpha=0.3)
# Save to plot container
from io import BytesIO
import base64
buf = BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
img_str = base64.b64encode(buf.read()).decode('utf-8')
# Display the plot
plot_div = document.getElementById('plot-container')
plot_div.innerHTML = f'<img src="data:image/png;base64,{img_str}" />'
print("\nCreated sample visualization since datalab_api import failed")
</textarea>
<button class="btn btn-success mt-2" id="runCodeBtn" disabled>Run Code</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
<div class="card">
<div class="card-header">Console Output</div>
<div class="card-body">
<div id="console"></div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Global variables
let pyodide = null;
let consoleElement = document.getElementById('console');
let loadingElement = document.getElementById('loading');
let loadingTextElement = document.getElementById('loading-text');
let pyodideStatusIndicator = document.getElementById('pyodide-status');
let pyodideStatusText = document.getElementById('pyodide-status-text');
let packageStatusIndicator = document.getElementById('package-status');
let packageStatusText = document.getElementById('package-status-text');
// Buttons
const loadPyodideBtn = document.getElementById('loadPyodideBtn');
const runExampleBtn = document.getElementById('runExampleBtn');
const resetBtn = document.getElementById('resetBtn');
const runCodeBtn = document.getElementById('runCodeBtn');
// Console logging functions
function logToConsole(message, type = 'normal') {
const logEntry = document.createElement('div');
logEntry.className = type;
logEntry.textContent = message;
consoleElement.appendChild(logEntry);
consoleElement.scrollTop = consoleElement.scrollHeight;
}
function clearConsole() {
consoleElement.innerHTML = '';
}
// Update status indicators
function updatePyodideStatus(loaded) {
pyodideStatusIndicator.className = `status-indicator ${loaded ? 'status-loaded' : 'status-not-loaded'}`;
pyodideStatusText.textContent = `Pyodide: ${loaded ? 'Loaded' : 'Not Loaded'}`;
}
function updatePackageStatus(loaded) {
packageStatusIndicator.className = `status-indicator ${loaded ? 'status-loaded' : 'status-not-loaded'}`;
packageStatusText.textContent = `Package: ${loaded ? 'Loaded' : 'Not Loaded'}`;
}
// Load Pyodide
async function loadPyodide() {
loadPyodideBtn.disabled = true;
loadingElement.style.display = 'block';
clearConsole();
logToConsole('Starting Pyodide initialization...', 'info');
try {
loadingTextElement.textContent = 'Loading Pyodide...';
logToConsole('Loading Pyodide core runtime...', 'info');
// Import Pyodide script
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js';
document.head.appendChild(script);
await new Promise((resolve, reject) => {
script.onload = resolve;
script.onerror = () => reject(new Error('Failed to load Pyodide script'));
});
logToConsole('Pyodide script loaded. Initializing...', 'info');
loadingTextElement.textContent = 'Initializing Python environment...';
// Initialize Pyodide
pyodide = await loadPyodide();
updatePyodideStatus(true);
logToConsole('Pyodide initialized successfully!', 'success');
// Set up stdout/stderr redirects
pyodide.runPython(`
import sys
from io import StringIO
class ConsoleOutput:
def __init__(self, console_type='stdout'):
self.console_type = console_type
self.buffer = StringIO()
def write(self, text):
self.buffer.write(text)
return len(text)
def flush(self):
self.buffer.flush()
sys.stdout = ConsoleOutput('stdout')
sys.stderr = ConsoleOutput('stderr')
`);
// Install micropip
loadingTextElement.textContent = 'Installing micropip...';
logToConsole('Installing micropip package manager...', 'info');
await pyodide.runPythonAsync(`
import pyodide_js
await pyodide_js.loadPackagesFromImports('import micropip')
`);
logToConsole('Micropip installed successfully!', 'success');
// Install base packages
loadingTextElement.textContent = 'Installing core packages...';
logToConsole('Installing numpy, pandas, and matplotlib...', 'info');
await pyodide.runPythonAsync(`
import micropip
await micropip.install(['numpy', 'pandas', 'matplotlib'])
`);
logToConsole('Core packages installed successfully!', 'success');
// Try to install datalab-api package
try {
loadingTextElement.textContent = 'Installing datalab-api package...';
logToConsole('Attempting to install datalab-api package...', 'info');
await pyodide.runPythonAsync(`
import micropip
try:
await micropip.install('datalab-api >= 0.2.8')
print("datalab-api package installed successfully!")
datalab_package_loaded = True
datalab_package_exc = None
except Exception as e:
print(f"Could not install datalab-api package: {str(e)}")
print("Continuing without datalab-api...")
datalab_package_loaded = False
datalab_package_exc = str(e)
`);
// Check if package was loaded
const packageLoaded = pyodide.runPython('datalab_package_loaded');
if (!packageLoaded) {
let packageLoadError = pyodide.runPython('datalab_package_exc');
logToConsole('Failed to install datalab-api package: ' + packageLoadError, 'error');
}
updatePackageStatus(packageLoaded);
if (packageLoaded) {
logToConsole('datalab-api package installed successfully!', 'success');
} else {
logToConsole('datalab-api package installation failed. Continuing with demo mode...', 'warning');
}
} catch (e) {
updatePackageStatus(false);
logToConsole('datalab-api package installation failed. Continuing with demo mode...', 'warning');
console.error('Package installation error:', e);
}
// Enable buttons
runExampleBtn.disabled = false;
resetBtn.disabled = false;
runCodeBtn.disabled = false;
loadingElement.style.display = 'none';
logToConsole('Pyodide environment ready. You can now run Python code!', 'success');
} catch (error) {
loadingElement.style.display = 'none';
loadPyodideBtn.disabled = false;
updatePyodideStatus(false);
updatePackageStatus(false);
logToConsole(`Error initializing Pyodide: ${error.message}`, 'error');
console.error('Pyodide initialization error:', error);
}
}
// Run example code
async function runExample() {
if (!pyodide) {
logToConsole('Pyodide is not initialized. Please load Pyodide first.', 'error');
return;
}
const codeEditor = document.getElementById('code-editor');
await runPythonCode(codeEditor.value);
}
// Run custom code
async function runCustomCode() {
if (!pyodide) {
logToConsole('Pyodide is not initialized. Please load Pyodide first.', 'error');
return;
}
const codeEditor = document.getElementById('code-editor');
await runPythonCode(codeEditor.value);
}
// Reset environment
function resetEnvironment() {
document.getElementById('plot-container').innerHTML = '<p class="text-muted">Visualization will appear here</p>';
clearConsole();
logToConsole('Environment reset. You can run code again.', 'info');
}
// Helper function to run Python code
async function runPythonCode(code) {
if (!pyodide) return;
try {
runExampleBtn.disabled = true;
runCodeBtn.disabled = true;
loadingElement.style.display = 'block';
loadingTextElement.textContent = 'Executing Python code...';
clearConsole();
logToConsole('Running Python code...', 'info');
// Clear previous stdout/stderr content
pyodide.runPython(`
sys.stdout.buffer = StringIO()
sys.stderr.buffer = StringIO()
`);
// Run the code
await pyodide.runPythonAsync(code);
// Get stdout and stderr content
const stdout = pyodide.runPython('sys.stdout.buffer.getvalue()');
const stderr = pyodide.runPython('sys.stderr.buffer.getvalue()');
if (stdout) {
logToConsole(stdout);
}
if (stderr) {
logToConsole(stderr, 'error');
}
// Check if datalab_api was successfully imported
const packageImported = await pyodide.runPythonAsync(`
try:
import datalab_api
True
except ImportError:
False
`);
updatePackageStatus(packageImported);
logToConsole('Code execution completed.', 'success');
} catch (error) {
logToConsole(`Execution error: ${error.message}`, 'error');
console.error('Python execution error:', error);
} finally {
loadingElement.style.display = 'none';
runExampleBtn.disabled = false;
runCodeBtn.disabled = false;
}
}
// Event listeners
loadPyodideBtn.addEventListener('click', loadPyodide);
runExampleBtn.addEventListener('click', runExample);
resetBtn.addEventListener('click', resetEnvironment);
runCodeBtn.addEventListener('click', runCustomCode);
</script>
</body>
</html>