From cbd8ea303102fb6fbe7a52c63ee362a4b72140e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9D=97=94=F0=9D=98=86=F0=9D=98=82=F0=9D=98=80?= =?UTF-8?q?=F0=9D=97=B5=20=F0=9D=97=9E?= <100coldice@gmail.com> Date: Mon, 23 Nov 2026 10:51:33 +0530 Subject: [PATCH 1/4] feat: serve web frontend directly from FastAPI app for standalone access --- Dockerfile | 4 +- backend/frontend/_headers | 14 + backend/frontend/app.js | 519 +++++++++++++++++++ backend/frontend/index.html | 247 ++++++++++ backend/frontend/style.css | 957 ++++++++++++++++++++++++++++++++++++ backend/main.py | 18 +- 6 files changed, 1757 insertions(+), 2 deletions(-) create mode 100644 backend/frontend/_headers create mode 100644 backend/frontend/app.js create mode 100644 backend/frontend/index.html create mode 100644 backend/frontend/style.css diff --git a/Dockerfile b/Dockerfile index 9c2c30c..952aa62 100644 --- a/Dockerfile +++ b/Dockerfile @@ -9,6 +9,8 @@ RUN apt-get update && \ WORKDIR /app COPY backend/requirements.txt ./requirements.txt RUN pip install --no-cache-dir -r requirements.txt -COPY backend/ ./ +COPY backend/ ./backend/ +COPY frontend/ ./frontend/ ENV STOCKFISH_PATH=/usr/games/stockfish +WORKDIR /app/backend CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}"] diff --git a/backend/frontend/_headers b/backend/frontend/_headers new file mode 100644 index 0000000..0594127 --- /dev/null +++ b/backend/frontend/_headers @@ -0,0 +1,14 @@ +# Cloudflare Pages — HTTP headers + +/* + X-Frame-Options: DENY + X-Content-Type-Options: nosniff + Referrer-Policy: strict-origin-when-cross-origin + Permissions-Policy: camera=* + +# Cache static assets +/style.css + Cache-Control: public, max-age=86400 + +/app.js + Cache-Control: public, max-age=86400 diff --git a/backend/frontend/app.js b/backend/frontend/app.js new file mode 100644 index 0000000..4133470 --- /dev/null +++ b/backend/frontend/app.js @@ -0,0 +1,519 @@ +/** + * Chess Vision Coach — Frontend Application v2.0 + */ + +const DEFAULT_API_BASE = "https://backend-production-e51676e6.up.railway.app"; +const urlParams = new URLSearchParams(window.location.search); +let API_BASE = urlParams.get("api") || localStorage.getItem("chess_api_base") || DEFAULT_API_BASE; + +const POLL_INTERVAL = 2500; +const MAX_CAPTURE_SIZE = 480; +const JPEG_QUALITY = 0.82; +const SESSION_ID = "session_" + Math.random().toString(36).slice(2, 9); + +const DEPTH_ELO = { + 4: 800, 5: 1000, 6: 1200, 7: 1400, 8: 1600, 9: 1750, + 10: 1900, 11: 2000, 12: 2100, 13: 2200, 14: 2300, 15: 2400, 16: 2600 +}; + +let isRunning = false; +let pollTimer = null; +let lastFrameHash = null; +let playerColor = "w"; +let playMode = "win"; +let depth = 10; +let currentInputTab = "camera"; +const recentMoves = []; + +const $ = id => document.getElementById(id); + +// UI Elements +const cameraFeed = $("cameraFeed"); +const captureCanvas = $("captureCanvas"); +const cameraOverlay = $("cameraOverlay"); +const liveIndicator = $("liveIndicator"); +const engineStatus = $("engineStatus"); +const engineBadge = $("engineBadge"); +const btnStart = $("btnStart"); +const btnStop = $("btnStop"); +const depthSlider = $("depthSlider"); +const depthVal = $("depthVal"); +const eloHint = $("eloHint"); + +const moveWaiting = $("moveWaiting"); +const moveResult = $("moveResult"); +const moveText = $("moveText"); +const moveSan = $("moveSan"); +const moveUci = $("moveUci"); +const waitText = $("waitText"); +const statusMsg = $("statusMsg"); +const statusBar = $("statusBar"); +const boardCard = $("boardCard"); +const boardImg = $("boardImg"); +const confBadge = $("confBadge"); +const modeInfo = $("modeInfo"); +const recentContainer = $("recentContainer"); +const recentPills = $("recentPills"); + +// Mode Tabs & Containers +const cameraContainer = $("cameraContainer"); +const uploadContainer = $("uploadContainer"); +const presetsContainer = $("presetsContainer"); +const dropZone = $("dropZone"); +const fileInput = $("fileInput"); +const customFenInput = $("customFenInput"); +const btnAnalyzeFen = $("btnAnalyzeFen"); + +// Modal Elements +const apiModal = $("apiModal"); +const apiUrlInput = $("apiUrlInput"); +const modalPingStatus = $("modalPingStatus"); +const btnTestPing = $("btnTestPing"); +const btnResetApiDefault = $("btnResetApiDefault"); +const btnSaveApi = $("btnSaveApi"); +const btnConfigApi = $("btnConfigApi"); + +window.addEventListener("DOMContentLoaded", () => { + initTabs(); + initToggleGroup("colorToggle", val => { playerColor = val; }); + initToggleGroup("modeToggle", val => { playMode = val; updateModeInfo(); }); + initPresets(); + initUpload(); + initModal(); + + depthSlider.addEventListener("input", onDepthChange); + btnStart.addEventListener("click", startAnalysis); + btnStop.addEventListener("click", stopAnalysis); + btnAnalyzeFen.addEventListener("click", () => analyzeDirectFen(customFenInput.value.trim())); + + checkBackendHealth(); + updateModeInfo(); +}); + +// ── Tab Navigation ──────────────────────────────────────────────────────── +function initTabs() { + document.querySelectorAll(".tab-btn").forEach(btn => { + btn.addEventListener("click", () => { + document.querySelectorAll(".tab-btn").forEach(b => { + b.classList.remove("active"); + b.setAttribute("aria-selected", "false"); + }); + btn.classList.add("active"); + btn.setAttribute("aria-selected", "true"); + + currentInputTab = btn.dataset.tab; + cameraContainer.style.display = currentInputTab === "camera" ? "block" : "none"; + uploadContainer.style.display = currentInputTab === "upload" ? "block" : "none"; + presetsContainer.style.display = currentInputTab === "presets" ? "block" : "none"; + + if (currentInputTab !== "camera" && isRunning) { + stopAnalysis(); + } + }); + }); +} + +// ── Quick Test Presets ──────────────────────────────────────────────────── +function initPresets() { + document.querySelectorAll(".preset-chip").forEach(chip => { + chip.addEventListener("click", () => { + document.querySelectorAll(".preset-chip").forEach(c => c.classList.remove("active")); + chip.classList.add("active"); + const fen = chip.dataset.fen; + const col = chip.dataset.color || "w"; + customFenInput.value = fen; + + // Update color toggle + const colorBtn = document.querySelector(`#colorToggle button[data-val="${col}"]`); + if (colorBtn) colorBtn.click(); + + analyzeDirectFen(fen); + }); + }); +} + +// ── File Upload & Drag/Drop ─────────────────────────────────────────────── +function initUpload() { + fileInput.addEventListener("change", e => { + const file = e.target.files[0]; + if (file) handleImageFile(file); + }); + + dropZone.addEventListener("dragover", e => { + e.preventDefault(); + dropZone.classList.add("dragover"); + }); + + dropZone.addEventListener("dragleave", () => { + dropZone.classList.remove("dragover"); + }); + + dropZone.addEventListener("drop", e => { + e.preventDefault(); + dropZone.classList.remove("dragover"); + const file = e.dataTransfer.files[0]; + if (file && file.type.startsWith("image/")) { + handleImageFile(file); + } + }); +} + +function handleImageFile(file) { + const reader = new FileReader(); + reader.onload = e => { + const dataUrl = e.target.result; + const b64 = dataUrl.split(",")[1]; + analyzeBase64Image(b64); + }; + reader.readAsDataURL(file); +} + +// ── Toggle Groups ───────────────────────────────────────────────────────── +function initToggleGroup(groupId, onChange) { + const group = $(groupId); + group.querySelectorAll(".toggle-btn").forEach(btn => { + btn.addEventListener("click", () => { + group.querySelectorAll(".toggle-btn").forEach(b => { + b.classList.remove("active"); + b.setAttribute("aria-pressed", "false"); + }); + btn.classList.add("active"); + btn.setAttribute("aria-pressed", "true"); + onChange(btn.dataset.val); + }); + }); +} + +function onDepthChange() { + depth = parseInt(depthSlider.value); + depthVal.textContent = depth; + eloHint.textContent = `≈ ${DEPTH_ELO[depth] ?? "?"} Elo*`; +} + +// ── Camera Capture & Analysis ───────────────────────────────────────────── +async function startAnalysis() { + if (isRunning) return; + + try { + const stream = await navigator.mediaDevices.getUserMedia({ + video: { facingMode: "environment", width: { ideal: 1280 }, height: { ideal: 720 } } + }); + cameraFeed.srcObject = stream; + await cameraFeed.play(); + cameraOverlay.classList.add("hidden"); + liveIndicator.style.display = "inline-block"; + } catch (err) { + setStatus(`Camera access error: ${err.message}`, "error"); + return; + } + + try { + await fetch(`${API_BASE}/api/reset-session?session_id=${SESSION_ID}`, { method: "POST" }); + } catch (_) { } + + isRunning = true; + lastFrameHash = null; + btnStart.disabled = true; + btnStop.disabled = false; + setStatus("Camera live. Analyzing overhead board…", ""); + showWaiting("Scanning camera frame for chess pieces…"); + + pollTimer = setInterval(captureAndAnalyze, POLL_INTERVAL); + captureAndAnalyze(); +} + +function stopAnalysis() { + if (!isRunning) return; + isRunning = false; + clearInterval(pollTimer); + pollTimer = null; + + const stream = cameraFeed.srcObject; + if (stream) stream.getTracks().forEach(t => t.stop()); + cameraFeed.srcObject = null; + cameraOverlay.classList.remove("hidden"); + liveIndicator.style.display = "none"; + + btnStart.disabled = false; + btnStop.disabled = true; + setStatus("Analysis stopped.", ""); +} + +async function captureAndAnalyze() { + if (!isRunning) return; + const vw = cameraFeed.videoWidth; + const vh = cameraFeed.videoHeight; + if (!vw || !vh) return; + + const scale = Math.min(MAX_CAPTURE_SIZE / vw, MAX_CAPTURE_SIZE / vh, 1); + const cw = Math.round(vw * scale); + const ch = Math.round(vh * scale); + + captureCanvas.width = cw; + captureCanvas.height = ch; + const ctx = captureCanvas.getContext("2d"); + ctx.drawImage(cameraFeed, 0, 0, cw, ch); + + const imageB64Full = captureCanvas.toDataURL("image/jpeg", JPEG_QUALITY); + const imageB64 = imageB64Full.split(",")[1]; + + const frameHash = await quickHash(imageB64.slice(0, 2000)); + if (frameHash === lastFrameHash) return; + lastFrameHash = frameHash; + + await analyzeBase64Image(imageB64); +} + +// ── API Invocation ──────────────────────────────────────────────────────── +async function analyzeBase64Image(imageB64) { + try { + const t0 = performance.now(); + const res = await fetch(`${API_BASE}/api/analyze`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + image_b64: imageB64, + player_color: playerColor, + depth: depth, + mode: playMode, + session_id: SESSION_ID, + }), + }); + + const elapsed = Math.round(performance.now() - t0); + + if (!res.ok) { + setStatus(`Server error ${res.status}`, "error"); + return; + } + + const data = await res.json(); + handleResponse(data, elapsed); + + } catch (err) { + setStatus(`Network error: ${err.message}`, "error"); + } +} + +async function analyzeDirectFen(fen) { + if (!fen) return; + showWaiting("Evaluating position with Stockfish…"); + try { + const t0 = performance.now(); + const res = await fetch(`${API_BASE}/api/analyze-fen`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + fen: fen, + player_color: playerColor, + depth: depth, + mode: playMode, + }), + }); + + const elapsed = Math.round(performance.now() - t0); + + if (!res.ok) { + const errData = await res.json().catch(() => ({})); + setStatus(`Error: ${errData.message || res.statusText}`, "error"); + return; + } + + const data = await res.json(); + handleResponse(data, elapsed); + + } catch (err) { + setStatus(`Network error: ${err.message}`, "error"); + } +} + +// ── Response Handler ────────────────────────────────────────────────────── +function handleResponse(data, elapsedMs) { + switch (data.status) { + + case "ok": + showMove(data.move_human, data.move_san, data.move_uci); + const confStr = data.confidence < 1.0 ? ` | Conf: ${pct(data.confidence)}` : ""; + setStatus(`Optimal move computed (${elapsedMs}ms)${confStr} • ≈${data.approx_elo} Elo`, "ok"); + if (data.board_image_b64) { + updateBoard(data.board_image_b64, data.confidence); + } + addRecentMove(data.move_san || data.move_uci); + break; + + case "no_change": + setStatus("Board unchanged — waiting for opponent's move…", ""); + break; + + case "opponent_turn": + setStatus("Opponent's turn detected. Waiting for their move…", ""); + break; + + case "detection_error": + setStatus(`⚠ ${data.message}`, "error"); + showWaiting("Board not fully visible. Reposition camera overhead."); + break; + + case "engine_error": + setStatus("⚙ Engine restarting… retrying automatically.", ""); + break; + + case "rate_limited": + setStatus("Slowing down analysis pace…", ""); + break; + + case "game_over": + setStatus("Checkmate, stalemate, or game over.", "ok"); + showWaiting("Game over — no legal moves remaining."); + break; + + default: + setStatus(data.message ?? "Unknown response.", ""); + } +} + +function showMove(humanText, san, uci) { + moveWaiting.style.display = "none"; + moveResult.style.display = "block"; + moveText.textContent = humanText ?? "—"; + moveSan.textContent = san ?? uci ?? ""; + moveUci.textContent = uci ? `${uci.slice(0, 2)} → ${uci.slice(2, 4)}` : ""; + + moveResult.classList.remove("move-anim"); + void moveResult.offsetWidth; + moveResult.classList.add("move-anim"); +} + +function showWaiting(msg) { + moveWaiting.style.display = "flex"; + moveResult.style.display = "none"; + if (msg) waitText.textContent = msg; +} + +function setStatus(msg, type = "") { + statusMsg.textContent = msg; + statusBar.className = "status-bar" + (type ? ` ${type}` : ""); +} + +function updateBoard(b64, confidence) { + if (!b64) return; + boardCard.style.display = "block"; + boardImg.src = `data:image/png;base64,${b64}`; + confBadge.textContent = pct(confidence); +} + +function addRecentMove(san) { + if (!san) return; + if (!recentMoves.includes(san)) { + recentMoves.unshift(san); + if (recentMoves.length > 5) recentMoves.pop(); + + recentContainer.style.display = "flex"; + recentPills.innerHTML = recentMoves.map(m => `${m}`).join(""); + } +} + +function pct(val) { + return val != null ? `${Math.round(val * 100)}%` : "—"; +} + +function updateModeInfo() { + const modes = { + win: { + icon: "🏆", + title: "Win Mode", + desc: "Calculates sharp, decisive, high-accuracy moves tailored to win quickly.", + }, + loss: { + icon: "🎭", + title: "Loss Mode", + desc: "Provides believable, human-like inaccuracies without obvious tactical blunders.", + }, + }; + const m = modes[playMode] || modes.win; + modeInfo.innerHTML = ` + ${m.icon} +
+ ${m.title} +

${m.desc}

