Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
398 lines (360 loc) · 11 KB
/
Copy pathserver.py
File metadata and controls
398 lines (360 loc) · 11 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
# server.py - Python network implementation using network.py
from __future__ import annotations
from flask import Flask, jsonify, request, Response
import json
import os
import time
import math
import network as net_python
from param_io import load_params
app = Flask(__name__)
# ---------- Load parameters ----------
PARAMS = None
# Load network parameters
try:
PARAMS = load_params() # Load from params.pkl
print("✓ Loaded network parameters")
except FileNotFoundError:
print("✗ Network parameters not found (params.pkl)")
# ---------- Network prediction function ----------
def predict(image_data):
"""Use the Python network implementation"""
if PARAMS is None:
raise ValueError("Network parameters not loaded")
# Use the forward pass from network.py
outputs = net_python.forward_pass(PARAMS, image_data)
probs = net_python.softmax(outputs)
return probs
# ---------- HTML Interface (same as server_jax.py) ----------
INDEX_HTML = r"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>28×28 Digit Test UI</title>
<style>
:root {
--bg: #ffffff;
--panel: #ffffff;
--ink: #111111;
--muted: #666666;
--border: #e0e0e0;
--shadow: 0 2px 4px rgba(0,0,0,0.1);
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background: var(--bg);
font-family: system-ui, sans-serif;
color: var(--ink);
display: grid;
place-items: center;
}
.wrap {
display: grid;
grid-template-columns: auto 300px;
gap: 24px;
align-items: center;
width: min(900px, 96vw);
}
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
box-shadow: var(--shadow);
}
/* Left: canvas + toolbar */
.draw-card {
padding: 16px;
display: grid;
gap: 12px;
justify-items: center;
}
.toolbar {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.btn {
appearance: none;
border: 1px solid var(--border);
background: #fff;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
font-weight: 500;
}
/* The 28x28 canvas (logical) scaled up cleanly */
#canvas {
width: 560px; /* display size */
height: 560px;
image-rendering: pixelated;
border-radius: 6px;
border: 1px solid var(--border);
display: block;
background: #fff;
}
/* Right: probabilities panel */
.prob-card {
padding: 16px;
display: grid;
gap: 12px;
}
.prob-header {
display: flex; align-items: baseline; justify-content: space-between;
}
.prob-header h2 {
font-size: 16px; margin: 0;
}
.prob-list {
display: grid; gap: 8px;
}
.prob-row {
display: grid;
grid-template-columns: 40px 1fr auto;
gap: 8px; align-items: center;
padding: 6px 8px;
border: 1px solid var(--border);
border-radius: 6px;
}
.dot {
width: 32px; height: 32px; border-radius: 50%;
border: 1px solid var(--border);
background: #fff;
}
.digit {
color: var(--ink); font-weight: 600; font-size: 14px;
}
.prob {
color: var(--muted);
font-variant-numeric: tabular-nums;
font-weight: 500;
}
@media (max-width: 800px) {
.wrap { grid-template-columns: 1fr; gap: 20px; }
#canvas { width: 90vw; height: 90vw; max-width: 400px; max-height: 400px; }
}
</style>
</head>
<body>
<div class="wrap">
<div class="card draw-card">
<canvas id="canvas" width="28" height="28"></canvas>
<div class="toolbar">
<button id="clear" class="btn">Clear</button>
</div>
</div>
<div class="card prob-card">
<div class="prob-header">
<h2>Probabilities (0–9)</h2>
<span class="hint">darker = higher</span>
</div>
<div id="probs" class="prob-list"></div>
</div>
</div>
<script>
(function() {
// ----- State -----
const W = 28, H = 28;
const pixels = new Uint8ClampedArray(W * H); // 0..255, 0 white, 255 black (ink)
let isDown = false;
let lastX = -1, lastY = -1;
let inFlight = false; // prevent fetch pileup
// ----- DOM -----
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d', { willReadFrequently: true });
const clearBtn = document.getElementById('clear');
const probsEl = document.getElementById('probs');
// Build the probabilities panel rows
const rows = [];
for (let d = 0; d < 10; d++) {
const row = document.createElement('div');
row.className = 'prob-row';
const dot = document.createElement('div');
dot.className = 'dot';
const digit = document.createElement('div');
digit.className = 'digit';
digit.textContent = String(d);
const prob = document.createElement('div');
prob.className = 'prob';
prob.textContent = '0.0%';
row.appendChild(dot); row.appendChild(digit); row.appendChild(prob);
probsEl.appendChild(row);
rows.push({dot, digit, prob});
}
// ----- Helpers -----
function clamp(v, lo, hi) { return v < lo ? lo : (v > hi ? hi : v); }
function posToCell(evt) {
const rect = canvas.getBoundingClientRect();
const x = ((evt.clientX - rect.left) / rect.width) * W;
const y = ((evt.clientY - rect.top) / rect.height) * H;
return { x, y, i: clamp(Math.floor(x), 0, W-1), j: clamp(Math.floor(y), 0, H-1) };
}
function drawDot(i, j, radius, value, erase) {
const r2 = radius * radius;
const cx = i, cy = j;
const i0 = clamp(Math.floor(cx - radius), 0, W-1);
const i1 = clamp(Math.ceil (cx + radius), 0, W-1);
const j0 = clamp(Math.floor(cy - radius), 0, H-1);
const j1 = clamp(Math.ceil (cy + radius), 0, H-1);
for (let y = j0; y <= j1; y++) {
for (let x = i0; x <= i1; x++) {
const dx = x - cx, dy = y - cy;
if (dx*dx + dy*dy <= r2) {
const idx = y * W + x;
if (erase) {
// fade out quickly
pixels[idx] = Math.max(0, pixels[idx] - value);
} else {
// additive ink capped at 255
pixels[idx] = Math.min(255, pixels[idx] + value);
}
}
}
}
}
function drawStroke(x0, y0, x1, y1) {
const radius = 1.2; // slightly smaller brush for crisper digits
const value = 128; // higher intensity per stroke for darker lines
const erase = false; // no eraser mode
const steps = Math.max(Math.abs(x1-x0), Math.abs(y1-y0)) * 1.5 + 1;
for (let s = 0; s <= steps; s++) {
const t = s / steps;
const xi = x0 + (x1 - x0) * t;
const yi = y0 + (y1 - y0) * t;
drawDot(xi, yi, radius, value, erase);
}
}
function render() {
// Draw pixels array to the 28×28 canvas. 0 -> white, 255 -> black
const img = ctx.getImageData(0, 0, W, H);
const data = img.data;
for (let j = 0; j < H; j++) {
for (let i = 0; i < W; i++) {
const v = pixels[j*W + i]; // 0..255 (ink)
const s = 255 - v; // screen shade: 255 white background, 0 black ink
const k = (j*W + i) * 4;
data[k+0] = s; data[k+1] = s; data[k+2] = s; data[k+3] = 255;
}
}
ctx.putImageData(img, 0, 0);
requestAnimationFrame(render);
}
// ----- Events -----
canvas.addEventListener('pointerdown', (e) => {
canvas.setPointerCapture(e.pointerId);
isDown = true;
const {x, y} = posToCell(e);
lastX = x; lastY = y;
drawStroke(x, y, x, y);
});
canvas.addEventListener('pointermove', (e) => {
if (!isDown) return;
const {x, y} = posToCell(e);
drawStroke(lastX, lastY, x, y);
lastX = x; lastY = y;
});
window.addEventListener('pointerup', () => { isDown = false; });
clearBtn.addEventListener('click', () => pixels.fill(0));
// ----- Poll the server every 10ms (avoid piling requests) -----
async function tick() {
if (!inFlight) {
inFlight = true;
// Send normalized array 0..1 to server
const arr = new Float32Array(W*H);
for (let i = 0; i < pixels.length; i++) {
const norm = pixels[i] / 255.0; // 0..1 where 1 = black ink in UI
arr[i] = norm; // send as-is
}
try {
const res = await fetch("/api/forward", {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
pixels: Array.from(arr)
}),
cache: "no-store",
});
if (res.ok) {
const { probs } = await res.json();
updateProbs(probs);
}
} catch (_) {
// ignore transient errors
} finally {
inFlight = false;
}
}
}
setInterval(tick, 10);
// ----- Update the right-hand panel -----
function updateProbs(p) {
if (!Array.isArray(p) || p.length !== 10) return;
for (let d = 0; d < 10; d++) {
const prob = Math.max(0, Math.min(1, Number(p[d]) || 0));
// Darker = higher: shade = 255 - (prob * 255)
const shade = Math.round(255 - prob * 255);
rows[d].dot.style.backgroundColor = `rgb(${shade}, ${shade}, ${shade})`;
rows[d].prob.textContent = (prob * 100).toFixed(1) + "%";
}
}
// Kick things off
render();
})();
</script>
</body>
</html>
"""
@app.get("/")
def index():
return Response(INDEX_HTML, mimetype="text/html")
@app.post("/api/forward")
def api_forward():
try:
payload = request.get_json(force=True, silent=False) or {}
raw = payload.get("pixels", [])
if not isinstance(raw, list) or len(raw) != 28 * 28:
return jsonify({"error": "Expected 'pixels' as list[784]"}), 400
# Normalize to [0,1]
arr = []
for v in raw:
try:
f = float(v)
except Exception:
f = 0.0
arr.append(f / 255.0 if f > 1.0 else f)
# Get predictions using Python network
if PARAMS is None:
return jsonify({"error": "Network parameters not loaded"}), 500
probs = predict(arr)
# Ensure we have 10 probabilities
if len(probs) != 10:
return jsonify({"error": "Network must return 10 probabilities"}), 500
# Basic sanity clamp
probs_list = [max(0.0, min(1.0, p)) for p in probs]
return jsonify({"probs": probs_list})
except Exception as e:
import traceback
print(f"ERROR /api/forward: {e}")
traceback.print_exc()
return jsonify({"error": f"{type(e).__name__}: {e}"}), 500
if __name__ == "__main__":
# Print network status
print("\n=== Network Status ===")
print(f"Network: {'✓ Available' if PARAMS else '✗ Not available'}")
# Port selection
import socket
port = 6969
for p in [6969, 6970, 6971]:
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("localhost", p))
port = p
break
except OSError:
continue
print(f"\nStarting server on port {port}")
print(f"Available at: http://localhost:{port}")
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)