-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse_python.ts
More file actions
142 lines (121 loc) · 5.03 KB
/
use_python.ts
File metadata and controls
142 lines (121 loc) · 5.03 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
import { Client } from "@deno/sandbox";
const client = new Client();
console.log("Starting Python sandbox from snapshot...");
// numpy, pandas, requests etc. are all pre-installed — no apt-get needed!
await using sandbox = await client.sandboxes.create({
region: "ord",
root: "fun-with-python-snapshot",
port: 8000,
timeout: "30m",
});
console.log("Writing Mandelbrot fractal explorer...");
// Write the Python app into the sandbox filesystem
const appCode = String.raw`#!/usr/bin/env python3
"""
Interactive Mandelbrot fractal explorer - powered by numpy.
Renders in coloured block characters, served over HTTP.
Zoom in/out via URL query params.
"""
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
import numpy as np
WIDTH = 120
HEIGHT = 55
MAX_IT = 128
def mandelbrot(xmin, xmax, ymin, ymax):
x = np.linspace(xmin, xmax, WIDTH)
y = np.linspace(ymin, ymax, HEIGHT)
C = x[np.newaxis, :] + 1j * y[:, np.newaxis]
Z = np.zeros_like(C)
M = np.zeros(C.shape, dtype=int)
for i in range(MAX_IT):
mask = np.abs(Z) <= 2
Z[mask] = Z[mask] ** 2 + C[mask]
M[mask] += 1
return M
def render_html(M, xmin, xmax, ymin, ymax):
rows = []
for row in M:
cells = []
for val in row:
if val == MAX_IT:
cells.append('<span style="color:#000">██</span>')
else:
hue = int((val / MAX_IT) ** 0.5 * 300)
lum = 35 + int((val / MAX_IT) * 30)
cells.append(f'<span style="color:hsl({hue},100%,{lum}%)">██</span>')
rows.append("".join(cells))
fractal = "<br>".join(rows)
w = xmax - xmin
h = ymax - ymin
cx, cy = (xmin + xmax) / 2, (ymin + ymax) / 2
zoom_in = f"/?xmin={cx-w*0.3:.6f}&xmax={cx+w*0.3:.6f}&ymin={cy-h*0.3:.6f}&ymax={cy+h*0.3:.6f}"
zoom_out = f"/?xmin={cx-w*1.6:.6f}&xmax={cx+w*1.6:.6f}&ymin={cy-h*1.6:.6f}&ymax={cy+h*1.6:.6f}"
pan_l = f"/?xmin={xmin-w*0.2:.6f}&xmax={xmax-w*0.2:.6f}&ymin={ymin:.6f}&ymax={ymax:.6f}"
pan_r = f"/?xmin={xmin+w*0.2:.6f}&xmax={xmax+w*0.2:.6f}&ymin={ymin:.6f}&ymax={ymax:.6f}"
pan_u = f"/?xmin={xmin:.6f}&xmax={xmax:.6f}&ymin={ymin-h*0.2:.6f}&ymax={ymax-h*0.2:.6f}"
pan_d = f"/?xmin={xmin:.6f}&xmax={xmax:.6f}&ymin={ymin+h*0.2:.6f}&ymax={ymax+h*0.2:.6f}"
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mandelbrot Explorer</title>
<style>
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
body {{ background: #0a0a0a; color: #ccc; font-family: monospace; }}
h1 {{ text-align: center; padding: 12px; color: #0f0;
text-shadow: 0 0 8px #0f0; font-size: 1.3rem; }}
.fractal {{ text-align: center; font-size: 9px; line-height: 1.05;
letter-spacing: 0; padding: 4px 0; }}
nav {{ display: flex; justify-content: center; gap: 8px;
padding: 10px; flex-wrap: wrap; }}
nav a {{ background: #111; border: 1px solid #0f06; color: #0f0;
padding: 4px 12px; text-decoration: none; border-radius: 4px; }}
nav a:hover {{ background: #0f01; }}
footer {{ text-align: center; padding: 8px; color: #444; font-size: 0.75rem; }}
</style>
</head>
<body>
<h1>🌀 Mandelbrot Explorer — numpy {np.__version__}</h1>
<nav>
<a href="{pan_u}">▲ Pan Up</a>
<a href="{pan_l}">◄ Pan Left</a>
<a href="{zoom_in}">🔍 Zoom In</a>
<a href="{zoom_out}">🔎 Zoom Out</a>
<a href="{pan_r}">Pan Right ►</a>
<a href="{pan_d}">Pan Down ▼</a>
<a href="/">↺ Reset</a>
</nav>
<div class="fractal">{fractal}</div>
<footer>
Viewport ({xmin:.4f}, {ymin:.4f}) → ({xmax:.4f}, {ymax:.4f}) |
numpy pre-installed via Deno Sandbox snapshot — zero setup time
</footer>
</body>
</html>"""
class FractalHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urllib.parse.urlparse(self.path)
p = urllib.parse.parse_qs(parsed.query)
xmin = float(p.get("xmin", [-2.5])[0])
xmax = float(p.get("xmax", [1.0])[0])
ymin = float(p.get("ymin", [-1.25])[0])
ymax = float(p.get("ymax", [1.25])[0])
M = mandelbrot(xmin, xmax, ymin, ymax)
body = render_html(M, xmin, xmax, ymin, ymax).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
pass # silence access logs
print("Mandelbrot Explorer ready on port 8000", flush=True)
HTTPServer(("0.0.0.0", 8000), FractalHandler).serve_forever()
`;
await sandbox.fs.writeTextFile("/tmp/app.py", appCode);
console.log("Launching fractal server...");
const p = await sandbox.sh`python3 /tmp/app.py`.spawn();
console.log("\nMandelbrot Explorer running at", sandbox.url);
console.log("Open the URL in your browser — numpy was pre-installed via snapshot, zero setup needed!\n");
await p.output();