+
`; +} + +// ── Health Check & Engine Status ────────────────────────────────────────── +async function checkBackendHealth() { + setEngineStatus("connecting", "Connecting…"); + try { + const t0 = performance.now(); + const res = await fetch(`${API_BASE}/health`, { signal: AbortSignal.timeout(5000) }); + const latency = Math.round(performance.now() - t0); + if (res.ok) { + const data = await res.json().catch(() => ({})); + const engineName = data.engine === "stockfish" ? "Stockfish 16" : "Python Engine"; + setEngineStatus("online", `Online (${latency}ms)`); + if (engineBadge) engineBadge.textContent = engineName; + } else { + setEngineStatus("offline", `Server Error (${res.status})`); + } + } catch { + setEngineStatus("offline", "Backend Offline"); + } +} + +function setEngineStatus(cls, label) { + engineStatus.className = `status-pill ${cls}`; + engineStatus.querySelector(".status-label").textContent = label; + engineStatus.title = `API: ${API_BASE} (Click to configure)`; +} + +// ── API Configuration Modal ─────────────────────────────────────────────── +function initModal() { + engineStatus.addEventListener("click", openApiModal); + if (btnConfigApi) btnConfigApi.addEventListener("click", openApiModal); + + btnTestPing.addEventListener("click", async () => { + const targetUrl = apiUrlInput.value.trim().replace(/\/+$/, ""); + modalPingStatus.textContent = "Testing connection…"; + try { + const t0 = performance.now(); + const res = await fetch(`${targetUrl}/health`, { signal: AbortSignal.timeout(5000) }); + const ms = Math.round(performance.now() - t0); + if (res.ok) { + modalPingStatus.textContent = `✓ Connected! Response in ${ms}ms`; + modalPingStatus.style.color = "var(--accent)"; + } else { + modalPingStatus.textContent = `✗ HTTP Error ${res.status}`; + modalPingStatus.style.color = "var(--danger)"; + } + } catch (e) { + modalPingStatus.textContent = `✗ Unreachable: ${e.message}`; + modalPingStatus.style.color = "var(--danger)"; + } + }); + + btnResetApiDefault.addEventListener("click", () => { + apiUrlInput.value = DEFAULT_API_BASE; + }); + + btnSaveApi.addEventListener("click", () => { + const val = apiUrlInput.value.trim().replace(/\/+$/, ""); + if (val) { + API_BASE = val; + localStorage.setItem("chess_api_base", API_BASE); + apiModal.close(); + checkBackendHealth(); + } + }); +} + +function openApiModal() { + apiUrlInput.value = API_BASE; + modalPingStatus.textContent = "Click 'Test Connection' to verify server reachability."; + modalPingStatus.style.color = "var(--text-dim)"; + apiModal.showModal(); +} + +async function quickHash(str) { + if (!crypto?.subtle) return str.slice(0, 64); + const buf = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(str)); + return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join(""); +} diff --git a/backend/frontend/index.html b/backend/frontend/index.html new file mode 100644 index 0000000..7466703 --- /dev/null +++ b/backend/frontend/index.html @@ -0,0 +1,247 @@ + + + + + + + + Chess Vision Coach • AI Move Suggester + + + + + + + +
+
+ +
+ +
+
+
+ + +
+ + +
+ + +
+
+ + + +
+
+ + +
+
+ Camera Feed + +
+
+ + +
+ 📷 + Point camera overhead at your physical board + Click "Start Analysis" below or switch to "Quick Test" to try without camera +
+
+
+ + + + + + + + + + +
+ + +
+ + +
+
Player Setup
+ + +
+ +
+ + +
+
+ + +
+ +
+ + +
+
+ + +
+
+ + ≈ 1900 Elo* +
+
+ + 10 +
+

* Approximate Elo estimate for practical human play

+
+ + +
+ + +
+
+ + +
+
+ Recommended Move + Stockfish 16 +
+ + +
+
+ ⏳ + Ready. Press "Start Analysis" or choose a Quick Test position. +
+ +
+ + + + + +
+ + Ready for moves. +
+
+ + +
+
+ 🏆 +
+ Win Mode +

Calculates sharp, decisive, high-accuracy moves tailored to win quickly.

+
+
+
+ +
+
+ + + + + + + + + + + + diff --git a/backend/frontend/style.css b/backend/frontend/style.css new file mode 100644 index 0000000..9603e67 --- /dev/null +++ b/backend/frontend/style.css @@ -0,0 +1,957 @@ +/* ═══════════════════════════════════════════════════════════ + Chess Vision Coach — Stylesheet v2.0 + Modern Dark Theme with Cyber-Emerald & Amber Accents + ═══════════════════════════════════════════════════════════ */ + +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; +} + +:root { + color-scheme: light dark; + --bg-deep: #090b0e; + --bg-card: #12161f; + --bg-card2: #1a202c; + --bg-card-hover: #222938; + --border-subtle: rgba(255, 255, 255, 0.08); + --border-focus: rgba(16, 185, 129, 0.5); + + --accent: #10b981; + --accent-light: #34d399; + --accent-glow: rgba(16, 185, 129, 0.25); + + --accent2: #f59e0b; + --accent2-glow: rgba(245, 158, 11, 0.2); + + --primary: #6366f1; + --danger: #ef4444; + --text: #f9fafb; + --text-dim: #9ca3af; + --text-muted: #6b7280; + + --radius-lg: 14px; + --radius-md: 10px; + --radius-sm: 6px; + --gap: 16px; + + accent-color: var(--accent); + scrollbar-color: var(--bg-card2) transparent; +} + +html { + font-size: 16px; + scroll-behavior: smooth; +} + +body { + font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + background: var(--bg-deep); + background-image: + radial-gradient(circle at 15% 15%, rgba(16, 185, 129, 0.05) 0%, transparent 40%), + radial-gradient(circle at 85% 85%, rgba(99, 102, 241, 0.04) 0%, transparent 40%); + background-attachment: fixed; + color: var(--text); + min-height: 100dvh; + display: flex; + flex-direction: column; + line-height: 1.5; +} + +/* ── Accessibility ───────────────────────────────── */ +.visually-hidden { + position: absolute !important; + clip-path: inset(50%) !important; + overflow: hidden !important; + width: 1px !important; + height: 1px !important; + margin: -1px !important; + padding: 0 !important; + border: 0 !important; + white-space: nowrap !important; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* ── Header ─────────────────────────────────────── */ +.header { + background: rgba(18, 22, 31, 0.85); + backdrop-filter: blur(12px); + -webkit-backdrop-filter: blur(12px); + border-bottom: 1px solid var(--border-subtle); + padding: 0 24px; + height: 64px; + position: sticky; + top: 0; + z-index: 100; +} + +.header-inner { + max-width: 1140px; + margin: 0 auto; + height: 100%; + display: flex; + align-items: center; + justify-content: space-between; +} + +.logo { + display: flex; + align-items: center; + gap: 12px; +} + +.logo-icon { + font-size: 1.8rem; + line-height: 1; + filter: drop-shadow(0 0 8px var(--accent-glow)); +} + +.logo-titles { + display: flex; + flex-direction: column; +} + +.logo-text { + font-weight: 700; + font-size: 1.15rem; + letter-spacing: -0.02em; + color: var(--text); +} + +.logo-badge { + font-size: 0.68rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--accent); +} + +/* Status Pill */ +.status-pill { + display: flex; + align-items: center; + gap: 8px; + background: var(--bg-card2); + border: 1px solid var(--border-subtle); + border-radius: 999px; + padding: 6px 16px; + font-size: 0.82rem; + font-family: inherit; + color: var(--text-dim); + cursor: pointer; + transition: all 0.2s ease; +} + +.status-pill:hover { + border-color: var(--accent); + background: var(--bg-card-hover); +} + +.status-dot { + width: 9px; + height: 9px; + border-radius: 50%; + background: #6b7280; + transition: all 0.3s ease; +} + +.status-pill.online .status-dot { + background: var(--accent); + box-shadow: 0 0 10px var(--accent); +} +.status-pill.online .status-label { + color: var(--accent-light); + font-weight: 600; +} + +.status-pill.offline .status-dot { + background: var(--danger); + box-shadow: 0 0 8px rgba(239, 68, 68, 0.4); +} +.status-pill.offline .status-label { + color: var(--danger); +} + +.status-pill.connecting .status-dot { + background: var(--accent2); + animation: pulse 1s infinite alternate; +} + +/* ── Main Layout ────────────────────────────────── */ +.main { + flex: 1; + max-width: 1140px; + width: 100%; + margin: 0 auto; + padding: var(--gap); + display: grid; + grid-template-columns: 1.05fr 0.95fr; + gap: var(--gap); + align-items: start; +} + +@media (max-width: 820px) { + .main { + grid-template-columns: 1fr; + padding: 12px; + } +} + +.col { + display: flex; + flex-direction: column; + gap: var(--gap); +} + +/* ── Universal Cards ────────────────────────────── */ +.card { + background: var(--bg-card); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + padding: 20px; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); + transition: border-color 0.2s ease; +} + +.card:hover { + border-color: rgba(255, 255, 255, 0.12); +} + +.card-label { + font-size: 0.74rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--text-dim); + margin-bottom: 14px; + display: flex; + align-items: center; + justify-content: space-between; +} + +/* ── Input Mode Tabs ────────────────────────────── */ +.mode-tabs-card { + padding: 8px; +} + +.tab-group { + display: flex; + gap: 6px; + background: var(--bg-deep); + padding: 4px; + border-radius: var(--radius-md); +} + +.tab-btn { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 6px; + background: transparent; + border: none; + border-radius: var(--radius-sm); + color: var(--text-dim); + font-family: inherit; + font-size: 0.85rem; + font-weight: 600; + padding: 10px 8px; + cursor: pointer; + transition: all 0.2s ease; +} + +.tab-btn:hover { + color: var(--text); + background: rgba(255, 255, 255, 0.04); +} + +.tab-btn.active { + background: var(--bg-card2); + color: var(--accent); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); +} + +/* ── Camera Card ────────────────────────────────── */ +.camera-wrapper { + position: relative; + background: #000; + border-radius: var(--radius-md); + overflow: hidden; + aspect-ratio: 4 / 3; + box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.8); +} + +#cameraFeed { + width: 100%; + height: 100%; + object-fit: cover; + display: block; +} + +.live-indicator { + font-size: 0.68rem; + font-weight: 700; + color: #ef4444; + letter-spacing: 0.05em; + animation: pulse 1s infinite alternate; +} + +.camera-overlay { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 24px; + background: rgba(10, 14, 20, 0.88); + color: var(--text); + transition: opacity 0.3s; +} + +.camera-overlay.hidden { + opacity: 0; + pointer-events: none; +} + +.overlay-icon { + font-size: 2.8rem; + margin-bottom: 8px; + color: var(--accent); +} + +.overlay-title { + font-size: 1rem; + font-weight: 600; + margin-bottom: 4px; +} + +.overlay-sub { + font-size: 0.82rem; + color: var(--text-dim); + max-width: 320px; +} + +/* ── Drag & Drop Photo Upload ───────────────────── */ +.upload-dropzone { + border: 2px dashed rgba(255, 255, 255, 0.15); + border-radius: var(--radius-md); + padding: 36px 20px; + text-align: center; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + cursor: pointer; + background: var(--bg-deep); + transition: all 0.2s ease; +} + +.upload-dropzone:hover, +.upload-dropzone.dragover { + border-color: var(--accent); + background: rgba(16, 185, 129, 0.04); +} + +.upload-icon { + font-size: 2.4rem; + color: var(--accent); +} + +.upload-text { + font-size: 0.92rem; + color: var(--text); +} + +.upload-link { + color: var(--accent); + text-decoration: underline; + cursor: pointer; +} + +.upload-hint { + font-size: 0.75rem; + color: var(--text-muted); +} + +/* ── Presets & Quick Test ───────────────────────── */ +.presets-intro { + font-size: 0.84rem; + color: var(--text-dim); + margin-bottom: 12px; +} + +.preset-buttons { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 8px; + margin-bottom: 16px; +} + +@media (max-width: 500px) { + .preset-buttons { + grid-template-columns: 1fr; + } +} + +.preset-chip { + background: var(--bg-card2); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-sm); + color: var(--text); + font-family: inherit; + font-size: 0.82rem; + font-weight: 600; + padding: 10px 12px; + text-align: left; + cursor: pointer; + transition: all 0.2s ease; +} + +.preset-chip:hover { + border-color: var(--accent); + background: var(--bg-card-hover); +} + +.preset-chip.active { + border-color: var(--accent); + background: rgba(16, 185, 129, 0.12); + color: var(--accent-light); +} + +.custom-fen-row { + display: flex; + gap: 8px; +} + +.custom-fen-input { + flex: 1; + background: var(--bg-deep); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-sm); + color: var(--text); + font-family: 'Space Mono', monospace; + font-size: 0.8rem; + padding: 10px 12px; + outline: none; + transition: border-color 0.2s; +} + +.custom-fen-input:focus { + border-color: var(--accent); +} + +/* ── Board preview card ─────────────────────────── */ +.board-wrapper { + border-radius: var(--radius-md); + overflow: hidden; + background: #000; + border: 1px solid var(--border-subtle); +} + +.board-wrapper img { + width: 100%; + display: block; +} + +.conf-badge { + font-size: 0.75rem; + background: var(--bg-card2); + border: 1px solid rgba(16, 185, 129, 0.3); + border-radius: 999px; + padding: 3px 10px; + color: var(--accent-light); + font-family: 'Space Mono', monospace; + font-weight: 700; +} + +/* ── Config card ────────────────────────────────── */ +.control-group { + margin-bottom: 20px; +} + +.ctrl-label { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 0.84rem; + font-weight: 600; + color: var(--text-dim); + margin-bottom: 8px; +} + +.elo-hint { + font-family: 'Space Mono', monospace; + font-size: 0.82rem; + color: var(--accent2); + font-weight: 700; +} + +/* Toggle buttons */ +.toggle-group { + display: flex; + gap: 8px; +} + +.toggle-btn { + flex: 1; + background: var(--bg-card2); + border: 1.5px solid var(--border-subtle); + border-radius: var(--radius-md); + color: var(--text-dim); + font-family: inherit; + font-size: 0.88rem; + font-weight: 600; + padding: 10px 8px; + cursor: pointer; + transition: all 0.15s ease; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; +} + +.toggle-btn:hover { + border-color: rgba(255, 255, 255, 0.2); + color: var(--text); +} + +.toggle-btn.active { + background: var(--accent); + border-color: var(--accent); + color: #062b1a; + font-weight: 700; + box-shadow: 0 2px 12px var(--accent-glow); +} + +.piece-icon { + font-size: 1.2rem; +} + +/* Depth slider */ +.depth-row { + display: flex; + align-items: center; + gap: 14px; +} + +input[type="range"] { + flex: 1; + -webkit-appearance: none; + appearance: none; + height: 6px; + border-radius: 3px; + background: var(--bg-card2); + outline: none; +} + +input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + appearance: none; + width: 20px; + height: 20px; + border-radius: 50%; + background: var(--accent); + cursor: pointer; + box-shadow: 0 0 10px var(--accent-glow); + transition: transform 0.1s; +} + +input[type="range"]::-webkit-slider-thumb:hover { + transform: scale(1.15); +} + +.depth-val { + font-family: 'Space Mono', monospace; + font-size: 1.2rem; + font-weight: 700; + color: var(--accent2); + min-width: 28px; + text-align: right; +} + +.elo-note { + font-size: 0.72rem; + color: var(--text-muted); + margin-top: 6px; +} + +/* Action Buttons */ +.btn-row { + display: flex; + gap: 10px; + margin-top: 8px; +} + +.btn { + font-family: inherit; + font-size: 0.92rem; + font-weight: 700; + padding: 12px 18px; + border-radius: var(--radius-md); + border: none; + cursor: pointer; + transition: all 0.15s ease; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; +} + +.btn-start { + flex: 1.4; + background: var(--accent); + color: #062b1a; + box-shadow: 0 4px 14px var(--accent-glow); +} + +.btn-start:hover:not(:disabled) { + background: var(--accent-light); + transform: translateY(-1px); +} + +.btn-stop { + flex: 1; + background: var(--bg-card2); + color: var(--danger); + border: 1.5px solid var(--danger); +} + +.btn-stop:hover:not(:disabled) { + background: var(--danger); + color: #fff; +} + +.btn-secondary { + background: var(--bg-card2); + color: var(--text); + border: 1px solid var(--border-subtle); + font-size: 0.85rem; +} + +.btn-secondary:hover { + background: var(--bg-card-hover); + border-color: rgba(255, 255, 255, 0.2); +} + +.btn:disabled { + opacity: 0.35; + cursor: not-allowed; + transform: none !important; +} + +/* ── Move Output Card ───────────────────────────── */ +.move-card { + position: relative; + overflow: hidden; +} + +.engine-badge { + font-family: 'Space Mono', monospace; + font-size: 0.7rem; + font-weight: 700; + color: var(--text-dim); + background: var(--bg-card2); + padding: 3px 10px; + border-radius: 999px; + border: 1px solid var(--border-subtle); +} + +.move-display { + background: linear-gradient(145deg, var(--bg-card2), var(--bg-deep)); + border-radius: var(--radius-md); + padding: 24px 20px; + min-height: 128px; + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 14px; + border: 1.5px solid rgba(255, 255, 255, 0.06); + position: relative; +} + +.move-waiting { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + color: var(--text-dim); + font-size: 0.9rem; + text-align: center; +} + +.wait-icon { + font-size: 2rem; + animation: pulse 1.5s infinite alternate; +} + +.move-result { + text-align: center; + width: 100%; +} + +.move-header { + display: flex; + align-items: center; + justify-content: center; + gap: 12px; + margin-bottom: 8px; +} + +.move-san { + font-family: 'Space Mono', monospace; + font-size: 1.7rem; + color: var(--accent); + font-weight: 700; + letter-spacing: 0.05em; + text-shadow: 0 0 16px var(--accent-glow); +} + +.move-uci-badge { + font-family: 'Space Mono', monospace; + font-size: 0.85rem; + font-weight: 700; + color: var(--accent2); + background: var(--bg-deep); + padding: 4px 10px; + border-radius: 999px; + border: 1px solid var(--border-subtle); +} + +.move-text { + font-size: 1.35rem; + font-weight: 700; + color: var(--text); + line-height: 1.3; + letter-spacing: -0.01em; +} + +/* Recent Suggestions Trail */ +.recent-moves-container { + margin-bottom: 14px; + display: flex; + align-items: center; + gap: 10px; +} + +.recent-label { + font-size: 0.74rem; + font-weight: 700; + text-transform: uppercase; + color: var(--text-muted); +} + +.recent-pills { + display: flex; + gap: 6px; + flex-wrap: wrap; +} + +.recent-chip { + font-family: 'Space Mono', monospace; + font-size: 0.78rem; + background: var(--bg-card2); + border: 1px solid var(--border-subtle); + border-radius: 999px; + padding: 2px 10px; + color: var(--text-dim); +} + +/* Status Bar */ +.status-bar { + background: var(--bg-card2); + border-radius: var(--radius-sm); + padding: 10px 14px; + font-size: 0.82rem; + color: var(--text-dim); + min-height: 40px; + display: flex; + align-items: center; + gap: 8px; + border: 1px solid var(--border-subtle); +} + +.status-indicator-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--text-muted); + flex-shrink: 0; +} + +.status-bar.error .status-indicator-dot { background: var(--danger); } +.status-bar.error { color: var(--danger); border-color: rgba(239, 68, 68, 0.3); } + +.status-bar.ok .status-indicator-dot { background: var(--accent); } +.status-bar.ok { color: var(--accent-light); border-color: rgba(16, 185, 129, 0.3); } + +/* ── Mode info card ─────────────────────────────── */ +.info-card { + padding: 14px 18px; +} + +.mode-info { + display: flex; + align-items: flex-start; + gap: 14px; + font-size: 0.84rem; +} + +.mode-icon { + font-size: 1.6rem; + flex-shrink: 0; +} + +.mode-info strong { + display: block; + margin-bottom: 2px; + color: var(--text); + font-size: 0.92rem; +} + +.mode-info p { + color: var(--text-dim); + line-height: 1.45; +} + +/* ── Modal Dialog ───────────────────────────────── */ +.modal-dialog { + border: 1px solid var(--border-subtle); + border-radius: var(--radius-lg); + background: var(--bg-card); + color: var(--text); + padding: 0; + max-width: 480px; + width: 90%; + margin: auto; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7); +} + +.modal-dialog::backdrop { + background: rgba(0, 0, 0, 0.75); + backdrop-filter: blur(4px); +} + +.modal-content { + padding: 24px; + display: flex; + flex-direction: column; + gap: 14px; +} + +.modal-title { + font-size: 1.15rem; + font-weight: 700; +} + +.modal-desc { + font-size: 0.85rem; + color: var(--text-dim); +} + +.modal-input { + background: var(--bg-deep); + border: 1px solid var(--border-subtle); + border-radius: var(--radius-sm); + color: var(--text); + font-family: 'Space Mono', monospace; + font-size: 0.85rem; + padding: 12px; + width: 100%; + outline: none; +} + +.modal-input:focus { + border-color: var(--accent); +} + +.modal-status { + font-size: 0.8rem; + font-family: 'Space Mono', monospace; + color: var(--text-dim); + padding: 6px 0; +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 10px; + margin-top: 8px; +} + +/* ── Footer ─────────────────────────────────────── */ +.footer { + font-size: 0.78rem; + color: var(--text-muted); + padding: 20px; + border-top: 1px solid var(--border-subtle); + margin-top: auto; +} + +.footer-inner { + max-width: 1140px; + margin: 0 auto; + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; +} + +.footer-links { + display: flex; + align-items: center; + gap: 8px; +} + +.footer-link-btn, +.footer-link { + background: none; + border: none; + color: var(--text-dim); + font-size: inherit; + font-family: inherit; + cursor: pointer; + text-decoration: underline; + transition: color 0.15s; +} + +.footer-link-btn:hover, +.footer-link:hover { + color: var(--accent); +} + +/* ── Animations ─────────────────────────────────── */ +@keyframes pulse { + 0% { opacity: 1; } + 100% { opacity: 0.4; } +} + +@keyframes slideIn { + from { + opacity: 0; + transform: translateY(10px) scale(0.98); + } + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.move-anim { + animation: slideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1); +} + +@media (prefers-reduced-motion: reduce) { + .move-anim, + .live-indicator, + .wait-icon { + animation: none; + } +} diff --git a/backend/main.py b/backend/main.py index 6fed4ec..aa6c1da 100644 --- a/backend/main.py +++ b/backend/main.py @@ -1,5 +1,7 @@ +import os from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware +from fastapi.staticfiles import StaticFiles from contextlib import asynccontextmanager import logging @@ -36,10 +38,11 @@ async def lifespan(app: FastAPI): app = FastAPI( title="Chess Vision Coach API", - version="1.0.0", + version="2.0.0", description="Lightweight chess move suggester via camera + Stockfish.", lifespan=lifespan, ) + app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -56,3 +59,16 @@ async def health(request: Request): if sf and sf.is_fallback: engine_name = "python-chess-fallback" return {"status": "ok", "engine": engine_name, "detector": "opencv"} + +# Serve frontend directly if present +frontend_candidates = [ + os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend")), + os.path.abspath(os.path.join(os.path.dirname(__file__), "frontend")), + "/app/frontend", +] + +for fdir in frontend_candidates: + if os.path.isdir(fdir) and os.path.isfile(os.path.join(fdir, "index.html")): + logger.info(f"Serving static frontend UI from: {fdir}") + app.mount("/", StaticFiles(directory=fdir, html=True), name="frontend") + break From 213c65e687edbd73b9d6941eea0ff4766ed3fbe3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9D=97=94=F0=9D=98=86=F0=9D=98=82=F0=9D=98=80?= =?UTF-8?q?=F0=9D=97=B5=20=F0=9D=97=9E?= <100coldice@gmail.com> Date: Tue, 24 Nov 2026 20:53:37 +0530 Subject: [PATCH 2/4] fix: track legal camera positions and return reliable move advice --- backend/main.py | 40 +- backend/routers/analysis.py | 464 ++++++++++------- backend/services/board_detector.py | 662 +++++++++++++----------- backend/services/stockfish_service.py | 112 ++-- backend/tests/test_api.py | 198 ++++++- backend/tests/test_board_detector.py | 372 ++++++++++--- backend/tests/test_stockfish_service.py | 54 +- 7 files changed, 1299 insertions(+), 603 deletions(-) diff --git a/backend/main.py b/backend/main.py index aa6c1da..3ae3610 100644 --- a/backend/main.py +++ b/backend/main.py @@ -2,6 +2,7 @@ from fastapi import FastAPI, Request from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles +from fastapi.responses import JSONResponse from contextlib import asynccontextmanager import logging @@ -38,7 +39,7 @@ async def lifespan(app: FastAPI): app = FastAPI( title="Chess Vision Coach API", - version="2.0.0", + version="3.0.0", description="Lightweight chess move suggester via camera + Stockfish.", lifespan=lifespan, ) @@ -52,23 +53,34 @@ async def lifespan(app: FastAPI): app.include_router(analysis.router, prefix="/api") +@app.middleware("http") +async def web_headers(request: Request, call_next): + response = await call_next(request) + response.headers["Permissions-Policy"] = "camera=(self)" + if request.url.path in ("/", "/index.html", "/app.js", "/overlay.js", "/style.css"): + # HTML, module code and styling must stay on the same deployed version. + response.headers["Cache-Control"] = "no-cache" + return response + @app.get("/health") async def health(request: Request): sf = getattr(request.app.state, "stockfish", None) engine_name = "stockfish" if sf and sf.is_fallback: engine_name = "python-chess-fallback" - return {"status": "ok", "engine": engine_name, "detector": "opencv"} - -# Serve frontend directly if present -frontend_candidates = [ - os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend")), - os.path.abspath(os.path.join(os.path.dirname(__file__), "frontend")), - "/app/frontend", -] + detector = getattr(request.app.state, "detector", None) + ready = bool(sf and sf.is_ready and detector and detector._ready) + return JSONResponse({ + "status": "ok" if ready else "starting", + "engine": engine_name, + "detector": "opencv", + "recognition": "legal-occupancy-tracking", + "requires_setup_for_unknown_positions": True, + "camera_overlay": True, + }, status_code=200 if ready else 503) -for fdir in frontend_candidates: - if os.path.isdir(fdir) and os.path.isfile(os.path.join(fdir, "index.html")): - logger.info(f"Serving static frontend UI from: {fdir}") - app.mount("/", StaticFiles(directory=fdir, html=True), name="frontend") - break +# One source of frontend assets for local development and both Docker entry points. +frontend_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "frontend")) +if os.path.isfile(os.path.join(frontend_dir, "index.html")): + logger.info(f"Serving static frontend UI from: {frontend_dir}") + app.mount("/", StaticFiles(directory=frontend_dir, html=True), name="frontend") diff --git a/backend/routers/analysis.py b/backend/routers/analysis.py index 0c9bbbc..bf559fe 100644 --- a/backend/routers/analysis.py +++ b/backend/routers/analysis.py @@ -1,205 +1,319 @@ -import os -import time +"""Camera sessions keep a trusted chess position and reusable move advice.""" + +import asyncio import base64 +import binascii import logging -from typing import Optional -import chess +import os +import time +from dataclasses import dataclass, field +from typing import Literal, Optional -from fastapi import APIRouter, Request, HTTPException +import chess +import cv2 +import numpy as np +from fastapi import APIRouter, HTTPException, Request from fastapi.responses import JSONResponse -from pydantic import BaseModel +from pydantic import BaseModel, Field, field_validator +from starlette.concurrency import run_in_threadpool -from services.stockfish_service import DEPTH_ELO_MAP +from services.stockfish_service import DEPTH_ELO_MAP, validate_fen logger = logging.getLogger(__name__) router = APIRouter() +MIN_INTERVAL_SEC = max(0.0, float(os.getenv("MIN_INTERVAL_SEC", "0.5"))) +SESSION_TTL_SEC = 30 * 60 +MAX_SESSIONS = 512 +MAX_IMAGE_BYTES = 6 * 1024 * 1024 + + +@dataclass +class CameraSession: + previous_fen: Optional[str] = None + cache_key: Optional[tuple] = None + result: Optional[dict] = None + last_request: float = 0.0 + last_seen: float = field(default_factory=time.monotonic) + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + + +_sessions: dict[str, CameraSession] = {} -_fen_cache: dict[str, str] = {} -_last_request: dict[str, float] = {} -MIN_INTERVAL_SEC = float(os.getenv("MIN_INTERVAL_SEC", "1.0")) class AnalyzeRequest(BaseModel): - image_b64: Optional[str] = None - fen: Optional[str] = None - player_color: str = "w" - depth: int = 10 - mode: str = "win" - session_id: str = "default" + image_b64: Optional[str] = Field(default=None, max_length=MAX_IMAGE_BYTES * 4 // 3 + 128) + fen: Optional[str] = Field(default=None, max_length=128) + setup_fen: Optional[str] = Field(default=None, max_length=128) + player_color: Literal["w", "b"] = "w" + orientation: Literal["w", "b", "auto"] = "auto" + side_to_move: Optional[Literal["w", "b"]] = None + board_corners: Optional[list[list[float]]] = None + depth: int = Field(default=10, ge=4, le=16) + mode: Literal["win", "loss"] = "win" + session_id: str = Field(default="default", min_length=1, max_length=128) + + @field_validator("board_corners") + @classmethod + def valid_corners(cls, value): + if value is not None: + if len(value) != 4 or any(len(point) != 2 for point in value): + raise ValueError("board_corners must contain four [x, y] points.") + if any(not np.isfinite(v) or not 0 <= v <= 1 for point in value for v in point): + raise ValueError("Board corner coordinates must be normalized between 0 and 1.") + # Screen coordinates are clockwise: TL, TR, BR, BL. Crossed or + # degenerate quadrilaterals cannot define a perspective overlay. + points = np.asarray(value, dtype=np.float64) + edges = np.roll(points, -1, axis=0) - points + following = np.roll(edges, -1, axis=0) + cross = edges[:, 0] * following[:, 1] - edges[:, 1] * following[:, 0] + if not (cross > 1e-6).all(): + raise ValueError("Board corners must form a convex clockwise quadrilateral: top-left, top-right, bottom-right, bottom-left.") + return value + class AnalyzeFenRequest(BaseModel): - fen: str - player_color: Optional[str] = None - depth: int = 10 - mode: str = "win" + fen: str = Field(max_length=128) + player_color: Optional[Literal["w", "b"]] = None + depth: int = Field(default=10, ge=4, le=16) + mode: Literal["win", "loss"] = "win" -@router.post("/analyze-fen") -async def analyze_fen(request: Request, body: AnalyzeFenRequest): - """Directly analyze a FEN string without camera image.""" - sf = request.app.state.stockfish + +def _session(session_id: str) -> CameraSession: + now = time.monotonic() + for key, value in list(_sessions.items()): + if now - value.last_seen > SESSION_TTL_SEC and not value.lock.locked(): + _sessions.pop(key, None) + if session_id not in _sessions: + if len(_sessions) >= MAX_SESSIONS: + idle = [(value.last_seen, key) for key, value in _sessions.items() if not value.lock.locked()] + if not idle: + raise HTTPException(status_code=503, detail="All analysis sessions are busy. Please retry.") + _sessions.pop(min(idle)[1], None) + _sessions[session_id] = CameraSession() + session = _sessions[session_id] + session.last_seen = now + return session + + +def _decode_image(encoded: str) -> bytes: + if encoded.startswith("data:"): + if ";base64," not in encoded: + raise HTTPException(status_code=400, detail="Invalid image data URL.") + encoded = encoded.split(",", 1)[1] try: - move_info = sf.get_best_move(body.fen, depth=body.depth, mode=body.mode) - except ValueError as e: - return JSONResponse({"status": "invalid_fen", "message": str(e)}, status_code=400) - except Exception as e: - logger.error(f"Engine error in analyze-fen: {e}") - raise HTTPException(status_code=500, detail=str(e)) + image = base64.b64decode(encoded, validate=True) + except (ValueError, binascii.Error): + raise HTTPException(status_code=400, detail="Invalid base64 image.") + if not image: + raise HTTPException(status_code=400, detail="The image is empty.") + if len(image) > MAX_IMAGE_BYTES: + raise HTTPException(status_code=413, detail="Image is too large. Use an image under 6 MB.") + return image + +def _position_key(fen: str) -> tuple[str, ...]: + # Turn, castling, en passant and the halfmove clock affect legal play and + # automatic draw outcomes even when the piece placement is unchanged. + return tuple(chess.Board(fen).fen().split()[:5]) + + +def _fen_equal(a, b): + if not a or not b: + return False try: - board = chess.Board(body.fen) - turn = "w" if board.turn == chess.WHITE else "b" - except Exception: - turn = body.player_color or "w" - - if not move_info.get("uci"): - return JSONResponse({ - "status": "game_over", - "message": move_info.get("human", "No legal moves."), - "fen": body.fen, - "confidence": 1.0, - }) - - return JSONResponse({ - "status": "ok", - "fen": body.fen, - "turn": turn, - "move_uci": move_info["uci"], - "move_san": move_info["san"], - "move_human": move_info["human"], - "confidence": 1.0, - "approx_elo": move_info["elo"], + return _position_key(a) == _position_key(b) + except ValueError: + return False + + +def _overlay(fen: str, uci: Optional[str], corners, orientation: str) -> Optional[dict]: + if not uci: + return None + move = chess.Move.from_uci(uci) + board = chess.Board(fen) + piece = board.piece_at(move.from_square) + result = { + "from_square": chess.square_name(move.from_square), + "to_square": chess.square_name(move.to_square), + "piece": chess.piece_name(piece.piece_type) if piece else None, + "promotion": chess.piece_name(move.promotion) if move.promotion else None, + "orientation": orientation, + } + if corners is None: + return result + transform = cv2.getPerspectiveTransform( + np.float32([[0, 0], [1, 0], [1, 1], [0, 1]]), np.float32(corners) + ) + + def square_points(square): + col, row = chess.square_file(square), 7 - chess.square_rank(square) + if orientation == "b": + col, row = 7 - col, 7 - row + return np.float32([ + [(col + 0.5) / 8, (row + 0.5) / 8], + [col / 8, row / 8], [(col + 1) / 8, row / 8], + [(col + 1) / 8, (row + 1) / 8], [col / 8, (row + 1) / 8], + ]) + + for prefix, square in [("from", move.from_square), ("to", move.to_square)]: + points = cv2.perspectiveTransform(square_points(square)[None, :, :], transform)[0] + result[prefix] = points[0].round(6).tolist() + result[prefix + "_polygon"] = points[1:].round(6).tolist() + return result + + +def _geometry(detection: Optional[dict], body: AnalyzeRequest) -> dict: + detection = detection or {} + return { + "board_detected": bool(detection.get("board_detected", detection.get("fen"))), + "board_corners": detection.get("board_corners", body.board_corners), + "orientation": detection.get("orientation", body.orientation if body.orientation != "auto" else "w"), + "requires_setup": bool(detection.get("requires_setup", False)), + "piece_count": detection.get("piece_count"), + "pieces_detected": bool(detection.get("pieces_detected", detection.get("fen"))), + } + + +def _attach_geometry(result: dict, geometry: dict) -> dict: + result = {**result, **geometry} + result["board_locked"] = bool(result["board_detected"] and result["pieces_detected"] and result["board_corners"]) + result["overlay"] = _overlay( + result["fen"], result.get("move_uci"), result["board_corners"], result["orientation"] + ) if result.get("fen") else None + return result + + +async def _engine_result(sf, fen: str, depth: int, mode: str, confidence: float) -> dict: + board = chess.Board(fen) + turn = "w" if board.turn else "b" + outcome = board.outcome() + if outcome is not None: + message = "Checkmate." if board.is_checkmate() else "Stalemate." if board.is_stalemate() else "Draw: " + outcome.termination.name.replace("_", " ").lower() + "." + return {"status": "game_over", "message": message, "fen": fen, "turn": turn, + "confidence": confidence, "move_uci": None, "move_san": None, "move_human": None, + "board_image_b64": None, "approx_elo": 0} + info = await run_in_threadpool(sf.get_best_move, fen, depth=depth, mode=mode) + if not info.get("uci"): + raise RuntimeError("Engine returned no move for a position with legal moves.") + move = chess.Move.from_uci(info["uci"]) + if move not in board.legal_moves: + raise RuntimeError("Engine returned an illegal move.") + return { + "status": "ok", "fen": fen, "turn": turn, + "move_uci": info["uci"], "move_san": info["san"], "move_human": info["human"], + "confidence": confidence, "approx_elo": info["elo"], "engine": info.get("engine", "stockfish"), "board_image_b64": None, - }) + } + + +@router.post("/analyze-fen") +async def analyze_fen(request: Request, body: AnalyzeFenRequest): + """A FEN is authoritative about whose turn it is; player color does not rewrite it.""" + valid, error = validate_fen(body.fen) + if not valid: + return JSONResponse({"status": "invalid_fen", "message": error}, status_code=400) + try: + return await _engine_result(request.app.state.stockfish, body.fen, body.depth, body.mode, 1.0) + except Exception: + logger.exception("Engine failed while analyzing FEN") + return JSONResponse({"status": "engine_error", "message": "Analysis unavailable. Please retry."}, status_code=503) + @router.post("/analyze") async def analyze(request: Request, body: AnalyzeRequest): - session_id = body.session_id - now = time.time() - - # Rate-limiting per session (bypassable in test sessions) - if not session_id.startswith("test_"): - if now - _last_request.get(session_id, 0) < MIN_INTERVAL_SEC: - return JSONResponse({"status": "rate_limited", "message": "Slow down."}, status_code=429) - _last_request[session_id] = now - - sf = request.app.state.stockfish - detector = request.app.state.detector - - # Branch 1: Direct FEN provided - if body.fen: - fen = body.fen - try: - b = chess.Board(fen) - turn = "w" if b.turn == chess.WHITE else "b" - except Exception as e: - return JSONResponse({"status": "detection_error", "message": f"Invalid FEN: {e}", "confidence": 0.0}) - - confidence = 1.0 - annotated_b64 = None - # Branch 2: Image provided - elif body.image_b64: - try: - image_bytes = base64.b64decode(body.image_b64) - except Exception: - raise HTTPException(status_code=400, detail="Invalid base64 image.") - - detection = detector.detect(image_bytes, player_color=body.player_color) - - if detection["error"]: - return JSONResponse({ - "status": "detection_error", - "message": detection["error"], - "confidence": detection["confidence"], - }) - - fen = detection["fen"] - turn = detection["turn"] - confidence = detection["confidence"] - annotated_b64 = detection.get("board_b64") - else: + if not body.fen and not body.image_b64: raise HTTPException(status_code=400, detail="Either image_b64 or fen must be provided.") + session = _session(body.session_id) + async with session.lock: + now = time.monotonic() + if now - session.last_request < MIN_INTERVAL_SEC: + return JSONResponse({"status": "rate_limited", "message": "Waiting for the next camera frame.", + "retry_after": MIN_INTERVAL_SEC}, status_code=429, + headers={"Retry-After": str(max(1, int(MIN_INTERVAL_SEC)))}) + session.last_request = now + detection = None + confidence = 1.0 + if body.fen: + fen = body.fen + else: + image = _decode_image(body.image_b64) + setup_fen = body.setup_fen + if setup_fen and body.side_to_move: + try: + setup_board = chess.Board(setup_fen) + setup_board.turn = body.side_to_move == "w" + setup_fen = setup_board.fen() + except ValueError: + pass # Validation below gives the readable FEN error. + if setup_fen: + valid, error = validate_fen(setup_fen) + if not valid: + return JSONResponse({"status": "invalid_fen", "message": error}, status_code=400) + try: + detection = await run_in_threadpool( + request.app.state.detector.detect, image, player_color=body.player_color, + orientation=body.orientation, previous_fen=session.previous_fen, + setup_fen=setup_fen, board_corners=body.board_corners, + ) + except Exception: + logger.exception("Board detector failed") + return JSONResponse({"status": "detection_error", "message": "Could not read this frame. Keep the full board visible.", + "confidence": 0.0, "board_detected": False, "board_locked": False, "overlay": None}) + confidence = detection.get("confidence", 0.0) + geometry = _geometry(detection, body) + if detection.get("error") or not detection.get("fen"): + return _attach_geometry({ + "status": detection.get("status", "detection_error"), + "message": detection.get("error") or "Set the current position to start tracking.", + "confidence": confidence, "fen": None, "move_uci": None, "move_human": None, + }, geometry) + fen = detection["fen"] + geometry = _geometry(detection, body) + valid, error = validate_fen(fen) + if not valid: + return JSONResponse(_attach_geometry({"status": "invalid_fen" if body.fen else "detection_error", + "message": error, "confidence": confidence, "fen": None}, geometry), + status_code=400 if body.fen else 200) + # Trusted position tracking is independent of the engine result cache. + session.previous_fen = fen + board = chess.Board(fen) + key = (_position_key(fen), body.player_color, body.depth, body.mode) + if key == session.cache_key and session.result is not None: + result = {**session.result, "fen": fen, "confidence": confidence, "cached": True} + if result["status"] == "ok": + result["status"] = "no_change" + result["message"] = "Board unchanged. Your suggested move is still ready." + return _attach_geometry(result, geometry) + if ("w" if board.turn else "b") != body.player_color and not board.is_game_over(): + result = {"status": "opponent_turn", "message": "Opponent's turn. Watching for their move.", + "fen": fen, "turn": "w" if board.turn else "b", "confidence": confidence, + "move_uci": None, "move_san": None, "move_human": None, "board_image_b64": None} + else: + try: + result = await _engine_result(request.app.state.stockfish, fen, body.depth, body.mode, confidence) + except Exception: + logger.exception("Engine failed for camera session") + return JSONResponse(_attach_geometry({ + "status": "engine_error", "message": "Analysis interrupted. Retrying this position automatically.", + "fen": fen, "confidence": confidence, "move_uci": None, "move_human": None, + }, geometry), status_code=503) + # Failed analyses never poison this cache. Depth/color/mode changes always reanalyze. + session.cache_key = key + session.result = result.copy() + return _attach_geometry(result, geometry) - # Guard: No-change check - if _fen_equal(fen, _fen_cache.get(session_id)): - return JSONResponse({ - "status": "no_change", - "message": "Board unchanged. Waiting for opponent's move.", - "fen": fen, - "confidence": confidence, - }) - - # Guard: Opponent's turn check - player_color = body.player_color.lower() - if turn != player_color: - _fen_cache[session_id] = fen - return JSONResponse({ - "status": "opponent_turn", - "message": "Opponent's turn. Watching for their move…", - "fen": fen, - "confidence": confidence, - }) - - _fen_cache[session_id] = fen - - try: - move_info = sf.get_best_move(fen, depth=body.depth, mode=body.mode) - except ValueError as e: - logger.warning(f"FEN invalid (detection issue): {e}") - return JSONResponse({ - "status": "detection_error", - "message": str(e), - "confidence": confidence, - }) - except RuntimeError as e: - logger.error(f"Engine runtime error: {e}") - return JSONResponse({ - "status": "engine_error", - "message": "Engine hiccup — will retry automatically.", - "confidence": confidence, - }) - except Exception as e: - logger.error(f"Unexpected engine error: {e}") - raise HTTPException(status_code=500, detail=str(e)) - - if not move_info["uci"]: - return JSONResponse({ - "status": "game_over", - "message": move_info["human"], - "fen": fen, - "confidence": confidence, - }) - - if annotated_b64 and move_info["uci"]: - try: - annotated_b64 = detector.draw_move(annotated_b64, move_info["uci"]) - except Exception: - pass - - return JSONResponse({ - "status": "ok", - "fen": fen, - "turn": turn, - "move_uci": move_info["uci"], - "move_san": move_info["san"], - "move_human": move_info["human"], - "confidence": confidence, - "approx_elo": move_info["elo"], - "board_image_b64": annotated_b64, - }) @router.get("/depth-info") async def depth_info(): - return { - "depths": [{"depth": d, "approx_elo": e} for d, e in DEPTH_ELO_MAP.items()], - "note": "Elo values are approximate estimates, not official ratings.", - } + return {"depths": [{"depth": d, "approx_elo": e} for d, e in DEPTH_ELO_MAP.items()], + "note": "Elo values are approximate estimates, not official ratings."} + @router.post("/reset-session") async def reset_session(session_id: str = "default"): - _fen_cache.pop(session_id, None) - _last_request.pop(session_id, None) + session = _sessions.get(session_id) + if session: + async with session.lock: + session.previous_fen = session.cache_key = session.result = None + session.last_request = 0.0 return {"status": "reset", "session_id": session_id} - -def _fen_equal(a, b): - if not a or not b: - return False - return a.split(" ")[0] == b.split(" ")[0] diff --git a/backend/services/board_detector.py b/backend/services/board_detector.py index fcb894e..1db4498 100644 --- a/backend/services/board_detector.py +++ b/backend/services/board_detector.py @@ -1,14 +1,23 @@ -import cv2 -import numpy as np -import logging +"""Board localisation and legal-move tracking without invented piece identities. + +OpenCV measures the board and piece colour/occupancy, not arbitrary piece type. +Calibrate a standard new game or a supplied FEN, then match legal moves to retain +identities. An unrecognised position is never repaired into a different position. +""" + import base64 +import logging + import chess +import cv2 +import numpy as np logger = logging.getLogger(__name__) +TARGET_SIZE = 960 +WARP_SIZE = 480 +MIN_BOARD_AREA_FRACTION = 0.08 +STARTING_FEN = chess.STARTING_FEN -TARGET_SIZE = 480 -MIN_BOARD_AREA_FRACTION = 0.10 -STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" class BoardDetector: def __init__(self): @@ -16,341 +25,370 @@ def __init__(self): def load(self): self._ready = True - logger.info("BoardDetector ready (OpenCV).") + logger.info("BoardDetector ready (verified checkerboard + legal tracking).") - def detect(self, image_bytes: bytes, player_color: str = "w") -> dict: - """ - Detect chess board from image bytes. - Returns dict with: fen, turn, confidence, error, board_b64 - """ + def detect(self, image_bytes: bytes, player_color: str = "w", + orientation: str = "w", previous_fen: str | None = None, + board_corners: list | None = None, setup_fen: str | None = None) -> dict: if not self._ready: return _err("Detector not initialised.") - try: - img = self._decode(image_bytes) - except Exception as e: - return _err(f"Could not decode image: {e}") - - img = self._resize(img) - corners, conf_c = self._find_corners(img) + img = self._resize(self._decode(image_bytes)) + except (ValueError, cv2.error) as exc: + return _err(f"Could not decode image: {exc}") + h, w = img.shape[:2] + if min(h, w) < 64: + return _err("Image is too small to read a chessboard. Use a full-resolution photo.") + corners, corner_confidence = None, 0.0 + if board_corners is not None: + try: + supplied = np.asarray(board_corners, dtype=np.float32) + if supplied.shape == (4, 2) and np.isfinite(supplied).all() and ( + supplied >= 0).all() and (supplied <= 1).all(): + candidate = supplied * np.array([w - 1, h - 1], np.float32) + if (cv2.isContourConvex(candidate) and + cv2.contourArea(candidate) >= h * w * MIN_BOARD_AREA_FRACTION): + candidate = _order_points(candidate) + score = self._checker_score(self._warp(img, candidate)) + if score >= 0.65: + corners, corner_confidence = candidate, score + except (ValueError, cv2.error): + pass if corners is None: - return _err( - "Board not found. Ensure the full board is visible and well-lit.", - confidence=conf_c, - ) + corners, corner_confidence = self._find_corners(img) + if corners is None: + return _err("Board not found. Keep all 64 squares visible and use an overhead view.") warped = self._warp(img, corners) - matrix, conf_p = self._classify_squares(warped) - overall = round(conf_c * 0.4 + conf_p * 0.6, 3) - - if overall < 0.40: - return _err( - "Board confidence too low. Move camera closer or improve lighting.", - confidence=overall, - ) - - fen, turn = self._matrix_to_fen(matrix, overall, player_color=player_color) - valid, fen = self._ensure_valid_fen(fen, turn) - - if not valid: - return _err( - "Could not read board clearly. Ensure all pieces are visible.", - confidence=overall, - ) - - board_b64 = self._encode_annotated(warped) - return { - "fen": fen, - "turn": turn, - "confidence": overall, - "error": None, - "board_b64": board_b64, + matrix, piece_confidence = self._classify_squares(warped) + confidence = round(0.45 * corner_confidence + 0.55 * piece_confidence, 3) + result = { + "fen": None, "turn": None, "confidence": confidence, + "error": None, "status": "ok", "board_detected": True, + "board_corners": np.clip(corners / np.array([w - 1, h - 1]), 0, 1).round(6).tolist(), + "orientation": "b" if orientation == "b" else "w", + "requires_setup": False, "board_b64": _cv2_to_b64(warped), + "occupancy": matrix, + "piece_count": sum(cell in ("W", "B") for row in matrix for cell in row), + "pieces_detected": any(cell in ("W", "B") for row in matrix for cell in row), } - def draw_move(self, board_b64: str, uci_move: str) -> str: + known_fen = setup_fen or previous_fen + if known_fen: + valid, canonical = self._ensure_valid_fen(known_fen, "w") + if not valid: + return self._uncertain(result, "setup_required", + "The supplied position is illegal. Correct the board and side to move.") + board = chess.Board(canonical) + possibilities = [] + choices = ("w", "b") if orientation == "auto" else (result["orientation"],) + for direction in choices: + observed = _orient(matrix, direction) + if setup_fen: + matches = [board.fen()] if observed == _occupancy(board) else [] + else: + matches = self._match_legal_position(board, observed) + possibilities.extend((fen, direction) for fen in matches) + unique = {(fen, direction) for fen, direction in possibilities} + if len(unique) == 1: + fen, direction = unique.pop() + result.update(fen=fen, turn="w" if chess.Board(fen).turn else "b", orientation=direction) + return result + if len(unique) > 1: + return self._uncertain(result, "position_uncertain", + "More than one legal position fits. Confirm the position, including any promotion.") + message = ("The pieces do not match the setup. Check board orientation and the position." + if setup_fen else + "Pieces are moving or the position is unclear. Remove your hand and hold the camera steady.") + return self._uncertain(result, "position_uncertain", message) + + # Standard new-game calibration: middle-rank pieces are never guessed. + starting = _occupancy(chess.Board()) + choices = ("w", "b") if orientation == "auto" else (result["orientation"],) + for direction in choices: + if _orient(matrix, direction) == starting: + result.update(fen=STARTING_FEN, turn="w", orientation=direction) + return result + return self._uncertain(result, "setup_required", + "Board locked. Start with the standard opening layout, or set this position once to track the game.") + + @staticmethod + def _uncertain(result, status, message): + result.update(status=status, error=message, requires_setup=status == "setup_required") + return result + + @staticmethod + def _match_legal_position(board: chess.Board, observed: list) -> list[str]: + """Match unchanged, one ply, or two plies; retain every chess rule. + + Matching is exact. A partly moved piece/hand cannot commit a speculative + position, and promotions with identical occupancy remain ambiguous. + """ + if observed == _occupancy(board): + return [board.fen()] + one_ply = [] + first_moves = list(board.legal_moves) + for move in first_moves: + board.push(move) + if observed == _occupancy(board): + one_ply.append(board.fen()) + board.pop() + if one_ply: + return list(dict.fromkeys(one_ply)) + two_ply = [] + for first in first_moves: + board.push(first) + # One reply changes at most four squares (castling). + if _difference(_occupancy(board), observed) <= 4: + for second in list(board.legal_moves): + board.push(second) + if observed == _occupancy(board): + two_ply.append(board.fen()) + board.pop() + board.pop() + return list(dict.fromkeys(two_ply)) + + @staticmethod + def _ensure_valid_fen(fen: str, turn: str) -> tuple[bool, str]: try: - img = _b64_to_cv2(board_b64) - h, w = img.shape[:2] - sq = w // 8 - fx, fy = _sq_to_pixel(uci_move[:2], sq) - tx, ty = _sq_to_pixel(uci_move[2:4], sq) - col = (ord(uci_move[2]) - ord("a")) * sq - row = (8 - int(uci_move[3])) * sq - overlay = img.copy() - cv2.rectangle(overlay, (col, row), (col + sq, row + sq), (0, 210, 90), -1) - cv2.addWeighted(overlay, 0.30, img, 0.70, 0, img) - cv2.arrowedLine(img, (fx, fy), (tx, ty), (0, 210, 90), thickness=4, tipLength=0.35) - return _cv2_to_b64(img) - except Exception as e: - logger.warning(f"draw_move failed: {e}") - return board_b64 - - def _decode(self, image_bytes: bytes) -> np.ndarray: - arr = np.frombuffer(image_bytes, np.uint8) - img = cv2.imdecode(arr, cv2.IMREAD_COLOR) + board = chess.Board(fen) + return board.is_valid(), board.fen() + except (ValueError, TypeError): + return False, fen + + @staticmethod + def _decode(image_bytes: bytes) -> np.ndarray: + if not image_bytes: + raise ValueError("Empty image.") + img = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), cv2.IMREAD_COLOR) if img is None: - raise ValueError("cv2.imdecode returned None.") + raise ValueError("Not a supported image.") return img - def _resize(self, img: np.ndarray) -> np.ndarray: + @staticmethod + def _resize(img: np.ndarray) -> np.ndarray: h, w = img.shape[:2] if max(h, w) > TARGET_SIZE: scale = TARGET_SIZE / max(h, w) - img = cv2.resize(img, (int(w * scale), int(h * scale)), interpolation=cv2.INTER_AREA) + return cv2.resize(img, (round(w * scale), round(h * scale)), interpolation=cv2.INTER_AREA) return img def _find_corners(self, img: np.ndarray): + """Only accept quadrilaterals containing a verified 8x8 checker pattern.""" gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) - blur = cv2.GaussianBlur(gray, (5, 5), 0) - edges = cv2.Canny(blur, 30, 100) - kernel = np.ones((3, 3), np.uint8) - edges = cv2.dilate(edges, kernel, iterations=1) - - cnts, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) - if not cnts: - return None, 0.0 - - img_area = img.shape[0] * img.shape[1] - best, best_area = None, 0 - - for cnt in cnts: - area = cv2.contourArea(cnt) - if area < img_area * MIN_BOARD_AREA_FRACTION: - continue - peri = cv2.arcLength(cnt, True) - approx = cv2.approxPolyDP(cnt, 0.02 * peri, True) - if len(approx) == 4 and area > best_area: - best_area = area - best = approx - - if best is None: - h, w = img.shape[:2] - corners = np.array([[0,0],[w,0],[w,h],[0,h]], dtype="float32") - return corners, 0.45 - - corners = best.reshape(4, 2).astype("float32") - conf = min(1.0, best_area / (img_area * 0.70)) - return corners, round(conf, 3) - - def _warp(self, img: np.ndarray, corners: np.ndarray) -> np.ndarray: - size = 480 - dst = np.array([[0,0],[size,0],[size,size],[0,size]], dtype="float32") - corners = _order_points(corners) - M = cv2.getPerspectiveTransform(corners, dst) - return cv2.warpPerspective(img, M, (size, size)) + h, w = gray.shape + candidates = [np.array([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]], np.float32)] + frame_score = self._checker_score(self._warp(img, candidates[0])) + if frame_score >= 0.95: + return candidates[0], round(frame_score, 3) + edges = cv2.Canny(cv2.GaussianBlur(gray, (5, 5), 0), 30, 100) + edges = cv2.dilate(edges, np.ones((3, 3), np.uint8)) + _, threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + for source in (edges, threshold, 255 - threshold): + contours, _ = cv2.findContours(source, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) + for contour in sorted(contours, key=cv2.contourArea, reverse=True)[:30]: + if cv2.contourArea(contour) < h * w * MIN_BOARD_AREA_FRACTION: + continue + approx = cv2.approxPolyDP(contour, 0.025 * cv2.arcLength(contour, True), True) + if len(approx) == 4 and cv2.isContourConvex(approx): + candidates.append(_order_points(approx.reshape(4, 2).astype(np.float32))) + + best, best_score = None, 0.0 + for candidate in candidates: + # Wooden boards often have an outer border; search projectively inward. + for inset in (0.0, 0.02, 0.04, 0.06, 0.08): + test = _inset_corners(candidate, inset) + score = self._checker_score(self._warp(img, test)) + if score > best_score: + best, best_score = test, score + if best_score >= 0.78: + return best, round(best_score, 3) + + # Internal grid intersections recover an obscured outline. Avoid an + # exhaustive detector on every phone frame. + found, points = cv2.findChessboardCorners( + gray, (7, 7), cv2.CALIB_CB_ADAPTIVE_THRESH | cv2.CALIB_CB_NORMALIZE_IMAGE | cv2.CALIB_CB_FAST_CHECK) + if found: + grid = np.array([[x, y] for y in range(1, 8) for x in range(1, 8)], np.float32) + transform, _ = cv2.findHomography(grid, points.reshape(-1, 2)) + if transform is not None: + outer = cv2.perspectiveTransform(np.array([[[0, 0], [8, 0], [8, 8], [0, 8]]], np.float32), transform)[0] + outer = _order_points(outer) + if (outer[:, 0] >= -2).all() and (outer[:, 0] <= w + 1).all() and ( + outer[:, 1] >= -2).all() and (outer[:, 1] <= h + 1).all(): + score = self._checker_score(self._warp(img, outer)) + if score > best_score: + best, best_score = outer, score + return (best, round(best_score, 3)) if best_score >= 0.65 else (None, 0.0) + + @staticmethod + def _warp(img: np.ndarray, corners: np.ndarray) -> np.ndarray: + dst = np.array([[0, 0], [WARP_SIZE - 1, 0], [WARP_SIZE - 1, WARP_SIZE - 1], [0, WARP_SIZE - 1]], np.float32) + transform = cv2.getPerspectiveTransform(_order_points(corners), dst) + return cv2.warpPerspective(img, transform, (WARP_SIZE, WARP_SIZE)) + + @staticmethod + def _backgrounds(board: np.ndarray) -> np.ndarray: + size = board.shape[0] // 8 + cells = board[:size * 8, :size * 8].reshape(8, size, 8, size, 3).transpose(0, 2, 1, 3, 4) + patches = [] + # Sample all 64 cells together. This avoids hundreds of Python/median + # calls for every candidate and keeps camera localisation responsive. + for py, px in ((0.14, 0.14), (0.14, 0.86), (0.86, 0.14), (0.86, 0.86)): + y, x = int(py * size), int(px * size) + patches.append(np.median(cells[:, :, y - 2:y + 3, x - 2:x + 3], axis=(2, 3))) + return np.median(np.stack(patches), axis=0).astype(np.float32) + + def _checker_score(self, board: np.ndarray) -> float: + colours = self._backgrounds(board) + parity = np.indices((8, 8)).sum(axis=0) % 2 + means = [np.median(colours[parity == value], axis=0) for value in (0, 1)] + contrast = float(np.linalg.norm(means[0] - means[1])) + if contrast < 35: + return 0.0 + distances = np.stack([np.linalg.norm(colours - mean, axis=2) for mean in means], axis=2) + agreement = float(np.mean(np.argmin(distances, axis=2) == parity)) + # Rectangles, stripes, and partially cropped grids must not lock. + if agreement < 0.88: + return 0.0 + residual = float(np.median(np.min(distances, axis=2))) / contrast + return float(np.clip(agreement * (1 - min(residual, 0.35)), 0, 1)) def _classify_squares(self, board: np.ndarray): - sq = board.shape[0] // 8 - hsv = cv2.cvtColor(board, cv2.COLOR_BGR2HSV) - matrix, confs = [], [] - + size = board.shape[0] // 8 + backgrounds = self._backgrounds(board) + lab = cv2.cvtColor(board, cv2.COLOR_BGR2LAB).astype(np.float32) + background_lab = cv2.cvtColor(backgrounds.astype(np.uint8), cv2.COLOR_BGR2LAB).astype(np.float32) + entries = [] for row in range(8): - rank = [] for col in range(8): - x0, y0 = col * sq, row * sq - x1, y1 = x0 + sq, y0 + sq - m = sq // 5 - cell = hsv[y0+m:y1-m, x0+m:x1-m] - - if cell.size == 0: - rank.append("empty") - confs.append(0.5) + cell = lab[row * size:(row + 1) * size, col * size:(col + 1) * size] + margin = max(3, size // 10) + interior = cell[margin:-margin, margin:-margin] + distance = np.linalg.norm(interior - background_lab[row, col], axis=2) + # Phone exposure and wood grain change the background noise. + # A fixed threshold misses pale wooden pieces on light squares. + # Measure noise where the square background was sampled and + # separate coherent foreground from that local variation. + corner_noise = [] + for py, px in ((0.14, 0.14), (0.14, 0.86), (0.86, 0.14), (0.86, 0.86)): + y, x = int(py * size), int(px * size) + patch = cell[y - 2:y + 3, x - 2:x + 3] + corner_noise.extend(np.linalg.norm(patch - background_lab[row, col], axis=2).ravel()) + threshold = max(14.0, float(np.percentile(corner_noise, 90)) * 1.75 + 3) + mask = (distance > threshold).astype(np.uint8) + mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((3, 3), np.uint8)) + count, labels, stats, _ = cv2.connectedComponentsWithStats(mask) + if count <= 1: + entries.append(("empty", None, 0.98)) continue - - mean_v = float(np.mean(cell[:, :, 2])) - mean_s = float(np.mean(cell[:, :, 1])) - is_light = (row + col) % 2 == 0 - - if is_light: - if mean_v < 110: - rank.append("B"); confs.append(min(1.0, (130-mean_v)/130)) - elif mean_v > 175 and mean_s < 35: - rank.append("empty"); confs.append(0.75) - else: - rank.append("W"); confs.append(0.60) - else: - if mean_v > 195 and mean_s < 45: - rank.append("W"); confs.append(min(1.0, (mean_v-170)/85)) - elif mean_v < 85: - rank.append("empty"); confs.append(0.70) - else: - rank.append("B"); confs.append(0.55) - - matrix.append(rank) - - return matrix, round(float(np.mean(confs)), 3) - - def _matrix_to_fen(self, matrix: list, confidence: float, player_color: str = "w") -> tuple[str, str]: - WHITE_BACK = list("RNBQKBNR") - BLACK_BACK = list("rnbqkbnr") - - ranks = [] - for row_idx, row in enumerate(matrix): - rank_str = "" - empty_run = 0 - for col_idx, cell in enumerate(row): - if cell == "empty": - empty_run += 1 + index = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + fraction = int(stats[index, cv2.CC_STAT_AREA]) / interior.shape[0] / interior.shape[1] + if fraction < 0.035: + entries.append(("empty", None, 0.9)) continue - if empty_run: - rank_str += str(empty_run) - empty_run = 0 - - if cell == "B": - if row_idx == 0: - rank_str += BLACK_BACK[col_idx] - elif row_idx == 7: - # Pawns cannot exist on 1st rank - rank_str += "q" - else: - rank_str += "p" - else: - if row_idx == 7: - rank_str += WHITE_BACK[col_idx] - elif row_idx == 0: - # Pawns cannot exist on 8th rank - rank_str += "Q" - else: - rank_str += "P" - - if empty_run: - rank_str += str(empty_run) - if not rank_str: - rank_str = "8" - ranks.append(rank_str) - - board_str = "/".join(ranks) - turn = player_color.lower() if player_color in ("w", "b") else "w" - fen = f"{board_str} {turn} - - 0 1" - return fen, turn - - def _ensure_valid_fen(self, fen: str, turn: str) -> tuple[bool, str]: - try: - board = chess.Board(fen) - if board.is_valid(): - return True, fen - except Exception: - pass - - try: - board = chess.Board(fen) - except Exception: - logger.warning("FEN completely invalid, using starting position.") - return True, STARTING_FEN - - # 1. Ensure exactly one White King - white_kings = list(board.pieces(chess.KING, chess.WHITE)) - if not white_kings: - # Place on e1 if empty, else find first empty square on rank 1 - placed = False - for sq in [chess.E1, chess.F1, chess.D1, chess.G1, chess.C1]: - if board.piece_at(sq) is None: - board.set_piece_at(sq, chess.Piece(chess.KING, chess.WHITE)) - placed = True - break - if not placed: - board.set_piece_at(chess.E1, chess.Piece(chess.KING, chess.WHITE)) - elif len(white_kings) > 1: - while len(white_kings) > 1: - board.remove_piece_at(white_kings.pop()) - - # 2. Ensure exactly one Black King - black_kings = list(board.pieces(chess.KING, chess.BLACK)) - if not black_kings: - placed = False - for sq in [chess.E8, chess.F8, chess.D8, chess.G8, chess.C8]: - if board.piece_at(sq) is None: - board.set_piece_at(sq, chess.Piece(chess.KING, chess.BLACK)) - placed = True + # A hand spanning most of a square is not a chess piece. + if fraction > 0.82: + entries.append(("?", None, 0.2)) + continue + lightness = float(np.median(interior[:, :, 0][labels == index])) + entries.append(("piece", lightness, min(0.98, 0.65 + fraction))) + + levels = [value for kind, value, _ in entries if kind == "piece"] + # Legal positions contain both kings. Adapt lighter/darker piece colour + # clusters to wood tones and exposure instead of hardcoded square RGB. + if len(levels) >= 2: + low, high = min(levels), max(levels) + for _ in range(6): + midpoint = (low + high) / 2 + darker = [value for value in levels if value < midpoint] + lighter = [value for value in levels if value >= midpoint] + if not darker or not lighter: break - if not placed: - board.set_piece_at(chess.E8, chess.Piece(chess.KING, chess.BLACK)) - elif len(black_kings) > 1: - while len(black_kings) > 1: - board.remove_piece_at(black_kings.pop()) - - # 3. Disallow pawns on back ranks (convert to Queens) - for sq in list(board.pieces(chess.PAWN, chess.WHITE)): - if chess.square_rank(sq) in (0, 7): - board.set_piece_at(sq, chess.Piece(chess.QUEEN, chess.WHITE)) - for sq in list(board.pieces(chess.PAWN, chess.BLACK)): - if chess.square_rank(sq) in (0, 7): - board.set_piece_at(sq, chess.Piece(chess.QUEEN, chess.BLACK)) - - # 4. Ensure kings are not adjacent - w_king = board.king(chess.WHITE) - b_king = board.king(chess.BLACK) - if w_king is not None and b_king is not None: - if chess.square_distance(w_king, b_king) < 2: - for candidate in [chess.E8, chess.A8, chess.H8, chess.A7, chess.H7]: - if candidate != w_king and chess.square_distance(w_king, candidate) >= 2: - board.remove_piece_at(b_king) - board.set_piece_at(candidate, chess.Piece(chess.KING, chess.BLACK)) - break - - # 5. Handle illegal simultaneous opposite checks (detection noise artifact) - if board.status() & chess.STATUS_OPPOSITE_CHECK: - moving_color = chess.WHITE if turn == "w" else chess.BLACK - non_moving_color = chess.BLACK if turn == "w" else chess.WHITE - opp_king = board.king(non_moving_color) - if opp_king is not None: - attackers = list(board.attackers(moving_color, opp_king)) - for att in attackers: - if att != board.king(moving_color): - board.remove_piece_at(att) - break - - repaired_fen = f"{board.board_fen()} {turn} - - 0 1" + low, high = float(np.median(darker)), float(np.median(lighter)) + threshold = (low + high) / 2 + distinguishable = high - low >= 25 + else: + threshold, distinguishable = 128, False + cells, confidence = [], [] + for kind, value, certainty in entries: + if kind == "piece": + kind = ("W" if value >= threshold else "B") if distinguishable else "?" + if kind == "?": + certainty = 0.2 + cells.append(kind) + confidence.append(certainty) + return [cells[index:index + 8] for index in range(0, 64, 8)], round(float(np.mean(confidence)), 3) + + def draw_move(self, board_b64: str, uci_move: str, orientation: str = "w") -> str: + """Compatibility helper; the web UI draws on the live camera instead.""" try: - test_board = chess.Board(repaired_fen) - if test_board.is_valid(): - return True, repaired_fen - - # If opposite king is in check, switch turn to escape check - if test_board.status() & chess.STATUS_OPPOSITE_CHECK: - opp_turn = "b" if turn == "w" else "w" - repaired_fen = f"{board.board_fen()} {opp_turn} - - 0 1" - if chess.Board(repaired_fen).is_valid(): - return True, repaired_fen - - return True, repaired_fen - except Exception: - logger.warning("FEN repair failed, using starting position.") - return True, STARTING_FEN - - def _encode_annotated(self, board: np.ndarray) -> str: - annotated = board.copy() - sq = annotated.shape[0] // 8 - for i in range(9): - cv2.line(annotated, (i*sq, 0), (i*sq, annotated.shape[0]), (160,160,160), 1) - cv2.line(annotated, (0, i*sq), (annotated.shape[1], i*sq), (160,160,160), 1) - return _cv2_to_b64(annotated) - -def _err(msg: str, confidence: float = 0.0) -> dict: - return {"fen": None, "turn": "w", "confidence": confidence, - "error": msg, "board_b64": None} - -def _order_points(pts: np.ndarray) -> np.ndarray: - rect = np.zeros((4, 2), dtype="float32") - s = pts.sum(axis=1) - diff = np.diff(pts, axis=1) - rect[0] = pts[np.argmin(s)] - rect[2] = pts[np.argmax(s)] - rect[1] = pts[np.argmin(diff)] - rect[3] = pts[np.argmax(diff)] - return rect - -def _sq_to_pixel(sq_name: str, sq_size: int) -> tuple[int, int]: - col = ord(sq_name[0]) - ord("a") - row = 8 - int(sq_name[1]) - return col * sq_size + sq_size // 2, row * sq_size + sq_size // 2 + img = _b64_to_cv2(board_b64) + size = img.shape[0] // 8 + start, end = (_sq_to_pixel(uci_move[:2], size, orientation), + _sq_to_pixel(uci_move[2:4], size, orientation)) + overlay = img.copy() + cv2.circle(overlay, end, int(size * 0.4), (90, 210, 0), -1) + cv2.addWeighted(overlay, 0.3, img, 0.7, 0, img) + cv2.arrowedLine(img, start, end, (90, 210, 0), thickness=5, tipLength=0.3) + return _cv2_to_b64(img) + except (ValueError, cv2.error, IndexError, TypeError) as exc: + logger.warning("draw_move failed: %s", exc) + return board_b64 + + +def _err(message: str, confidence: float = 0.0) -> dict: + return {"fen": None, "turn": None, "confidence": confidence, "error": message, + "status": "detection_error", "board_detected": False, "board_corners": None, + "requires_setup": False, "board_b64": None, "piece_count": 0, "pieces_detected": False} + + +def _occupancy(board: chess.Board) -> list: + return [[("W" if piece.color else "B") if (piece := board.piece_at(chess.square(col, 7 - row))) + else "empty" for col in range(8)] for row in range(8)] + + +def _orient(matrix: list, orientation: str) -> list: + return [list(reversed(row)) for row in reversed(matrix)] if orientation == "b" else matrix + + +def _difference(first: list, second: list) -> int: + return sum(a != b for row_a, row_b in zip(first, second) for a, b in zip(row_a, row_b)) + + +def _order_points(points: np.ndarray) -> np.ndarray: + points = np.asarray(points, np.float32) + # Sorting by sums/differences can select the same vertex twice when a + # board is rotated 45 degrees. Order around the centre first so every + # distinct vertex is retained, then start at the upper-left corner. + centre = points.mean(axis=0) + angles = np.arctan2(points[:, 1] - centre[1], points[:, 0] - centre[0]) + ordered = points[np.argsort(angles)] + return np.roll(ordered, -int(np.argmin(ordered.sum(axis=1))), axis=0) + + +def _inset_corners(corners: np.ndarray, fraction: float) -> np.ndarray: + transform = cv2.getPerspectiveTransform(np.array([[0, 0], [1, 0], [1, 1], [0, 1]], np.float32), corners) + points = np.array([[[fraction, fraction], [1 - fraction, fraction], + [1 - fraction, 1 - fraction], [fraction, 1 - fraction]]], np.float32) + return cv2.perspectiveTransform(points, transform)[0] + + +def _sq_to_pixel(square: str, size: int, orientation: str = "w") -> tuple[int, int]: + index = chess.parse_square(square) + col, row = chess.square_file(index), 7 - chess.square_rank(index) + if orientation == "b": + col, row = 7 - col, 7 - row + return round((col + 0.5) * size), round((row + 0.5) * size) + def _cv2_to_b64(img: np.ndarray) -> str: - _, buf = cv2.imencode(".png", img) - return base64.b64encode(buf).decode("utf-8") + success, buffer = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 82]) + if not success: + raise ValueError("Image encoding failed.") + return base64.b64encode(buffer).decode("ascii") + -def _b64_to_cv2(b64: str) -> np.ndarray: - data = base64.b64decode(b64) - arr = np.frombuffer(data, np.uint8) - return cv2.imdecode(arr, cv2.IMREAD_COLOR) +def _b64_to_cv2(value: str) -> np.ndarray: + return BoardDetector._decode(base64.b64decode(value, validate=True)) diff --git a/backend/services/stockfish_service.py b/backend/services/stockfish_service.py index 4413e1c..dce0459 100644 --- a/backend/services/stockfish_service.py +++ b/backend/services/stockfish_service.py @@ -3,8 +3,9 @@ import threading import logging import random +import time import chess -from stockfish import Stockfish +import chess.engine logger = logging.getLogger(__name__) @@ -100,10 +101,16 @@ def validate_fen(fen: str) -> tuple[bool, str]: if chess.square_rank(sq) in (0, 7): return False, "Black pawn detected on first or eighth rank." - # Ensure board status is valid enough for search + # Validate the complete chess state before either engine searches it. status = board.status() if status & chess.STATUS_OPPOSITE_CHECK: - return False, "Opposite king is in check — impossible position." + return False, "The side that just moved is still in check. Check the side to move and the piece placement." + if status & chess.STATUS_BAD_CASTLING_RIGHTS: + return False, "Castling rights do not match the king and rook positions." + if status & chess.STATUS_INVALID_EP_SQUARE: + return False, "The en passant square does not match this position." + if not board.is_valid(): + return False, "This position is not legal. Check the kings, piece counts and side to move." return True, "" except Exception as e: @@ -124,9 +131,9 @@ def _evaluate_board(board: chess.Board) -> int: # Piece-square bonuses if piece.piece_type == chess.PAWN: - pos_bonus = PAWN_TABLE[sq if piece.color == chess.WHITE else chess.square_mirror(sq)] + pos_bonus = PAWN_TABLE[chess.square_mirror(sq) if piece.color == chess.WHITE else sq] elif piece.piece_type == chess.KNIGHT: - pos_bonus = KNIGHT_TABLE[sq if piece.color == chess.WHITE else chess.square_mirror(sq)] + pos_bonus = KNIGHT_TABLE[chess.square_mirror(sq) if piece.color == chess.WHITE else sq] else: r, c = chess.square_rank(sq), chess.square_file(sq) pos_bonus = int((3 - abs(3.5 - r) + (3 - abs(3.5 - c))) * 4) @@ -137,8 +144,14 @@ def _evaluate_board(board: chess.Board) -> int: return score -def _alpha_beta_search(board: chess.Board, depth: int, alpha: int, beta: int, maximizing: bool): +class SearchTimeout(Exception): + pass + + +def _alpha_beta_search(board: chess.Board, depth: int, alpha: int, beta: int, maximizing: bool, deadline: float | None = None): """Minimax search with alpha-beta pruning for fallback engine.""" + if deadline is not None and time.monotonic() >= deadline: + raise SearchTimeout() if depth <= 0 or board.is_game_over(): return _evaluate_board(board), None @@ -154,8 +167,10 @@ def _alpha_beta_search(board: chess.Board, depth: int, alpha: int, beta: int, ma max_eval = -999999 for move in legal_moves: board.push(move) - eval_score, _ = _alpha_beta_search(board, depth - 1, alpha, beta, False) - board.pop() + try: + eval_score, _ = _alpha_beta_search(board, depth - 1, alpha, beta, False, deadline) + finally: + board.pop() if eval_score > max_eval: max_eval = eval_score best_move = move @@ -167,8 +182,10 @@ def _alpha_beta_search(board: chess.Board, depth: int, alpha: int, beta: int, ma min_eval = 999999 for move in legal_moves: board.push(move) - eval_score, _ = _alpha_beta_search(board, depth - 1, alpha, beta, True) - board.pop() + try: + eval_score, _ = _alpha_beta_search(board, depth - 1, alpha, beta, True, deadline) + finally: + board.pop() if eval_score < min_eval: min_eval = eval_score best_move = move @@ -192,16 +209,27 @@ def get_best_move(self, fen: str, depth: int = 10, mode: str = "win") -> str | N if not legal_moves: return None - # Search depth: clamped to 2-3 for sub-100ms response time + # Finish shallower iterations before deepening so every request has a + # legal answer within a bounded CPU budget, including crowded boards. search_depth = 3 if depth >= 8 else 2 + deadline = time.monotonic() + 0.3 maximizing = (board.turn == chess.WHITE) - scored_moves = [] - for move in legal_moves: - board.push(move) - score, _ = _alpha_beta_search(board, search_depth - 1, -1000000, 1000000, not maximizing) - board.pop() - scored_moves.append((score, move)) + for current_depth in range(1, search_depth + 1): + iteration = [] + try: + for move in legal_moves: + board.push(move) + try: + score, _ = _alpha_beta_search(board, current_depth - 1, -1000000, 1000000, not maximizing, + deadline if current_depth > 1 else None) + finally: + board.pop() + iteration.append((score, move)) + except SearchTimeout: + break + scored_moves = iteration + legal_moves = [move for _, move in sorted(scored_moves, key=lambda item: item[0], reverse=maximizing)] # Sort moves best to worst for current player scored_moves.sort(key=lambda x: x[0], reverse=maximizing) @@ -219,7 +247,7 @@ def get_best_move(self, fen: str, depth: int = 10, mode: str = "win") -> str | N class StockfishService: def __init__(self): - self._engine: Stockfish | None = None + self._engine: chess.engine.SimpleEngine | None = None self._path: str | None = None self._lock = threading.Lock() self._fallback_engine = PythonFallbackEngine() @@ -249,16 +277,12 @@ def start(self): def _spawn(self): try: - self._engine = Stockfish( - path=self._path, - depth=10, - parameters={ - "Threads": 1, - "Hash": 32, - }, - ) + self._engine = chess.engine.SimpleEngine.popen_uci(self._path, timeout=3.0) + self._engine.configure({"Threads": 1, "Hash": 32}) logger.info("Stockfish engine process spawned successfully.") except Exception as e: + if self._engine: + self._engine.close() self._engine = None logger.error(f"Stockfish spawn failed: {e}") raise @@ -267,10 +291,11 @@ def stop(self): with self._lock: if self._engine: try: - del self._engine + self._engine.quit() except Exception: pass self._engine = None + self._is_fallback = False logger.info("Stockfish service stopped.") def get_best_move(self, fen: str, depth: int = 10, mode: str = "win") -> dict: @@ -280,20 +305,27 @@ def get_best_move(self, fen: str, depth: int = 10, mode: str = "win") -> dict: raise ValueError(err) depth = max(4, min(16, depth)) + board = chess.Board(fen) + if board.is_game_over(): + return {"uci": None, "san": None, "human": "No legal moves.", "elo": 0, + "engine": "python-chess-fallback" if self._is_fallback else "stockfish"} uci = None + used_fallback = False # Attempt 1: Use Stockfish if available if not self._is_fallback and self._engine is not None: try: effective_depth = depth if mode == "win" else max(4, depth - 3) - self._engine.set_depth(effective_depth) - self._engine.set_fen_position(fen) - uci = self._engine.get_best_move() + limit = chess.engine.Limit(depth=effective_depth, time=0.35) + result = self._engine.play(board, limit) + uci = result.move.uci() if result.move else None if mode == "loss" and uci: - uci = self._weaken_stockfish(uci) + uci = self._weaken_stockfish(uci, board) except Exception as e: logger.warning(f"Stockfish engine execution failed ({e}), using fallback.") + if self._engine: + self._engine.close() self._engine = None try: self._spawn() @@ -302,28 +334,34 @@ def get_best_move(self, fen: str, depth: int = 10, mode: str = "win") -> dict: # Attempt 2: Use fallback engine if Stockfish is unavailable or failed if not uci: + used_fallback = True uci = self._fallback_engine.get_best_move(fen, depth=depth, mode=mode) if not uci: return {"uci": None, "san": None, "human": "No legal moves.", "elo": 0} + if chess.Move.from_uci(uci) not in board.legal_moves: + raise RuntimeError("Chess engine returned an illegal move.") san, human = self._to_human(fen, uci) return { "uci": uci, "san": san, "human": human, - "elo": DEPTH_ELO_MAP.get(depth, 1900), + "elo": None if used_fallback else DEPTH_ELO_MAP.get(depth, 1900), + "engine": "python-chess-fallback" if used_fallback else "stockfish", } - def _weaken_stockfish(self, best_uci: str) -> str: + def _weaken_stockfish(self, best_uci: str, board: chess.Board) -> str: if random.random() > 0.40: return best_uci try: - top = self._engine.get_top_moves(3) + top = self._engine.analyse(board, chess.engine.Limit(time=0.15), multipv=3) if len(top) >= 2: - cp_loss = abs((top[0].get("Centipawn") or 0) - (top[1].get("Centipawn") or 0)) + first = top[0]["score"].pov(board.turn).score(mate_score=100000) + second = top[1]["score"].pov(board.turn).score(mate_score=100000) + cp_loss = abs(first - second) if cp_loss < 250: - return top[1]["Move"] + return top[1]["pv"][0].uci() except Exception: pass return best_uci @@ -352,7 +390,7 @@ def _to_human(self, fen: str, uci: str) -> tuple[str, str]: elif board.is_capture(move): human = f"Capture on {to} with {pname}" else: - human = f"Move {pname} to {to}" + human = f"{pname} to {to}" if "#" in san: human += " (Checkmate!)" diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index 8f9946d..d8c48c9 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1,6 +1,16 @@ import pytest +import chess from fastapi.testclient import TestClient from main import app +from routers import analysis + + +@pytest.fixture(autouse=True) +def fresh_sessions(monkeypatch): + analysis._sessions.clear() + monkeypatch.setattr(analysis, "MIN_INTERVAL_SEC", 0.0) + yield + analysis._sessions.clear() @pytest.fixture(scope="module") def client(): @@ -38,7 +48,7 @@ def test_analyze_fen_valid(client): assert "move_uci" in data assert "move_san" in data assert "move_human" in data - assert data["approx_elo"] == 1900 + assert data["approx_elo"] == (None if data["engine"] == "python-chess-fallback" else 1900) def test_analyze_fen_invalid(client): res = client.post("/api/analyze-fen", json={"fen": "not-valid", "depth": 10}) @@ -63,7 +73,7 @@ def test_analyze_direct_fen(client): def test_analyze_no_change(client): fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" # First request - client.post("/api/analyze", json={ + first = client.post("/api/analyze", json={ "fen": fen, "player_color": "w", "session_id": "test_no_change", @@ -76,6 +86,9 @@ def test_analyze_no_change(client): }) assert res.status_code == 200 assert res.json()["status"] == "no_change" + assert res.json()["move_uci"] == first.json()["move_uci"] + assert res.json()["move_human"] == first.json()["move_human"] + assert res.json()["overlay"]["to_square"] == first.json()["move_uci"][2:4] def test_analyze_opponent_turn(client): fen = "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1" @@ -94,3 +107,184 @@ def test_analyze_invalid_base64(client): "session_id": "test_invalid_b64", }) assert res.status_code == 400 + + +def test_failed_engine_request_can_retry_same_position(client, monkeypatch): + original = app.state.stockfish.get_best_move + calls = 0 + + def fail_once(*args, **kwargs): + nonlocal calls + calls += 1 + if calls == 1: + raise RuntimeError("temporary engine failure") + return original(*args, **kwargs) + + monkeypatch.setattr(app.state.stockfish, "get_best_move", fail_once) + body = {"fen": chess.STARTING_FEN, "session_id": "retry"} + failed = client.post("/api/analyze", json=body) + assert failed.status_code == 503 + assert failed.json()["status"] == "engine_error" + assert analysis._sessions["retry"].previous_fen == chess.STARTING_FEN + retry = client.post("/api/analyze", json=body) + assert retry.json()["status"] == "ok" + assert retry.json()["move_uci"] + assert calls == 2 + + +def test_strength_mode_and_player_changes_invalidate_advice(client, monkeypatch): + calls = [] + + def evaluate(fen, depth, mode): + calls.append((depth, mode)) + return {"uci": "e2e4", "san": "e4", "human": "Pawn to e4", "elo": 1900} + + monkeypatch.setattr(app.state.stockfish, "get_best_move", evaluate) + body = {"fen": chess.STARTING_FEN, "session_id": "settings"} + assert client.post("/api/analyze", json=body).json()["status"] == "ok" + assert client.post("/api/analyze", json={**body, "depth": 12}).json()["status"] == "ok" + assert client.post("/api/analyze", json={**body, "mode": "loss"}).json()["status"] == "ok" + assert client.post("/api/analyze", json={**body, "player_color": "b"}).json()["status"] == "opponent_turn" + assert len(calls) == 3 + + +def test_fen_comparison_includes_side_castling_and_en_passant(): + starting = chess.STARTING_FEN + assert not analysis._fen_equal(starting, starting.replace(" w ", " b ")) + assert not analysis._fen_equal(starting, starting.replace("KQkq", "-")) + board = chess.Board() + board.push_uci("e2e4") + board.push_uci("a7a6") + board.push_uci("e4e5") + board.push_uci("d7d5") + assert not analysis._fen_equal(board.fen(), board.fen().replace(" d6 ", " - ")) + + +def test_turn_change_same_pieces_does_not_keep_opponent_cache(client): + body = {"fen": chess.STARTING_FEN.replace(" w ", " b "), "session_id": "turns"} + assert client.post("/api/analyze", json=body).json()["status"] == "opponent_turn" + result = client.post("/api/analyze", json={**body, "fen": chess.STARTING_FEN}).json() + assert result["status"] == "ok" + assert result["move_uci"] + + +def test_camera_geometry_and_previous_position_passed_to_detector(client, monkeypatch): + board = chess.Board() + calls = [] + corners = [[0.1, 0.2], [0.9, 0.2], [0.9, 0.8], [0.1, 0.8]] + + def detect(image, **kwargs): + calls.append(kwargs) + return {"fen": board.fen(), "turn": "w" if board.turn else "b", "confidence": 0.95, + "error": None, "status": "ok", "board_detected": True, "board_corners": corners, + "orientation": kwargs["orientation"]} + + monkeypatch.setattr(app.state.detector, "detect", detect) + body = {"image_b64": "ZmFrZQ==", "session_id": "camera", "orientation": "b"} + first = client.post("/api/analyze", json=body).json() + assert first["status"] == "ok" + assert first["board_locked"] + assert first["board_corners"] == corners + assert first["overlay"]["orientation"] == "b" + assert first["overlay"]["from"] and first["overlay"]["to"] + assert calls[0]["previous_fen"] is None + move = first["move_uci"] + board.push_uci(move) + second = client.post("/api/analyze", json=body).json() + assert second["status"] == "opponent_turn" + assert second["overlay"] is None + assert calls[1]["previous_fen"] == chess.STARTING_FEN + board.push(next(iter(board.legal_moves))) + third = client.post("/api/analyze", json=body).json() + assert third["status"] == "ok" + assert chess.Move.from_uci(third["move_uci"]) in board.legal_moves + + +def test_unknown_camera_position_returns_setup_with_geometry(client, monkeypatch): + corners = [[0, 0], [1, 0], [1, 1], [0, 1]] + monkeypatch.setattr(app.state.detector, "detect", lambda *args, **kwargs: { + "fen": None, "error": "Set the current pieces once to start tracking.", "status": "setup_required", + "confidence": 0.8, "board_detected": True, "board_corners": corners, "requires_setup": True, + "orientation": "w", "pieces_detected": True, "piece_count": 12, + }) + data = client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "setup"}).json() + assert data["status"] == "setup_required" + assert data["board_locked"] and data["requires_setup"] + assert data["move_uci"] is None and data["overlay"] is None + assert analysis._sessions["setup"].previous_fen is None + + +def test_perspective_overlay_centers_and_black_orientation(): + corners = [[0.1, 0.2], [0.9, 0.2], [0.9, 0.8], [0.1, 0.8]] + white = analysis._overlay(chess.STARTING_FEN, "e2e4", corners, "w") + black = analysis._overlay(chess.STARTING_FEN, "e2e4", corners, "b") + assert white["from"] == pytest.approx([0.55, 0.6875]) + assert white["to"] == pytest.approx([0.55, 0.5375]) + assert black["from"] == pytest.approx([0.45, 0.3125]) + assert black["to"] == pytest.approx([0.45, 0.4625]) + assert len(white["to_polygon"]) == 4 + + +@pytest.mark.parametrize("body", [ + {"player_color": "blue"}, {"orientation": "sideways"}, {"depth": 99}, {"mode": "random"}, + {"board_corners": [[0, 0]]}, {"board_corners": [[-1, 0], [1, 0], [1, 1], [0, 1]]}, + {"board_corners": [[0, 0], [1, 1], [1, 0], [0, 1]]}, + {"board_corners": [[0, 0], [1, 0], [1, 0], [0, 0]]}, +]) +def test_invalid_camera_settings_rejected(client, body): + response = client.post("/api/analyze", json={"fen": chess.STARTING_FEN, **body}) + assert response.status_code == 422 + + +def test_test_prefix_does_not_bypass_rate_limiting(client, monkeypatch): + monkeypatch.setattr(analysis, "MIN_INTERVAL_SEC", 10.0) + body = {"fen": chess.STARTING_FEN, "session_id": "test_not_privileged"} + assert client.post("/api/analyze", json=body).status_code == 200 + limited = client.post("/api/analyze", json=body) + assert limited.status_code == 429 + assert limited.json()["status"] == "rate_limited" + + +@pytest.mark.parametrize("fen, message", [ + ("rnb1kbnr/pppp1ppp/8/4p3/5PPq/8/PPPPP2P/RNBQKBNR w KQkq - 1 3", "Checkmate."), + ("7k/5Q2/6K1/8/8/8/8/8 b - - 0 1", "Stalemate."), + ("7k/8/6K1/8/8/8/8/8 w - - 0 1", "Draw: insufficient material."), +]) +def test_game_over_has_specific_reason_and_no_arrow(client, fen, message): + data = client.post("/api/analyze", json={"fen": fen, "session_id": "ended"}).json() + assert data["status"] == "game_over" + assert data["message"] == message + assert data["move_uci"] is None and data["overlay"] is None + + +def test_illegal_engine_move_is_never_cached_or_shown(client, monkeypatch): + monkeypatch.setattr(app.state.stockfish, "get_best_move", lambda *args, **kwargs: { + "uci": "e2e5", "san": "e5", "human": "Pawn to e5", "elo": 1900, + }) + response = client.post("/api/analyze", json={"fen": chess.STARTING_FEN, "session_id": "illegal"}) + assert response.status_code == 503 + assert response.json()["move_uci"] is None + assert analysis._sessions["illegal"].result is None + + +def test_halfmove_clock_draw_does_not_reuse_a_cached_move(client): + fen = "4k3/8/8/8/8/8/8/R3K3 w - - 149 76" + body = {"fen": fen, "session_id": "draw_clock"} + first = client.post("/api/analyze", json=body).json() + assert first["status"] == "ok" + assert first["move_uci"] + second = client.post("/api/analyze", json={**body, "fen": fen.replace("149", "150")}).json() + assert second["status"] == "game_over" + assert second["move_uci"] is None + assert "seventyfive moves" in second["message"] + + +def test_empty_detected_board_does_not_lock_or_suggest_a_move(client, monkeypatch): + monkeypatch.setattr(app.state.detector, "detect", lambda *args, **kwargs: { + "fen": None, "error": "Put the pieces on the board.", "status": "setup_required", + "confidence": 0.9, "board_detected": True, "board_corners": [[0, 0], [1, 0], [1, 1], [0, 1]], + "orientation": "w", "pieces_detected": False, "piece_count": 0, + }) + result = client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "empty_board"}).json() + assert result["board_detected"] and not result["board_locked"] + assert result["move_uci"] is None and result["overlay"] is None diff --git a/backend/tests/test_board_detector.py b/backend/tests/test_board_detector.py index 12c937b..e67d823 100644 --- a/backend/tests/test_board_detector.py +++ b/backend/tests/test_board_detector.py @@ -1,62 +1,314 @@ +import base64 +import time + +import chess import cv2 import numpy as np -import chess -from services.board_detector import BoardDetector, STARTING_FEN - -def test_detector_load(): - detector = BoardDetector() - assert not detector._ready - detector.load() - assert detector._ready - -def test_matrix_to_fen_no_backrank_pawns(): - detector = BoardDetector() - matrix = [["empty"] * 8 for _ in range(8)] - matrix[0][4] = "B" # Black king on e8 - matrix[7][4] = "W" # White king on e1 - matrix[0][0] = "W" # White piece on row 0 (rank 8) -> should be 'Q', not 'P' - matrix[7][0] = "B" # Black piece on row 7 (rank 1) -> should be 'q', not 'p' - - fen, turn = detector._matrix_to_fen(matrix, 0.8, player_color="w") - ranks = fen.split(" ")[0].split("/") - assert "P" not in ranks[0], "White pawn should not be placed on rank 8" - assert "p" not in ranks[7], "Black pawn should not be placed on rank 1" - assert turn == "w" - -def test_ensure_valid_fen_repairs(): - detector = BoardDetector() - - # Missing kings - empty_fen = "8/8/8/8/8/8/8/8 w - - 0 1" - valid, repaired = detector._ensure_valid_fen(empty_fen, "w") - assert valid - b = chess.Board(repaired) - assert len(b.pieces(chess.KING, chess.WHITE)) == 1 - assert len(b.pieces(chess.KING, chess.BLACK)) == 1 - - # Duplicate kings - dup_fen = "4k3/4k3/8/8/8/8/4K3/4K3 w - - 0 1" - valid, repaired = detector._ensure_valid_fen(dup_fen, "w") - assert valid - b = chess.Board(repaired) - assert len(b.pieces(chess.KING, chess.WHITE)) == 1 - assert len(b.pieces(chess.KING, chess.BLACK)) == 1 - -def test_detect_blank_image(): - detector = BoardDetector() - detector.load() - blank = np.zeros((480, 480, 3), dtype=np.uint8) - _, buf = cv2.imencode(".png", blank) - res = detector.detect(buf.tobytes()) - assert res["error"] is not None - assert "Board not found" in res["error"] - -def test_draw_move(): - detector = BoardDetector() - blank = np.zeros((480, 480, 3), dtype=np.uint8) - _, buf = cv2.imencode(".png", blank) - import base64 - b64 = base64.b64encode(buf).decode("utf-8") - annotated = detector.draw_move(b64, "e2e4") - assert annotated is not None - assert len(annotated) > 0 +import pytest + +from services.board_detector import BoardDetector, STARTING_FEN, _occupancy, _sq_to_pixel, _order_points + + +@pytest.fixture +def detector(): + value = BoardDetector() + value.load() + return value + + +def board_image(board=None, rotation=False, exposure=1.0, perspective=False, pieces=True): + """Synthetic camera fixture: checkerboard, contrasting piece footprints, + optional camera perspective and changed exposure. No detector mocking. + """ + board = board or chess.Board() + image = np.zeros((480, 480, 3), np.uint8) + for row in range(8): + for col in range(8): + colour = (170, 195, 210) if (row + col) % 2 == 0 else (55, 90, 120) + cv2.rectangle(image, (col * 60, row * 60), ((col + 1) * 60 - 1, (row + 1) * 60 - 1), colour, -1) + piece = board.piece_at(chess.square(col, 7 - row)) if pieces else None + if piece: + colour = (240, 240, 240) if piece.color else (20, 20, 20) + cv2.circle(image, (col * 60 + 30, row * 60 + 30), 15, colour, -1) + if rotation: + image = cv2.rotate(image, cv2.ROTATE_180) + if perspective: + corners = np.array([[105, 65], [575, 105], [530, 570], [60, 515]], np.float32) + transform = cv2.getPerspectiveTransform(np.array([[0, 0], [479, 0], [479, 479], [0, 479]], np.float32), corners) + output = np.full((640, 640, 3), (130, 140, 150), np.uint8) + warped = cv2.warpPerspective(image, transform, (640, 640)) + mask = cv2.warpPerspective(np.full((480, 480), 255, np.uint8), transform, (640, 640)) + output[mask > 0] = warped[mask > 0] + image = output + return np.clip(image.astype(np.float32) * exposure, 0, 255).astype(np.uint8) + + +def encode(image): + success, value = cv2.imencode(".png", image) + assert success + return value.tobytes() + + +def test_detector_requires_loading(): + value = BoardDetector() + assert value.detect(b"")["status"] == "detection_error" + value.load() + assert value._ready + + +@pytest.mark.parametrize("image", [np.zeros((480, 480, 3), np.uint8), + np.full((480, 480, 3), 220, np.uint8)]) +def test_blank_image_never_returns_a_position(detector, image): + result = detector.detect(encode(image)) + assert result["status"] == "detection_error" + assert not result["board_detected"] + assert result["fen"] is None + + +def test_rectangle_is_not_a_board(detector): + image = np.full((480, 480, 3), 210, np.uint8) + cv2.rectangle(image, (50, 50), (420, 420), (30, 30, 30), 10) + assert not detector.detect(encode(image))["board_detected"] + + +def test_empty_checkerboard_has_no_fake_kings_or_opening(detector): + result = detector.detect(encode(board_image(pieces=False))) + assert result["board_detected"] + assert not result["pieces_detected"] + assert result["piece_count"] == 0 + assert result["fen"] is None + assert result["status"] == "setup_required" + + +@pytest.mark.parametrize("exposure", [0.7, 1.0]) +def test_starting_position_calibrates_with_pieces(detector, exposure): + result = detector.detect(encode(board_image(exposure=exposure))) + assert result["status"] == "ok", result["error"] + assert result["fen"] == STARTING_FEN + assert result["turn"] == "w" + assert result["piece_count"] == 32 + assert result["confidence"] > 0.75 + assert np.allclose(result["board_corners"], [[0, 0], [1, 0], [1, 1], [0, 1]], atol=0.02) + + +def test_player_colour_does_not_change_starting_turn(detector): + result = detector.detect(encode(board_image()), player_color="b") + assert result["turn"] == "w" + assert chess.Board(result["fen"]).turn == chess.WHITE + + +def test_orientation_is_independent_of_player_colour(detector): + result = detector.detect(encode(board_image(rotation=True)), player_color="w", orientation="b") + assert result["fen"] == STARTING_FEN + assert result["orientation"] == "b" + automatic = detector.detect(encode(board_image(rotation=True)), orientation="auto") + assert automatic["fen"] == STARTING_FEN + assert automatic["orientation"] == "b" + + +def test_perspective_corners_map_back_to_camera(detector): + result = detector.detect(encode(board_image(perspective=True))) + assert result["status"] == "ok", result["error"] + expected = np.array([[105, 65], [575, 105], [530, 570], [60, 515]]) / 639 + assert np.allclose(result["board_corners"], expected, atol=0.018) + + +def test_knight_move_keeps_piece_identity_and_changes_turn(detector): + board = chess.Board() + board.push_uci("g1f3") + result = detector.detect(encode(board_image(board)), previous_fen=STARTING_FEN) + assert result["status"] == "ok", result["error"] + assert result["fen"] == board.fen() + assert chess.Board(result["fen"]).piece_at(chess.F3).piece_type == chess.KNIGHT + assert result["turn"] == "b" + + +def test_two_moves_between_frames_are_tracked(detector): + board = chess.Board() + board.push_uci("e2e4") + board.push_uci("d7d5") + result = detector.detect(encode(board_image(board)), previous_fen=STARTING_FEN) + assert result["status"] == "ok", result["error"] + assert result["fen"] == board.fen() + assert result["turn"] == "w" + + +def test_capture_is_tracked(): + board = chess.Board() + for move in ("e2e4", "d7d5"): + board.push_uci(move) + before = board.copy() + board.push_uci("e4d5") + assert BoardDetector._match_legal_position(before, _occupancy(board)) == [board.fen()] + + +@pytest.mark.parametrize("fen,move", [ + ("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", "e1g1"), + ("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", "e5d6"), +]) +def test_special_moves_retain_castling_and_en_passant_rules(fen, move): + board = chess.Board(fen) + before = board.copy() + board.push_uci(move) + assert BoardDetector._match_legal_position(before, _occupancy(board)) == [board.fen()] + + +def test_promotion_is_not_guessed_from_occupancy(): + board = chess.Board("7k/P7/8/8/8/8/8/7K w - - 0 1") + before = board.copy() + board.push_uci("a7a8q") + matches = BoardDetector._match_legal_position(before, _occupancy(board)) + assert len(matches) == 4 + + +def test_unknown_midgame_requires_setup_instead_of_fake_fen(detector): + board = chess.Board("4k3/8/8/3q4/8/2N5/8/4K3 w - - 0 1") + result = detector.detect(encode(board_image(board))) + assert result["board_detected"] + assert result["pieces_detected"] + assert result["fen"] is None + assert result["status"] == "setup_required" + assert result["board_corners"] + calibrated = detector.detect(encode(board_image(board)), setup_fen=board.fen()) + assert calibrated["fen"] == board.fen() + + +def test_partial_move_does_not_commit_a_position(detector): + image = board_image() + # Remove a pawn without placing it anywhere; no legal move fits. + cv2.rectangle(image, (240, 360), (299, 419), (170, 195, 210), -1) + result = detector.detect(encode(image), previous_fen=STARTING_FEN) + assert result["status"] == "position_uncertain" + assert result["fen"] is None + + +def test_locked_corners_are_revalidated_when_camera_moves(detector): + initial = detector.detect(encode(board_image())) + moved = detector.detect(encode(board_image(perspective=True)), board_corners=initial["board_corners"], + previous_fen=STARTING_FEN) + assert moved["status"] == "ok", moved["error"] + assert not np.allclose(moved["board_corners"], initial["board_corners"], atol=0.05) + lost = detector.detect(encode(np.zeros((480, 480, 3), np.uint8)), board_corners=moved["board_corners"], + previous_fen=STARTING_FEN) + assert not lost["board_detected"] + + +@pytest.mark.parametrize("fen", ["nonsense", "8/8/8/8/8/8/8/8 w - - 0 1", + "4k3/4k3/8/8/8/8/4K3/4K3 w - - 0 1"]) +def test_illegal_fens_are_rejected_without_repair(fen): + valid, value = BoardDetector._ensure_valid_fen(fen, "w") + assert not valid + if fen != "nonsense": + assert chess.Board(value).board_fen() == chess.Board(fen).board_fen() + + +def test_draw_move_matches_orientation(detector): + image = board_image() + original = base64.b64encode(encode(image)).decode("ascii") + assert detector.draw_move(original, "e2e4") != original + assert _sq_to_pixel("e2", 60, "w") == (270, 390) + assert _sq_to_pixel("e2", 60, "b") == (210, 90) + assert detector.draw_move(original, "wrong") == original + + +@pytest.mark.parametrize("size", [(1, 1), (40, 400), (400, 40)]) +def test_tiny_images_return_detection_error_instead_of_invalid_transform(detector, size): + result = detector.detect(encode(np.zeros((*size, 3), np.uint8))) + assert result["status"] == "detection_error" + assert result["fen"] is None + + +def test_diagonal_board_corners_preserve_four_distinct_vertices(): + corners = np.array([[240, 0], [480, 240], [240, 480], [0, 240]], np.float32) + ordered = _order_points(corners) + assert len(np.unique(ordered, axis=0)) == 4 + assert cv2.isContourConvex(ordered) + assert cv2.contourArea(ordered) == 115200 + + +@pytest.mark.parametrize("corners", [ + [[0, 0], [1, 1], [1, 0], [0, 1]], + [[0, 0], [1, 0], [1, 0], [0, 0]], + [[0, 0], [2, 0], [1, 1], [0, 1]], +]) +def test_invalid_manual_corners_fall_back_to_valid_auto_detection(detector, corners): + result = detector.detect(encode(board_image()), board_corners=corners) + assert result["fen"] == STARTING_FEN + assert np.allclose(result["board_corners"], [[0, 0], [1, 0], [1, 1], [0, 1]], atol=0.02) + + +@pytest.mark.parametrize("fen,move", [ + ("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", "e1c1"), + ("r3k2r/8/8/8/8/8/8/R3K2R b KQkq - 0 1", "e8g8"), + ("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", "e5d6"), +]) +def test_special_moves_are_detected_from_the_camera_image(detector, fen, move): + board = chess.Board(fen) + board.push_uci(move) + result = detector.detect(encode(board_image(board)), previous_fen=fen) + assert result["status"] == "ok", result["error"] + assert result["fen"] == board.fen() + + +def test_promotion_image_requires_confirmation_instead_of_guessing_queen(detector): + fen = "7k/P7/8/8/8/8/8/7K w - - 0 1" + board = chess.Board(fen) + board.push_uci("a7a8q") + result = detector.detect(encode(board_image(board)), previous_fen=fen) + assert result["status"] == "position_uncertain" + assert result["fen"] is None + assert "promotion" in result["error"] + + +def test_letterboxed_landscape_camera_jpeg_coordinates_and_move_tracking(detector): + camera = np.full((540, 960, 3), (80, 100, 110), np.uint8) + frame = np.full((720, 720, 3), (35, 41, 24), np.uint8) + camera[30:510, 240:720] = board_image() + frame[157:562] = cv2.resize(camera, (720, 405)) + ok, jpeg = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 90]) + assert ok + initial = detector.detect(jpeg.tobytes()) + assert initial["fen"] == STARTING_FEN + assert np.allclose(initial["board_corners"], [[.25, .25], [.75, .25], [.75, .75], [.25, .75]], atol=.02) + moved = chess.Board() + moved.push_uci("e2e4") + camera[30:510, 240:720] = board_image(moved) + frame[157:562] = cv2.resize(camera, (720, 405)) + ok, jpeg = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 90]) + assert ok + result = detector.detect(jpeg.tobytes(), previous_fen=STARTING_FEN, + board_corners=initial["board_corners"]) + assert result["fen"] == moved.fen() + assert result["turn"] == "b" + + +def test_cropped_squares_do_not_auto_calibrate(detector): + result = detector.detect(encode(board_image()[30:450, 30:450])) + assert not result["board_detected"] + assert result["fen"] is None + + +def test_hand_over_board_does_not_commit_a_legal_position(detector): + image = board_image() + cv2.rectangle(image, (190, 290), (350, 440), (100, 145, 200), -1) + result = detector.detect(encode(image), previous_fen=STARTING_FEN) + assert result["status"] in ("detection_error", "position_uncertain") + assert result["fen"] is None + + +@pytest.mark.parametrize("pieces", [True, False]) +def test_warm_wooden_piece_tones_and_camera_noise_are_not_hardcoded_black_white(detector, pieces): + image = board_image(pieces=pieces) + image[np.all(image == (240, 240, 240), axis=2)] = (185, 225, 240) + image[np.all(image == (20, 20, 20), axis=2)] = (35, 60, 90) + noise = np.random.default_rng(3).normal(0, 2.5, image.shape) + image = np.clip(image.astype(np.float32) * .85 + noise, 0, 255).astype(np.uint8) + result = detector.detect(encode(image)) + assert result["board_detected"] + if pieces: + assert result["status"] == "ok", result["error"] + assert result["fen"] == STARTING_FEN + assert result["piece_count"] == 32 + else: + assert result["piece_count"] == 0 + assert result["fen"] is None diff --git a/backend/tests/test_stockfish_service.py b/backend/tests/test_stockfish_service.py index 1246690..450e35e 100644 --- a/backend/tests/test_stockfish_service.py +++ b/backend/tests/test_stockfish_service.py @@ -1,5 +1,6 @@ import pytest import chess +import time from services.stockfish_service import ( StockfishService, validate_fen, @@ -60,7 +61,7 @@ def test_get_best_move_win_and_loss_modes(): assert res_win["uci"] is not None assert res_win["san"] is not None assert res_win["human"] is not None - assert res_win["elo"] == 1900 + assert res_win["elo"] == (None if res_win["engine"] == "python-chess-fallback" else 1900) board = chess.Board(start_fen) assert chess.Move.from_uci(res_win["uci"]) in board.legal_moves @@ -77,12 +78,12 @@ def test_to_human_descriptions(): # Pawn push san, human = sf._to_human(start_fen, "e2e4") assert san == "e4" - assert human == "Move Pawn to e4" + assert human == "Pawn to e4" # Knight move san, human = sf._to_human(start_fen, "g1f3") assert san == "Nf3" - assert human == "Move Knight to f3" + assert human == "Knight to f3" # Capture capture_fen = "r1bqkbnr/ppp1pppp/2n5/3p4/4P3/5N2/PPPP1PPP/RNBQKB1R w KQkq - 0 3" @@ -96,3 +97,50 @@ def test_to_human_descriptions(): res = sf.get_best_move(check_fen) assert res["uci"] is None assert res["human"] == "No legal moves." + + +@pytest.mark.parametrize("fen", [ + "8/8/8/8/8/8/4k3/4K3 w - - 0 1", # Adjacent kings. + "4k3/8/8/8/8/8/8/4K3 w KQ - 0 1", # Castling without rooks. + "4k3/8/8/8/8/8/8/4K3 w - e3 0 1", # Impossible en passant. + "4k3/8/8/8/8/8/PPPPPPPP/P3K3 w - - 0 1", # Back-rank pawn. + "4k3/8/8/8/8/8/8/4K2R w - - 0 1".replace("4k3", "7k"), # Non-moving king in check. +]) +def test_complete_fen_legality(fen): + valid, message = validate_fen(fen) + assert not valid + assert message + + +def test_correct_side_to_move_allows_check_evasion(): + checked = "7k/8/6K1/8/8/8/8/7R b - - 0 1" + assert validate_fen(checked)[0] + assert not validate_fen(checked.replace(" b ", " w "))[0] + sf = StockfishService() + sf.start() + try: + result = sf.get_best_move(checked) + assert chess.Move.from_uci(result["uci"]) in chess.Board(checked).legal_moves + finally: + sf.stop() + + +def test_fallback_is_bounded_and_reports_actual_engine(): + sf = StockfishService() + sf._is_fallback = True + started = time.monotonic() + result = sf.get_best_move(chess.STARTING_FEN, depth=16) + assert time.monotonic() - started < 2.0 + assert result["engine"] == "python-chess-fallback" + assert result["elo"] is None + assert chess.Move.from_uci(result["uci"]) in chess.Board().legal_moves + + +def test_human_text_castling_promotion_and_en_passant(): + sf = StockfishService() + _, castle = sf._to_human("r3k2r/8/8/8/8/8/8/R3K2R w KQkq - 0 1", "e1g1") + assert castle == "Castle Kingside" + _, promotion = sf._to_human("7k/P7/8/8/8/8/8/4K3 w - - 0 1", "a7a8q") + assert "Promote Pawn to Queen on a8" in promotion + _, capture = sf._to_human("4k3/8/8/3pP3/8/8/8/4K3 w - d6 0 1", "e5d6") + assert capture == "Capture on d6 with Pawn" From 266b6d9fe1034a0fa13f554b7a244425d5501670 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9D=97=94=F0=9D=98=86=F0=9D=98=82=F0=9D=98=80?= =?UTF-8?q?=F0=9D=97=B5=20=F0=9D=97=9E?= <100coldice@gmail.com> Date: Tue, 24 Nov 2026 20:53:38 +0530 Subject: [PATCH 3/4] feat: redesign mobile camera view with aligned move overlays --- frontend/_headers | 7 +- frontend/app.js | 840 +++++++++++----------- frontend/index.html | 304 ++------ frontend/overlay.js | 64 ++ frontend/style.css | 1185 +++++++------------------------- frontend/tests/app.browser.js | 244 +++++++ frontend/tests/overlay.test.js | 43 ++ package-lock.json | 42 ++ package.json | 12 + 9 files changed, 1106 insertions(+), 1635 deletions(-) create mode 100644 frontend/overlay.js create mode 100644 frontend/tests/app.browser.js create mode 100644 frontend/tests/overlay.test.js create mode 100644 package-lock.json create mode 100644 package.json diff --git a/frontend/_headers b/frontend/_headers index 0594127..7bb7dc7 100644 --- a/frontend/_headers +++ b/frontend/_headers @@ -8,7 +8,10 @@ # Cache static assets /style.css - Cache-Control: public, max-age=86400 + Cache-Control: no-cache /app.js - Cache-Control: public, max-age=86400 + Cache-Control: no-cache + +/overlay.js + Cache-Control: no-cache diff --git a/frontend/app.js b/frontend/app.js index 4133470..7a5d5e7 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -1,519 +1,459 @@ -/** - * Chess Vision Coach — Frontend Application v2.0 - */ - -const DEFAULT_API_BASE = "https://backend-production-e51676e6.up.railway.app"; -const urlParams = new URLSearchParams(window.location.search); -let API_BASE = urlParams.get("api") || localStorage.getItem("chess_api_base") || DEFAULT_API_BASE; - -const POLL_INTERVAL = 2500; -const MAX_CAPTURE_SIZE = 480; -const JPEG_QUALITY = 0.82; -const SESSION_ID = "session_" + Math.random().toString(36).slice(2, 9); - -const DEPTH_ELO = { - 4: 800, 5: 1000, 6: 1200, 7: 1400, 8: 1600, 9: 1750, - 10: 1900, 11: 2000, 12: 2100, 13: 2200, 14: 2300, 15: 2400, 16: 2600 -}; - -let isRunning = false; -let pollTimer = null; -let lastFrameHash = null; -let playerColor = "w"; -let playMode = "win"; -let depth = 10; -let currentInputTab = "camera"; -const recentMoves = []; +import { fitInside, moveGeometry, validCorners, resolveApiBase } from "./overlay.js"; +const DEFAULT_API = "https://backend-production-e51676e6.up.railway.app"; +const STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; const $ = id => document.getElementById(id); - -// UI Elements -const cameraFeed = $("cameraFeed"); -const captureCanvas = $("captureCanvas"); -const cameraOverlay = $("cameraOverlay"); -const liveIndicator = $("liveIndicator"); -const engineStatus = $("engineStatus"); -const engineBadge = $("engineBadge"); -const btnStart = $("btnStart"); -const btnStop = $("btnStop"); -const depthSlider = $("depthSlider"); -const depthVal = $("depthVal"); -const eloHint = $("eloHint"); - -const moveWaiting = $("moveWaiting"); -const moveResult = $("moveResult"); -const moveText = $("moveText"); -const moveSan = $("moveSan"); -const moveUci = $("moveUci"); -const waitText = $("waitText"); -const statusMsg = $("statusMsg"); -const statusBar = $("statusBar"); -const boardCard = $("boardCard"); -const boardImg = $("boardImg"); -const confBadge = $("confBadge"); -const modeInfo = $("modeInfo"); -const recentContainer = $("recentContainer"); -const recentPills = $("recentPills"); - -// Mode Tabs & Containers -const cameraContainer = $("cameraContainer"); -const uploadContainer = $("uploadContainer"); -const presetsContainer = $("presetsContainer"); -const dropZone = $("dropZone"); -const fileInput = $("fileInput"); -const customFenInput = $("customFenInput"); -const btnAnalyzeFen = $("btnAnalyzeFen"); - -// Modal Elements -const apiModal = $("apiModal"); -const apiUrlInput = $("apiUrlInput"); -const modalPingStatus = $("modalPingStatus"); -const btnTestPing = $("btnTestPing"); -const btnResetApiDefault = $("btnResetApiDefault"); -const btnSaveApi = $("btnSaveApi"); -const btnConfigApi = $("btnConfigApi"); - -window.addEventListener("DOMContentLoaded", () => { - initTabs(); - initToggleGroup("colorToggle", val => { playerColor = val; }); - initToggleGroup("modeToggle", val => { playMode = val; updateModeInfo(); }); - initPresets(); - initUpload(); - initModal(); - - depthSlider.addEventListener("input", onDepthChange); - btnStart.addEventListener("click", startAnalysis); - btnStop.addEventListener("click", stopAnalysis); - btnAnalyzeFen.addEventListener("click", () => analyzeDirectFen(customFenInput.value.trim())); - - checkBackendHealth(); - updateModeInfo(); -}); - -// ── Tab Navigation ──────────────────────────────────────────────────────── -function initTabs() { - document.querySelectorAll(".tab-btn").forEach(btn => { - btn.addEventListener("click", () => { - document.querySelectorAll(".tab-btn").forEach(b => { - b.classList.remove("active"); - b.setAttribute("aria-selected", "false"); - }); - btn.classList.add("active"); - btn.setAttribute("aria-selected", "true"); - - currentInputTab = btn.dataset.tab; - cameraContainer.style.display = currentInputTab === "camera" ? "block" : "none"; - uploadContainer.style.display = currentInputTab === "upload" ? "block" : "none"; - presetsContainer.style.display = currentInputTab === "presets" ? "block" : "none"; - - if (currentInputTab !== "camera" && isRunning) { - stopAnalysis(); - } - }); - }); +const state = { + running: false, starting: false, source: null, facing: "environment", timer: null, + generation: 0, controller: null, session: crypto.randomUUID(), corners: null, + cameraAttempt: 0, + manualCorners: [], locking: false, move: null, fen: null, setupFen: null, + player: "w", orientation: "auto", resolvedOrientation: "w", depth: 10, mode: "win", busy: false, +}; +let apiBase; +try { + apiBase = resolveApiBase({ origin: location.origin, search: location.search, + stored: localStorage.getItem("chess_api_base") || "", fallback: DEFAULT_API }); +} catch { apiBase = DEFAULT_API; } + +function setStatus(message, type = "") { + $("statusMsg").textContent = message; + $("statusBar").className = `status-bar ${type}`; } -// ── Quick Test Presets ──────────────────────────────────────────────────── -function initPresets() { - document.querySelectorAll(".preset-chip").forEach(chip => { - chip.addEventListener("click", () => { - document.querySelectorAll(".preset-chip").forEach(c => c.classList.remove("active")); - chip.classList.add("active"); - const fen = chip.dataset.fen; - const col = chip.dataset.color || "w"; - customFenInput.value = fen; - - // Update color toggle - const colorBtn = document.querySelector(`#colorToggle button[data-val="${col}"]`); - if (colorBtn) colorBtn.click(); - - analyzeDirectFen(fen); - }); - }); +function clearMove(message = "Point your camera at the board to find your next move.") { + state.move = null; + $("frameMoveLabel").hidden = true; + $("moveWaiting").hidden = false; + $("moveResult").hidden = true; + $("waitText").textContent = message; + drawOverlay(); } -// ── File Upload & Drag/Drop ─────────────────────────────────────────────── -function initUpload() { - fileInput.addEventListener("change", e => { - const file = e.target.files[0]; - if (file) handleImageFile(file); - }); - - dropZone.addEventListener("dragover", e => { - e.preventDefault(); - dropZone.classList.add("dragover"); - }); - - dropZone.addEventListener("dragleave", () => { - dropZone.classList.remove("dragover"); - }); - - dropZone.addEventListener("drop", e => { - e.preventDefault(); - dropZone.classList.remove("dragover"); - const file = e.dataTransfer.files[0]; - if (file && file.type.startsWith("image/")) { - handleImageFile(file); - } - }); +function updateControls() { + $("btnStart").disabled = state.running || state.starting; + $("btnStop").disabled = !state.running && !state.starting; + $("btnSwitchCamera").disabled = state.starting; + $("liveIndicator").hidden = !state.running; + $("btnLockBoard").disabled = !state.source || state.source === "demo"; + $("btnUnlockBoard").disabled = !state.corners && !state.locking; + $("btnAnalyzeFen").disabled = state.busy; + $("btnSetPosition").disabled = state.busy; + $("cameraFrame").classList.toggle("is-locking", state.locking); } -function handleImageFile(file) { - const reader = new FileReader(); - reader.onload = e => { - const dataUrl = e.target.result; - const b64 = dataUrl.split(",")[1]; - analyzeBase64Image(b64); - }; - reader.readAsDataURL(file); +function cancelRequest() { + state.generation++; + state.controller?.abort(); + state.controller = null; + state.busy = false; + clearTimeout(state.timer); } -// ── Toggle Groups ───────────────────────────────────────────────────────── -function initToggleGroup(groupId, onChange) { - const group = $(groupId); - group.querySelectorAll(".toggle-btn").forEach(btn => { - btn.addEventListener("click", () => { - group.querySelectorAll(".toggle-btn").forEach(b => { - b.classList.remove("active"); - b.setAttribute("aria-pressed", "false"); - }); - btn.classList.add("active"); - btn.setAttribute("aria-pressed", "true"); - onChange(btn.dataset.val); - }); - }); +function resetTracking({ keepCorners = false } = {}) { + cancelRequest(); + state.session = crypto.randomUUID(); + state.fen = null; + state.setupFen = null; + state.resolvedOrientation = state.orientation === "b" ? "b" : "w"; + if (!keepCorners) state.corners = null; + state.manualCorners = []; + state.locking = false; + $("boardStatus").textContent = state.corners ? "Board locked" : "Looking for board"; + $("confBadge").textContent = "Auto detection"; + $("confBadge").hidden = !state.corners; + clearMove(); + updateControls(); } -function onDepthChange() { - depth = parseInt(depthSlider.value); - depthVal.textContent = depth; - eloHint.textContent = `≈ ${DEPTH_ELO[depth] ?? "?"} Elo*`; +function stopCamera({ clear = true } = {}) { + cancelRequest(); + state.cameraAttempt++; + state.running = false; + state.starting = false; + $("cameraFeed").srcObject?.getTracks().forEach(track => track.stop()); + $("cameraFeed").srcObject = null; + $("cameraFeed").hidden = true; + if (clear) { + state.source = null; + state.corners = null; + state.locking = false; + $("photoPreview").hidden = true; + $("cameraOverlay").hidden = false; + $("boardStatus").textContent = "Camera paused"; + $("confBadge").hidden = true; + clearMove("Camera paused. Start it again to continue."); + setStatus("Camera paused."); + } + updateControls(); } -// ── Camera Capture & Analysis ───────────────────────────────────────────── -async function startAnalysis() { - if (isRunning) return; - +async function startCamera() { + if (state.running || state.starting) return; + if (!navigator.mediaDevices?.getUserMedia) { + setStatus("Camera needs a secure HTTPS connection. You can upload a photo instead.", "error"); return; + } + resetTracking(); + state.source = null; + state.starting = true; + const attempt = ++state.cameraAttempt; + updateControls(); setStatus("Opening camera…"); try { - const stream = await navigator.mediaDevices.getUserMedia({ - video: { facingMode: "environment", width: { ideal: 1280 }, height: { ideal: 720 } } + const stream = await navigator.mediaDevices.getUserMedia({ audio: false, + video: { facingMode: { ideal: state.facing }, width: { ideal: 1280 }, height: { ideal: 1280 } } }); + if (attempt !== state.cameraAttempt) { stream.getTracks().forEach(t => t.stop()); return; } + $("cameraFeed").srcObject = stream; + await $("cameraFeed").play(); + if (attempt !== state.cameraAttempt) { stream.getTracks().forEach(t => t.stop()); return; } + cancelRequest(); + state.running = true; + state.source = "camera"; + $("cameraFeed").hidden = false; + $("photoPreview").hidden = true; + $("cameraOverlay").hidden = true; + setStatus("Scanning automatically. Keep the full board visible and your hands clear."); + stream.getVideoTracks()[0]?.addEventListener("ended", () => { + if ($("cameraFeed").srcObject === stream) stopCamera(); }); - cameraFeed.srcObject = stream; - await cameraFeed.play(); - cameraOverlay.classList.add("hidden"); - liveIndicator.style.display = "inline-block"; + schedule(0); } catch (err) { - setStatus(`Camera access error: ${err.message}`, "error"); - return; - } - - try { - await fetch(`${API_BASE}/api/reset-session?session_id=${SESSION_ID}`, { method: "POST" }); - } catch (_) { } - - isRunning = true; - lastFrameHash = null; - btnStart.disabled = true; - btnStop.disabled = false; - setStatus("Camera live. Analyzing overhead board…", ""); - showWaiting("Scanning camera frame for chess pieces…"); - - pollTimer = setInterval(captureAndAnalyze, POLL_INTERVAL); - captureAndAnalyze(); + if (attempt !== state.cameraAttempt) return; + stopCamera({ clear: false }); + setStatus(err.name === "NotAllowedError" ? "Camera access was denied. Allow camera access in your browser or upload a photo." + : `Could not open the camera: ${err.message}`, "error"); + } finally { if (attempt === state.cameraAttempt) state.starting = false; updateControls(); } } -function stopAnalysis() { - if (!isRunning) return; - isRunning = false; - clearInterval(pollTimer); - pollTimer = null; - - const stream = cameraFeed.srcObject; - if (stream) stream.getTracks().forEach(t => t.stop()); - cameraFeed.srcObject = null; - cameraOverlay.classList.remove("hidden"); - liveIndicator.style.display = "none"; - - btnStart.disabled = false; - btnStop.disabled = true; - setStatus("Analysis stopped.", ""); +function captureFrame() { + const source = state.source === "camera" ? $("cameraFeed") : $("photoPreview"); + const width = source.videoWidth || source.naturalWidth, height = source.videoHeight || source.naturalHeight; + if (!width || !height) return null; + const canvas = $("captureCanvas"), size = 720; + canvas.width = canvas.height = size; + const ctx = canvas.getContext("2d"), fit = fitInside(width, height, size); + ctx.fillStyle = "#182923"; ctx.fillRect(0, 0, size, size); + ctx.drawImage(source, fit.x, fit.y, fit.width, fit.height); + return canvas.toDataURL("image/jpeg", .9).split(",")[1]; } -async function captureAndAnalyze() { - if (!isRunning) return; - const vw = cameraFeed.videoWidth; - const vh = cameraFeed.videoHeight; - if (!vw || !vh) return; - - const scale = Math.min(MAX_CAPTURE_SIZE / vw, MAX_CAPTURE_SIZE / vh, 1); - const cw = Math.round(vw * scale); - const ch = Math.round(vh * scale); - - captureCanvas.width = cw; - captureCanvas.height = ch; - const ctx = captureCanvas.getContext("2d"); - ctx.drawImage(cameraFeed, 0, 0, cw, ch); - - const imageB64Full = captureCanvas.toDataURL("image/jpeg", JPEG_QUALITY); - const imageB64 = imageB64Full.split(",")[1]; - - const frameHash = await quickHash(imageB64.slice(0, 2000)); - if (frameHash === lastFrameHash) return; - lastFrameHash = frameHash; - - await analyzeBase64Image(imageB64); +function schedule(delay = 1250) { + clearTimeout(state.timer); + if (state.running && !state.locking && !document.hidden) state.timer = setTimeout(scanFrame, delay); } -// ── API Invocation ──────────────────────────────────────────────────────── -async function analyzeBase64Image(imageB64) { +async function apiRequest(path, body, generation) { + const controller = new AbortController(); + state.controller = controller; + const timeout = setTimeout(() => controller.abort(), 15000); try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/api/analyze`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - image_b64: imageB64, - player_color: playerColor, - depth: depth, - mode: playMode, - session_id: SESSION_ID, - }), - }); - - const elapsed = Math.round(performance.now() - t0); - - if (!res.ok) { - setStatus(`Server error ${res.status}`, "error"); - return; - } - + const res = await fetch(`${apiBase}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), signal: controller.signal }); const data = await res.json(); - handleResponse(data, elapsed); - + if (generation !== state.generation) return null; + if (!res.ok && !data.status) throw new Error(typeof data.detail === "string" ? data.detail : `Server returned ${res.status}`); + return data; } catch (err) { - setStatus(`Network error: ${err.message}`, "error"); + if (generation !== state.generation) return null; + if (err.name === "AbortError") throw new Error("Analysis timed out. Check your connection; the camera will retry."); + throw err; + } finally { + clearTimeout(timeout); + if (state.controller === controller) state.controller = null; } } -async function analyzeDirectFen(fen) { - if (!fen) return; - showWaiting("Evaluating position with Stockfish…"); +async function scanFrame() { + if (state.busy || state.locking || !state.source || state.source === "demo") { schedule(); return; } + const b64 = captureFrame(); + if (!b64) { schedule(250); return; } + const generation = state.generation, setupFen = state.setupFen; + state.busy = true; updateControls(); + const t0 = performance.now(); try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/api/analyze-fen`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - fen: fen, - player_color: playerColor, - depth: depth, - mode: playMode, - }), - }); - - const elapsed = Math.round(performance.now() - t0); - - if (!res.ok) { - const errData = await res.json().catch(() => ({})); - setStatus(`Error: ${errData.message || res.statusText}`, "error"); - return; + const data = await apiRequest("/api/analyze", { + image_b64: b64, player_color: state.player, orientation: state.orientation, + depth: state.depth, mode: state.mode, session_id: state.session, + ...(state.corners ? { board_corners: state.corners } : {}), + ...(setupFen ? { setup_fen: setupFen } : {}), + }, generation); + if (data) { + handleResponse(data, Math.round(performance.now() - t0)); + if (["ok", "no_change", "opponent_turn", "game_over"].includes(data.status) && state.setupFen === setupFen) state.setupFen = null; } - - const data = await res.json(); - handleResponse(data, elapsed); - } catch (err) { - setStatus(`Network error: ${err.message}`, "error"); + if (generation === state.generation) { clearMove("Connection interrupted. Retrying…"); setStatus(err.message, "error"); } + } finally { + if (generation === state.generation) { state.busy = false; updateControls(); schedule(); } } } -// ── Response Handler ────────────────────────────────────────────────────── -function handleResponse(data, elapsedMs) { +function handleResponse(data, elapsed) { + const hasPieces = data.pieces_detected !== false; + if (["w", "b"].includes(data.orientation)) state.resolvedOrientation = data.orientation; + if (!hasPieces) { + state.corners = null; + $("boardStatus").textContent = "Board found · add pieces"; + $("confBadge").hidden = true; + } + if (hasPieces && validCorners(data.board_corners)) { + state.corners = data.board_corners; + $("boardStatus").textContent = "Board locked"; + $("confBadge").textContent = `${Math.round((data.confidence || 0) * 100)}% confidence`; + $("confBadge").hidden = false; + } + if (data.fen && ["ok", "no_change", "opponent_turn", "game_over"].includes(data.status)) { + state.fen = data.fen; + $("customFenInput").value = data.fen; + $("turnSelect").value = data.turn || data.fen.split(" ")[1]; + } + if (data.engine) $("engineBadge").textContent = data.engine === "stockfish" ? "Stockfish" : "Basic engine"; switch (data.status) { - case "ok": - showMove(data.move_human, data.move_san, data.move_uci); - const confStr = data.confidence < 1.0 ? ` | Conf: ${pct(data.confidence)}` : ""; - setStatus(`Optimal move computed (${elapsedMs}ms)${confStr} • ≈${data.approx_elo} Elo`, "ok"); - if (data.board_image_b64) { - updateBoard(data.board_image_b64, data.confidence); - } - addRecentMove(data.move_san || data.move_uci); - break; - case "no_change": - setStatus("Board unchanged — waiting for opponent's move…", ""); + if (data.move_uci) { + state.move = data.move_uci; + $("moveWaiting").hidden = true; $("moveResult").hidden = false; + $("moveText").textContent = (data.move_human || `Play ${data.move_uci}`).replace(/^Move /, ""); + $("frameMoveLabel").textContent = $("moveText").textContent; + $("frameMoveLabel").hidden = !state.corners; + $("moveSan").textContent = data.move_san || data.move_uci; + $("moveUci").textContent = `${data.move_uci.slice(0, 2)} → ${data.move_uci.slice(2, 4)}`; + setStatus(`Your move · ${elapsed} ms${data.status === "no_change" ? " · Position unchanged" : ""}`, "ok"); + drawOverlay(); + } else if (data.status === "no_change" && state.move) setStatus("Position unchanged. Your suggested move is still shown.", "ok"); + else clearMove(data.message || "Waiting for a move suggestion."); break; - case "opponent_turn": - setStatus("Opponent's turn detected. Waiting for their move…", ""); - break; - - case "detection_error": - setStatus(`⚠ ${data.message}`, "error"); - showWaiting("Board not fully visible. Reposition camera overhead."); + clearMove("Opponent’s turn. Watching for their move…"); + setStatus("Board locked. The next suggestion appears after your opponent moves."); break; + case "setup_required": + clearMove(hasPieces ? "Board found. Set the current position to begin tracking." : "Board found. Put the pieces on the board to begin."); + setStatus(data.message || "Start from the normal starting position, or set the current position below."); + if (hasPieces) $("setupPanel").open = true; break; - - case "engine_error": - setStatus("⚙ Engine restarting… retrying automatically.", ""); - break; - - case "rate_limited": - setStatus("Slowing down analysis pace…", ""); - break; - case "game_over": - setStatus("Checkmate, stalemate, or game over.", "ok"); - showWaiting("Game over — no legal moves remaining."); - break; - + clearMove(data.message || "Game over. No legal moves remain."); setStatus(data.message || "Game over.", "ok"); break; + case "rate_limited": setStatus("Waiting briefly before the next scan."); break; + case "detection_error": + case "position_uncertain": + case "tracking_error": + case "tracking_lost": + if (!data.board_detected && !data.board_locked) { + state.corners = null; + $("boardStatus").textContent = "Looking for board"; + $("confBadge").hidden = true; + } + clearMove("Keep the board steady and your hands clear. Scanning again…"); + setStatus(data.message || "Could not read this frame. Scanning again…"); break; default: - setStatus(data.message ?? "Unknown response.", ""); + clearMove(data.message || "Could not analyze this position."); + setStatus(data.message || "Analysis failed. Check the position and try again.", "error"); } + updateControls(); drawOverlay(); } -function showMove(humanText, san, uci) { - moveWaiting.style.display = "none"; - moveResult.style.display = "block"; - moveText.textContent = humanText ?? "—"; - moveSan.textContent = san ?? uci ?? ""; - moveUci.textContent = uci ? `${uci.slice(0, 2)} → ${uci.slice(2, 4)}` : ""; - - moveResult.classList.remove("move-anim"); - void moveResult.offsetWidth; - moveResult.classList.add("move-anim"); -} - -function showWaiting(msg) { - moveWaiting.style.display = "flex"; - moveResult.style.display = "none"; - if (msg) waitText.textContent = msg; +function drawOverlay() { + const svg = $("moveOverlay"); svg.replaceChildren(); + svg.setAttribute("aria-label", "Detected board alignment"); + const ns = "http://www.w3.org/2000/svg"; + const add = (name, attrs, parent = svg) => { + const node = document.createElementNS(ns, name); + Object.entries(attrs).forEach(([key, val]) => node.setAttribute(key, val)); + parent.appendChild(node); return node; + }; + const points = arr => arr.map(([x, y]) => `${x * 1000},${y * 1000}`).join(" "); + if (state.locking) { + state.manualCorners.forEach(([x, y], i) => { + add("circle", { cx: x * 1000, cy: y * 1000, r: 16, fill: "#c3f578", stroke: "#17392d", "stroke-width": 4 }); + const text = add("text", { x: x * 1000, y: y * 1000 + 5, "text-anchor": "middle", fill: "#17392d", "font-size": 17 }); + text.textContent = i + 1; + }); return; + } + if (!state.corners) return; + add("polygon", { points: points(state.corners), fill: "none", stroke: "#c3f578", "stroke-width": 3, "stroke-linejoin": "round", opacity: .85 }); + state.corners.forEach(([x, y]) => add("circle", { cx: x * 1000, cy: y * 1000, r: 6, fill: "#c3f578" })); + if (!state.move) return; + const geometry = moveGeometry(state.move, state.corners, state.resolvedOrientation); + if (!geometry) return; + const defs = add("defs", {}); + const marker = add("marker", { id: "moveArrow", viewBox: "0 0 10 10", refX: 8, refY: 5, markerWidth: 3.4, markerHeight: 3.4, orient: "auto-start-reverse" }, defs); + add("path", { d: "M 0 0 L 10 5 L 0 10 z", fill: "#c3f578" }, marker); + add("polygon", { points: points(geometry.target), fill: "#c3f578", "fill-opacity": .28, stroke: "#c3f578", "stroke-width": 3 }); + const [fx, fy] = geometry.from.map(v => v * 1000), [tx, ty] = geometry.to.map(v => v * 1000); + add("line", { x1: fx, y1: fy, x2: tx, y2: ty, stroke: "#17392d", "stroke-opacity": .85, "stroke-width": 19, "stroke-linecap": "round" }); + add("line", { x1: fx, y1: fy, x2: tx, y2: ty, stroke: "#c3f578", "stroke-width": 11, "stroke-linecap": "round", "marker-end": "url(#moveArrow)" }); + add("circle", { cx: fx, cy: fy, r: 13, fill: "#c3f578", stroke: "#17392d", "stroke-width": 4 }); + svg.setAttribute("aria-label", `Suggested move from ${state.move.slice(0, 2)} to ${state.move.slice(2, 4)}`); } -function setStatus(msg, type = "") { - statusMsg.textContent = msg; - statusBar.className = "status-bar" + (type ? ` ${type}` : ""); +async function uploadPhoto(file) { + if (!file) return; + if (!file.type.startsWith("image/") || file.size > 10 * 1024 * 1024) { setStatus("Choose an image smaller than 10 MB.", "error"); return; } + stopCamera({ clear: false }); resetTracking(); + state.source = null; + const attempt = state.cameraAttempt, url = URL.createObjectURL(file), img = $("photoPreview"); + try { + img.src = url; await img.decode(); + if (attempt !== state.cameraAttempt) return; + cancelRequest(); + state.source = "photo"; img.hidden = false; $("cameraOverlay").hidden = true; + setStatus("Reading your board photo…"); updateControls(); await scanFrame(); + } catch { if (attempt === state.cameraAttempt) setStatus("Could not open this image. Try a JPEG or PNG.", "error"); } + finally { URL.revokeObjectURL(url); $("fileInput").value = ""; } } -function updateBoard(b64, confidence) { - if (!b64) return; - boardCard.style.display = "block"; - boardImg.src = `data:image/png;base64,${b64}`; - confBadge.textContent = pct(confidence); +function beginManualLock() { + if (!state.source || state.source === "demo") return; + cancelRequest(); state.locking = true; state.manualCorners = []; + clearMove("Set the four board corners to align the move arrow."); + setStatus("Tap the board’s top-left, top-right, bottom-right, then bottom-left corner."); + $("boardStatus").textContent = "Tap corner 1 of 4"; + drawOverlay(); updateControls(); } -function addRecentMove(san) { - if (!san) return; - if (!recentMoves.includes(san)) { - recentMoves.unshift(san); - if (recentMoves.length > 5) recentMoves.pop(); +$("cameraFrame").addEventListener("click", event => { + if (!state.locking) return; + const rect = $("cameraFrame").getBoundingClientRect(); + state.manualCorners.push([(event.clientX - rect.left) / rect.width, (event.clientY - rect.top) / rect.height]); + if (state.manualCorners.length === 4) { + if (!validCorners(state.manualCorners)) { state.manualCorners = []; setStatus("Those corners crossed. Tap top-left, top-right, bottom-right, bottom-left.", "error"); } + else { + state.corners = state.manualCorners; state.locking = false; + $("boardStatus").textContent = "Board locked"; setStatus("Board corners set. Reading the position…"); scanFrame(); + } + } + if (state.locking) $("boardStatus").textContent = `Tap corner ${state.manualCorners.length + 1} of 4`; + drawOverlay(); updateControls(); +}); - recentContainer.style.display = "flex"; - recentPills.innerHTML = recentMoves.map(m => `${m}`).join(""); +function drawDemoBoard(fen) { + const canvas = document.createElement("canvas"); canvas.width = canvas.height = 720; + const ctx = canvas.getContext("2d"), sq = 90; + const symbols = { p: "♟", r: "♜", n: "♞", b: "♝", q: "♛", k: "♚", P: "♙", R: "♖", N: "♘", B: "♗", Q: "♕", K: "♔" }; + const rows = fen.split(" ")[0].split("/"); + for (let row = 0; row < 8; row++) for (let col = 0; col < 8; col++) { + ctx.fillStyle = (row + col) % 2 ? "#779581" : "#e6edde"; ctx.fillRect(col * sq, row * sq, sq, sq); } + ctx.font = "70px Georgia, serif"; ctx.textAlign = "center"; ctx.textBaseline = "middle"; + rows.forEach((rank, row) => { + let col = 0; + for (const cell of rank) { + if (/^[1-8]$/.test(cell)) { col += Number(cell); continue; } + if (symbols[cell] && col < 8) { + const r = state.resolvedOrientation === "b" ? 7 - row : row, c = state.resolvedOrientation === "b" ? 7 - col : col; + ctx.fillStyle = cell === cell.toUpperCase() ? "#fffdf2" : "#19372c"; ctx.strokeStyle = "#19372c"; ctx.lineWidth = 1.5; + ctx.strokeText(symbols[cell], (c + .5) * sq, (r + .53) * sq); ctx.fillText(symbols[cell], (c + .5) * sq, (r + .53) * sq); + } col++; + } + }); + $("photoPreview").src = canvas.toDataURL(); $("photoPreview").hidden = false; $("cameraOverlay").hidden = true; + state.corners = [[0, 0], [1, 0], [1, 1], [0, 1]]; + $("boardStatus").textContent = "Example board"; $("confBadge").textContent = "Demo position"; $("confBadge").hidden = false; } -function pct(val) { - return val != null ? `${Math.round(val * 100)}%` : "—"; +async function analyzeFen(fen) { + if (!fen) return; + stopCamera({ clear: false }); resetTracking(); state.source = "demo"; state.busy = true; + clearMove("Calculating your next move…"); updateControls(); + const generation = state.generation, t0 = performance.now(); + try { + const data = await apiRequest("/api/analyze-fen", { fen, depth: state.depth, mode: state.mode }, generation); + if (data) { + if (["ok", "game_over"].includes(data.status)) drawDemoBoard(fen); + handleResponse(data, Math.round(performance.now() - t0)); + } + } catch (err) { if (generation === state.generation) setStatus(err.message, "error"); } + finally { if (generation === state.generation) { state.busy = false; updateControls(); } } } -function updateModeInfo() { - const modes = { - win: { - icon: "🏆", - title: "Win Mode", - desc: "Calculates sharp, decisive, high-accuracy moves tailored to win quickly.", - }, - loss: { - icon: "🎭", - title: "Loss Mode", - desc: "Provides believable, human-like inaccuracies without obvious tactical blunders.", - }, - }; - const m = modes[playMode] || modes.win; - modeInfo.innerHTML = ` - ${m.icon} -
- ${m.title} -

