-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
271 lines (247 loc) · 6.74 KB
/
Copy pathindex.html
File metadata and controls
271 lines (247 loc) · 6.74 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
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Python embebido (Pyodide)</title>
<script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
<style>
:root{
color-scheme:dark;
--bg:#0b0d11;--panel:#141820;--text:#e5e7eb;--muted:#9aa4b2;--border:#232839;
--acc:#3b82f6;--err:#f87171
}
html,body{
margin:0;
height:100%;
background:var(--bg);
color:var(--text);
font:14px system-ui,Segoe UI,Roboto,Arial
}
.wrap{padding:10px}
.panel{
border:1px solid var(--border);
background:var(--panel);
border-radius:12px;
max-width:1200px;
margin:0 auto;
padding:10px
}
.row{
display:flex;
gap:8px;
flex-wrap:wrap;
margin-bottom:8px
}
textarea{
flex:1 1 420px;
min-height:140px;
border:1px solid var(--border);
background:#0d1017;
color:var(--text);
border-radius:10px;
padding:8px;
font-family:monospace
}
button{
border:1px solid var(--border);
background:#0d1017;
color:var(--text);
border-radius:10px;
padding:8px 12px;
cursor:pointer;
transition:.2s
}
button:hover{
background:var(--acc);
color:white
}
#out{
border:1px dashed var(--border);
border-radius:10px;
padding:10px;
background:#0d1017;
min-height:120px;
font-family:monospace;
font-size:13px;
overflow:auto;
white-space:pre-wrap; /* conserva saltos de línea para texto normal */
}
small{color:var(--muted)}
</style>
</head>
<body>
<div class="wrap">
<div class="panel">
<!-- Ocultamos el editor y el botón limpiar, sin eliminarlos -->
<div class="row" style="display:none">
<textarea id="code" placeholder="print('Hola desde Pyodide')"></textarea>
<div style="display:flex;flex-direction:column;gap:8px">
<button id="clear">Limpiar</button>
</div>
</div>
<small id="state">Cargando Pyodide…</small>
<div id="out"></div>
</div>
</div>
<script>
const $state = document.getElementById('state'),
$code = document.getElementById('code'),
$out = document.getElementById('out');
// Función de ayuda: siempre usar innerHTML
function setOutput(html) {
$out.innerHTML = html;
}
// Leer parámetros de la URL (?code=..., ?autoeval=...)
const q = (n,d='')=>{
const m = location.search.match(new RegExp('[?&]'+n+'=([^&]+)'));
return m ? decodeURIComponent(m[1].replace(/\+/g,' ')) : d;
};
const auto = /^(1|true|yes)$/i.test(q('autoeval','1'));
const initial = q('code',"print('Hola desde Pyodide')\n");
$code.value = initial;
// Pyodide global
let pyodide = null;
// Paquetes ya cargados para no repetir descargas
const loadedPackages = new Set();
// Reglas: qué paquetes cargar según el código
const PACKAGE_RULES = [
{
// numpy
test: /(import\s+numpy|from\s+numpy)/,
packages: ['numpy']
},
{
// pandas
test: /(import\s+pandas|from\s+pandas)/,
packages: ['pandas'] // numpy viene como dependencia
},
{
// matplotlib
test: /(import\s+matplotlib|from\s+matplotlib|import\s+pyplot|from\s+matplotlib\.pyplot)/,
packages: ['matplotlib']
},
{
// scikit-learn con dependencias
test: /(import\s+sklearn|from\s+sklearn)/,
packages: ['numpy', 'scipy', 'scikit-learn']
},
{
// scipy (por si algún ejemplo futuro lo usa)
test: /(import\s+scipy|from\s+scipy)/,
packages: ['scipy']
}
];
// Dado el texto de código, determina y carga los paquetes necesarios
async function ensurePackagesForCode(codeText) {
if (!pyodide) return;
const needed = new Set();
for (const rule of PACKAGE_RULES) {
if (rule.test.test(codeText)) {
for (const pkg of rule.packages) {
if (!loadedPackages.has(pkg)) {
needed.add(pkg);
}
}
}
}
if (needed.size === 0) {
return; // no hay nada que cargar
}
const toLoad = Array.from(needed);
try {
$state.textContent = 'Cargando paquetes: ' + toLoad.join(', ') + ' …';
await pyodide.loadPackage(toLoad);
toLoad.forEach(p => loadedPackages.add(p));
$state.textContent = 'Paquetes listos: ' + toLoad.join(', ');
} catch (e) {
$state.textContent = 'Error cargando paquetes';
setOutput('⚠️ ' + String(e));
throw e;
}
}
// Inicializar Pyodide
(async () => {
try {
$state.textContent = 'Cargando Pyodide…';
pyodide = await loadPyodide();
$state.textContent = 'Pyodide listo.';
if (auto) run();
} catch (e) {
$state.textContent = 'Error al cargar Pyodide';
setOutput(String(e));
}
})();
// Ejecutar el código que está en el textarea (botón "Ejecutar" o autoeval)
async function run(){
if (!pyodide) {
$state.textContent = 'Pyodide aún no está listo…';
return;
}
const codeText = $code.value;
// 1) Cargar automáticamente los paquetes necesarios
try {
await ensurePackagesForCode(codeText);
} catch (e) {
return; // falló la carga de paquetes
}
// 2) Ejecutar el código
$state.textContent = 'Ejecutando…';
setOutput('');
try {
await pyodide.runPythonAsync(`
import sys, io
_stdout, _stderr = sys.stdout, sys.stderr
buf_out, buf_err = io.StringIO(), io.StringIO()
sys.stdout, sys.stderr = buf_out, buf_err
`);
await pyodide.runPythonAsync(codeText);
const out = pyodide.runPython('buf_out.getvalue()');
const err = pyodide.runPython('buf_err.getvalue()');
setOutput((out || '') + (err ? ("\n[stderr]\n" + err) : ''));
$state.textContent = 'Listo.';
} catch (e) {
$state.textContent = 'Error en ejecución';
setOutput('⚠️ ' + String(e));
} finally {
await pyodide.runPythonAsync(`sys.stdout, sys.stderr = _stdout, _stderr`);
}
}
// Función opcional para que Animate ejecute código directamente
async function runPythonFromFlash(code) {
if (!pyodide) {
$state.textContent = 'Pyodide aún no está listo…';
return;
}
// Cargar paquetes necesarios según el código
try {
await ensurePackagesForCode(code);
} catch (e) {
return;
}
$state.textContent = 'Ejecutando código…';
setOutput('');
try {
await pyodide.runPythonAsync(`
import sys, io
_stdout, _stderr = sys.stdout, sys.stderr
buf_out, buf_err = io.StringIO(), io.StringIO()
sys.stdout, sys.stderr = buf_out, buf_err
`);
await pyodide.runPythonAsync(code);
const out = pyodide.runPython("buf_out.getvalue()");
const err = pyodide.runPython("buf_err.getvalue()");
setOutput((out || "") + (err ? ("\n[stderr]\n" + err) : ""));
$state.textContent = "Listo.";
} catch (e) {
$state.textContent = "Error en ejecución";
setOutput("⚠️ " + String(e));
} finally {
await pyodide.runPythonAsync(`sys.stdout, sys.stderr = _stdout, _stderr`);
}
}
// Asignación de eventos a los botones de la página (el botón está oculto)
document.getElementById('clear').onclick = () => { setOutput(''); };
</script>
</body>
</html>