sh1k4ku commited on
Commit
646794f
·
verified ·
1 Parent(s): b50fb29

Upload index.html with huggingface_hub

Browse files
Files changed (1) hide show
  1. index.html +458 -18
index.html CHANGED
@@ -1,19 +1,459 @@
1
- <!doctype html>
2
- <html>
3
- <head>
4
- <meta charset="utf-8" />
5
- <meta name="viewport" content="width=device-width" />
6
- <title>My static Space</title>
7
- <link rel="stylesheet" href="style.css" />
8
- </head>
9
- <body>
10
- <div class="card">
11
- <h1>Welcome to your static Space!</h1>
12
- <p>You can modify this app directly by editing <i>index.html</i> in the Files and versions tab.</p>
13
- <p>
14
- Also don't forget to check the
15
- <a href="https://huggingface.co/docs/hub/spaces" target="_blank">Spaces documentation</a>.
16
- </p>
17
- </div>
18
- </body>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  </html>
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Python Black-Box Testing Playground</title>
7
+
8
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
9
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css">
10
+
11
+ <style>
12
+ :root {
13
+ --bg: #1e1e2e; --panel: #252535; --border: #353550;
14
+ --accent: #89b4fa; --accent-hover: #74a0f0;
15
+ --text: #cdd6f4; --muted: #7f849c;
16
+ --err: #f38ba8; --ok: #a6e3a1;
17
+ }
18
+ * { box-sizing: border-box; }
19
+ html, body {
20
+ margin: 0; height: 100%;
21
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
22
+ background: var(--bg); color: var(--text);
23
+ }
24
+ body { display: flex; flex-direction: column; height: 100vh; }
25
+
26
+ header {
27
+ display: flex; align-items: center; gap: 12px;
28
+ padding: 10px 16px; background: var(--panel);
29
+ border-bottom: 1px solid var(--border);
30
+ }
31
+ header h1 { font-size: 15px; margin: 0; font-weight: 600; }
32
+ header .status { font-size: 12px; color: var(--muted); margin-left: auto; }
33
+ header .status.ready { color: var(--ok); }
34
+ header .status.error { color: var(--err); }
35
+
36
+ button {
37
+ background: var(--accent); color: #11111b; border: none;
38
+ padding: 7px 16px; border-radius: 6px; font-size: 13px;
39
+ font-weight: 600; cursor: pointer; transition: background .15s;
40
+ }
41
+ button:hover:not(:disabled) { background: var(--accent-hover); }
42
+ button:disabled { opacity: .5; cursor: not-allowed; }
43
+ button.ghost { background: transparent; color: var(--muted); }
44
+ button.ghost:hover:not(:disabled) { color: var(--text); background: var(--border); }
45
+ .kbd { font-size: 11px; color: var(--muted); }
46
+
47
+ /* Mode toggle (segmented control) */
48
+ .seg { display: flex; background: var(--bg); border: 1px solid var(--border); border-radius: 7px; padding: 2px; }
49
+ .seg-btn {
50
+ background: transparent; color: var(--muted); font-weight: 600;
51
+ padding: 5px 12px; border-radius: 5px; font-size: 12px;
52
+ }
53
+ .seg-btn:hover:not(.active) { color: var(--text); }
54
+ .seg-btn.active { background: var(--accent); color: #11111b; }
55
+
56
+ main { flex: 1; display: flex; min-height: 0; }
57
+ .pane { flex: 1; display: flex; flex-direction: column; min-width: 0; }
58
+ .pane-label {
59
+ padding: 6px 12px; font-size: 11px; text-transform: uppercase;
60
+ letter-spacing: .05em; color: var(--muted); background: var(--panel);
61
+ border-bottom: 1px solid var(--border);
62
+ display: flex; align-items: center; gap: 8px;
63
+ }
64
+ .pane-label .badge {
65
+ font-size: 10px; background: var(--border); color: var(--muted);
66
+ padding: 1px 7px; border-radius: 10px; text-transform: none; letter-spacing: 0;
67
+ }
68
+ #problem {
69
+ background: var(--bg); color: var(--text);
70
+ border: 1px solid var(--border); border-radius: 8px;
71
+ padding: 8px 14px; font-size: 16px; font-weight: 700; cursor: pointer;
72
+ text-transform: none; letter-spacing: 0; min-width: 90px;
73
+ }
74
+ #problem:hover { border-color: var(--accent); }
75
+ #problem:focus { outline: none; border-color: var(--accent); }
76
+
77
+ .editor-wrap { flex: 1; min-height: 0; overflow: hidden; }
78
+ .CodeMirror { height: 100% !important; font-size: 14px; font-family: "SF Mono", Menlo, Consolas, monospace; }
79
+
80
+ .divider { width: 1px; background: var(--border); cursor: col-resize; }
81
+ .divider:hover { background: var(--accent); }
82
+
83
+ #summary {
84
+ padding: 8px 16px; font-size: 13px; font-weight: 600;
85
+ border-bottom: 1px solid var(--border); background: var(--panel);
86
+ display: none;
87
+ }
88
+ #summary.pass { color: var(--ok); }
89
+ #summary.fail { color: var(--err); }
90
+
91
+ #output {
92
+ flex: 1; margin: 0; padding: 12px 16px; overflow: auto;
93
+ font-family: "SF Mono", Menlo, Consolas, monospace; font-size: 13px;
94
+ line-height: 1.55; white-space: pre-wrap; word-break: break-word;
95
+ background: #181825;
96
+ }
97
+ #output .err { color: var(--err); }
98
+ #output .ok { color: var(--ok); }
99
+ #output .meta { color: var(--muted); }
100
+ #output img { max-width: 100%; background: #fff; border-radius: 4px; margin: 8px 0; }
101
+ </style>
102
+ </head>
103
+ <body>
104
+
105
+ <header>
106
+ <h1>Python Playground</h1>
107
+ <div class="seg">
108
+ <button id="mode-run" class="seg-btn active">Run</button>
109
+ <button id="mode-test" class="seg-btn">Black-Box Test</button>
110
+ </div>
111
+ <button id="run" disabled>▶ Run <span class="kbd">⌘/Ctrl+Enter</span></button>
112
+ <button id="reset" class="ghost">Reset Template</button>
113
+ <span id="status" class="status">Loading runtime…</span>
114
+ </header>
115
+
116
+ <main>
117
+ <div class="pane" id="left">
118
+ <div class="pane-label">
119
+ <select id="problem" title="Select a problem">
120
+ <option value="Q1">Q1</option>
121
+ <option value="Q2">Q2</option>
122
+ </select>
123
+ <span id="leftLabel">Your Code</span>
124
+ <span class="badge">editable</span>
125
+ </div>
126
+ <div class="editor-wrap"><textarea id="code"></textarea></div>
127
+ </div>
128
+ <div class="divider" id="divider"></div>
129
+ <div class="pane" id="right">
130
+ <div class="pane-label"><span id="rightLabel">Output</span> <span class="badge" id="modinfo">blackbox: not loaded</span></div>
131
+ <div id="summary"></div>
132
+ <div id="output"><span class="meta">(Click "Run" once the runtime is ready)</span></div>
133
+ </div>
134
+ </main>
135
+
136
+ <script src="https://cdn.jsdelivr.net/pyodide/v0.26.2/full/pyodide.js"></script>
137
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
138
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script>
139
+
140
+ <script>
141
+ // ===== Plain "Run" mode starter =====
142
+ const RUN_TEMPLATE = `# Plain Python -- runs in your browser. Edit and press Run.
143
+ import sys
144
+ print("Python", sys.version.split()[0])
145
+
146
+ def fib(n):
147
+ a, b = 0, 1
148
+ for _ in range(n):
149
+ a, b = b, a + b
150
+ return a
151
+
152
+ print([fib(i) for i in range(10)])
153
+
154
+ # Want plots? Install a package (downloads on first use):
155
+ # import micropip; await micropip.install("matplotlib")
156
+ `;
157
+
158
+ // ===== Problems: each has a hidden .dat (its blackbox) + a test starter =====
159
+ const PROBLEMS = {
160
+ Q1: {
161
+ data: "q1.dat",
162
+ testTemplate: `# Q1 -- functions: grade(score), clamp(x, lo, hi), fizzbuzz(n)
163
+ # The module "blackbox" is hidden. Write tests to verify its behaviour.
164
+ import blackbox
165
+
166
+ # expect(actual, expected, label): records one case; keeps going on failure
167
+ expect(blackbox.grade(85), "HD", "85 should be HD")
168
+ expect(blackbox.grade(84), "DN", "boundary 84")
169
+ expect(blackbox.grade(50), "PS", "pass lower bound 50")
170
+ expect(blackbox.grade(49), "FL", "49 should fail")
171
+
172
+ expect(blackbox.fizzbuzz(15), "FizzBuzz", "15")
173
+ expect(blackbox.fizzbuzz(7), "7", "7")
174
+
175
+ expect(blackbox.clamp(12, 0, 10), 10, "above upper bound")
176
+ expect(blackbox.clamp(-3, 0, 10), 0, "below lower bound")
177
+
178
+ # See which functions blackbox exposes:
179
+ print("callable:", [n for n in dir(blackbox) if not n.startswith('_')])
180
+ `,
181
+ },
182
+ Q2: {
183
+ data: "q2.dat",
184
+ testTemplate: `# Q2 -- functions: is_palindrome(s), count_vowels(s), reverse_words(s)
185
+ # The module "blackbox" is hidden. Write tests to verify its behaviour.
186
+ import blackbox
187
+
188
+ expect(blackbox.is_palindrome("Race car"), True, "ignores case & spaces")
189
+ expect(blackbox.is_palindrome("hello"), False, "not a palindrome")
190
+
191
+ expect(blackbox.count_vowels("Education"), 5, "count vowels")
192
+ expect(blackbox.count_vowels("xyz"), 0, "no vowels")
193
+
194
+ expect(blackbox.reverse_words("the quick fox"), "fox quick the", "reverse word order")
195
+
196
+ print("callable:", [n for n in dir(blackbox) if not n.startswith('_')])
197
+ `,
198
+ },
199
+ };
200
+
201
+ // ===== State + working copies (so switching never loses your edits) =====
202
+ let mode = "run"; // "run" | "test"
203
+ let prob = "Q1"; // current problem key
204
+ const work = {
205
+ run: RUN_TEMPLATE,
206
+ test: { Q1: PROBLEMS.Q1.testTemplate, Q2: PROBLEMS.Q2.testTemplate },
207
+ };
208
+ const slotTemplate = () => (mode === "run" ? RUN_TEMPLATE : PROBLEMS[prob].testTemplate);
209
+ const saveEditor = () => { if (mode === "run") work.run = editor.getValue(); else work.test[prob] = editor.getValue(); };
210
+ const loadEditor = () => editor.setValue(mode === "run" ? work.run : work.test[prob]);
211
+
212
+ const output = document.getElementById("output");
213
+ const summary = document.getElementById("summary");
214
+ const statusEl = document.getElementById("status");
215
+ const modinfo = document.getElementById("modinfo");
216
+ const runBtn = document.getElementById("run");
217
+ const resetBtn = document.getElementById("reset");
218
+ const leftLabel = document.getElementById("leftLabel");
219
+ const rightLabel= document.getElementById("rightLabel");
220
+ const modeRunBtn = document.getElementById("mode-run");
221
+ const modeTestBtn = document.getElementById("mode-test");
222
+ const problemSel = document.getElementById("problem");
223
+
224
+ function append(text, cls) {
225
+ const span = document.createElement("span");
226
+ if (cls) span.className = cls;
227
+ span.textContent = text;
228
+ output.appendChild(span);
229
+ output.scrollTop = output.scrollHeight;
230
+ }
231
+
232
+ // ===== Editor =====
233
+ const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
234
+ mode: "python", theme: "material-darker",
235
+ lineNumbers: true, indentUnit: 4, tabSize: 4, indentWithTabs: false,
236
+ extraKeys: {
237
+ "Cmd-Enter": run, "Ctrl-Enter": run,
238
+ Tab: (cm) => cm.replaceSelection(" "),
239
+ },
240
+ });
241
+ loadEditor();
242
+ resetBtn.onclick = () => {
243
+ if (mode === "run") work.run = RUN_TEMPLATE; else work.test[prob] = PROBLEMS[prob].testTemplate;
244
+ loadEditor();
245
+ };
246
+
247
+ // ===== Mode switching (Run <-> Black-Box Test) =====
248
+ function applyMode() {
249
+ modeRunBtn.classList.toggle("active", mode === "run");
250
+ modeTestBtn.classList.toggle("active", mode === "test");
251
+ leftLabel.textContent = mode === "test" ? "Your Test Code" : "Your Code";
252
+ rightLabel.textContent = mode === "test" ? "Test Results" : "Output";
253
+ modinfo.style.display = mode === "test" ? "" : "none";
254
+ summary.style.display = "none";
255
+ runBtn.innerHTML = (mode === "test" ? "▶ Run Tests " : "▶ Run ")
256
+ + '<span class="kbd">⌘/Ctrl+Enter</span>';
257
+ }
258
+ function switchMode(next) {
259
+ if (next === mode) return;
260
+ saveEditor();
261
+ mode = next;
262
+ applyMode();
263
+ loadEditor();
264
+ }
265
+ modeRunBtn.onclick = () => switchMode("run");
266
+ modeTestBtn.onclick = () => switchMode("test");
267
+
268
+ // ===== Problem switching (Q1 / Q2) =====
269
+ problemSel.onchange = async () => {
270
+ saveEditor();
271
+ prob = problemSel.value;
272
+ loadEditor(); // show this problem's test code
273
+ await loadProblem(prob); // swap the hidden blackbox module
274
+ };
275
+
276
+ applyMode();
277
+
278
+ // ===== Test-framework prelude that runs inside Python =====
279
+ // Reset on every run; expect() writes PASS to stdout, FAIL to stderr (rendered red).
280
+ const PRELUDE = `
281
+ import sys as _sys
282
+ __bb_pass = 0
283
+ __bb_fail = 0
284
+ def expect(got, want, label=""):
285
+ global __bb_pass, __bb_fail
286
+ ok = got == want
287
+ if ok:
288
+ __bb_pass += 1
289
+ print(f"[PASS] {label}".rstrip())
290
+ else:
291
+ __bb_fail += 1
292
+ print(f"[FAIL] {label} got={got!r} want={want!r}".rstrip(), file=_sys.stderr)
293
+ return ok
294
+ `;
295
+
296
+ // ===== Load Pyodide + the hidden implementation =====
297
+ let pyodide;
298
+
299
+ // Fetch problem <key>'s hidden source, (re)import it as module "blackbox",
300
+ // then erase its runtime traces so students can't read the implementation.
301
+ async function loadProblem(key) {
302
+ if (!pyodide) return; // not ready yet; startup will load the current prob
303
+ const b64 = (await (await fetch(PROBLEMS[key].data)).text()).trim();
304
+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
305
+ const src = new TextDecoder("utf-8").decode(bytes);
306
+ pyodide.FS.writeFile("blackbox.py", src);
307
+ pyodide.runPython(`
308
+ import os, sys, linecache
309
+ if '.' not in sys.path:
310
+ sys.path.insert(0, '.')
311
+ sys.modules.pop('blackbox', None) # drop any previously loaded problem
312
+ import blackbox
313
+ for _a in ('__file__', '__loader__', '__spec__', '__cached__'):
314
+ if hasattr(blackbox, _a):
315
+ try: delattr(blackbox, _a)
316
+ except Exception: pass
317
+ try: os.remove('blackbox.py')
318
+ except Exception: pass
319
+ linecache.cache.clear()
320
+ `);
321
+ const funcs = pyodide.runPython(
322
+ "[n for n in dir(__import__('blackbox')) if not n.startswith('_')]"
323
+ ).toJs();
324
+ modinfo.textContent = key + ": " + funcs.length + " function" + (funcs.length === 1 ? "" : "s");
325
+ }
326
+
327
+ (async () => {
328
+ try {
329
+ pyodide = await loadPyodide({
330
+ // In test mode stdout carries PASS lines (green); in run mode it's normal output.
331
+ stdout: (s) => append(s + "\n", mode === "test" ? "ok" : null),
332
+ stderr: (s) => append(s + "\n", "err"),
333
+ });
334
+
335
+ // Install the source-hiding guard ONCE (applies to any module named "blackbox").
336
+ pyodide.runPython(`
337
+ import inspect
338
+ _orig_getsource = inspect.getsource
339
+ def _guard_getsource(obj, *a, **k):
340
+ if getattr(obj, '__module__', None) == 'blackbox':
341
+ raise OSError("source code is not available for blackbox")
342
+ return _orig_getsource(obj, *a, **k)
343
+ inspect.getsource = _guard_getsource
344
+ inspect.getsourcelines = lambda obj, *a, **k: (_ for _ in ()).throw(OSError("not available"))
345
+ `);
346
+
347
+ await loadProblem(prob); // load the currently selected problem
348
+
349
+ statusEl.textContent = "✓ Ready";
350
+ statusEl.className = "status ready";
351
+ runBtn.disabled = false;
352
+ } catch (e) {
353
+ statusEl.textContent = "Failed to load";
354
+ statusEl.className = "status error";
355
+ append("Failed to load runtime: " + e + "\n", "err");
356
+ }
357
+ })();
358
+
359
+ // ===== Run the student's tests =====
360
+ async function run() {
361
+ if (!pyodide || runBtn.disabled) return;
362
+ runBtn.disabled = true;
363
+ output.innerHTML = "";
364
+ summary.style.display = "none";
365
+
366
+ try {
367
+ if (mode === "test") {
368
+ // Reset the test framework (same global namespace so student code sees expect)
369
+ await pyodide.runPythonAsync(PRELUDE);
370
+ await pyodide.runPythonAsync(editor.getValue()); // top-level await supported
371
+ renderMatplotlib();
372
+ showSummary();
373
+ } else {
374
+ // Plain run: just execute and show output, no test harness/summary
375
+ const result = await pyodide.runPythonAsync(editor.getValue());
376
+ renderMatplotlib();
377
+ if (result !== undefined && result !== null) append(String(result) + "\n", "meta");
378
+ }
379
+ } catch (e) {
380
+ // assert / syntax / runtime error: show cleaned traceback, then current stats
381
+ append("\nExecution stopped:\n" + cleanError(e.message || String(e)) + "\n", "err");
382
+ if (mode === "test") showSummary(true);
383
+ } finally {
384
+ runBtn.disabled = false;
385
+ }
386
+ }
387
+ runBtn.onclick = run;
388
+
389
+ function showSummary(aborted) {
390
+ let p = 0, f = 0;
391
+ try {
392
+ p = pyodide.runPython("__bb_pass");
393
+ f = pyodide.runPython("__bb_fail");
394
+ } catch (_) {}
395
+ if (p === 0 && f === 0 && !aborted) {
396
+ summary.style.display = "none";
397
+ return;
398
+ }
399
+ summary.style.display = "block";
400
+ if (f === 0 && !aborted) {
401
+ summary.className = "pass";
402
+ summary.textContent = `✓ All passed: ${p}/${p}`;
403
+ } else {
404
+ summary.className = "fail";
405
+ const total = p + f;
406
+ summary.textContent =
407
+ `✗ Passed ${p}/${total}, failed ${f}` + (aborted ? " (execution interrupted)" : "");
408
+ }
409
+ }
410
+
411
+ // Strip internal file paths from tracebacks to avoid leakage/noise
412
+ function cleanError(msg) {
413
+ return msg
414
+ .split("\n")
415
+ .filter((l) => !l.includes("/lib/python") && !l.includes("pyodide"))
416
+ .join("\n")
417
+ .trim();
418
+ }
419
+
420
+ function renderMatplotlib() {
421
+ try {
422
+ const has = pyodide.runPython(`"matplotlib" in __import__("sys").modules`);
423
+ if (!has) return;
424
+ const b64 = pyodide.runPython(`
425
+ import io, base64
426
+ import matplotlib.pyplot as _plt
427
+ _imgs = []
428
+ for _n in _plt.get_fignums():
429
+ _buf = io.BytesIO()
430
+ _plt.figure(_n).savefig(_buf, format="png", dpi=110, bbox_inches="tight")
431
+ _imgs.append(base64.b64encode(_buf.getvalue()).decode())
432
+ _plt.close("all")
433
+ "\\n".join(_imgs)
434
+ `);
435
+ for (const data of (b64 || "").split("\n")) {
436
+ if (!data) continue;
437
+ const img = document.createElement("img");
438
+ img.src = "data:image/png;base64," + data;
439
+ output.appendChild(img);
440
+ }
441
+ } catch (_) {}
442
+ }
443
+
444
+ // ===== Draggable divider =====
445
+ const divider = document.getElementById("divider");
446
+ const left = document.getElementById("left");
447
+ const mainEl = document.querySelector("main");
448
+ let dragging = false;
449
+ divider.addEventListener("mousedown", () => (dragging = true));
450
+ window.addEventListener("mouseup", () => (dragging = false));
451
+ window.addEventListener("mousemove", (e) => {
452
+ if (!dragging) return;
453
+ const rect = mainEl.getBoundingClientRect();
454
+ const pct = ((e.clientX - rect.left) / rect.width) * 100;
455
+ if (pct > 15 && pct < 85) left.style.flex = "0 0 " + pct + "%";
456
+ });
457
+ </script>
458
+ </body>
459
  </html>