${m.desc}

-
`; +function setPosition(fen) { + const fields = fen.trim().split(/\s+/); + if (fields.length !== 6 || !/^[wb]$/.test(fields[1])) { setStatus("Enter a complete FEN with six fields, or use the starting position.", "error"); return; } + fields[1] = $("turnSelect").value; + if (state.source && state.source !== "demo") { + resetTracking({ keepCorners: true }); state.setupFen = fields.join(" "); + clearMove("Checking the supplied position against the board…"); scanFrame(); + } else analyzeFen(fields.join(" ")); } -// ── Health Check & Engine Status ────────────────────────────────────────── -async function checkBackendHealth() { - setEngineStatus("connecting", "Connecting…"); +async function checkHealth(base = apiBase, label = $("engineStatus").querySelector(".status-label")) { + const mainLabel = label === $("engineStatus").querySelector(".status-label"); + const displayLabel = text => { if (!mainLabel || base === apiBase) label.textContent = text; }; + displayLabel("Connecting…"); try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/health`, { signal: AbortSignal.timeout(5000) }); - const latency = Math.round(performance.now() - t0); - if (res.ok) { - const data = await res.json().catch(() => ({})); - const engineName = data.engine === "stockfish" ? "Stockfish 16" : "Python Engine"; - setEngineStatus("online", `Online (${latency}ms)`); - if (engineBadge) engineBadge.textContent = engineName; - } else { - setEngineStatus("offline", `Server Error (${res.status})`); - } + const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(6000) }); + if (!res.ok) throw new Error(`Server returned ${res.status}`); + const data = await res.json(); if (data.status !== "ok") throw new Error("Engine is not ready"); + displayLabel(data.engine === "stockfish" ? "Engine online" : "Basic engine online"); + if (base === apiBase) { $("engineStatus").className = "status-pill online"; $("engineBadge").textContent = data.engine === "stockfish" ? "Stockfish" : "Basic engine"; } + return true; } catch { - setEngineStatus("offline", "Backend Offline"); + displayLabel("Engine offline"); if (base === apiBase) $("engineStatus").className = "status-pill offline"; return false; } } -function setEngineStatus(cls, label) { - engineStatus.className = `status-pill ${cls}`; - engineStatus.querySelector(".status-label").textContent = label; - engineStatus.title = `API: ${API_BASE} (Click to configure)`; +function openApiSettings() { + $("apiUrlInput").value = apiBase; $("modalPingStatus").textContent = "Use your Railway backend or a local server."; $("apiModal").showModal(); } - -// ── API Configuration Modal ─────────────────────────────────────────────── -function initModal() { - engineStatus.addEventListener("click", openApiModal); - if (btnConfigApi) btnConfigApi.addEventListener("click", openApiModal); - - btnTestPing.addEventListener("click", async () => { - const targetUrl = apiUrlInput.value.trim().replace(/\/+$/, ""); - modalPingStatus.textContent = "Testing connection…"; - try { - const t0 = performance.now(); - const res = await fetch(`${targetUrl}/health`, { signal: AbortSignal.timeout(5000) }); - const ms = Math.round(performance.now() - t0); - if (res.ok) { - modalPingStatus.textContent = `✓ Connected! Response in ${ms}ms`; - modalPingStatus.style.color = "var(--accent)"; - } else { - modalPingStatus.textContent = `✗ HTTP Error ${res.status}`; - modalPingStatus.style.color = "var(--danger)"; - } - } catch (e) { - modalPingStatus.textContent = `✗ Unreachable: ${e.message}`; - modalPingStatus.style.color = "var(--danger)"; - } - }); - - btnResetApiDefault.addEventListener("click", () => { - apiUrlInput.value = DEFAULT_API_BASE; - }); - - btnSaveApi.addEventListener("click", () => { - const val = apiUrlInput.value.trim().replace(/\/+$/, ""); - if (val) { - API_BASE = val; - localStorage.setItem("chess_api_base", API_BASE); - apiModal.close(); - checkBackendHealth(); - } - }); -} - -function openApiModal() { - apiUrlInput.value = API_BASE; - modalPingStatus.textContent = "Click 'Test Connection' to verify server reachability."; - modalPingStatus.style.color = "var(--text-dim)"; - apiModal.showModal(); +function refreshAnalysis(message) { + cancelRequest(); clearMove(message); + if (state.source === "demo" && state.fen) analyzeFen(state.fen); + else if (state.source) scanFrame(); } -async function quickHash(str) { - if (!crypto?.subtle) return str.slice(0, 64); - const buf = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(str)); - return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join(""); +$("btnStart").addEventListener("click", startCamera); +$("btnStop").addEventListener("click", () => stopCamera()); +$("btnSwitchCamera").addEventListener("click", () => { + state.facing = state.facing === "environment" ? "user" : "environment"; + if (state.running) { stopCamera({ clear: false }); startCamera(); } + else setStatus(`The ${state.facing === "environment" ? "rear" : "front"} camera will open next.`); +}); +$("btnUploadPhoto").addEventListener("click", () => $("fileInput").click()); +$("fileInput").addEventListener("change", e => uploadPhoto(e.target.files[0])); +$("btnLockBoard").addEventListener("click", beginManualLock); +$("btnUnlockBoard").addEventListener("click", () => { resetTracking(); if (state.source && state.source !== "demo") scanFrame(); }); +$("btnDemo").addEventListener("click", () => analyzeFen(STARTING_FEN)); +$("btnAnalyzeFen").addEventListener("click", () => analyzeFen($("customFenInput").value.trim())); +$("btnSetPosition").addEventListener("click", () => setPosition($("customFenInput").value)); +$("btnResetPosition").addEventListener("click", () => { $("turnSelect").value = "w"; $("customFenInput").value = STARTING_FEN; setPosition(STARTING_FEN); }); +$("orientationSelect").addEventListener("change", () => { + state.orientation = $("orientationSelect").value; + state.resolvedOrientation = state.orientation === "b" ? "b" : "w"; + if (state.source === "demo" && state.fen) { drawDemoBoard(state.fen); drawOverlay(); } + else { resetTracking(); if (state.source) scanFrame(); } +}); +for (const [id, property, message] of [["colorToggle", "player", "Updating your playing color…"], ["modeToggle", "mode", "Updating analysis…"]]) { + $(id).querySelectorAll("button").forEach(button => button.addEventListener("click", () => { + state[property] = button.dataset.val; + $(id).querySelectorAll("button").forEach(b => { b.classList.toggle("active", b === button); b.setAttribute("aria-pressed", String(b === button)); }); + refreshAnalysis(message); + })); } +$("depthSlider").addEventListener("input", () => { + state.depth = Number($("depthSlider").value); $("depthVal").textContent = state.depth; + $("eloHint").textContent = state.depth <= 6 ? "Quick" : state.depth <= 11 ? "Balanced" : "Deeper"; +}); +$("depthSlider").addEventListener("change", () => refreshAnalysis("Updating analysis depth…")); +$("engineStatus").addEventListener("click", openApiSettings); +$("btnConfigApi").addEventListener("click", openApiSettings); +$("btnCloseApi").addEventListener("click", () => $("apiModal").close()); +$("btnResetApiDefault").addEventListener("click", () => { $("apiUrlInput").value = resolveApiBase({ origin: location.origin, fallback: DEFAULT_API }); }); +$("btnTestPing").addEventListener("click", async () => { + try { await checkHealth(resolveApiBase({ origin: location.origin, stored: $("apiUrlInput").value, fallback: DEFAULT_API }), $("modalPingStatus")); } + catch (err) { $("modalPingStatus").textContent = err.message; } +}); +$("btnSaveApi").addEventListener("click", () => { + try { + apiBase = resolveApiBase({ origin: location.origin, stored: $("apiUrlInput").value.trim(), fallback: DEFAULT_API }); + localStorage.setItem("chess_api_base", apiBase); + state.session = crypto.randomUUID(); + if (state.source && state.source !== "demo") state.setupFen = state.fen; + $("apiModal").close(); checkHealth(); refreshAnalysis("Connecting to the selected engine…"); + } catch (err) { $("modalPingStatus").textContent = err.message; } +}); +window.addEventListener("pagehide", () => stopCamera({ clear: false })); +document.addEventListener("visibilitychange", () => { + if (document.hidden && state.running) { cancelRequest(); clearMove("Camera analysis paused while this tab is hidden."); } + else if (state.running) schedule(0); +}); +clearMove(); updateControls(); checkHealth(); diff --git a/frontend/index.html b/frontend/index.html index 7466703..8ec61e3 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,246 +2,94 @@ - - - - Chess Vision Coach • AI Move Suggester - - - + + + + + Chess Vision — Your next move, in focus - -
-
- -
- -
-
-
+ + +
+ ChessVisionTHE CAMERA CHESS COACH + +
-
- - -
- - -
-
- - - -
-
- - -
-
- Camera Feed - -
-
- +

A LITTLE CLARITY. A BETTER MOVE.

Your next move, in focus.

Point your camera at the board.
Follow the move, right where you play.

+
+
+

Your board

1:1 CAMERA VIEW
+
+ + + +
- 📷 - Point camera overhead at your physical board - Click "Start Analysis" below or switch to "Quick Test" to try without camera -
-
-
- - - - - - - - - - -
- - -
- - -
-
Player Setup
- - -
- -
- - -
-
- - -
- -
- - -
-
- - -
-
- - ≈ 1900 Elo* + +

Your board, in focus

Keep the full board in view.
We’ll lock it and find your next move.

START WITH THE PIECES IN THEIR STARTING POSITION
-
- - 10 +
Camera off
+
+
+ + + +
+
+
Board alignment
+

An overhead view works best. Keep hands clear while the board is being read.

+
+ +
- - - - - + + - + - - + diff --git a/frontend/overlay.js b/frontend/overlay.js new file mode 100644 index 0000000..923a7fe --- /dev/null +++ b/frontend/overlay.js @@ -0,0 +1,64 @@ +/** Geometry shared by the camera overlay and its regression tests. */ +export function fitInside(width, height, size = 1000) { + const w = width >= height ? size : size * width / height; + const h = height >= width ? size : size * height / width; + return { x: (size - w) / 2, y: (size - h) / 2, width: w, height: h }; +} + +// Project unit board coordinates into the actual camera quadrilateral. A +// bilinear interpolation is insufficient for a tilted/perspective board. +export function projectPoint(corners, x, y) { + const [[x0, y0], [x1, y1], [x2, y2], [x3, y3]] = corners; + const dx1 = x1 - x2, dx2 = x3 - x2, dx3 = x0 - x1 + x2 - x3; + const dy1 = y1 - y2, dy2 = y3 - y2, dy3 = y0 - y1 + y2 - y3; + const det = dx1 * dy2 - dx2 * dy1; + let g = 0, h = 0; + if (Math.abs(dx3) + Math.abs(dy3) > 1e-10 && Math.abs(det) > 1e-10) { + g = (dx3 * dy2 - dx2 * dy3) / det; + h = (dx1 * dy3 - dx3 * dy1) / det; + } + const a = x1 - x0 + g * x1, b = x3 - x0 + h * x3; + const d = y1 - y0 + g * y1, e = y3 - y0 + h * y3; + const denominator = g * x + h * y + 1; + return [(a * x + b * y + x0) / denominator, (d * x + e * y + y0) / denominator]; +} + +export function squarePosition(square, orientation = "w") { + if (!/^[a-h][1-8]$/.test(square)) throw new Error("Invalid chess square"); + const col = square.charCodeAt(0) - 97, row = 8 - Number(square[1]); + return orientation === "b" ? [7 - col, 7 - row] : [col, row]; +} + +export function moveGeometry(uci, corners, orientation = "w") { + if (!/^[a-h][1-8][a-h][1-8][qrbn]?$/.test(uci)) return null; + const from = squarePosition(uci.slice(0, 2), orientation); + const to = squarePosition(uci.slice(2, 4), orientation); + const point = (x, y) => projectPoint(corners, x / 8, y / 8); + return { + from: point(from[0] + .5, from[1] + .5), + to: point(to[0] + .5, to[1] + .5), + target: [[0, 0], [1, 0], [1, 1], [0, 1]].map(([x, y]) => point(to[0] + x, to[1] + y)), + }; +} + +export function validCorners(corners) { + if (!Array.isArray(corners) || corners.length !== 4 || !corners.every(p => + Array.isArray(p) && p.length === 2 && p.every(v => Number.isFinite(v) && v >= 0 && v <= 1))) return false; + const crosses = corners.map((p, i) => { + const q = corners[(i + 1) % 4], r = corners[(i + 2) % 4]; + return (q[0] - p[0]) * (r[1] - q[1]) - (q[1] - p[1]) * (r[0] - q[0]); + }); + return crosses.every(v => v > .0001); +} + +export function resolveApiBase({ origin, search = "", stored = "", fallback }) { + const override = new URLSearchParams(search).get("api") || stored; + if (override) { + const url = new URL(override); + if (!["http:", "https:"].includes(url.protocol)) throw new Error("Use an HTTP or HTTPS server URL"); + return url.origin; + } + // Railway serves both the app and API: it must use its own deployment. + if (/\.up\.railway\.app$/.test(new URL(origin).hostname) || /^(localhost|127\.0\.0\.1)$/.test(new URL(origin).hostname)) return origin; + return fallback; +} diff --git a/frontend/style.css b/frontend/style.css index 9603e67..0c744c4 100644 --- a/frontend/style.css +++ b/frontend/style.css @@ -1,957 +1,232 @@ -/* ═══════════════════════════════════════════════════════════ - Chess Vision Coach — Stylesheet v2.0 - Modern Dark Theme with Cyber-Emerald & Amber Accents - ═══════════════════════════════════════════════════════════ */ - -*, *::before, *::after { - box-sizing: border-box; - margin: 0; - padding: 0; -} - -:root { - color-scheme: light dark; - --bg-deep: #090b0e; - --bg-card: #12161f; - --bg-card2: #1a202c; - --bg-card-hover: #222938; - --border-subtle: rgba(255, 255, 255, 0.08); - --border-focus: rgba(16, 185, 129, 0.5); - - --accent: #10b981; - --accent-light: #34d399; - --accent-glow: rgba(16, 185, 129, 0.25); - - --accent2: #f59e0b; - --accent2-glow: rgba(245, 158, 11, 0.2); - - --primary: #6366f1; - --danger: #ef4444; - --text: #f9fafb; - --text-dim: #9ca3af; - --text-muted: #6b7280; - - --radius-lg: 14px; - --radius-md: 10px; - --radius-sm: 6px; - --gap: 16px; - - accent-color: var(--accent); - scrollbar-color: var(--bg-card2) transparent; -} - -html { - font-size: 16px; - scroll-behavior: smooth; -} - -body { - font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; - background: var(--bg-deep); - background-image: - radial-gradient(circle at 15% 15%, rgba(16, 185, 129, 0.05) 0%, transparent 40%), - radial-gradient(circle at 85% 85%, rgba(99, 102, 241, 0.04) 0%, transparent 40%); - background-attachment: fixed; - color: var(--text); - min-height: 100dvh; - display: flex; - flex-direction: column; - line-height: 1.5; -} - -/* ── Accessibility ───────────────────────────────── */ -.visually-hidden { - position: absolute !important; - clip-path: inset(50%) !important; - overflow: hidden !important; - width: 1px !important; - height: 1px !important; - margin: -1px !important; - padding: 0 !important; - border: 0 !important; - white-space: nowrap !important; -} - -:focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; -} - -/* ── Header ─────────────────────────────────────── */ -.header { - background: rgba(18, 22, 31, 0.85); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border-bottom: 1px solid var(--border-subtle); - padding: 0 24px; - height: 64px; - position: sticky; - top: 0; - z-index: 100; -} - -.header-inner { - max-width: 1140px; - margin: 0 auto; - height: 100%; - display: flex; - align-items: center; - justify-content: space-between; -} - -.logo { - display: flex; - align-items: center; - gap: 12px; -} - -.logo-icon { - font-size: 1.8rem; - line-height: 1; - filter: drop-shadow(0 0 8px var(--accent-glow)); -} - -.logo-titles { - display: flex; - flex-direction: column; -} - -.logo-text { - font-weight: 700; - font-size: 1.15rem; - letter-spacing: -0.02em; - color: var(--text); -} - -.logo-badge { - font-size: 0.68rem; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--accent); -} - -/* Status Pill */ -.status-pill { - display: flex; - align-items: center; - gap: 8px; - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: 999px; - padding: 6px 16px; - font-size: 0.82rem; - font-family: inherit; - color: var(--text-dim); - cursor: pointer; - transition: all 0.2s ease; -} - -.status-pill:hover { - border-color: var(--accent); - background: var(--bg-card-hover); -} - -.status-dot { - width: 9px; - height: 9px; - border-radius: 50%; - background: #6b7280; - transition: all 0.3s ease; -} - -.status-pill.online .status-dot { - background: var(--accent); - box-shadow: 0 0 10px var(--accent); -} -.status-pill.online .status-label { - color: var(--accent-light); - font-weight: 600; -} - -.status-pill.offline .status-dot { - background: var(--danger); - box-shadow: 0 0 8px rgba(239, 68, 68, 0.4); -} -.status-pill.offline .status-label { - color: var(--danger); -} - -.status-pill.connecting .status-dot { - background: var(--accent2); - animation: pulse 1s infinite alternate; -} - -/* ── Main Layout ────────────────────────────────── */ -.main { - flex: 1; - max-width: 1140px; - width: 100%; - margin: 0 auto; - padding: var(--gap); - display: grid; - grid-template-columns: 1.05fr 0.95fr; - gap: var(--gap); - align-items: start; -} - -@media (max-width: 820px) { - .main { - grid-template-columns: 1fr; - padding: 12px; - } -} - -.col { - display: flex; - flex-direction: column; - gap: var(--gap); -} - -/* ── Universal Cards ────────────────────────────── */ -.card { - background: var(--bg-card); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-lg); - padding: 20px; - box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); - transition: border-color 0.2s ease; -} - -.card:hover { - border-color: rgba(255, 255, 255, 0.12); -} - -.card-label { - font-size: 0.74rem; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; - color: var(--text-dim); - margin-bottom: 14px; - display: flex; - align-items: center; - justify-content: space-between; -} - -/* ── Input Mode Tabs ────────────────────────────── */ -.mode-tabs-card { - padding: 8px; -} - -.tab-group { - display: flex; - gap: 6px; - background: var(--bg-deep); - padding: 4px; - border-radius: var(--radius-md); -} - -.tab-btn { - flex: 1; - display: flex; - align-items: center; - justify-content: center; - gap: 6px; - background: transparent; - border: none; - border-radius: var(--radius-sm); - color: var(--text-dim); - font-family: inherit; - font-size: 0.85rem; - font-weight: 600; - padding: 10px 8px; - cursor: pointer; - transition: all 0.2s ease; -} - -.tab-btn:hover { - color: var(--text); - background: rgba(255, 255, 255, 0.04); -} - -.tab-btn.active { - background: var(--bg-card2); - color: var(--accent); - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); -} - -/* ── Camera Card ────────────────────────────────── */ -.camera-wrapper { - position: relative; - background: #000; - border-radius: var(--radius-md); - overflow: hidden; - aspect-ratio: 4 / 3; - box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.8); -} - -#cameraFeed { - width: 100%; - height: 100%; - object-fit: cover; - display: block; -} - -.live-indicator { - font-size: 0.68rem; - font-weight: 700; - color: #ef4444; - letter-spacing: 0.05em; - animation: pulse 1s infinite alternate; -} - -.camera-overlay { - position: absolute; - inset: 0; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - text-align: center; - padding: 24px; - background: rgba(10, 14, 20, 0.88); - color: var(--text); - transition: opacity 0.3s; -} - -.camera-overlay.hidden { - opacity: 0; - pointer-events: none; -} - -.overlay-icon { - font-size: 2.8rem; - margin-bottom: 8px; - color: var(--accent); -} - -.overlay-title { - font-size: 1rem; - font-weight: 600; - margin-bottom: 4px; -} - -.overlay-sub { - font-size: 0.82rem; - color: var(--text-dim); - max-width: 320px; -} - -/* ── Drag & Drop Photo Upload ───────────────────── */ -.upload-dropzone { - border: 2px dashed rgba(255, 255, 255, 0.15); - border-radius: var(--radius-md); - padding: 36px 20px; - text-align: center; - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; - cursor: pointer; - background: var(--bg-deep); - transition: all 0.2s ease; -} - -.upload-dropzone:hover, -.upload-dropzone.dragover { - border-color: var(--accent); - background: rgba(16, 185, 129, 0.04); -} - -.upload-icon { - font-size: 2.4rem; - color: var(--accent); -} - -.upload-text { - font-size: 0.92rem; - color: var(--text); -} - -.upload-link { - color: var(--accent); - text-decoration: underline; - cursor: pointer; -} - -.upload-hint { - font-size: 0.75rem; - color: var(--text-muted); -} - -/* ── Presets & Quick Test ───────────────────────── */ -.presets-intro { - font-size: 0.84rem; - color: var(--text-dim); - margin-bottom: 12px; -} - -.preset-buttons { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 8px; - margin-bottom: 16px; -} - -@media (max-width: 500px) { - .preset-buttons { - grid-template-columns: 1fr; - } -} - -.preset-chip { - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: inherit; - font-size: 0.82rem; - font-weight: 600; - padding: 10px 12px; - text-align: left; - cursor: pointer; - transition: all 0.2s ease; -} - -.preset-chip:hover { - border-color: var(--accent); - background: var(--bg-card-hover); -} - -.preset-chip.active { - border-color: var(--accent); - background: rgba(16, 185, 129, 0.12); - color: var(--accent-light); -} - -.custom-fen-row { - display: flex; - gap: 8px; -} - -.custom-fen-input { - flex: 1; - background: var(--bg-deep); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: 'Space Mono', monospace; - font-size: 0.8rem; - padding: 10px 12px; - outline: none; - transition: border-color 0.2s; -} - -.custom-fen-input:focus { - border-color: var(--accent); -} - -/* ── Board preview card ─────────────────────────── */ -.board-wrapper { - border-radius: var(--radius-md); - overflow: hidden; - background: #000; - border: 1px solid var(--border-subtle); -} - -.board-wrapper img { - width: 100%; - display: block; -} - -.conf-badge { - font-size: 0.75rem; - background: var(--bg-card2); - border: 1px solid rgba(16, 185, 129, 0.3); - border-radius: 999px; - padding: 3px 10px; - color: var(--accent-light); - font-family: 'Space Mono', monospace; - font-weight: 700; -} - -/* ── Config card ────────────────────────────────── */ -.control-group { - margin-bottom: 20px; -} - -.ctrl-label { - display: flex; - align-items: center; - justify-content: space-between; - font-size: 0.84rem; - font-weight: 600; - color: var(--text-dim); - margin-bottom: 8px; -} - -.elo-hint { - font-family: 'Space Mono', monospace; - font-size: 0.82rem; - color: var(--accent2); - font-weight: 700; -} - -/* Toggle buttons */ -.toggle-group { - display: flex; - gap: 8px; -} - -.toggle-btn { - flex: 1; - background: var(--bg-card2); - border: 1.5px solid var(--border-subtle); - border-radius: var(--radius-md); - color: var(--text-dim); - font-family: inherit; - font-size: 0.88rem; - font-weight: 600; - padding: 10px 8px; - cursor: pointer; - transition: all 0.15s ease; - display: flex; - align-items: center; - justify-content: center; - gap: 8px; -} - -.toggle-btn:hover { - border-color: rgba(255, 255, 255, 0.2); - color: var(--text); -} - -.toggle-btn.active { - background: var(--accent); - border-color: var(--accent); - color: #062b1a; - font-weight: 700; - box-shadow: 0 2px 12px var(--accent-glow); -} - -.piece-icon { - font-size: 1.2rem; -} - -/* Depth slider */ -.depth-row { - display: flex; - align-items: center; - gap: 14px; -} - -input[type="range"] { - flex: 1; - -webkit-appearance: none; - appearance: none; - height: 6px; - border-radius: 3px; - background: var(--bg-card2); - outline: none; -} - -input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 20px; - height: 20px; - border-radius: 50%; - background: var(--accent); - cursor: pointer; - box-shadow: 0 0 10px var(--accent-glow); - transition: transform 0.1s; -} - -input[type="range"]::-webkit-slider-thumb:hover { - transform: scale(1.15); -} - -.depth-val { - font-family: 'Space Mono', monospace; - font-size: 1.2rem; - font-weight: 700; - color: var(--accent2); - min-width: 28px; - text-align: right; -} - -.elo-note { - font-size: 0.72rem; - color: var(--text-muted); - margin-top: 6px; -} - -/* Action Buttons */ -.btn-row { - display: flex; - gap: 10px; - margin-top: 8px; -} - -.btn { - font-family: inherit; - font-size: 0.92rem; - font-weight: 700; - padding: 12px 18px; - border-radius: var(--radius-md); - border: none; - cursor: pointer; - transition: all 0.15s ease; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 6px; -} - -.btn-start { - flex: 1.4; - background: var(--accent); - color: #062b1a; - box-shadow: 0 4px 14px var(--accent-glow); -} - -.btn-start:hover:not(:disabled) { - background: var(--accent-light); - transform: translateY(-1px); -} - -.btn-stop { - flex: 1; - background: var(--bg-card2); - color: var(--danger); - border: 1.5px solid var(--danger); -} - -.btn-stop:hover:not(:disabled) { - background: var(--danger); - color: #fff; -} - -.btn-secondary { - background: var(--bg-card2); - color: var(--text); - border: 1px solid var(--border-subtle); - font-size: 0.85rem; -} - -.btn-secondary:hover { - background: var(--bg-card-hover); - border-color: rgba(255, 255, 255, 0.2); -} - -.btn:disabled { - opacity: 0.35; - cursor: not-allowed; - transform: none !important; -} - -/* ── Move Output Card ───────────────────────────── */ -.move-card { - position: relative; - overflow: hidden; -} - -.engine-badge { - font-family: 'Space Mono', monospace; - font-size: 0.7rem; - font-weight: 700; - color: var(--text-dim); - background: var(--bg-card2); - padding: 3px 10px; - border-radius: 999px; - border: 1px solid var(--border-subtle); -} - -.move-display { - background: linear-gradient(145deg, var(--bg-card2), var(--bg-deep)); - border-radius: var(--radius-md); - padding: 24px 20px; - min-height: 128px; - display: flex; - align-items: center; - justify-content: center; - margin-bottom: 14px; - border: 1.5px solid rgba(255, 255, 255, 0.06); - position: relative; -} - -.move-waiting { - display: flex; - flex-direction: column; - align-items: center; - gap: 10px; - color: var(--text-dim); - font-size: 0.9rem; - text-align: center; -} - -.wait-icon { - font-size: 2rem; - animation: pulse 1.5s infinite alternate; -} - -.move-result { - text-align: center; - width: 100%; -} - -.move-header { - display: flex; - align-items: center; - justify-content: center; - gap: 12px; - margin-bottom: 8px; -} - -.move-san { - font-family: 'Space Mono', monospace; - font-size: 1.7rem; - color: var(--accent); - font-weight: 700; - letter-spacing: 0.05em; - text-shadow: 0 0 16px var(--accent-glow); -} - -.move-uci-badge { - font-family: 'Space Mono', monospace; - font-size: 0.85rem; - font-weight: 700; - color: var(--accent2); - background: var(--bg-deep); - padding: 4px 10px; - border-radius: 999px; - border: 1px solid var(--border-subtle); -} - -.move-text { - font-size: 1.35rem; - font-weight: 700; - color: var(--text); - line-height: 1.3; - letter-spacing: -0.01em; -} - -/* Recent Suggestions Trail */ -.recent-moves-container { - margin-bottom: 14px; - display: flex; - align-items: center; - gap: 10px; -} - -.recent-label { - font-size: 0.74rem; - font-weight: 700; - text-transform: uppercase; - color: var(--text-muted); -} - -.recent-pills { - display: flex; - gap: 6px; - flex-wrap: wrap; -} - -.recent-chip { - font-family: 'Space Mono', monospace; - font-size: 0.78rem; - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: 999px; - padding: 2px 10px; - color: var(--text-dim); -} - -/* Status Bar */ -.status-bar { - background: var(--bg-card2); - border-radius: var(--radius-sm); - padding: 10px 14px; - font-size: 0.82rem; - color: var(--text-dim); - min-height: 40px; - display: flex; - align-items: center; - gap: 8px; - border: 1px solid var(--border-subtle); -} - -.status-indicator-dot { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--text-muted); - flex-shrink: 0; -} - +*, *::before, *::after { box-sizing: border-box; } +:root { color-scheme: light; --bg: #f4f5f0; --paper: #fff; --ink: #1e302c; --muted: #68756e; --line: #e3e8e0; --green: #245b49; --green-hover: #194634; --mint: #e7f0df; --lime: #d9efb4; --danger: #ab3e36; --radius: 20px; accent-color: var(--green); } +html { scroll-behavior: smooth; } +body { margin: 0; background: var(--bg); color: var(--ink); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; font-size: 14px; line-height: 1.5; min-width: 280px; -webkit-font-smoothing: antialiased; } +button, input, select, textarea { font: inherit; } +button, a, input, select, textarea { -webkit-tap-highlight-color: transparent; } +button { cursor: pointer; } +button:disabled { opacity: .4; cursor: not-allowed; } +a { color: inherit; } +h1, h2, h3, p { margin: 0; } +button, a { touch-action: manipulation; } +:focus-visible { outline: 3px solid #8abd67; outline-offset: 4px; } +[hidden] { display: none !important; } +.visually-hidden { position: absolute !important; width: 1px !important; height: 1px !important; padding: 0 !important; margin: -1px !important; overflow: hidden !important; clip: rect(0,0,0,0) !important; clip-path: inset(50%) !important; white-space: nowrap !important; border: 0 !important; } +.icon-library { position: absolute; width: 0; height: 0; overflow: hidden; } +.icon { width: 20px; height: 20px; flex: 0 0 20px; fill: none; stroke: currentColor; stroke-width: 1.7; stroke-linecap: round; stroke-linejoin: round; } +.header { border-bottom: 1px solid var(--line); } +.header-inner, .main, .footer { max-width: 1160px; margin: 0 auto; } +.header-inner { min-height: 88px; padding: 18px 32px; display: flex; align-items: center; justify-content: space-between; gap: 12px; } +.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font-size: 22px; font-weight: 750; letter-spacing: -.8px; line-height: 1.15; } +.brand-mark { width: 42px; height: 42px; border-radius: 13px; background: var(--green); color: #edf4e9; display: grid; place-items: center; } +.brand-mark .icon { width: 28px; height: 28px; } +.brand-light { font-weight: 400; } +.brand small { display: block; margin-top: 6px; font-size: 8px; font-weight: 650; letter-spacing: 1.9px; color: var(--muted); } +.status-pill { border: 1px solid var(--line); border-radius: 30px; min-height: 36px; background: #fff9; color: var(--muted); display: inline-flex; align-items: center; gap: 7px; padding: 8px 13px; font-size: 11px; font-weight: 650; white-space: nowrap; } +.status-dot, .status-indicator-dot { width: 6px; height: 6px; flex: 0 0 6px; border-radius: 50%; background: #8c9b93; } +.status-pill.online { color: var(--green); background: #e9f0e5; border-color: #dce7d6; } +.status-pill.online .status-dot { background: #478751; } +.status-pill.offline { color: var(--danger); } +.status-pill.offline .status-dot { background: var(--danger); } +.status-pill.connecting .status-dot { background: #b1903c; } +.main { padding: 34px 32px 36px; } +.page-intro { display: flex; align-items: flex-end; justify-content: space-between; gap: 20px; margin-bottom: 30px; } +.eyebrow { color: var(--muted); font-size: 9px; letter-spacing: 2px; font-weight: 650; margin-bottom: 11px; } +h1 { font-size: clamp(27px, 3.5vw, 39px); font-weight: 700; line-height: 1.15; letter-spacing: -1.6px; } +h1 span { color: #789166; font-weight: 400; } +.intro-description { color: var(--muted); font-size: 12px; line-height: 1.7; padding-bottom: 2px; } +.workspace { display: grid; grid-template-columns: minmax(0, 1.38fr) minmax(0, 1fr); align-items: start; gap: 24px; } +.camera-panel, .card { background: var(--paper); border: 1px solid var(--line); border-radius: var(--radius); } +.camera-panel { padding: 20px; min-width: 0; } +.panel-heading, .card-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; } +.panel-heading { margin-bottom: 16px; } +h2 { font-size: 13px; font-weight: 650; display: flex; align-items: center; gap: 8px; letter-spacing: -.15px; } +h2 .icon { width: 17px; height: 17px; flex-basis: 17px; color: #7b8a80; } +.frame-ratio { color: #97a095; font-size: 8px; font-weight: 600; letter-spacing: 1.3px; } +.camera-frame { position: relative; width: 100%; aspect-ratio: 1 / 1; overflow: hidden; border-radius: 13px; background: #182521; isolation: isolate; } +#cameraFeed, #photoPreview { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; display: block; } +#moveOverlay { position: absolute; inset: 0; width: 100%; height: 100%; z-index: 2; pointer-events: none; overflow: visible; } +.frame-move-label { position: absolute; bottom: 14px; left: 50%; transform: translateX(-50%); max-width: calc(100% - 28px); padding: 8px 14px; border: 1px solid #d9efb440; border-radius: 9px; background: #163326ed; color: #e6f6cf; font-size: 14px; font-weight: 650; text-align: center; z-index: 4; pointer-events: none; } +.camera-frame.is-locking, .camera-frame.calibrating { cursor: crosshair; touch-action: none; } +.camera-overlay { position: absolute; inset: 0; z-index: 3; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 28px 24px; color: #e4e9df; text-align: center; background: radial-gradient(ellipse at 50% 40%, #2b3c30 0%, #192620 60%, #15211c 100%); pointer-events: none; } +.camera-overlay.hidden { display: none; } +.empty-board { width: 117px; height: 117px; position: relative; margin-bottom: 26px; background: conic-gradient(#4e6040 25%, #3d4b36 0 50%, #4e6040 0 75%, #3d4b36 0) 50% 50% / 29.25px 29.25px; border-radius: 2px; box-shadow: 0 14px 24px #07120d30; } +.empty-knight { position: absolute; left: 32px; top: 25px; width: 57px; height: 66px; color: #bdce9f; fill: #3d4b36; stroke: currentColor; stroke-width: 1.1; stroke-linecap: round; stroke-linejoin: round; } +.view-corner { position: absolute; width: 18px; height: 18px; border-color: #b1ce90; border-style: solid; opacity: .65; } +.view-corner.tl { top: -10px; left: -10px; border-width: 2px 0 0 2px; border-radius: 5px 0 0 0; } +.view-corner.tr { top: -10px; right: -10px; border-width: 2px 2px 0 0; border-radius: 0 5px 0 0; } +.view-corner.bl { bottom: -10px; left: -10px; border-width: 0 0 2px 2px; border-radius: 0 0 0 5px; } +.view-corner.br { bottom: -10px; right: -10px; border-width: 0 2px 2px 0; border-radius: 0 0 5px 0; } +.camera-overlay h3 { font-size: 20px; font-weight: 550; letter-spacing: -.4px; margin-bottom: 8px; } +.camera-overlay p { font-size: 12px; color: #a3b1a0; line-height: 1.7; } +.camera-empty-note { margin-top: 23px; font-size: 7px; letter-spacing: 1.2px; color: #83937c; } +.frame-hud { position: absolute; inset: 13px 13px auto; display: flex; align-items: center; gap: 8px; z-index: 4; pointer-events: none; } +.frame-tag { display: inline-flex; align-items: center; gap: 6px; min-height: 26px; background: #0d191acc; color: #dbe6dd; border: 1px solid #ffffff12; border-radius: 6px; padding: 5px 8px; font-size: 9px; font-weight: 600; line-height: 1.3; backdrop-filter: blur(8px); } +.hud-dot { width: 5px; height: 5px; border-radius: 50%; background: #819388; } +.frame-tag.locked { color: var(--lime); } +.live-indicator { margin-left: auto; font-size: 8px; letter-spacing: 1px; } +.live-indicator .hud-dot { background: #b9d795; } +.confidence { margin-left: auto; font-variant-numeric: tabular-nums; } +.live-indicator:not([hidden]) + .confidence { margin-left: 0; } +.camera-actions { display: flex; gap: 9px; margin-top: 16px; } +.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; min-height: 46px; border-radius: 10px; padding: 11px 16px; border: 1px solid transparent; font-size: 12px; font-weight: 650; line-height: 1.3; transition: background .15s, border-color .15s; } +.btn .icon { width: 17px; height: 17px; flex-basis: 17px; } +.btn-primary { background: var(--green); color: #fff; } +.btn-primary:hover:not(:disabled) { background: var(--green-hover); } +.btn-secondary, .btn-icon { background: #f5f7f2; color: var(--ink); border-color: var(--line); } +.btn-secondary:hover:not(:disabled), .btn-icon:hover:not(:disabled) { background: #eaf0e4; } +.camera-actions .btn-primary { flex: 1; } +.camera-actions .btn-secondary { min-width: 88px; } +.btn-icon { width: 46px; padding: 10px; flex: 0 0 46px; } +.camera-secondary-actions { display: flex; justify-content: center; gap: 28px; margin: 10px 0 8px; } +.text-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; border: 0; background: transparent; color: var(--muted); font-size: 11px; font-weight: 550; padding: 9px 0; min-height: 36px; border-radius: 4px; text-decoration: none; } +.text-btn .icon { width: 14px; height: 14px; flex-basis: 14px; } +.text-btn:hover:not(:disabled) { color: var(--green); } +.board-tools { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding-top: 10px; border-top: 1px solid var(--line); color: var(--muted); font-size: 10px; } +.board-tools > div { display: flex; gap: 16px; } +.board-tools .text-btn { font-size: 10px; } +.camera-tip { margin-top: 6px; color: #8b968d; font-size: 10px; line-height: 1.6; } +.coach-panel { display: flex; flex-direction: column; gap: 18px; min-width: 0; } +.card { padding: 22px; } +.move-card { background: #f0f5e9; border-color: #e1e9d6; } +.move-card h2 .icon { color: #688052; } +.engine-badge { background: #fff9; color: #728267; border: 1px solid #e3e9d8; border-radius: 20px; font-size: 8px; padding: 3px 8px; white-space: nowrap; } +.move-display { min-height: 178px; display: flex; align-items: center; padding: 24px 0 20px; } +.move-waiting { width: 100%; } +.waiting-arrow { display: grid; place-items: center; width: 34px; height: 34px; border-radius: 10px; background: #e2ebd6; color: #759455; margin-bottom: 15px; } +.waiting-arrow .icon { width: 19px; height: 19px; } +.move-waiting h3 { font-size: 21px; letter-spacing: -.5px; font-weight: 600; margin-bottom: 8px; } +.move-waiting p { color: #7a8871; font-size: 12px; max-width: 270px; line-height: 1.65; } +.move-result { width: 100%; } +.move-overline { font-size: 8px; letter-spacing: 1.3px; color: #748464; font-weight: 650; margin-bottom: 8px; } +.move-text { font-size: 30px; line-height: 1.17; font-weight: 650; letter-spacing: -1px; overflow-wrap: anywhere; } +.move-notation { display: flex; align-items: center; gap: 10px; margin-top: 14px; } +.move-san { background: #dfeace; border: 1px solid #d5e2c2; padding: 4px 11px; border-radius: 6px; font-weight: 700; font-size: 13px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; } +.move-uci { color: #77836d; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; } +.move-caption { color: #7a8871; font-size: 10px; margin-top: 12px; } +.status-bar { display: flex; align-items: flex-start; gap: 7px; border-top: 1px solid #dfe7d6; padding-top: 13px; color: #798671; font-size: 10px; line-height: 1.6; } +.status-indicator-dot { margin-top: 5px; width: 5px; height: 5px; flex-basis: 5px; background: #8d9d7d; } +.status-bar.ok { color: var(--green); } +.status-bar.ok .status-indicator-dot { background: #629744; } +.status-bar.error { color: var(--danger); } .status-bar.error .status-indicator-dot { background: var(--danger); } -.status-bar.error { color: var(--danger); border-color: rgba(239, 68, 68, 0.3); } - -.status-bar.ok .status-indicator-dot { background: var(--accent); } -.status-bar.ok { color: var(--accent-light); border-color: rgba(16, 185, 129, 0.3); } - -/* ── Mode info card ─────────────────────────────── */ -.info-card { - padding: 14px 18px; -} - -.mode-info { - display: flex; - align-items: flex-start; - gap: 14px; - font-size: 0.84rem; -} - -.mode-icon { - font-size: 1.6rem; - flex-shrink: 0; -} - -.mode-info strong { - display: block; - margin-bottom: 2px; - color: var(--text); - font-size: 0.92rem; -} - -.mode-info p { - color: var(--text-dim); - line-height: 1.45; -} - -/* ── Modal Dialog ───────────────────────────────── */ -.modal-dialog { - border: 1px solid var(--border-subtle); - border-radius: var(--radius-lg); - background: var(--bg-card); - color: var(--text); - padding: 0; - max-width: 480px; - width: 90%; - margin: auto; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7); -} - -.modal-dialog::backdrop { - background: rgba(0, 0, 0, 0.75); - backdrop-filter: blur(4px); -} - -.modal-content { - padding: 24px; - display: flex; - flex-direction: column; - gap: 14px; -} - -.modal-title { - font-size: 1.15rem; - font-weight: 700; -} - -.modal-desc { - font-size: 0.85rem; - color: var(--text-dim); -} - -.modal-input { - background: var(--bg-deep); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: 'Space Mono', monospace; - font-size: 0.85rem; - padding: 12px; - width: 100%; - outline: none; -} - -.modal-input:focus { - border-color: var(--accent); -} - -.modal-status { - font-size: 0.8rem; - font-family: 'Space Mono', monospace; - color: var(--text-dim); - padding: 6px 0; -} - -.modal-actions { - display: flex; - justify-content: flex-end; - gap: 10px; - margin-top: 8px; -} - -/* ── Footer ─────────────────────────────────────── */ -.footer { - font-size: 0.78rem; - color: var(--text-muted); - padding: 20px; - border-top: 1px solid var(--border-subtle); - margin-top: auto; -} - -.footer-inner { - max-width: 1140px; - margin: 0 auto; - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 12px; -} - -.footer-links { - display: flex; - align-items: center; - gap: 8px; -} - -.footer-link-btn, -.footer-link { - background: none; - border: none; - color: var(--text-dim); - font-size: inherit; - font-family: inherit; - cursor: pointer; - text-decoration: underline; - transition: color 0.15s; -} - -.footer-link-btn:hover, -.footer-link:hover { - color: var(--accent); -} - -/* ── Animations ─────────────────────────────────── */ -@keyframes pulse { - 0% { opacity: 1; } - 100% { opacity: 0.4; } -} - -@keyframes slideIn { - from { - opacity: 0; - transform: translateY(10px) scale(0.98); - } - to { - opacity: 1; - transform: translateY(0) scale(1); - } -} - -.move-anim { - animation: slideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1); -} - -@media (prefers-reduced-motion: reduce) { - .move-anim, - .live-indicator, - .wait-icon { - animation: none; - } +.recent-moves { padding-bottom: 12px; display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 9px; color: #7b886f; } +#recentPills { display: flex; flex-wrap: wrap; gap: 4px; } +.recent-chip { border: 1px solid #dce5d0; border-radius: 4px; padding: 2px 6px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 9px; } +.settings-card .card-heading { margin-bottom: 22px; } +.section-number { color: #b1bbad; font-size: 10px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; } +.control-group { margin-bottom: 20px; } +.ctrl-label { display: flex; align-items: center; justify-content: space-between; gap: 8px; font-size: 11px; font-weight: 550; color: #768272; margin-bottom: 9px; } +.toggle-group { display: flex; gap: 8px; } +.toggle-btn { display: flex; align-items: center; justify-content: center; gap: 8px; min-height: 42px; flex: 1; border: 1px solid var(--line); border-radius: 8px; background: #fff; color: #7b8579; font-size: 12px; font-weight: 600; } +.toggle-btn.active { border-color: #a9ba9c; background: #f1f5eb; color: var(--green); } +.piece-dot { width: 11px; height: 11px; border-radius: 50%; } +.piece-dot.white { border: 1px solid #a3afa0; background: #fff; box-shadow: inset 0 -2px 0 #e7ebe3; } +.piece-dot.black { background: #334338; border: 1px solid #334338; } +.field-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 22px; color: #768272; font-size: 11px; } +select { max-width: 58%; min-height: 36px; border: 1px solid var(--line); border-radius: 7px; background: #f8f9f5; color: var(--ink); padding: 7px 24px 7px 9px; font-size: 11px; } +.strength-control { margin-bottom: 19px; } +.depth-value { color: var(--green); font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 12px; font-weight: 700; } +.depth-unit { color: #a1ada0; font-size: 10px; font-weight: 400; } +input[type="range"] { width: 100%; height: 26px; margin: 0; background: transparent; cursor: pointer; } +.range-labels { display: flex; justify-content: space-between; font-size: 9px; color: #9ba594; margin-top: 2px; } +.advanced-settings { border-top: 1px solid var(--line); } +.advanced-settings summary { display: flex; align-items: center; justify-content: space-between; cursor: pointer; min-height: 44px; margin-bottom: -8px; padding-top: 6px; font-size: 10px; font-weight: 600; color: #819078; list-style: none; } +.advanced-settings summary::-webkit-details-marker { display: none; } +.advanced-settings summary .icon { width: 16px; height: 16px; flex-basis: 16px; transition: transform .15s; } +.advanced-settings[open] summary .icon { transform: rotate(180deg); } +.advanced-content { padding-top: 20px; } +.field-help { font-size: 10px; line-height: 1.7; color: #929d8b; } +.fen-field .field-help { margin-bottom: 8px; } +textarea, .modal-input { display: block; width: 100%; border: 1px solid var(--line); border-radius: 8px; color: var(--ink); background: #f8f9f5; padding: 10px; font-size: 11px; } +textarea { resize: vertical; min-height: 74px; font-family: ui-monospace, SFMono-Regular, Consolas, monospace; line-height: 1.7; margin-bottom: 7px; } +textarea::placeholder, .modal-input::placeholder { color: #a3ad9b; } +.setup-actions { display: flex; gap: 7px; margin-top: 12px; } +.setup-actions .btn { flex: 1; } +.btn-small { min-height: 39px; padding: 9px 10px; font-size: 10px; border-radius: 8px; } +.reset-btn { margin-top: 8px; font-size: 10px; } +.how-it-works { display: flex; gap: 12px; padding: 2px 10px; } +.how-icon { width: 33px; height: 33px; flex: 0 0 33px; border: 1px solid #e0e6d9; background: #eef2e8; border-radius: 10px; display: grid; place-items: center; color: #879676; margin-top: 2px; } +.how-icon .icon { width: 17px; height: 17px; } +.how-it-works h3 { color: #7a8970; font-size: 11px; font-weight: 600; margin-bottom: 5px; } +.how-it-works p { color: #a0a998; font-size: 10px; line-height: 1.7; max-width: 285px; } +.footer { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 16px 32px 25px; color: #9ba693; font-size: 10px; } +.footer > div { display: flex; align-items: center; gap: 20px; } +.footer .text-btn, .footer a { color: #89977e; font-size: 10px; text-decoration: none; } +.footer a:hover { color: var(--green); } +.modal-dialog { border: 1px solid var(--line); border-radius: var(--radius); padding: 0; width: min(460px, calc(100% - 32px)); margin: auto; color: var(--ink); background: var(--paper); box-shadow: 0 30px 100px #18302440; } +.modal-dialog::backdrop { background: #14231b80; backdrop-filter: blur(4px); } +.modal-content { padding: 24px; } +.modal-content .card-heading { margin-bottom: 12px; } +.modal-content .card-heading .btn-icon { min-height: 32px; width: 32px; flex-basis: 32px; padding: 0; font-size: 23px; font-weight: 400; } +.modal-content > .field-help { margin-bottom: 18px; } +.modal-input { min-height: 44px; } +.modal-status { min-height: 30px; padding-top: 10px; font-size: 11px; color: var(--muted); } +.modal-actions { display: flex; flex-wrap: wrap; gap: 7px; margin-top: 12px; } +.modal-actions .btn-primary { margin-left: auto; } +@media (max-width: 800px) { + .header-inner { min-height: 72px; padding: 15px 20px; } + .brand { font-size: 20px; } + .brand-mark { width: 37px; height: 37px; border-radius: 11px; } + .brand small { font-size: 7px; letter-spacing: 1.5px; } + .main { padding: 26px 20px 18px; max-width: 600px; } + .page-intro { margin-bottom: 23px; } + .intro-description { display: none; } + .eyebrow { font-size: 8px; letter-spacing: 1.6px; margin-bottom: 9px; } + h1 { font-size: 30px; letter-spacing: -1.1px; } + .workspace { grid-template-columns: minmax(0, 1fr); gap: 16px; } + .camera-panel { padding: 16px; } + .panel-heading { margin-bottom: 13px; } + .coach-panel { gap: 16px; } + .card { padding: 20px; } + .move-display { min-height: 145px; padding-top: 21px; } + .move-waiting { display: grid; grid-template-columns: 37px minmax(0, 1fr); align-items: center; column-gap: 13px; } + .waiting-arrow { grid-row: span 2; margin-bottom: 0; } + .move-waiting h3 { font-size: 19px; margin-bottom: 5px; } + .move-waiting p { font-size: 11px; max-width: none; } + .settings-card .card-heading { margin-bottom: 18px; } + .how-it-works { padding: 4px 8px; } + .how-it-works p { max-width: none; } + .footer { max-width: 600px; padding: 17px 20px 25px; font-size: 9px; } + .footer > div { gap: 14px; } + .footer .text-btn, .footer a { font-size: 9px; } +} +@media (max-width: 400px) { + .header-inner { padding-left: 16px; padding-right: 16px; } + .main { padding-left: 12px; padding-right: 12px; } + .status-pill { font-size: 10px; padding: 7px 10px; gap: 6px; } + h1 { font-size: 27px; } + .camera-panel { padding: 13px; border-radius: 16px; } + .camera-overlay { padding: 22px 16px; } + .empty-board { width: 88px; height: 88px; background-size: 22px 22px; margin-bottom: 24px; } + .empty-knight { left: 23px; top: 17px; width: 44px; height: 52px; } + .camera-overlay h3 { font-size: 18px; } + .camera-overlay p { font-size: 11px; } + .camera-empty-note { font-size: 6px; margin-top: 18px; letter-spacing: .7px; } + .camera-actions { gap: 7px; margin-top: 13px; } + .camera-actions .btn { font-size: 11px; padding-left: 12px; padding-right: 12px; } + .camera-actions .btn-secondary { min-width: 74px; } + .board-tools > div { gap: 12px; } + .card { padding: 18px; border-radius: 16px; } + .move-text { font-size: 28px; } + .footer { padding-left: 16px; padding-right: 16px; flex-wrap: wrap; gap: 0; } +} +@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } *, *::before, *::after { animation: none !important; transition: none !important; } } + +/* Supporting copy and controls remain readable at phone viewing distance. */ +.ctrl-label, .field-row, .field-help, .camera-tip, .status-bar, .move-caption, .move-uci, .text-btn, .how-it-works p { font-size: 12px; color: #5f6e62; } +.move-waiting p { color: #5f7056; } +.how-it-works h3, .advanced-settings summary { color: #506749; font-size: 12px; } +.camera-overlay p { color: #bbc8b5; } +.camera-empty-note { color: #abbc9d; font-size: 9px; } +.frame-hud { flex-wrap: wrap; } +.frame-tag { font-size: 10px; } +.toggle-btn, .btn-small { min-height: 44px; font-size: 12px; } +.text-btn { min-height: 44px; } +@media (max-width: 800px) { + select, textarea, .modal-input { font-size: 16px; min-height: 44px; } + select { max-width: 65%; padding-right: 18px; font-size: 13px; } + .status-pill { min-height: 44px; } + .main { padding-bottom: max(18px, env(safe-area-inset-bottom)); } + .board-tools .text-btn { font-size: 11px; } } diff --git a/frontend/tests/app.browser.js b/frontend/tests/app.browser.js new file mode 100644 index 0000000..1497997 --- /dev/null +++ b/frontend/tests/app.browser.js @@ -0,0 +1,244 @@ +import test, { before, after } from "node:test"; +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { createServer } from "node:http"; +import { readFile, mkdir } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import path from "node:path"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const repo = path.dirname(root); +const startFen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; +const corners = [[.1, .15], [.85, .2], [.9, .9], [.08, .87]]; +const advice = { status: "ok", fen: startFen, turn: "w", move_uci: "d2d4", move_san: "d4", move_human: "Pawn to d4", + confidence: .95, board_corners: corners, board_detected: true, board_locked: true, pieces_detected: true, + orientation: "w", engine: "stockfish" }; +let browser, server, origin; +before(async () => { + server = createServer(async (req, res) => { + try { + if (req.url === "/health") { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ status: "ok", engine: "stockfish" })); return; } + const file = req.url === "/" ? "index.html" : req.url.split("?")[0].slice(1); + if (!/^(index\.html|style\.css|app\.js|overlay\.js)$/.test(file)) { res.writeHead(404); res.end(); return; } + res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "text/html"); + res.end(await readFile(path.join(root, file))); + } catch { res.writeHead(500); res.end(); } + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + origin = `http://127.0.0.1:${server.address().port}`; + const chrome = process.env.CHROME_PATH || (process.platform === "win32" ? "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe" : undefined); + browser = await chromium.launch({ ...(chrome && existsSync(chrome) ? { executablePath: chrome } : {}), headless: true }); +}); +after(async () => { await browser?.close(); await new Promise(resolve => server?.close(resolve)); }); + +async function newPage(viewport = { width: 390, height: 844 }) { + const page = await browser.newPage({ viewport }); + const errors = []; + page.on("pageerror", err => errors.push(err.message)); + page.errors = errors; + return page; +} +async function respond(route, data = advice) { await route.fulfill({ json: data }); } +async function photo(page) { + const b64 = await page.evaluate(() => { + const canvas = document.createElement("canvas"); canvas.width = 800; canvas.height = 450; + const ctx = canvas.getContext("2d"); ctx.fillStyle = "#e2edde"; ctx.fillRect(0, 0, 800, 450); + return canvas.toDataURL("image/png").split(",")[1]; + }); + await page.locator("#fileInput").setInputFiles({ name: "board.png", mimeType: "image/png", buffer: Buffer.from(b64, "base64") }); +} +async function fakeCamera(page, delay = 0) { + await page.addInitScript(({ delay }) => { + navigator.mediaDevices.getUserMedia = async () => { + await new Promise(resolve => setTimeout(resolve, delay)); + const canvas = document.createElement("canvas"); canvas.width = 640; canvas.height = 480; + const ctx = canvas.getContext("2d"); ctx.fillStyle = "#cbdac8"; ctx.fillRect(0, 0, 640, 480); + const stream = canvas.captureStream(5); + window.fakeStream = stream; + const draw = setInterval(() => ctx.fillRect(0, 0, 640, 480), 200); + stream.getTracks()[0].addEventListener("ended", () => clearInterval(draw)); + return stream; + }; + }, { delay }); +} + +test("mobile and desktop layouts have one square frame, no overflow, and usable connection dialog", async () => { + for (const viewport of [{ width: 360, height: 800 }, { width: 390, height: 844 }, { width: 768, height: 1024 }, { width: 1440, height: 1000 }]) { + const page = await newPage(viewport); + await page.goto(origin); + await page.getByText("Engine online", { exact: true }).waitFor(); + const box = await page.locator("#cameraFrame").boundingBox(); + assert.ok(Math.abs(box.width - box.height) < 1); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + assert.equal(await page.locator("#boardCard").count(), 0); + await page.locator("#engineStatus").click(); + assert.equal(await page.locator("#apiModal").isVisible(), true); + await page.locator("#btnCloseApi").click(); + assert.deepEqual(page.errors, []); + await mkdir(path.join(repo, ".tmp", "screens"), { recursive: true }); + await page.screenshot({ path: path.join(repo, ".tmp", "screens", `ui-${viewport.width}.png`), fullPage: true }); + await page.close(); + } +}); + +test("photo overlay uses the camera frame and cached suggestions remain visible", async () => { + const page = await newPage(); let requests = 0; + await page.route("**/api/analyze", route => respond(route, { ...advice, status: ++requests === 1 ? "ok" : "no_change" })); + await page.goto(origin); await photo(page); + await page.locator("#moveResult").waitFor(); + assert.equal(await page.locator("#moveText").textContent(), "Pawn to d4"); + assert.equal(await page.locator("#moveOverlay").getAttribute("aria-label"), "Suggested move from d2 to d4"); + assert.equal(await page.locator("#frameMoveLabel").isVisible(), true); + const frame = await page.locator("#cameraFrame").boundingBox(), overlay = await page.locator("#moveOverlay").boundingBox(); + assert.deepEqual(overlay, frame); + await page.locator("#depthSlider").evaluate(el => { el.value = "11"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); }); + await page.getByText(/Position unchanged/).waitFor(); + assert.equal(await page.locator("#moveOverlay line").count(), 2); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("camera polls every settled frame, clears opponent arrow, and resumes suggestions", async () => { + const page = await newPage(); await fakeCamera(page); let requests = 0, active = 0, maxActive = 0; + await page.route("**/api/analyze", async route => { + active++; maxActive = Math.max(maxActive, active); requests++; + assert.equal(route.request().postDataJSON().orientation, "auto"); + await new Promise(resolve => setTimeout(resolve, 150)); + const data = requests === 1 ? advice : requests === 2 ? { ...advice, status: "no_change" } : requests === 3 ? + { ...advice, status: "opponent_turn", move_uci: null, turn: "b" } : { ...advice, move_uci: "g1f3", move_san: "Nf3", move_human: "Knight to f3" }; + await respond(route, data); active--; + }); + await page.goto(origin); await page.locator("#btnStart").click(); + await page.locator("#moveResult").waitFor(); + await page.getByText(/Position unchanged/).waitFor(); + await page.locator("#waitText").filter({ hasText: "Opponent’s turn" }).waitFor(); + assert.equal(await page.locator("#moveOverlay line").count(), 0); + await page.locator("#moveText").filter({ hasText: "Knight to f3" }).waitFor(); + assert.ok(requests >= 4); assert.equal(maxActive, 1); + await page.locator("#btnStop").click(); + assert.equal(await page.locator("#moveOverlay line").count(), 0); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("a stopped camera cannot display an in-flight result or reopen after delayed permission", async () => { + const page = await newPage(); await fakeCamera(page); let started; + const requestStarted = new Promise(resolve => { started = resolve; }); + await page.route("**/api/analyze", async route => { + started(); await new Promise(resolve => setTimeout(resolve, 1000)); + try { await respond(route); } catch { /* Request was canceled by stop. */ } + }); + await page.goto(origin); await page.locator("#btnStart").click(); await requestStarted; + await page.locator("#btnStop").click(); + await page.waitForTimeout(1200); + assert.equal(await page.locator("#moveResult").isVisible(), false); + assert.equal(await page.locator("#moveOverlay line").count(), 0); + await page.close(); + const delayed = await newPage(); await fakeCamera(delayed, 500); + await delayed.goto(origin); await delayed.locator("#btnStart").click(); await delayed.locator("#btnStop").click(); + await delayed.waitForTimeout(700); + assert.equal(await delayed.locator("#cameraFeed").isVisible(), false); + assert.equal(await delayed.evaluate(() => fakeStream.getTracks()[0].readyState), "ended"); + assert.deepEqual(delayed.errors, []); await delayed.close(); +}); + +test("unclear position removes stale arrows while retaining the detected board lock", async () => { + const page = await newPage(); let requests = 0; + await page.route("**/api/analyze", route => respond(route, ++requests === 1 ? advice : + { ...advice, status: "position_uncertain", fen: null, move_uci: null, message: "Remove your hand." })); + await page.goto(origin); await photo(page); await page.locator("#moveResult").waitFor(); + await page.locator("#depthSlider").evaluate(el => { el.value = "12"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); }); + await page.getByText("Remove your hand.", { exact: true }).waitFor(); + assert.equal(await page.locator("#moveOverlay line").count(), 0); + assert.equal(await page.locator("#moveOverlay polygon").count(), 1); + assert.equal(await page.locator("#moveResult").isVisible(), false); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("auto black orientation rotates the arrow and an empty board is never locked", async () => { + const page = await newPage(); let requests = 0; + await page.route("**/api/analyze", route => respond(route, ++requests === 1 ? + { ...advice, board_corners: [[0, 0], [1, 0], [1, 1], [0, 1]], orientation: "b" } : + { ...advice, status: "setup_required", fen: null, move_uci: null, pieces_detected: false, board_locked: false })); + await page.goto(origin); await photo(page); await page.locator("#moveResult").waitFor(); + const line = page.locator("#moveOverlay line").last(); + assert.equal(Number(await line.getAttribute("x1")), 562.5); + assert.equal(Number(await line.getAttribute("y1")), 187.5); + await page.locator("#depthSlider").evaluate(el => { el.value = "12"; el.dispatchEvent(new Event("input")); el.dispatchEvent(new Event("change")); }); + await page.locator("#waitText").filter({ hasText: "Put the pieces" }).waitFor(); + assert.equal(await page.locator("#moveOverlay polygon").count(), 0); + assert.equal(await page.locator("#frameMoveLabel").isVisible(), false); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("denied camera permission leaves controls usable and explains photo fallback", async () => { + const page = await newPage(); + await page.addInitScript(() => { + navigator.mediaDevices.getUserMedia = async () => { throw new DOMException("Permission denied", "NotAllowedError"); }; + }); + await page.goto(origin); await page.locator("#btnStart").click(); + await page.locator("#statusMsg").filter({ hasText: "Camera access was denied" }).waitFor(); + assert.equal(await page.locator("#btnStart").isEnabled(), true); + assert.equal(await page.locator("#btnStop").isEnabled(), false); + assert.equal(await page.locator("#btnUploadPhoto").isEnabled(), true); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("settings during camera permission do not strand Start and stale denial cannot cancel a photo", async () => { + const page = await newPage(); await fakeCamera(page, 500); + await page.route("**/api/analyze", route => respond(route)); + await page.goto(origin); await page.locator("#btnStart").click(); + await page.locator('#colorToggle button[data-val="b"]').click(); + await page.locator("#cameraFeed").waitFor(); await page.locator("#moveResult").waitFor(); + assert.equal(await page.locator("#btnStop").isEnabled(), true); + await page.locator("#btnStop").click(); + assert.equal(await page.locator("#btnStart").isEnabled(), true); + await page.close(); + const denied = await newPage(); + await denied.addInitScript(() => { + navigator.mediaDevices.getUserMedia = async () => { + await new Promise(resolve => setTimeout(resolve, 600)); + throw new DOMException("Permission denied", "NotAllowedError"); + }; + }); + await denied.route("**/api/analyze", route => respond(route)); + await denied.goto(origin); await denied.locator("#btnStart").click(); await photo(denied); + await denied.locator("#moveResult").waitFor(); await denied.waitForTimeout(800); + assert.equal(await denied.locator("#moveResult").isVisible(), true); + assert.equal(await denied.locator("#photoPreview").isVisible(), true); + assert.equal(await denied.locator("#moveText").textContent(), "Pawn to d4"); + assert.deepEqual(denied.errors, []); await denied.close(); +}); + +test("Try demo switches an active scan and static suggestions survive tab visibility changes", async () => { + const page = await newPage(); await fakeCamera(page); let started; + const requestStarted = new Promise(resolve => { started = resolve; }); + await page.route("**/api/analyze", async route => { started(); await new Promise(resolve => setTimeout(resolve, 700)); try { await respond(route); } catch {} }); + await page.route("**/api/analyze-fen", route => respond(route, { ...advice, board_corners: undefined })); + await page.goto(origin); await page.locator("#btnStart").click(); await requestStarted; + await page.locator("#btnDemo").click(); await page.locator("#moveResult").waitFor(); + assert.equal(await page.locator("#cameraFeed").isVisible(), false); + assert.equal(await page.locator("#photoPreview").isVisible(), true); + await page.evaluate(() => { + Object.defineProperty(document, "hidden", { configurable: true, get: () => true }); + document.dispatchEvent(new Event("visibilitychange")); + Object.defineProperty(document, "hidden", { configurable: true, get: () => false }); + document.dispatchEvent(new Event("visibilitychange")); + }); + assert.equal(await page.locator("#moveResult").isVisible(), true); + assert.equal(await page.locator("#moveOverlay line").count(), 2); + assert.deepEqual(page.errors, []); await page.close(); +}); + +test("live backend photo reads return an overlay and a legal next move", { skip: !process.env.CHESS_API_URL }, async () => { + const page = await newPage(); + await page.goto(process.env.CHESS_API_URL); + await page.locator("#fileInput").setInputFiles(path.join(repo, ".tmp", "camera-start.png")); + await page.locator("#moveResult").waitFor(); + assert.equal(await page.locator("#boardStatus").textContent(), "Board locked"); + assert.equal(await page.locator("#moveOverlay line").count(), 2); + assert.match(await page.locator("#moveUci").textContent(), /^[a-h][1-8] → [a-h][1-8]$/); + await page.screenshot({ path: path.join(repo, ".tmp", "screens", "live-overlay-mobile.png"), fullPage: true }); + await page.locator("#btnDemo").click(); await page.locator("#moveResult").waitFor(); + assert.equal(await page.locator("#moveOverlay line").count(), 2); + assert.deepEqual(page.errors, []); await page.close(); +}); diff --git a/frontend/tests/overlay.test.js b/frontend/tests/overlay.test.js new file mode 100644 index 0000000..cd5e4e5 --- /dev/null +++ b/frontend/tests/overlay.test.js @@ -0,0 +1,43 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { fitInside, projectPoint, moveGeometry, validCorners, resolveApiBase } from "../overlay.js"; + +test("landscape and portrait camera fit matches the square capture letterbox", () => { + assert.deepEqual(fitInside(1920, 1080), { x: 0, y: 218.75, width: 1000, height: 562.5 }); + assert.deepEqual(fitInside(1080, 1920), { x: 218.75, y: 0, width: 562.5, height: 1000 }); +}); + +test("perspective projection maps all four actual board corners exactly", () => { + const corners = [[.12, .18], [.84, .25], [.97, .9], [.05, .95]]; + [[0, 0], [1, 0], [1, 1], [0, 1]].forEach(([x, y], i) => { + const p = projectPoint(corners, x, y); + assert.ok(Math.abs(p[0] - corners[i][0]) < 1e-10); + assert.ok(Math.abs(p[1] - corners[i][1]) < 1e-10); + }); +}); + +test("e2 to e4 points to the correct squares for either board orientation", () => { + const corners = [[0, 0], [1, 0], [1, 1], [0, 1]]; + assert.deepEqual(moveGeometry("e2e4", corners).from, [.5625, .8125]); + assert.deepEqual(moveGeometry("e2e4", corners).to, [.5625, .5625]); + assert.deepEqual(moveGeometry("e2e4", corners, "b").from, [.4375, .1875]); + assert.deepEqual(moveGeometry("e2e4", corners, "b").to, [.4375, .4375]); + assert.deepEqual(moveGeometry("e7e8q", corners).to, [.5625, .0625]); + assert.equal(moveGeometry("bad", corners), null); +}); + +test("crossed, out-of-frame and degenerate manual locks are rejected", () => { + assert.equal(validCorners([[.1, .1], [.9, .1], [.9, .9], [.1, .9]]), true); + assert.equal(validCorners([[0, 0], [1, 1], [1, 0], [0, 1]]), false); + assert.equal(validCorners([[0, 0], [1, 0], [1, 0], [0, 0]]), false); + assert.equal(validCorners([[0, 0], [2, 0], [1, 1], [0, 1]]), false); +}); + +test("Railway and local apps use their own API; Pages and overrides resolve safely", () => { + const fallback = "https://backend.up.railway.app"; + assert.equal(resolveApiBase({ origin: "https://preview.up.railway.app", fallback }), "https://preview.up.railway.app"); + assert.equal(resolveApiBase({ origin: "http://127.0.0.1:8080", fallback }), "http://127.0.0.1:8080"); + assert.equal(resolveApiBase({ origin: "https://chess.pages.dev", fallback }), fallback); + assert.equal(resolveApiBase({ origin: "https://chess.pages.dev", search: "?api=https://other.example/", fallback }), "https://other.example"); + assert.throws(() => resolveApiBase({ origin: "https://chess.pages.dev", stored: "javascript:bad", fallback })); +}); diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..e5d1da3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,42 @@ +{ + "name": "chess-vision-coach", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "chess-vision-coach", + "devDependencies": { + "playwright": "^1.57.0" + } + }, + "node_modules/playwright": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz", + "integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.65.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.65.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz", + "integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..b365e1f --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "chess-vision-coach", + "private": true, + "type": "module", + "scripts": { + "test": "node --test frontend/tests/*.test.js", + "test:browser": "node --test frontend/tests/*.browser.js" + }, + "devDependencies": { + "playwright": "^1.57.0" + } +} From 671f9c3a656489eeb4f1bacaa9b5feaa295bcc8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=F0=9D=97=94=F0=9D=98=86=F0=9D=98=82=F0=9D=98=80?= =?UTF-8?q?=F0=9D=97=B5=20=F0=9D=97=9E?= <100coldice@gmail.com> Date: Tue, 24 Nov 2026 20:53:40 +0530 Subject: [PATCH 4/4] chore: unify deployment assets and add camera regression CI --- .dockerignore | 11 + .github/workflows/checks.yml | 51 ++ .gitignore | 6 + README.md | 87 +- backend/DEPLOY.md | 80 +- backend/Dockerfile | 6 +- backend/frontend/_headers | 14 - backend/frontend/app.js | 519 ------------ backend/frontend/index.html | 247 ------ backend/frontend/style.css | 957 ---------------------- backend/requirements-dev.txt | 3 + backend/tests/generate_camera_fixtures.py | 19 + docs/API.md | 221 +++-- docs/PERFORMANCE.md | 92 +-- docs/README.md | 269 ++---- 15 files changed, 384 insertions(+), 2198 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/workflows/checks.yml delete mode 100644 backend/frontend/_headers delete mode 100644 backend/frontend/app.js delete mode 100644 backend/frontend/index.html delete mode 100644 backend/frontend/style.css create mode 100644 backend/requirements-dev.txt create mode 100644 backend/tests/generate_camera_fixtures.py diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..8bcf8ca --- /dev/null +++ b/.dockerignore @@ -0,0 +1,11 @@ +.git +.venv +.tmp +.pytest_cache +.wrangler +node_modules +test-results +**/__pycache__ +**/*.pyc +.env +.env.* diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 0000000..a4ed76a --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,51 @@ +name: Camera coach checks +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + regression: + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + cache: pip + cache-dependency-path: backend/requirements.txt + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: npm + - name: Install dependencies + run: | + sudo apt-get update + sudo apt-get install -y stockfish + python -m pip install -r backend/requirements.txt pytest httpx + npm ci --ignore-scripts + npx playwright install --with-deps chromium + - name: Backend and overlay regressions + run: | + python -m pytest backend/tests -q -p no:cacheprovider + npm test + - name: Mobile browser and live backend regressions + env: + CHESS_API_URL: http://127.0.0.1:8080 + STOCKFISH_PATH: /usr/games/stockfish + run: | + python backend/tests/generate_camera_fixtures.py + python -m uvicorn main:app --app-dir backend --host 127.0.0.1 --port 8080 > /tmp/chess-api.log 2>&1 & + for attempt in $(seq 1 30); do + if curl --fail --silent http://127.0.0.1:8080/health; then break; fi + sleep 1 + done + npm run test:browser + - uses: actions/upload-artifact@v4 + if: always() + with: + name: camera-ui-screenshots + path: .tmp/screens + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index 8e7eafa..7c50ded 100644 --- a/.gitignore +++ b/.gitignore @@ -25,3 +25,9 @@ models/*.weights # Node (if using Wrangler CLI) node_modules/ + +# Local verification and deployment artifacts +.tmp/ +.pytest_cache/ +.wrangler/ +test-results/ diff --git a/README.md b/README.md index 796260f..f665467 100644 --- a/README.md +++ b/README.md @@ -1,57 +1,66 @@ # Chess Vision Coach -
- Python Version - FastAPI - OpenCV - Stockfish -
+A phone-friendly chess camera coach with a move arrow directly over your board and a plain-language suggestion such as **Pawn to d4**. -

- Point your phone camera at a chess board. Get your next move. No bullshit. -

+The camera, uploaded photo, detected board boundary, and move arrow share one square view. Start the camera, keep the whole board visible, and the app detects and locks the board automatically. It follows the position as you and your opponent move, and shows advice when it is your turn. -## 🌟 Overview +## Board recognition -Chess Vision Coach is a lightweight, blazing-fast web application that helps you analyze over-the-board chess positions in real-time. Simply point your smartphone camera at a physical chess board, and the app will instantly suggest the best move using the powerful Stockfish engine. +This version uses OpenCV to find a verified checkerboard and measure piece color and occupancy. It does **not** contain a trained model for identifying arbitrary physical piece types. -## ✨ Features +- Begin with the pieces in their standard starting positions for automatic calibration. +- To join a game already in progress, enter its exact FEN once under **Position & preferences**, choose the side to move, and select **Use for camera**. The supplied piece identities are then retained through legal move tracking. +- Keep the board in view between moves. The tracker can match an unchanged position, one legal move, or two consecutive legal moves. Unclear frames and ambiguous promotions request a clear frame or position confirmation instead of inventing pieces. -- **Zero-weight Board Detection:** Utilizes OpenCV for fast, accurate board detection without the need for heavy GPU models. Perfect for overhead phone cameras. -- **Persistent Engine:** Stockfish is started once on boot and kept alive for all requests, ensuring zero restart overhead between moves. -- **Smart FEN Caching:** The engine is only called when the board position actually changes, saving resources and battery life. -- **Multiple Play Modes:** Choose between "Win Mode" for the strongest possible moves, or "Loss Mode" for more human-like, believable inaccuracies. -- **Adjustable Strength:** Easily change the engine depth to match your desired Elo rating (approx. 800 to 2600+). +Board orientation and your playing color are separate settings. Orientation is detected automatically; you can also select **White at bottom** or **Black at bottom** regardless of which color you play. -## 🚀 Quick Deploy +## Run locally -Get your own instance running in under a minute! +Use Python 3.11+ and install Stockfish for full engine strength. The app also provides a bounded Python fallback when the Stockfish binary is unavailable. -```bash -# 1. Deploy the Backend to Railway -cd backend && railway up +From the repository root: -# 2. Deploy the Frontend to Cloudflare Pages -# - Edit API_BASE in frontend/app.js to point to your Railway URL -# - Push to GitHub and connect in Cloudflare Pages dashboard +```powershell +python -m venv .venv +& .venv\Scripts\python.exe -m pip install -r backend/requirements.txt +& .venv\Scripts\python.exe -m uvicorn main:app --app-dir backend --host 127.0.0.1 --port 8080 ``` -## 🏗️ Architecture & Design +Open `http://127.0.0.1:8080`. FastAPI serves the frontend and API together; no frontend build is required. Phone camera access needs HTTPS when accessing a server on another device. -- **Frontend:** Pure HTML/CSS/Vanilla JS for minimal footprint. Hosted on **Cloudflare Pages** for global Edge CDN delivery and custom `Permissions-Policy` headers (crucial for camera access). -- **Backend:** **FastAPI** providing a robust, async API. Deployed on **Railway** for easy containerized hosting. -- **Vision:** **OpenCV** was chosen over YOLOv8 for its zero-megabyte model size and ultra-fast inference on standard CPUs, making it ideal for the Railway free tier. -- **Chess Engine:** **Stockfish** integrated via a persistent, thread-safe service wrapper that auto-recovers from any edge-case crashes. +If Stockfish is outside the standard system paths, set `STOCKFISH_PATH` to its executable path before starting the server. -## 📚 Documentation +## Deploy to Railway -For more detailed information, check out our comprehensive docs: +Deploy **the repository root**, which contains the Dockerfile that packages both `backend/` and `frontend/`: -- [Full Documentation](docs/README.md) -- [API Reference](docs/API.md) -- [Performance Notes](docs/PERFORMANCE.md) +```powershell +railway login +railway link +railway up --service backend +``` + +Open the service's HTTPS domain. The Railway-hosted frontend uses that deployment's own API by default. The Docker image installs Stockfish; Railway supplies `PORT`. + +For a separate static frontend, publish `frontend/` and use **Connection settings** or a `?api=https://your-backend.up.railway.app` URL to select its backend. + +## Tests + +From the repository root: + +```powershell +& .venv\Scripts\python.exe -m pip install -r backend/requirements-dev.txt +& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider +npm ci +npm test +npm run test:browser +``` + +The browser suite starts its own test server and uses installed Chrome on Windows. On Linux, install its browser with `npx playwright install --with-deps chromium`. To include real backend integration, generate synthetic camera fixtures with `python backend/tests/generate_camera_fixtures.py`, start the local backend, and set `CHESS_API_URL=http://127.0.0.1:8080` before running the browser suite. CI runs all three suites and saves mobile/desktop screenshots. + +## Documentation ---- -
- Built with ❤️ for chess enthusiasts everywhere. -
+- [Setup and camera workflow](docs/README.md) +- [API reference](docs/API.md) +- [Performance and operating limits](docs/PERFORMANCE.md) +- [Railway deployment](backend/DEPLOY.md) diff --git a/backend/DEPLOY.md b/backend/DEPLOY.md index 998dbd1..65facda 100644 --- a/backend/DEPLOY.md +++ b/backend/DEPLOY.md @@ -1,57 +1,61 @@ -# Railway Deploy — Chess Vision Coach Backend +# Railway deployment -## THIS IS THE FOLDER YOU DEPLOY TO RAILWAY -Do not deploy the whole repo root. Deploy only this `railway-deploy/` folder. +## Deploy the repository root ---- +Use the root `Dockerfile` and root `railway.json`. The root image copies both `backend/` and `frontend/`, installs Stockfish, and runs FastAPI. The service serves the web UI at `/`, API routes at `/api/`, and health at `/health`. -## Method 1: Railway CLI (recommended — 2 commands) +Deploying only `backend/` does not package the current root frontend. The recommended deployment is the whole repository from its root directory. -```bash -# 1. Install Railway CLI if you haven't -npm install -g @railway/cli +## Existing project with Railway CLI -# 2. Login -railway login - -# 3. Navigate INTO this folder -cd railway-deploy +From the repository root: -# 4. Link to your existing Railway project +```powershell +railway login railway link -# → select your project: chess-machine-production - -# 5. Deploy -railway up +railway status +railway up --service backend ``` -Railway will detect the Dockerfile automatically and build it. +Use your actual service name if it differs from `backend`. The CLI can also select an environment with `--environment production`. A detached deployment returns before it is healthy; verify deployment status and `/health` afterward. ---- +## GitHub deployment -## Method 2: GitHub (auto-deploy on push) +Connect the Railway service to the repository and its intended release branch. Leave the service root directory at the repository root so the root Dockerfile packages the UI and API together. The root Railway configuration defines `/health` as the deployment health check. -1. Create a new GitHub repo (e.g. `chess-backend`) -2. Copy ONLY the contents of this `railway-deploy/` folder into it (not the folder itself) -3. Push to GitHub -4. In Railway dashboard → your service → Settings → Source → connect that GitHub repo -5. Railway will auto-deploy on every push +The Docker image installs Stockfish and sets its executable path. Railway injects `PORT`; do not hard-code a different port in the service configuration. ---- +## Configuration -## Environment variables (already set in Dockerfile — nothing extra needed) +| Variable | Default | Purpose | +| --- | --- | --- | +| `STOCKFISH_PATH` | `/usr/games/stockfish` in the Docker image | Stockfish executable. | +| `PORT` | Supplied by Railway; local Docker fallback `8080` | HTTP listening port. | +| `MIN_INTERVAL_SEC` | `0.5` | Minimum interval between analysis requests for one session. | -| Variable | Value | Set by | -|---|---|---| -| `STOCKFISH_PATH` | `/usr/games/stockfish` | Dockerfile ENV | -| `PORT` | auto-assigned | Railway injects at runtime | +Camera sessions are stored in backend memory. A restart requires starting or calibrating tracking again. For multiple replicas, add session affinity or shared state before relying on continuous position tracking across replicas. ---- +## Verify the service -## Verify it's working +Open `https://YOUR-SERVICE.up.railway.app/health`. A ready Stockfish deployment returns: -After deploy, visit: -``` -https://YOUR-APP.up.railway.app/health +```json +{ + "status": "ok", + "engine": "stockfish", + "detector": "opencv", + "recognition": "legal-occupancy-tracking", + "requires_setup_for_unknown_positions": true, + "camera_overlay": true +} ``` -Should return: `{"status":"ok","engine":"stockfish","detector":"opencv"}` + +`engine: "python-chess-fallback"` means the service is available with the weaker fallback engine. Check deployment logs and `STOCKFISH_PATH` if Stockfish is expected. A readiness failure returns HTTP 503. + +Then open the HTTPS root URL and use **Try a demo** to verify an engine result and an arrow in the square frame. On a phone, start the camera with a normal starting setup, verify board lock and a suggestion, then move a piece and verify the turn changes. Joining a midgame position requires its exact FEN once; this detector does not independently identify arbitrary piece types. + +## Separate frontend hosting + +The current frontend has no build step. A static host can publish the `frontend/` directory. Use the UI's **Connection settings** or a `?api=https://YOUR-SERVICE.up.railway.app` URL to select the backend. The Railway-hosted frontend selects its own origin automatically. + +Serve phone camera access over HTTPS. The `frontend/_headers` file supplies headers for hosts that support that convention; browser camera permission still comes from the user. diff --git a/backend/Dockerfile b/backend/Dockerfile index 24cf7a1..952aa62 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -7,8 +7,10 @@ RUN apt-get update && \ && rm -rf /var/lib/apt/lists/* WORKDIR /app -COPY requirements.txt . +COPY backend/requirements.txt ./requirements.txt RUN pip install --no-cache-dir -r requirements.txt -COPY . . +COPY backend/ ./backend/ +COPY frontend/ ./frontend/ ENV STOCKFISH_PATH=/usr/games/stockfish +WORKDIR /app/backend CMD ["sh", "-c", "uvicorn main:app --host 0.0.0.0 --port ${PORT:-8080}"] diff --git a/backend/frontend/_headers b/backend/frontend/_headers deleted file mode 100644 index 0594127..0000000 --- a/backend/frontend/_headers +++ /dev/null @@ -1,14 +0,0 @@ -# Cloudflare Pages — HTTP headers - -/* - X-Frame-Options: DENY - X-Content-Type-Options: nosniff - Referrer-Policy: strict-origin-when-cross-origin - Permissions-Policy: camera=* - -# Cache static assets -/style.css - Cache-Control: public, max-age=86400 - -/app.js - Cache-Control: public, max-age=86400 diff --git a/backend/frontend/app.js b/backend/frontend/app.js deleted file mode 100644 index 4133470..0000000 --- a/backend/frontend/app.js +++ /dev/null @@ -1,519 +0,0 @@ -/** - * Chess Vision Coach — Frontend Application v2.0 - */ - -const DEFAULT_API_BASE = "https://backend-production-e51676e6.up.railway.app"; -const urlParams = new URLSearchParams(window.location.search); -let API_BASE = urlParams.get("api") || localStorage.getItem("chess_api_base") || DEFAULT_API_BASE; - -const POLL_INTERVAL = 2500; -const MAX_CAPTURE_SIZE = 480; -const JPEG_QUALITY = 0.82; -const SESSION_ID = "session_" + Math.random().toString(36).slice(2, 9); - -const DEPTH_ELO = { - 4: 800, 5: 1000, 6: 1200, 7: 1400, 8: 1600, 9: 1750, - 10: 1900, 11: 2000, 12: 2100, 13: 2200, 14: 2300, 15: 2400, 16: 2600 -}; - -let isRunning = false; -let pollTimer = null; -let lastFrameHash = null; -let playerColor = "w"; -let playMode = "win"; -let depth = 10; -let currentInputTab = "camera"; -const recentMoves = []; - -const $ = id => document.getElementById(id); - -// UI Elements -const cameraFeed = $("cameraFeed"); -const captureCanvas = $("captureCanvas"); -const cameraOverlay = $("cameraOverlay"); -const liveIndicator = $("liveIndicator"); -const engineStatus = $("engineStatus"); -const engineBadge = $("engineBadge"); -const btnStart = $("btnStart"); -const btnStop = $("btnStop"); -const depthSlider = $("depthSlider"); -const depthVal = $("depthVal"); -const eloHint = $("eloHint"); - -const moveWaiting = $("moveWaiting"); -const moveResult = $("moveResult"); -const moveText = $("moveText"); -const moveSan = $("moveSan"); -const moveUci = $("moveUci"); -const waitText = $("waitText"); -const statusMsg = $("statusMsg"); -const statusBar = $("statusBar"); -const boardCard = $("boardCard"); -const boardImg = $("boardImg"); -const confBadge = $("confBadge"); -const modeInfo = $("modeInfo"); -const recentContainer = $("recentContainer"); -const recentPills = $("recentPills"); - -// Mode Tabs & Containers -const cameraContainer = $("cameraContainer"); -const uploadContainer = $("uploadContainer"); -const presetsContainer = $("presetsContainer"); -const dropZone = $("dropZone"); -const fileInput = $("fileInput"); -const customFenInput = $("customFenInput"); -const btnAnalyzeFen = $("btnAnalyzeFen"); - -// Modal Elements -const apiModal = $("apiModal"); -const apiUrlInput = $("apiUrlInput"); -const modalPingStatus = $("modalPingStatus"); -const btnTestPing = $("btnTestPing"); -const btnResetApiDefault = $("btnResetApiDefault"); -const btnSaveApi = $("btnSaveApi"); -const btnConfigApi = $("btnConfigApi"); - -window.addEventListener("DOMContentLoaded", () => { - initTabs(); - initToggleGroup("colorToggle", val => { playerColor = val; }); - initToggleGroup("modeToggle", val => { playMode = val; updateModeInfo(); }); - initPresets(); - initUpload(); - initModal(); - - depthSlider.addEventListener("input", onDepthChange); - btnStart.addEventListener("click", startAnalysis); - btnStop.addEventListener("click", stopAnalysis); - btnAnalyzeFen.addEventListener("click", () => analyzeDirectFen(customFenInput.value.trim())); - - checkBackendHealth(); - updateModeInfo(); -}); - -// ── Tab Navigation ──────────────────────────────────────────────────────── -function initTabs() { - document.querySelectorAll(".tab-btn").forEach(btn => { - btn.addEventListener("click", () => { - document.querySelectorAll(".tab-btn").forEach(b => { - b.classList.remove("active"); - b.setAttribute("aria-selected", "false"); - }); - btn.classList.add("active"); - btn.setAttribute("aria-selected", "true"); - - currentInputTab = btn.dataset.tab; - cameraContainer.style.display = currentInputTab === "camera" ? "block" : "none"; - uploadContainer.style.display = currentInputTab === "upload" ? "block" : "none"; - presetsContainer.style.display = currentInputTab === "presets" ? "block" : "none"; - - if (currentInputTab !== "camera" && isRunning) { - stopAnalysis(); - } - }); - }); -} - -// ── Quick Test Presets ──────────────────────────────────────────────────── -function initPresets() { - document.querySelectorAll(".preset-chip").forEach(chip => { - chip.addEventListener("click", () => { - document.querySelectorAll(".preset-chip").forEach(c => c.classList.remove("active")); - chip.classList.add("active"); - const fen = chip.dataset.fen; - const col = chip.dataset.color || "w"; - customFenInput.value = fen; - - // Update color toggle - const colorBtn = document.querySelector(`#colorToggle button[data-val="${col}"]`); - if (colorBtn) colorBtn.click(); - - analyzeDirectFen(fen); - }); - }); -} - -// ── File Upload & Drag/Drop ─────────────────────────────────────────────── -function initUpload() { - fileInput.addEventListener("change", e => { - const file = e.target.files[0]; - if (file) handleImageFile(file); - }); - - dropZone.addEventListener("dragover", e => { - e.preventDefault(); - dropZone.classList.add("dragover"); - }); - - dropZone.addEventListener("dragleave", () => { - dropZone.classList.remove("dragover"); - }); - - dropZone.addEventListener("drop", e => { - e.preventDefault(); - dropZone.classList.remove("dragover"); - const file = e.dataTransfer.files[0]; - if (file && file.type.startsWith("image/")) { - handleImageFile(file); - } - }); -} - -function handleImageFile(file) { - const reader = new FileReader(); - reader.onload = e => { - const dataUrl = e.target.result; - const b64 = dataUrl.split(",")[1]; - analyzeBase64Image(b64); - }; - reader.readAsDataURL(file); -} - -// ── Toggle Groups ───────────────────────────────────────────────────────── -function initToggleGroup(groupId, onChange) { - const group = $(groupId); - group.querySelectorAll(".toggle-btn").forEach(btn => { - btn.addEventListener("click", () => { - group.querySelectorAll(".toggle-btn").forEach(b => { - b.classList.remove("active"); - b.setAttribute("aria-pressed", "false"); - }); - btn.classList.add("active"); - btn.setAttribute("aria-pressed", "true"); - onChange(btn.dataset.val); - }); - }); -} - -function onDepthChange() { - depth = parseInt(depthSlider.value); - depthVal.textContent = depth; - eloHint.textContent = `≈ ${DEPTH_ELO[depth] ?? "?"} Elo*`; -} - -// ── Camera Capture & Analysis ───────────────────────────────────────────── -async function startAnalysis() { - if (isRunning) return; - - try { - const stream = await navigator.mediaDevices.getUserMedia({ - video: { facingMode: "environment", width: { ideal: 1280 }, height: { ideal: 720 } } - }); - cameraFeed.srcObject = stream; - await cameraFeed.play(); - cameraOverlay.classList.add("hidden"); - liveIndicator.style.display = "inline-block"; - } catch (err) { - setStatus(`Camera access error: ${err.message}`, "error"); - return; - } - - try { - await fetch(`${API_BASE}/api/reset-session?session_id=${SESSION_ID}`, { method: "POST" }); - } catch (_) { } - - isRunning = true; - lastFrameHash = null; - btnStart.disabled = true; - btnStop.disabled = false; - setStatus("Camera live. Analyzing overhead board…", ""); - showWaiting("Scanning camera frame for chess pieces…"); - - pollTimer = setInterval(captureAndAnalyze, POLL_INTERVAL); - captureAndAnalyze(); -} - -function stopAnalysis() { - if (!isRunning) return; - isRunning = false; - clearInterval(pollTimer); - pollTimer = null; - - const stream = cameraFeed.srcObject; - if (stream) stream.getTracks().forEach(t => t.stop()); - cameraFeed.srcObject = null; - cameraOverlay.classList.remove("hidden"); - liveIndicator.style.display = "none"; - - btnStart.disabled = false; - btnStop.disabled = true; - setStatus("Analysis stopped.", ""); -} - -async function captureAndAnalyze() { - if (!isRunning) return; - const vw = cameraFeed.videoWidth; - const vh = cameraFeed.videoHeight; - if (!vw || !vh) return; - - const scale = Math.min(MAX_CAPTURE_SIZE / vw, MAX_CAPTURE_SIZE / vh, 1); - const cw = Math.round(vw * scale); - const ch = Math.round(vh * scale); - - captureCanvas.width = cw; - captureCanvas.height = ch; - const ctx = captureCanvas.getContext("2d"); - ctx.drawImage(cameraFeed, 0, 0, cw, ch); - - const imageB64Full = captureCanvas.toDataURL("image/jpeg", JPEG_QUALITY); - const imageB64 = imageB64Full.split(",")[1]; - - const frameHash = await quickHash(imageB64.slice(0, 2000)); - if (frameHash === lastFrameHash) return; - lastFrameHash = frameHash; - - await analyzeBase64Image(imageB64); -} - -// ── API Invocation ──────────────────────────────────────────────────────── -async function analyzeBase64Image(imageB64) { - try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/api/analyze`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - image_b64: imageB64, - player_color: playerColor, - depth: depth, - mode: playMode, - session_id: SESSION_ID, - }), - }); - - const elapsed = Math.round(performance.now() - t0); - - if (!res.ok) { - setStatus(`Server error ${res.status}`, "error"); - return; - } - - const data = await res.json(); - handleResponse(data, elapsed); - - } catch (err) { - setStatus(`Network error: ${err.message}`, "error"); - } -} - -async function analyzeDirectFen(fen) { - if (!fen) return; - showWaiting("Evaluating position with Stockfish…"); - try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/api/analyze-fen`, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - fen: fen, - player_color: playerColor, - depth: depth, - mode: playMode, - }), - }); - - const elapsed = Math.round(performance.now() - t0); - - if (!res.ok) { - const errData = await res.json().catch(() => ({})); - setStatus(`Error: ${errData.message || res.statusText}`, "error"); - return; - } - - const data = await res.json(); - handleResponse(data, elapsed); - - } catch (err) { - setStatus(`Network error: ${err.message}`, "error"); - } -} - -// ── Response Handler ────────────────────────────────────────────────────── -function handleResponse(data, elapsedMs) { - switch (data.status) { - - case "ok": - showMove(data.move_human, data.move_san, data.move_uci); - const confStr = data.confidence < 1.0 ? ` | Conf: ${pct(data.confidence)}` : ""; - setStatus(`Optimal move computed (${elapsedMs}ms)${confStr} • ≈${data.approx_elo} Elo`, "ok"); - if (data.board_image_b64) { - updateBoard(data.board_image_b64, data.confidence); - } - addRecentMove(data.move_san || data.move_uci); - break; - - case "no_change": - setStatus("Board unchanged — waiting for opponent's move…", ""); - break; - - case "opponent_turn": - setStatus("Opponent's turn detected. Waiting for their move…", ""); - break; - - case "detection_error": - setStatus(`⚠ ${data.message}`, "error"); - showWaiting("Board not fully visible. Reposition camera overhead."); - break; - - case "engine_error": - setStatus("⚙ Engine restarting… retrying automatically.", ""); - break; - - case "rate_limited": - setStatus("Slowing down analysis pace…", ""); - break; - - case "game_over": - setStatus("Checkmate, stalemate, or game over.", "ok"); - showWaiting("Game over — no legal moves remaining."); - break; - - default: - setStatus(data.message ?? "Unknown response.", ""); - } -} - -function showMove(humanText, san, uci) { - moveWaiting.style.display = "none"; - moveResult.style.display = "block"; - moveText.textContent = humanText ?? "—"; - moveSan.textContent = san ?? uci ?? ""; - moveUci.textContent = uci ? `${uci.slice(0, 2)} → ${uci.slice(2, 4)}` : ""; - - moveResult.classList.remove("move-anim"); - void moveResult.offsetWidth; - moveResult.classList.add("move-anim"); -} - -function showWaiting(msg) { - moveWaiting.style.display = "flex"; - moveResult.style.display = "none"; - if (msg) waitText.textContent = msg; -} - -function setStatus(msg, type = "") { - statusMsg.textContent = msg; - statusBar.className = "status-bar" + (type ? ` ${type}` : ""); -} - -function updateBoard(b64, confidence) { - if (!b64) return; - boardCard.style.display = "block"; - boardImg.src = `data:image/png;base64,${b64}`; - confBadge.textContent = pct(confidence); -} - -function addRecentMove(san) { - if (!san) return; - if (!recentMoves.includes(san)) { - recentMoves.unshift(san); - if (recentMoves.length > 5) recentMoves.pop(); - - recentContainer.style.display = "flex"; - recentPills.innerHTML = recentMoves.map(m => `${m}`).join(""); - } -} - -function pct(val) { - return val != null ? `${Math.round(val * 100)}%` : "—"; -} - -function updateModeInfo() { - const modes = { - win: { - icon: "🏆", - title: "Win Mode", - desc: "Calculates sharp, decisive, high-accuracy moves tailored to win quickly.", - }, - loss: { - icon: "🎭", - title: "Loss Mode", - desc: "Provides believable, human-like inaccuracies without obvious tactical blunders.", - }, - }; - const m = modes[playMode] || modes.win; - modeInfo.innerHTML = ` - ${m.icon} -
- ${m.title} -

${m.desc}

-
`; -} - -// ── Health Check & Engine Status ────────────────────────────────────────── -async function checkBackendHealth() { - setEngineStatus("connecting", "Connecting…"); - try { - const t0 = performance.now(); - const res = await fetch(`${API_BASE}/health`, { signal: AbortSignal.timeout(5000) }); - const latency = Math.round(performance.now() - t0); - if (res.ok) { - const data = await res.json().catch(() => ({})); - const engineName = data.engine === "stockfish" ? "Stockfish 16" : "Python Engine"; - setEngineStatus("online", `Online (${latency}ms)`); - if (engineBadge) engineBadge.textContent = engineName; - } else { - setEngineStatus("offline", `Server Error (${res.status})`); - } - } catch { - setEngineStatus("offline", "Backend Offline"); - } -} - -function setEngineStatus(cls, label) { - engineStatus.className = `status-pill ${cls}`; - engineStatus.querySelector(".status-label").textContent = label; - engineStatus.title = `API: ${API_BASE} (Click to configure)`; -} - -// ── API Configuration Modal ─────────────────────────────────────────────── -function initModal() { - engineStatus.addEventListener("click", openApiModal); - if (btnConfigApi) btnConfigApi.addEventListener("click", openApiModal); - - btnTestPing.addEventListener("click", async () => { - const targetUrl = apiUrlInput.value.trim().replace(/\/+$/, ""); - modalPingStatus.textContent = "Testing connection…"; - try { - const t0 = performance.now(); - const res = await fetch(`${targetUrl}/health`, { signal: AbortSignal.timeout(5000) }); - const ms = Math.round(performance.now() - t0); - if (res.ok) { - modalPingStatus.textContent = `✓ Connected! Response in ${ms}ms`; - modalPingStatus.style.color = "var(--accent)"; - } else { - modalPingStatus.textContent = `✗ HTTP Error ${res.status}`; - modalPingStatus.style.color = "var(--danger)"; - } - } catch (e) { - modalPingStatus.textContent = `✗ Unreachable: ${e.message}`; - modalPingStatus.style.color = "var(--danger)"; - } - }); - - btnResetApiDefault.addEventListener("click", () => { - apiUrlInput.value = DEFAULT_API_BASE; - }); - - btnSaveApi.addEventListener("click", () => { - const val = apiUrlInput.value.trim().replace(/\/+$/, ""); - if (val) { - API_BASE = val; - localStorage.setItem("chess_api_base", API_BASE); - apiModal.close(); - checkBackendHealth(); - } - }); -} - -function openApiModal() { - apiUrlInput.value = API_BASE; - modalPingStatus.textContent = "Click 'Test Connection' to verify server reachability."; - modalPingStatus.style.color = "var(--text-dim)"; - apiModal.showModal(); -} - -async function quickHash(str) { - if (!crypto?.subtle) return str.slice(0, 64); - const buf = await crypto.subtle.digest("SHA-1", new TextEncoder().encode(str)); - return Array.from(new Uint8Array(buf)).map(b => b.toString(16).padStart(2, "0")).join(""); -} diff --git a/backend/frontend/index.html b/backend/frontend/index.html deleted file mode 100644 index 7466703..0000000 --- a/backend/frontend/index.html +++ /dev/null @@ -1,247 +0,0 @@ - - - - - - - - Chess Vision Coach • AI Move Suggester - - - - - - - -
-
- -
- -
-
-
- - -
- - -
- - -
-
- - - -
-
- - -
-
- Camera Feed - -
-
- - -
- 📷 - Point camera overhead at your physical board - Click "Start Analysis" below or switch to "Quick Test" to try without camera -
-
-
- - - - - - - - - - -
- - -
- - -
-
Player Setup
- - -
- -
- - -
-
- - -
- -
- - -
-
- - -
-
- - ≈ 1900 Elo* -
-
- - 10 -
-

* Approximate Elo estimate for practical human play

-
- - -
- - -
-
- - -
-
- Recommended Move - Stockfish 16 -
- - -
-
- ⏳ - Ready. Press "Start Analysis" or choose a Quick Test position. -
- -
- - - - - -
- - Ready for moves. -
-
- - -
-
- 🏆 -
- Win Mode -

Calculates sharp, decisive, high-accuracy moves tailored to win quickly.

-
-
-
- -
-
- - - - - - - - - - - - diff --git a/backend/frontend/style.css b/backend/frontend/style.css deleted file mode 100644 index 9603e67..0000000 --- a/backend/frontend/style.css +++ /dev/null @@ -1,957 +0,0 @@ -/* ═══════════════════════════════════════════════════════════ - Chess Vision Coach — Stylesheet v2.0 - Modern Dark Theme with Cyber-Emerald & Amber Accents - ═══════════════════════════════════════════════════════════ */ - -*, *::before, *::after { - box-sizing: border-box; - margin: 0; - padding: 0; -} - -:root { - color-scheme: light dark; - --bg-deep: #090b0e; - --bg-card: #12161f; - --bg-card2: #1a202c; - --bg-card-hover: #222938; - --border-subtle: rgba(255, 255, 255, 0.08); - --border-focus: rgba(16, 185, 129, 0.5); - - --accent: #10b981; - --accent-light: #34d399; - --accent-glow: rgba(16, 185, 129, 0.25); - - --accent2: #f59e0b; - --accent2-glow: rgba(245, 158, 11, 0.2); - - --primary: #6366f1; - --danger: #ef4444; - --text: #f9fafb; - --text-dim: #9ca3af; - --text-muted: #6b7280; - - --radius-lg: 14px; - --radius-md: 10px; - --radius-sm: 6px; - --gap: 16px; - - accent-color: var(--accent); - scrollbar-color: var(--bg-card2) transparent; -} - -html { - font-size: 16px; - scroll-behavior: smooth; -} - -body { - font-family: 'Space Grotesk', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; - background: var(--bg-deep); - background-image: - radial-gradient(circle at 15% 15%, rgba(16, 185, 129, 0.05) 0%, transparent 40%), - radial-gradient(circle at 85% 85%, rgba(99, 102, 241, 0.04) 0%, transparent 40%); - background-attachment: fixed; - color: var(--text); - min-height: 100dvh; - display: flex; - flex-direction: column; - line-height: 1.5; -} - -/* ── Accessibility ───────────────────────────────── */ -.visually-hidden { - position: absolute !important; - clip-path: inset(50%) !important; - overflow: hidden !important; - width: 1px !important; - height: 1px !important; - margin: -1px !important; - padding: 0 !important; - border: 0 !important; - white-space: nowrap !important; -} - -:focus-visible { - outline: 2px solid var(--accent); - outline-offset: 2px; -} - -/* ── Header ─────────────────────────────────────── */ -.header { - background: rgba(18, 22, 31, 0.85); - backdrop-filter: blur(12px); - -webkit-backdrop-filter: blur(12px); - border-bottom: 1px solid var(--border-subtle); - padding: 0 24px; - height: 64px; - position: sticky; - top: 0; - z-index: 100; -} - -.header-inner { - max-width: 1140px; - margin: 0 auto; - height: 100%; - display: flex; - align-items: center; - justify-content: space-between; -} - -.logo { - display: flex; - align-items: center; - gap: 12px; -} - -.logo-icon { - font-size: 1.8rem; - line-height: 1; - filter: drop-shadow(0 0 8px var(--accent-glow)); -} - -.logo-titles { - display: flex; - flex-direction: column; -} - -.logo-text { - font-weight: 700; - font-size: 1.15rem; - letter-spacing: -0.02em; - color: var(--text); -} - -.logo-badge { - font-size: 0.68rem; - font-weight: 600; - text-transform: uppercase; - letter-spacing: 0.08em; - color: var(--accent); -} - -/* Status Pill */ -.status-pill { - display: flex; - align-items: center; - gap: 8px; - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: 999px; - padding: 6px 16px; - font-size: 0.82rem; - font-family: inherit; - color: var(--text-dim); - cursor: pointer; - transition: all 0.2s ease; -} - -.status-pill:hover { - border-color: var(--accent); - background: var(--bg-card-hover); -} - -.status-dot { - width: 9px; - height: 9px; - border-radius: 50%; - background: #6b7280; - transition: all 0.3s ease; -} - -.status-pill.online .status-dot { - background: var(--accent); - box-shadow: 0 0 10px var(--accent); -} -.status-pill.online .status-label { - color: var(--accent-light); - font-weight: 600; -} - -.status-pill.offline .status-dot { - background: var(--danger); - box-shadow: 0 0 8px rgba(239, 68, 68, 0.4); -} -.status-pill.offline .status-label { - color: var(--danger); -} - -.status-pill.connecting .status-dot { - background: var(--accent2); - animation: pulse 1s infinite alternate; -} - -/* ── Main Layout ────────────────────────────────── */ -.main { - flex: 1; - max-width: 1140px; - width: 100%; - margin: 0 auto; - padding: var(--gap); - display: grid; - grid-template-columns: 1.05fr 0.95fr; - gap: var(--gap); - align-items: start; -} - -@media (max-width: 820px) { - .main { - grid-template-columns: 1fr; - padding: 12px; - } -} - -.col { - display: flex; - flex-direction: column; - gap: var(--gap); -} - -/* ── Universal Cards ────────────────────────────── */ -.card { - background: var(--bg-card); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-lg); - padding: 20px; - box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2); - transition: border-color 0.2s ease; -} - -.card:hover { - border-color: rgba(255, 255, 255, 0.12); -} - -.card-label { - font-size: 0.74rem; - font-weight: 700; - letter-spacing: 0.08em; - text-transform: uppercase; - color: var(--text-dim); - margin-bottom: 14px; - display: flex; - align-items: center; - justify-content: space-between; -} - -/* ── Input Mode Tabs ────────────────────────────── */ -.mode-tabs-card { - padding: 8px; -} - -.tab-group { - display: flex; - gap: 6px; - background: var(--bg-deep); - padding: 4px; - border-radius: var(--radius-md); -} - -.tab-btn { - flex: 1; - display: flex; - align-items: center; - justify-content: center; - gap: 6px; - background: transparent; - border: none; - border-radius: var(--radius-sm); - color: var(--text-dim); - font-family: inherit; - font-size: 0.85rem; - font-weight: 600; - padding: 10px 8px; - cursor: pointer; - transition: all 0.2s ease; -} - -.tab-btn:hover { - color: var(--text); - background: rgba(255, 255, 255, 0.04); -} - -.tab-btn.active { - background: var(--bg-card2); - color: var(--accent); - box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3); -} - -/* ── Camera Card ────────────────────────────────── */ -.camera-wrapper { - position: relative; - background: #000; - border-radius: var(--radius-md); - overflow: hidden; - aspect-ratio: 4 / 3; - box-shadow: inset 0 0 20px rgba(0, 0, 0, 0.8); -} - -#cameraFeed { - width: 100%; - height: 100%; - object-fit: cover; - display: block; -} - -.live-indicator { - font-size: 0.68rem; - font-weight: 700; - color: #ef4444; - letter-spacing: 0.05em; - animation: pulse 1s infinite alternate; -} - -.camera-overlay { - position: absolute; - inset: 0; - display: flex; - flex-direction: column; - align-items: center; - justify-content: center; - text-align: center; - padding: 24px; - background: rgba(10, 14, 20, 0.88); - color: var(--text); - transition: opacity 0.3s; -} - -.camera-overlay.hidden { - opacity: 0; - pointer-events: none; -} - -.overlay-icon { - font-size: 2.8rem; - margin-bottom: 8px; - color: var(--accent); -} - -.overlay-title { - font-size: 1rem; - font-weight: 600; - margin-bottom: 4px; -} - -.overlay-sub { - font-size: 0.82rem; - color: var(--text-dim); - max-width: 320px; -} - -/* ── Drag & Drop Photo Upload ───────────────────── */ -.upload-dropzone { - border: 2px dashed rgba(255, 255, 255, 0.15); - border-radius: var(--radius-md); - padding: 36px 20px; - text-align: center; - display: flex; - flex-direction: column; - align-items: center; - gap: 8px; - cursor: pointer; - background: var(--bg-deep); - transition: all 0.2s ease; -} - -.upload-dropzone:hover, -.upload-dropzone.dragover { - border-color: var(--accent); - background: rgba(16, 185, 129, 0.04); -} - -.upload-icon { - font-size: 2.4rem; - color: var(--accent); -} - -.upload-text { - font-size: 0.92rem; - color: var(--text); -} - -.upload-link { - color: var(--accent); - text-decoration: underline; - cursor: pointer; -} - -.upload-hint { - font-size: 0.75rem; - color: var(--text-muted); -} - -/* ── Presets & Quick Test ───────────────────────── */ -.presets-intro { - font-size: 0.84rem; - color: var(--text-dim); - margin-bottom: 12px; -} - -.preset-buttons { - display: grid; - grid-template-columns: 1fr 1fr; - gap: 8px; - margin-bottom: 16px; -} - -@media (max-width: 500px) { - .preset-buttons { - grid-template-columns: 1fr; - } -} - -.preset-chip { - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: inherit; - font-size: 0.82rem; - font-weight: 600; - padding: 10px 12px; - text-align: left; - cursor: pointer; - transition: all 0.2s ease; -} - -.preset-chip:hover { - border-color: var(--accent); - background: var(--bg-card-hover); -} - -.preset-chip.active { - border-color: var(--accent); - background: rgba(16, 185, 129, 0.12); - color: var(--accent-light); -} - -.custom-fen-row { - display: flex; - gap: 8px; -} - -.custom-fen-input { - flex: 1; - background: var(--bg-deep); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: 'Space Mono', monospace; - font-size: 0.8rem; - padding: 10px 12px; - outline: none; - transition: border-color 0.2s; -} - -.custom-fen-input:focus { - border-color: var(--accent); -} - -/* ── Board preview card ─────────────────────────── */ -.board-wrapper { - border-radius: var(--radius-md); - overflow: hidden; - background: #000; - border: 1px solid var(--border-subtle); -} - -.board-wrapper img { - width: 100%; - display: block; -} - -.conf-badge { - font-size: 0.75rem; - background: var(--bg-card2); - border: 1px solid rgba(16, 185, 129, 0.3); - border-radius: 999px; - padding: 3px 10px; - color: var(--accent-light); - font-family: 'Space Mono', monospace; - font-weight: 700; -} - -/* ── Config card ────────────────────────────────── */ -.control-group { - margin-bottom: 20px; -} - -.ctrl-label { - display: flex; - align-items: center; - justify-content: space-between; - font-size: 0.84rem; - font-weight: 600; - color: var(--text-dim); - margin-bottom: 8px; -} - -.elo-hint { - font-family: 'Space Mono', monospace; - font-size: 0.82rem; - color: var(--accent2); - font-weight: 700; -} - -/* Toggle buttons */ -.toggle-group { - display: flex; - gap: 8px; -} - -.toggle-btn { - flex: 1; - background: var(--bg-card2); - border: 1.5px solid var(--border-subtle); - border-radius: var(--radius-md); - color: var(--text-dim); - font-family: inherit; - font-size: 0.88rem; - font-weight: 600; - padding: 10px 8px; - cursor: pointer; - transition: all 0.15s ease; - display: flex; - align-items: center; - justify-content: center; - gap: 8px; -} - -.toggle-btn:hover { - border-color: rgba(255, 255, 255, 0.2); - color: var(--text); -} - -.toggle-btn.active { - background: var(--accent); - border-color: var(--accent); - color: #062b1a; - font-weight: 700; - box-shadow: 0 2px 12px var(--accent-glow); -} - -.piece-icon { - font-size: 1.2rem; -} - -/* Depth slider */ -.depth-row { - display: flex; - align-items: center; - gap: 14px; -} - -input[type="range"] { - flex: 1; - -webkit-appearance: none; - appearance: none; - height: 6px; - border-radius: 3px; - background: var(--bg-card2); - outline: none; -} - -input[type="range"]::-webkit-slider-thumb { - -webkit-appearance: none; - appearance: none; - width: 20px; - height: 20px; - border-radius: 50%; - background: var(--accent); - cursor: pointer; - box-shadow: 0 0 10px var(--accent-glow); - transition: transform 0.1s; -} - -input[type="range"]::-webkit-slider-thumb:hover { - transform: scale(1.15); -} - -.depth-val { - font-family: 'Space Mono', monospace; - font-size: 1.2rem; - font-weight: 700; - color: var(--accent2); - min-width: 28px; - text-align: right; -} - -.elo-note { - font-size: 0.72rem; - color: var(--text-muted); - margin-top: 6px; -} - -/* Action Buttons */ -.btn-row { - display: flex; - gap: 10px; - margin-top: 8px; -} - -.btn { - font-family: inherit; - font-size: 0.92rem; - font-weight: 700; - padding: 12px 18px; - border-radius: var(--radius-md); - border: none; - cursor: pointer; - transition: all 0.15s ease; - display: inline-flex; - align-items: center; - justify-content: center; - gap: 6px; -} - -.btn-start { - flex: 1.4; - background: var(--accent); - color: #062b1a; - box-shadow: 0 4px 14px var(--accent-glow); -} - -.btn-start:hover:not(:disabled) { - background: var(--accent-light); - transform: translateY(-1px); -} - -.btn-stop { - flex: 1; - background: var(--bg-card2); - color: var(--danger); - border: 1.5px solid var(--danger); -} - -.btn-stop:hover:not(:disabled) { - background: var(--danger); - color: #fff; -} - -.btn-secondary { - background: var(--bg-card2); - color: var(--text); - border: 1px solid var(--border-subtle); - font-size: 0.85rem; -} - -.btn-secondary:hover { - background: var(--bg-card-hover); - border-color: rgba(255, 255, 255, 0.2); -} - -.btn:disabled { - opacity: 0.35; - cursor: not-allowed; - transform: none !important; -} - -/* ── Move Output Card ───────────────────────────── */ -.move-card { - position: relative; - overflow: hidden; -} - -.engine-badge { - font-family: 'Space Mono', monospace; - font-size: 0.7rem; - font-weight: 700; - color: var(--text-dim); - background: var(--bg-card2); - padding: 3px 10px; - border-radius: 999px; - border: 1px solid var(--border-subtle); -} - -.move-display { - background: linear-gradient(145deg, var(--bg-card2), var(--bg-deep)); - border-radius: var(--radius-md); - padding: 24px 20px; - min-height: 128px; - display: flex; - align-items: center; - justify-content: center; - margin-bottom: 14px; - border: 1.5px solid rgba(255, 255, 255, 0.06); - position: relative; -} - -.move-waiting { - display: flex; - flex-direction: column; - align-items: center; - gap: 10px; - color: var(--text-dim); - font-size: 0.9rem; - text-align: center; -} - -.wait-icon { - font-size: 2rem; - animation: pulse 1.5s infinite alternate; -} - -.move-result { - text-align: center; - width: 100%; -} - -.move-header { - display: flex; - align-items: center; - justify-content: center; - gap: 12px; - margin-bottom: 8px; -} - -.move-san { - font-family: 'Space Mono', monospace; - font-size: 1.7rem; - color: var(--accent); - font-weight: 700; - letter-spacing: 0.05em; - text-shadow: 0 0 16px var(--accent-glow); -} - -.move-uci-badge { - font-family: 'Space Mono', monospace; - font-size: 0.85rem; - font-weight: 700; - color: var(--accent2); - background: var(--bg-deep); - padding: 4px 10px; - border-radius: 999px; - border: 1px solid var(--border-subtle); -} - -.move-text { - font-size: 1.35rem; - font-weight: 700; - color: var(--text); - line-height: 1.3; - letter-spacing: -0.01em; -} - -/* Recent Suggestions Trail */ -.recent-moves-container { - margin-bottom: 14px; - display: flex; - align-items: center; - gap: 10px; -} - -.recent-label { - font-size: 0.74rem; - font-weight: 700; - text-transform: uppercase; - color: var(--text-muted); -} - -.recent-pills { - display: flex; - gap: 6px; - flex-wrap: wrap; -} - -.recent-chip { - font-family: 'Space Mono', monospace; - font-size: 0.78rem; - background: var(--bg-card2); - border: 1px solid var(--border-subtle); - border-radius: 999px; - padding: 2px 10px; - color: var(--text-dim); -} - -/* Status Bar */ -.status-bar { - background: var(--bg-card2); - border-radius: var(--radius-sm); - padding: 10px 14px; - font-size: 0.82rem; - color: var(--text-dim); - min-height: 40px; - display: flex; - align-items: center; - gap: 8px; - border: 1px solid var(--border-subtle); -} - -.status-indicator-dot { - width: 7px; - height: 7px; - border-radius: 50%; - background: var(--text-muted); - flex-shrink: 0; -} - -.status-bar.error .status-indicator-dot { background: var(--danger); } -.status-bar.error { color: var(--danger); border-color: rgba(239, 68, 68, 0.3); } - -.status-bar.ok .status-indicator-dot { background: var(--accent); } -.status-bar.ok { color: var(--accent-light); border-color: rgba(16, 185, 129, 0.3); } - -/* ── Mode info card ─────────────────────────────── */ -.info-card { - padding: 14px 18px; -} - -.mode-info { - display: flex; - align-items: flex-start; - gap: 14px; - font-size: 0.84rem; -} - -.mode-icon { - font-size: 1.6rem; - flex-shrink: 0; -} - -.mode-info strong { - display: block; - margin-bottom: 2px; - color: var(--text); - font-size: 0.92rem; -} - -.mode-info p { - color: var(--text-dim); - line-height: 1.45; -} - -/* ── Modal Dialog ───────────────────────────────── */ -.modal-dialog { - border: 1px solid var(--border-subtle); - border-radius: var(--radius-lg); - background: var(--bg-card); - color: var(--text); - padding: 0; - max-width: 480px; - width: 90%; - margin: auto; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7); -} - -.modal-dialog::backdrop { - background: rgba(0, 0, 0, 0.75); - backdrop-filter: blur(4px); -} - -.modal-content { - padding: 24px; - display: flex; - flex-direction: column; - gap: 14px; -} - -.modal-title { - font-size: 1.15rem; - font-weight: 700; -} - -.modal-desc { - font-size: 0.85rem; - color: var(--text-dim); -} - -.modal-input { - background: var(--bg-deep); - border: 1px solid var(--border-subtle); - border-radius: var(--radius-sm); - color: var(--text); - font-family: 'Space Mono', monospace; - font-size: 0.85rem; - padding: 12px; - width: 100%; - outline: none; -} - -.modal-input:focus { - border-color: var(--accent); -} - -.modal-status { - font-size: 0.8rem; - font-family: 'Space Mono', monospace; - color: var(--text-dim); - padding: 6px 0; -} - -.modal-actions { - display: flex; - justify-content: flex-end; - gap: 10px; - margin-top: 8px; -} - -/* ── Footer ─────────────────────────────────────── */ -.footer { - font-size: 0.78rem; - color: var(--text-muted); - padding: 20px; - border-top: 1px solid var(--border-subtle); - margin-top: auto; -} - -.footer-inner { - max-width: 1140px; - margin: 0 auto; - display: flex; - align-items: center; - justify-content: space-between; - flex-wrap: wrap; - gap: 12px; -} - -.footer-links { - display: flex; - align-items: center; - gap: 8px; -} - -.footer-link-btn, -.footer-link { - background: none; - border: none; - color: var(--text-dim); - font-size: inherit; - font-family: inherit; - cursor: pointer; - text-decoration: underline; - transition: color 0.15s; -} - -.footer-link-btn:hover, -.footer-link:hover { - color: var(--accent); -} - -/* ── Animations ─────────────────────────────────── */ -@keyframes pulse { - 0% { opacity: 1; } - 100% { opacity: 0.4; } -} - -@keyframes slideIn { - from { - opacity: 0; - transform: translateY(10px) scale(0.98); - } - to { - opacity: 1; - transform: translateY(0) scale(1); - } -} - -.move-anim { - animation: slideIn 0.35s cubic-bezier(0.16, 1, 0.3, 1); -} - -@media (prefers-reduced-motion: reduce) { - .move-anim, - .live-indicator, - .wait-icon { - animation: none; - } -} diff --git a/backend/requirements-dev.txt b/backend/requirements-dev.txt new file mode 100644 index 0000000..5ae2984 --- /dev/null +++ b/backend/requirements-dev.txt @@ -0,0 +1,3 @@ +-r requirements.txt +pytest>=8,<10 +httpx>=0.27,<0.29 diff --git a/backend/tests/generate_camera_fixtures.py b/backend/tests/generate_camera_fixtures.py new file mode 100644 index 0000000..e9fe24a --- /dev/null +++ b/backend/tests/generate_camera_fixtures.py @@ -0,0 +1,19 @@ +"""Generate reproducible synthetic camera fixtures for browser integration QA.""" +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import chess +import cv2 +from test_board_detector import board_image + + +if __name__ == "__main__": + output = Path(__file__).resolve().parents[2] / ".tmp" + output.mkdir(exist_ok=True) + board = chess.Board() + for name, move in [("camera-start.png", None), ("camera-e4.png", "e2e4")]: + if move: + board.push_uci(move) + assert cv2.imwrite(str(output / name), board_image(board)), "Could not write camera fixture" + print("Generated synthetic camera fixtures in .tmp") diff --git a/docs/API.md b/docs/API.md index a3cca0f..5fe8a55 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1,155 +1,152 @@ -# API Documentation — Chess Vision Coach +# API reference -Base URL: `https://your-app.up.railway.app` +The API is served by FastAPI at the same origin as the Railway-hosted frontend. Interactive documentation is available at `/docs`. ---- +## `GET /health` -## Endpoints +Returns HTTP 200 when the engine service and detector are ready, or HTTP 503 while they are not ready. -### `GET /health` - -Health check. Returns 200 if the backend is running. - -**Response:** ```json -{ "status": "ok", "engine": "stockfish", "detector": "opencv" } +{ + "status": "ok", + "engine": "stockfish", + "detector": "opencv", + "recognition": "legal-occupancy-tracking", + "requires_setup_for_unknown_positions": true, + "camera_overlay": true +} ``` ---- +`engine` is `python-chess-fallback` when Stockfish is unavailable. A ready fallback service does not imply Stockfish strength. -### `GET /api/depth-info` +## `POST /api/analyze` -Returns the depth → approximate Elo mapping used by the frontend dropdown. +Analyzes a camera frame or an authoritative FEN within a tracking session. -**Response:** ```json { - "depths": [ - { "depth": 4, "approx_elo": 800 }, - { "depth": 5, "approx_elo": 1000 }, - { "depth": 6, "approx_elo": 1200 }, - { "depth": 7, "approx_elo": 1400 }, - { "depth": 8, "approx_elo": 1600 }, - { "depth": 9, "approx_elo": 1750 }, - { "depth": 10, "approx_elo": 1900 }, - { "depth": 11, "approx_elo": 2000 }, - { "depth": 12, "approx_elo": 2100 }, - { "depth": 13, "approx_elo": 2200 }, - { "depth": 14, "approx_elo": 2300 }, - { "depth": 15, "approx_elo": 2400 }, - { "depth": 16, "approx_elo": 2600 } - ], - "note": "Elo values are approximate estimates, not official ratings." + "image_b64": "", + "player_color": "w", + "orientation": "w", + "depth": 10, + "mode": "win", + "session_id": "" } ``` ---- +| Field | Default | Meaning | +| --- | --- | --- | +| `image_b64` | `null` | Encoded image; a base64 data URL is also accepted. Decoded image limit: 6 MB. | +| `fen` | `null` | Direct position input. When present, it takes precedence over the image. | +| `setup_fen` | `null` | Exact position used to calibrate an image once. Later frames omit it and use the session's trusted position. | +| `player_color` | `"w"` | The color receiving advice: `w` or `b`. | +| `orientation` | `"auto"` | Color at the bottom of the captured board: `w`, `b`, or `auto`. Automatic inference is most useful at the standard opening setup. | +| `side_to_move` | `null` | Optional `w` or `b` override when calibrating `setup_fen`; it does not rewrite an ordinary trusted FEN. | +| `board_corners` | `null` | Four normalized `[x, y]` points in image order: top-left, top-right, bottom-right, bottom-left. | +| `depth` | `10` | Integer from 4 through 16. Engine search also has a time budget. | +| `mode` | `"win"` | `win` for stronger advice; `loss` for deliberately weaker choices. | +| `session_id` | `"default"` | Unique identifier, 1–128 characters. Use a separate identifier for each camera session. | -### `POST /api/analyze` +Supply `image_b64` or `fen`. FEN strings have a maximum length of 128 characters and must describe a legal chess position. Piece types in a supplied FEN are authoritative: the detector can verify their colors and occupied squares, but cannot independently verify arbitrary physical piece identities. -Main analysis endpoint. +For a standard new game, the detector uses the standard piece arrangement when the observed starting occupancy matches. For an unknown midgame image, it returns `setup_required`; it does not invent a position. Subsequent frames match an unchanged position, one legal move, or two consecutive legal moves from the session's trusted position. + +### Move response -**Request body (JSON):** ```json { - "image_b64": "string (base64 JPEG/PNG — no data URL prefix)", - "player_color": "w | b", - "depth": 10, - "mode": "win | loss", - "session_id": "string (unique per browser session)" + "status": "ok", + "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "turn": "w", + "move_uci": "e2e4", + "move_san": "e4", + "move_human": "Pawn to e4", + "confidence": 0.9, + "engine": "stockfish", + "approx_elo": 1900, + "board_image_b64": null, + "board_detected": true, + "board_locked": true, + "board_corners": [[0.1, 0.1], [0.9, 0.1], [0.9, 0.9], [0.1, 0.9]], + "orientation": "w", + "requires_setup": false, + "piece_count": 32, + "pieces_detected": true, + "overlay": { + "from_square": "e2", + "to_square": "e4", + "piece": "pawn", + "promotion": null, + "orientation": "w", + "from": [0.55, 0.75], + "to": [0.55, 0.55], + "from_polygon": [[0.5, 0.7], [0.6, 0.7], [0.6, 0.8], [0.5, 0.8]], + "to_polygon": [[0.5, 0.5], [0.6, 0.5], [0.6, 0.6], [0.5, 0.6]] + } } ``` -**Response statuses and their meanings:** +The move above illustrates the response format; the engine can select another legal opening move. `fen` describes the position **before** the suggested move. `turn` comes from that position rather than the player's selected color. -#### `ok` — Move found -```json -{ - "status": "ok", - "fen": "rnbqkbnr/.../8 w KQkq - 0 1", - "turn": "w", - "move_uci": "e2e4", - "move_san": "e4", - "move_human": "Move Pawn to e4", - "confidence": 0.87, - "approx_elo": 1900, - "board_image_b64": "" -} -``` +All geometry uses the uploaded image coordinate system, normalized to `[0, 1]`. The frontend captures its complete camera image inside a square with letterboxing, and draws the returned geometry over that same square. `from` and `to` are projected square centers; the polygons are the projected square boundaries. When there is no image geometry, `overlay` can contain the square names without coordinate fields. -Field notes: -- `confidence` — 0.0 to 1.0. Board detection quality. Values below 0.45 are rejected server-side. -- `approx_elo` — Approximate strength of the suggestion. Matches `depth-info` values. -- `board_image_b64` — 480×480 PNG of the warped/detected board with a green arrow showing the recommended move. Can be null. +`board_image_b64` remains `null` for compatibility; the client renders the overlay directly. `confidence` describes detector measurements, not a calibrated probability of piece-type recognition. `approx_elo` is a legacy rough estimate, not a measured rating, and is `null` for the Python fallback. -#### `no_change` — Board hasn't moved -```json -{ - "status": "no_change", - "message": "Board unchanged. Waiting for opponent's move.", - "fen": "...", - "confidence": 0.91 -} -``` -Frontend should display a waiting message and not call Stockfish. +### Response statuses -#### `opponent_turn` — Board changed but it's not your move -```json -{ - "status": "opponent_turn", - "message": "Opponent's turn detected. Waiting...", - "fen": "...", - "confidence": 0.88 -} -``` +| Status | Meaning and client behavior | +| --- | --- | +| `ok` | Legal move found. Display its text and overlay. | +| `no_change` | Cached advice for the unchanged chess state and analysis settings. The full move remains in the response. Keep displaying it and use the current frame's geometry. | +| `opponent_turn` | Trusted position is the opponent's turn. Clear the move arrow and keep scanning. | +| `setup_required` | Board geometry exists, but piece identities need calibration. Offer standard starting setup or an exact FEN. | +| `position_uncertain` | No unique legal tracked position matches the frame. Clear the arrow and request a steady, unobstructed board or position confirmation. | +| `detection_error` | No reliable board or readable image was found. Clear the arrow and keep scanning. | +| `invalid_fen` | Illegal or malformed supplied position. Correct its pieces, side to move, and state fields. HTTP 400. | +| `rate_limited` | Requests are too close together. HTTP 429; observe `Retry-After` and the `retry_after` JSON field. | +| `game_over` | Checkmate, stalemate, or another automatic game-ending condition. No move is returned. | +| `engine_error` | Analysis failed. HTTP 503; retry the same position. Failed results do not poison the move cache. | -#### `detection_error` — Board could not be reliably detected -```json -{ - "status": "detection_error", - "message": "Board not detected. Please ensure the full board is visible and well-lit.", - "confidence": 0.22 -} -``` -Frontend should show the message and request the user reposition the camera. +Detected geometry can be returned even when the position needs setup. `board_locked` requires both a detected board and detected pieces. An empty checkerboard does not produce a move. -#### `rate_limited` — Too many requests per session -```json -{ - "status": "rate_limited", - "message": "Analysing too fast. Slow down." -} -``` -HTTP 429. Frontend should back off. +The cache includes piece placement, turn, castling rights, en passant state, the halfmove clock, player color, depth, and mode. Changing those settings triggers fresh advice. Camera tracking advances only from a validated position, and the engine result is checked against its legal moves. + +## `POST /api/analyze-fen` + +Evaluates a legal FEN directly without camera detection or a tracking session: -#### `game_over` — No legal moves in position ```json { - "status": "game_over", - "message": "Game over or no legal moves." + "fen": "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "depth": 10, + "mode": "win" } ``` ---- - -### `POST /api/reset-session` +The endpoint returns `ok`, `game_over`, `invalid_fen`, or `engine_error` and the corresponding move fields. It uses the side to move from the FEN. Optional `player_color` is accepted for compatibility and does not change that side. Confidence is `1.0` for supplied-position input; it is not a camera recognition score. -Clears the FEN cache and rate-limit timer for a session. -Call this when the user presses "Start Analysis". +## `POST /api/reset-session?session_id=...` -**Query param:** `session_id` (string) +Clears the trusted position, cached result, and request timer for one session: -**Response:** ```json -{ "status": "reset", "session_id": "abc123" } +{"status": "reset", "session_id": "camera-session"} ``` ---- +The frontend can also begin a new game by creating a new session identifier. Sessions are kept in process memory, expire after 30 minutes of inactivity, and are lost when the backend restarts. + +## `GET /api/depth-info` + +Returns the legacy `depths` list with entries containing `depth` and `approx_elo`, plus a note that the estimates are not official ratings. The frontend presents depth as Quick, Balanced, or Deeper rather than promising an Elo rating. + +## HTTP errors -## Error codes +| Code | Meaning | +| --- | --- | +| 400 | Missing input, invalid base64, or illegal FEN. | +| 413 | Decoded image exceeds 6 MB. | +| 422 | Request field validation failed, such as invalid color, depth, or corner coordinates. | +| 429 | Per-session request interval reached. | +| 503 | Engine unavailable or all tracking-session slots busy. | -| HTTP Code | Meaning | -|---|---| -| 400 | Invalid base64 image data | -| 429 | Rate limited (min 1s between requests per session) | -| 500 | Stockfish engine error | +Read `message` for structured status errors or `detail` for FastAPI input errors. Do not reuse a stale arrow after an uncertain position or failed analysis. diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index d6b6bc9..af008fc 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -1,82 +1,58 @@ -# Performance Optimization Notes +# Performance and operating limits -## Image Pipeline +The application favors prompt, bounded analysis and reliable state transitions. These notes describe implementation choices, not measured guarantees for a particular phone, network, board, or Railway plan. -### Resolution choice: 480×480 -- Phone camera native: ~1920×1080 (≈4MB JPEG raw) -- After resize to 480×480: ≈30-70KB JPEG at quality 0.82 -- Bandwidth savings: ~97% reduction -- Board detection accuracy: No meaningful loss at 480px — chess squares are 60px each, plenty for colour classification. +## Camera and network -### JPEG quality 0.82 -- Quality 0.90+ → no accuracy gain, +40% file size -- Quality 0.70 → noticeable artifacts in square boundaries, reduces detection accuracy -- 0.82 is the sweet spot for phone camera over 4G +The frontend captures a 720-by-720 JPEG at quality `0.9`. The complete native camera frame is scaled to fit and letterboxed, so a landscape or portrait source keeps all visible board corners. The square view and captured image use the same alignment. ---- +Camera scans are scheduled after the preceding request completes, with a 1.25-second interval. This prevents overlapping requests from building a backlog. Requests time out after 15 seconds, and a generation check discards responses from an old camera, photo, or settings state. -## Stockfish +The previous partial-image hash shortcut has been removed. Hashing a JPEG prefix can miss changed squares; every scheduled frame now reaches detection. An unchanged validated position still avoids an engine search through the server's result cache. -### Persistent process -- Without persistence: each request spawns a new process = 200-400ms overhead + CPU spike -- With persistence: process kept alive, reused = 0ms spawn overhead -- Lock used: `threading.Lock` guards concurrent access (FastAPI uses thread pool for sync code) +Scanning pauses when the tab is hidden. Camera tracks are stopped when the user stops the camera or leaves the page. Payload size and elapsed time depend on image content and network conditions; there is no fixed bandwidth-per-move guarantee. -### Hash/RAM settings (Railway free tier safe) -- `Hash: 64MB` — transposition table. 256MB would be faster but risks OOM on Railway Starter ($5/mo). -- `Threads: 2` — Railway Starter has 2 vCPUs. Setting higher has no benefit. +## Vision ---- +The detector limits incoming images to a maximum dimension of 960 pixels and warps a verified board to 480-by-480 for square measurements. It checks an 8-by-8 alternating pattern before accepting a candidate rectangle and uses adaptive foreground/color measurements for occupancy. -## Board Detection +This pipeline has no learned piece-type model. Its valid operating path is: -### Duplicate frame skip -- SHA-1 hash of the first 2KB of the base64 image -- If hash matches last frame, skip the entire detection + Stockfish pipeline -- Eliminates ~80% of redundant work during static positions +1. Calibrate the standard starting arrangement or an exact supplied FEN. +2. Measure occupied squares and piece colors in the next frame. +3. Match an unchanged position, one legal move, or two consecutive legal moves. +4. Keep the position uncommitted when no unique match exists. -### FEN cache -- Full FEN comparison (board part only, ignoring clocks) -- Prevents Stockfish calls when the board hasn't changed between frames +Clear overhead views and visible square backgrounds work best. Glare, shadows, similar piece and board colors, hands over squares, partial boards, and missed move sequences can prevent a unique result. Different promotions can have the same occupancy and require explicit position confirmation. ---- +Automatic starting calibration assumes that a matching starting occupancy contains the normal starting piece arrangement. Same-color piece types cannot be distinguished from occupancy alone. -## Network (4G India) +## Chess engine -- Poll interval: 2500ms — fast enough to catch moves, slow enough not to waste data -- Per-frame upload: ~40-60KB JPEG -- Per-frame download: ~25KB (JSON with base64 board image) -- Total per move: ~100KB — negligible on 4G +Stockfish is kept in a persistent UCI process with one thread and a 32 MB hash table. A lock serializes commands to that process, while FastAPI runs detector and engine work in a thread pool so health and unrelated API requests can proceed. ---- +Stockfish search uses both the selected depth and a 350 ms search budget. Weaker mode can perform an additional short candidate analysis. Process startup, UCI communication, detection, queueing, and network time are additional overhead; the search budget is not a whole-request latency guarantee. -## Railway resource usage (estimated) +When Stockfish cannot run, the Python evaluator performs a shallower search with a 300 ms target budget and returns legal advice. Responses label this fallback and omit an Elo estimate. Its recommendations should not be treated as Stockfish strength. -| Resource | Idle | During analysis | -|---|---|---| -| CPU | ~1% | ~15-25% | -| RAM | ~80MB | ~120MB | -| Network | 0 | ~100KB/move | +## Sessions and caching -Fits comfortably in Railway Starter plan ($5/mo). +The server caches successful advice using the chess state that affects legal moves: piece placement, side to move, castling rights, and en passant state, together with player color, depth, and mode. An unchanged position returns the complete cached suggestion and recalculated geometry for the current frame. ---- +Failed engine calls do not store a successful-result cache entry. The validated camera position remains available so the next frame can retry it. Invalid or unclear detections cannot overwrite the trusted position. -## Future optimizations +Each session serializes its requests. Session state is in memory, with up to 512 sessions and a 30-minute inactivity expiry. A backend restart clears it. Multiple server processes or replicas do not share that state; keep a camera session on one backend instance unless shared storage is added. -1. **WebSocket instead of HTTP polling** - - Eliminates HTTP handshake overhead (~20ms saved per frame) - - Use if latency becomes noticeable in fast bullet games +The default minimum request interval is 0.5 seconds per session and can be changed with `MIN_INTERVAL_SEC`. The frontend's normal scan interval already exceeds this default. -2. **YOLOv8 piece detection** - - Would improve piece-type classification (currently all pieces shown as pawns in FEN) - - Add `ultralytics` to requirements, download `yolov8n-chess.pt` (~6MB) - - Trade-off: +100ms inference on CPU, +200MB RAM +## Validation -3. **Frontend PWA** - - Add `manifest.json` and service worker for home screen install on Android - - Enables offline caching of static assets +Run the detector, engine, and API regressions together: -4. **Rate limit tuning** - - Current: 1s minimum between requests per session - - Reduce to 0.5s for faster capture during fast games +```powershell +& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider +npm test +npm run test:browser +``` + +Camera geometry tests and synthetic-board regressions verify expected transformations and state changes. They do not establish recognition accuracy across arbitrary physical chess sets. Evaluate real phone-camera captures from the intended board and lighting before making accuracy or latency claims. diff --git a/docs/README.md b/docs/README.md index bf0bc14..744a50e 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,238 +1,83 @@ -# Chess Vision Coach +# Setup and camera workflow -A lightweight web-based chess move suggester powered by Stockfish + OpenCV. -Point your phone camera at the board — get your next move instantly. +## How the app works ---- +The frontend captures the complete camera image into a square canvas with letterboxing rather than cropping away board corners. The backend detects the board quadrilateral, verifies its alternating 8-by-8 pattern, and measures piece color and occupied squares. The returned corners and move coordinates are normalized to that same captured image. -## Architecture Decisions +The frontend uses a perspective transform to draw the move arrow over the live camera or uploaded photo. It does not open a separate board-overlay window. -### Why Cloudflare Pages (not GitHub Pages)? +Piece identity comes from a known position: either the normal opening setup or an exact FEN supplied by the user. Legal move matching then preserves kings, queens, other piece types, side to move, castling rights, and en passant information. The detector never repairs an unreadable image by adding kings, changing pieces to queens, or deleting attacking pieces. -| Feature | GitHub Pages | Cloudflare Pages | -|---|---|---| -| HTTPS | ✓ | ✓ | -| Camera API (requires HTTPS) | ✓ | ✓ | -| Edge CDN | Basic | Global PoPs (faster in India) | -| Custom headers (Permissions-Policy) | ✗ | ✓ (via `_headers`) | -| Deploy from CLI | Extra setup | `wrangler pages deploy` | +## Start a new game -**Chosen: Cloudflare Pages** — custom headers let us set `Permissions-Policy: camera=*` -explicitly, which avoids camera permission issues on some Android browsers. -GitHub Pages works too if you prefer it (just push frontend/ to gh-pages branch). +1. Arrange the pieces in their normal starting positions. +2. Select your playing color and the color at the bottom of the camera view. +3. Select **Start camera** and allow camera access in the browser. +4. Keep all 64 squares visible, preferably from overhead with even light. +5. Once the board is locked, follow the arrow and the move written below the camera view. ---- +After you move, the app watches for your opponent's reply. An unchanged board retains the current suggestion; a detected opponent turn clears it. Keep hands clear while a new position is being read. -### Why OpenCV (not YOLOv8)? +## Analyze an existing game -| | OpenCV | YOLOv8 | -|---|---|---| -| Model size | 0 MB | ~50-200 MB | -| Inference time | ~20-40ms | ~100-200ms (CPU) | -| GPU required | No | No (but much slower) | -| Accuracy (overhead angle, stable board) | Good | Excellent | -| Railway RAM usage | Low | High | +Open **Position & preferences**, enter the exact current FEN, choose the side to move, and select **Use for camera** while the camera or photo is visible. The backend checks that the observed piece colors and occupancy match that setup before starting tracking. Piece types cannot be verified from color and occupancy alone, so the FEN must describe the real board accurately. -**Chosen: OpenCV** for this use-case (stable overhead phone camera, standard board). -YOLOv8 would be the right choice if: boards are partially visible, taken at odd angles, -or pieces are exotic 3D sets. The hybrid approach (OpenCV for board detection, YOLO -for piece classification) would be the ideal future upgrade. +**Analyze FEN** evaluates a position directly and displays an example board in the same square frame. **Try a demo** provides a starting-position example without camera access. ---- +The vision pipeline does not independently identify arbitrary midgame pieces. It needs calibration when joining a game midway, after more than two moves are missed, or when several legal positions have identical observed occupancy, such as different promotion choices. -## Project Structure +## Board alignment -``` -chess-vision-coach/ -├── frontend/ -│ ├── index.html # Single-page UI -│ ├── style.css # Dark theme, Space Grotesk font -│ ├── app.js # Camera capture, API calls, UI logic -│ └── _headers # Cloudflare Pages HTTP headers -│ -├── backend/ -│ ├── main.py # FastAPI app, lifespan startup -│ ├── Procfile # Railway process definition -│ ├── nixpacks.toml # Installs stockfish binary on Railway -│ ├── requirements.txt -│ ├── routers/ -│ │ └── analysis.py # POST /api/analyze, GET /api/depth-info -│ └── services/ -│ ├── stockfish_service.py # Persistent Stockfish wrapper -│ └── board_detector.py # OpenCV board + piece detection -│ -├── docs/ -│ ├── README.md # ← you are here -│ ├── API.md # Full API reference -│ └── PERFORMANCE.md # Optimization notes -│ -└── models/ # Empty — reserved for future YOLO weights -``` - ---- +Automatic alignment verifies the board pattern instead of treating any rectangle as a chessboard. When automatic alignment is difficult, select **Set corners** and tap the board's top-left, top-right, bottom-right, then bottom-left corner. Crossed or degenerate corners are rejected. **Unlock** clears the calibration and scans again. -## Local Setup +Orientation describes the camera view, independently of whose turn it is or which color you play. Turning the camera to the opposite side requires changing the orientation and recalibrating. A partial board, glare, low contrast, or a hand over pieces can cause the app to withhold a suggestion until a readable frame returns. -### Prerequisites +## Local development -- Python 3.11+ -- Stockfish installed locally - - **Ubuntu/Debian:** `sudo apt install stockfish` - - **macOS:** `brew install stockfish` - - **Windows:** Download from https://stockfishchess.org/download/ +From the repository root on Windows: -### Backend - -```bash -cd backend +```powershell python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate -pip install -r requirements.txt - -# If Stockfish is not at /usr/games/stockfish, set the path: -export STOCKFISH_PATH=/path/to/stockfish - -uvicorn main:app --reload --port 8000 +& .venv\Scripts\python.exe -m pip install -r backend/requirements.txt +& .venv\Scripts\python.exe -m uvicorn main:app --app-dir backend --reload --host 127.0.0.1 --port 8080 ``` -API will be available at: http://localhost:8000 -Docs at: http://localhost:8000/docs - -### Frontend - -```bash -# No build step needed — pure HTML/CSS/JS - -# Option 1: Python simple server -cd frontend -python -m http.server 5500 - -# Option 2: VS Code Live Server extension - -# Option 3: npx serve -npx serve frontend/ -``` - -**Important:** Edit `frontend/app.js` line 12: -```js -const API_BASE = "http://localhost:8000"; // for local dev +On macOS or Linux, use `.venv/bin/python` in place of `.venv\Scripts\python.exe`. Open `http://127.0.0.1:8080` for the app and `/docs` for interactive API documentation. + +Install Stockfish through your system package manager or [the official download page](https://stockfishchess.org/download/). Set `STOCKFISH_PATH` if the executable is not discoverable. Health and move responses distinguish Stockfish from the weaker Python fallback. + +The frontend is plain HTML, CSS, and JavaScript modules. No frontend compilation is needed. Serve it through FastAPI to use the local API automatically. If a separate frontend server runs on another port, use its URL with `?api=http://127.0.0.1:8080` or select the API in **Connection settings**. + +## Project layout + +```text +frontend/ + index.html Mobile-first camera UI + style.css Responsive styles + app.js Camera, requests, tracking UI, and overlay rendering + overlay.js Perspective and square-coordinate helpers + tests/ Frontend regression tests + _headers Headers for separate static hosting +backend/ + main.py FastAPI startup, health, and static frontend serving + routers/analysis.py + services/board_detector.py + services/stockfish_service.py + tests/ + requirements.txt +Dockerfile Root deployment: backend and frontend together +railway.json Railway build and health-check configuration ``` ---- - -## Railway Deployment (Backend) - -1. **Create Railway project** - ``` - railway login - railway new chess-vision-coach - ``` - -2. **Link backend folder** - ``` - cd backend - railway link - ``` - -3. **Set environment variables** (in Railway dashboard or CLI) - ``` - STOCKFISH_PATH=/run/current-system/sw/bin/stockfish - PORT=8000 - ``` - > `nixpacks.toml` automatically installs stockfish via Nix packages. - > After first deploy, check the exact binary path in Railway logs and update STOCKFISH_PATH if needed. - -4. **Deploy** - ``` - railway up - ``` - -5. **Get your Railway URL** - Railway will assign: `https://your-app-name.up.railway.app` +## Deployment and checks -6. **Update frontend** — edit `frontend/app.js`: - ```js - const API_BASE = "https://your-app-name.up.railway.app"; - ``` +See [Railway deployment](../backend/DEPLOY.md) for the recommended single-service deployment. A separate static host can publish `frontend/` with no build command and select the Railway API through connection settings. ---- - -## Cloudflare Pages Deployment (Frontend) - -1. **Install Wrangler** - ``` - npm install -g wrangler - wrangler login - ``` - -2. **Deploy** - ``` - cd frontend - wrangler pages deploy . --project-name chess-vision-coach - ``` - -3. Your app is live at: `https://chess-vision-coach.pages.dev` - -**Alternative — GitHub auto-deploy:** -1. Push repo to GitHub. -2. Go to Cloudflare Pages → Create Project → Connect to Git. -3. Set build output directory: `frontend/` -4. Leave build command empty. - ---- - -## Environment Variables - -| Variable | Default | Description | -|---|---|---| -| `STOCKFISH_PATH` | `/usr/games/stockfish` | Absolute path to the Stockfish binary | -| `PORT` | `8000` | HTTP port (Railway sets this automatically) | - ---- - -## API Reference - -See `docs/API.md` for full details. - -### Quick reference - -**POST `/api/analyze`** -```json -{ - "image_b64": "", - "player_color": "w", - "depth": 10, - "mode": "win", - "session_id": "abc123" -} -``` - -**Response (success):** -```json -{ - "status": "ok", - "fen": "rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1", - "turn": "w", - "move_uci": "e2e4", - "move_san": "e4", - "move_human": "Move Pawn to e4", - "confidence": 0.87, - "approx_elo": 1900, - "board_image_b64": "" -} +```powershell +& .venv\Scripts\python.exe -m pytest backend/tests -q -p no:cacheprovider +npm install +npm test +npm run test:browser ``` -**Other statuses:** `no_change` · `opponent_turn` · `detection_error` · `rate_limited` · `game_over` - ---- - -## Performance Notes - -See `docs/PERFORMANCE.md` for full details. - -- **Frame capture:** 480×480 px JPEG at quality 0.82 ≈ 30-60 KB per upload. -- **Poll interval:** 2500ms (one frame every 2.5 seconds) is plenty for over-the-board play. -- **Duplicate frame skip:** SHA-1 hash of first 2KB avoids sending identical frames. -- **Persistent Stockfish:** Engine started once at boot; each request reuses the same process. -- **FEN cache:** Board changes detected before calling Stockfish — zero engine calls for unchanged positions. -- **OpenCV no-model:** No model weights to load; board detection is instant CPU math. +See [API reference](API.md) for request and response details and [performance notes](PERFORMANCE.md) for timing and tracking limits.