-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpytml.js
More file actions
443 lines (400 loc) · 17.2 KB
/
Copy pathpytml.js
File metadata and controls
443 lines (400 loc) · 17.2 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
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
// At the very top of pytml.js
fetch('https://pytml.vercel.app/api/count')
.then(r => r.json())
.then(data => console.log('Pytml loaded:', data.message, 'times'));
(function(window) {
'use strict';
// ----------------------------------------------
// PYTML – Main Class
// ----------------------------------------------
class PYTML {
constructor() {
this.outputContainer = null;
this.statusElement = null;
this.isReady = false;
this.pendingPromises = [];
this.init();
}
// --------------------------------------------------
// Initialisation
// --------------------------------------------------
async init() {
console.log('[PYTML] Initialising...');
this.createOutputContainer();
this.showStatus('Loading Python engine...');
try {
// Load Pyodide script
await this.loadPyodideScript();
// Initialise Pyodide
const pyodide = await loadPyodide({
indexURL: 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/'
});
window.pyodide = pyodide;
// Setup Python environment
await this.setupPythonEnvironment();
this.isReady = true;
this.hideStatus();
console.log('[PYTML] Ready!');
// Execute all Python scripts (inline and external)
await this.runAllPythonScripts();
} catch (error) {
this.showStatus('Initialisation failed: ' + error.message, true);
this.addError('PYTML initialisation error: ' + error.message);
console.error('[PYTML] Fatal error:', error);
}
}
// --------------------------------------------------
// DOM Setup
// --------------------------------------------------
createOutputContainer() {
let container = document.getElementById('pytml-output');
if (!container) {
container = document.createElement('div');
container.id = 'pytml-output';
container.className = 'pytml-output';
// Apply base styles via a style element to keep them scoped
const style = document.createElement('style');
style.textContent = `
.pytml-output {
background: #0a0e27;
border-radius: 15px;
padding: 20px;
margin: 20px 0;
font-family: 'Courier New', monospace;
font-size: 14px;
box-shadow: 0 10px 40px rgba(0,0,0,0.3);
border: 1px solid rgba(102, 126, 234, 0.3);
max-height: 500px;
overflow-y: auto;
color: #e0e0e0;
}
.pytml-output .pytml-line {
margin: 4px 0;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
}
.pytml-output .pytml-error {
color: #fa709a;
background: rgba(250,112,154,0.15);
padding: 10px;
margin: 10px 0;
border-radius: 8px;
}
.pytml-output .pytml-success {
color: #43e97b;
}
.pytml-output .pytml-info {
color: #667eea;
}
.pytml-output .pytml-input-container {
background: rgba(102,126,234,0.1);
border-radius: 10px;
padding: 15px;
margin: 15px 0;
border: 1px solid rgba(102,126,234,0.3);
}
.pytml-output .pytml-input-prompt {
color: #ffd93d;
font-weight: 500;
margin-bottom: 10px;
font-family: system-ui, sans-serif;
}
.pytml-output .pytml-input-field {
width: 100%;
padding: 10px 12px;
background: rgba(255,255,255,0.1);
border: 1px solid rgba(102,126,234,0.5);
border-radius: 8px;
color: white;
font-size: 14px;
font-family: monospace;
outline: none;
box-sizing: border-box;
margin-bottom: 10px;
}
.pytml-output .pytml-input-submit {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
padding: 10px 20px;
border-radius: 8px;
color: white;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s;
font-size: 14px;
touch-action: manipulation;
}
.pytml-output .pytml-input-submit:hover {
transform: scale(1.02);
}
.pytml-status {
position: fixed;
bottom: 20px;
right: 20px;
background: #667eea;
color: white;
padding: 8px 16px;
border-radius: 20px;
font-family: monospace;
font-size: 12px;
z-index: 9999;
max-width: 80vw;
word-break: break-word;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
transition: opacity 0.3s;
}
.pytml-status.error {
background: #fa709a;
}
`;
document.head.appendChild(style);
const hideStyle = document.createElement('style');
hideStyle.textContent = 'py { display: none; }';
document.head.appendChild(hideStyle);
// Insert container before the first Python script, or at the top of body
const firstScript = document.querySelector('py, script[type="text/python"]');
if (firstScript) {
firstScript.insertAdjacentElement('beforebegin', container);
} else {
document.body.insertAdjacentElement('afterbegin', container);
}
}
this.outputContainer = container;
}
// --------------------------------------------------
// Pyodide Loading
// --------------------------------------------------
loadPyodideScript() {
return new Promise((resolve, reject) => {
if (typeof loadPyodide !== 'undefined') {
resolve();
return;
}
const script = document.createElement('script');
script.src = 'https://cdn.jsdelivr.net/pyodide/v0.26.4/full/pyodide.js';
script.onload = () => resolve();
script.onerror = () => reject(new Error('Failed to load Pyodide script from CDN.'));
document.head.appendChild(script);
});
}
// --------------------------------------------------
// Python Environment Setup
// --------------------------------------------------
async setupPythonEnvironment() {
const pyodide = window.pyodide;
// Override stdout and stderr
await pyodide.runPythonAsync(`
import sys
import js
class OutputRedirect:
def __init__(self, is_error=False):
self.is_error = is_error
def write(self, text):
if text:
js.pyodideInstance.addOutput(str(text), self.is_error)
def flush(self):
pass
sys.stdout = OutputRedirect(False)
sys.stderr = OutputRedirect(True)
# Override input – async function that calls JS
async def input(prompt=""):
# We do NOT print(prompt) here – the JS will show it in the DOM
result = await js.pyodideInstance.getUserInput(str(prompt))
return result
`);
// Also expose the instance to Python's js module
window.pyodideInstance = this;
// Store a reference to the Python input function for later use in transformation
// Not needed because we'll transform the user code.
}
// --------------------------------------------------
// Running Python Scripts (inline & external)
// --------------------------------------------------
async runAllPythonScripts() {
// Find all <py> tags (inline)
const pyTags = document.querySelectorAll('py');
for (const tag of pyTags) {
const code = tag.textContent;
await this.executePythonCode(code, tag);
tag.remove(); // optional: remove after execution
}
// Find external scripts (<script type="text/python" src="...">)
const scriptTags = document.querySelectorAll('script[type="text/python"][src]');
for (const tag of scriptTags) {
const src = tag.getAttribute('src');
await this.executeExternalPython(src, tag);
tag.remove();
}
}
async executePythonCode(code, sourceElement = null) {
if (!this.isReady) {
this.addError('Python engine not ready yet.');
return;
}
try {
// Transform the code safely using AST
const transformed = await this.transformPythonCode(code);
// Execute with async wrapper
await window.pyodide.runPythonAsync(transformed);
} catch (error) {
this.addError('Execution error: ' + error.message);
console.error('[PYTML] Execution error:', error);
}
}
async executeExternalPython(src, tag) {
this.showStatus('Loading: ' + src);
try {
const response = await fetch(src);
if (!response.ok) {
throw new Error(`HTTP ${response.status} – ${src}`);
}
const code = await response.text();
this.showStatus('Running: ' + src);
await this.executePythonCode(code, tag);
this.hideStatus();
} catch (error) {
this.addError('Failed to load external script: ' + error.message);
this.showStatus('Error loading ' + src, true);
console.error('[PYTML] External script error:', error);
}
}
// --------------------------------------------------
// AST‑Based Code Transformation (safe input replacement)
// --------------------------------------------------
async transformPythonCode(code) {
// We use Python's ast module to rewrite `input()` calls into `await input()`
// This ensures we only replace actual function calls, not strings, comments, or variable names.
const pyodide = window.pyodide;
const transformScript = `
import ast
class InputTransformer(ast.NodeTransformer):
def visit_Call(self, node):
# Check if it's a call to 'input'
if isinstance(node.func, ast.Name) and node.func.id == 'input':
# Wrap the call in an Await node
new_node = ast.Await(value=node)
return ast.copy_location(new_node, node)
# Recursively transform child nodes
self.generic_visit(node)
return node
def transform(code):
tree = ast.parse(code)
transformer = InputTransformer()
new_tree = transformer.visit(tree)
ast.fix_missing_locations(new_tree)
return ast.unparse(new_tree)
`;
await pyodide.runPythonAsync(transformScript);
// Call the transform function
const result = await pyodide.runPythonAsync(`
transform('''${code.replace(/'/g, "\\'")}''')
`);
return result;
}
// --------------------------------------------------
// Interactive Input via DOM
// --------------------------------------------------
getUserInput(prompt) {
return new Promise((resolve) => {
const container = document.createElement('div');
container.className = 'pytml-input-container';
const promptDiv = document.createElement('div');
promptDiv.className = 'pytml-input-prompt';
promptDiv.textContent = prompt || 'Enter value:';
container.appendChild(promptDiv);
const inputField = document.createElement('input');
inputField.type = 'text';
inputField.className = 'pytml-input-field';
inputField.placeholder = 'Type your answer…';
container.appendChild(inputField);
const submitBtn = document.createElement('button');
submitBtn.textContent = '✓ Submit';
submitBtn.className = 'pytml-input-submit';
container.appendChild(submitBtn);
// Append to output container
this.outputContainer.appendChild(container);
const submit = () => {
const value = inputField.value;
container.remove();
resolve(value);
};
submitBtn.addEventListener('click', submit);
inputField.addEventListener('keypress', (e) => {
if (e.key === 'Enter') submit();
});
inputField.focus();
// Scroll into view
container.scrollIntoView({ behavior: 'smooth', block: 'center' });
});
}
// --------------------------------------------------
// Output Methods
// --------------------------------------------------
addOutput(text, isError = false) {
if (!this.outputContainer) return;
const line = document.createElement('div');
line.className = 'pytml-line';
if (isError) {
line.className += ' pytml-error';
} else {
// Basic heuristic for coloring (optional)
if (text.includes('Error') || text.includes('Traceback')) {
line.className += ' pytml-error';
} else if (text.includes('successfully') || text.includes('OK')) {
line.className += ' pytml-success';
} else if (text.includes('+----') || text.includes('----+')) {
line.className += ' pytml-info';
}
}
line.textContent = text;
this.outputContainer.appendChild(line);
line.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
addError(text) {
const line = document.createElement('div');
line.className = 'pytml-line pytml-error';
line.textContent = '❌ ' + text;
this.outputContainer.appendChild(line);
}
// --------------------------------------------------
// Status Badge
// --------------------------------------------------
showStatus(message, isError = false) {
if (!this.statusElement) {
const el = document.createElement('div');
el.className = 'pytml-status';
document.body.appendChild(el);
this.statusElement = el;
}
this.statusElement.textContent = message;
this.statusElement.className = 'pytml-status' + (isError ? ' error' : '');
this.statusElement.style.display = 'block';
}
hideStatus() {
if (this.statusElement) {
this.statusElement.style.display = 'none';
}
}
}
// --------------------------------------------------
// Global Bridge for Python
// --------------------------------------------------
// We expose the instance as a global for Python's js module.
// The instance will be set after construction.
let instance;
function init() {
if (!instance) {
instance = new PYTML();
// Make it available to Python (already done in setupPythonEnvironment)
// but also expose as a global for debugging
window.pytml = instance;
}
}
// Auto‑initialise when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})(window);