Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.git
.venv
.tmp
.pytest_cache
.wrangler
node_modules
test-results
**/__pycache__
**/*.pyc
.env
.env.*
51 changes: 51 additions & 0 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
@@ -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
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,9 @@ models/*.weights

# Node (if using Wrangler CLI)
node_modules/

# Local verification and deployment artifacts
.tmp/
.pytest_cache/
.wrangler/
test-results/
4 changes: 3 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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}"]
87 changes: 48 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,57 +1,66 @@
# Chess Vision Coach

<div align="center">
<img src="https://img.shields.io/badge/Python-3.11+-blue.svg" alt="Python Version" />
<img src="https://img.shields.io/badge/FastAPI-0.111.0-green.svg" alt="FastAPI" />
<img src="https://img.shields.io/badge/OpenCV-4.9.0-red.svg" alt="OpenCV" />
<img src="https://img.shields.io/badge/Stockfish-16-orange.svg" alt="Stockfish" />
</div>
A phone-friendly chess camera coach with a move arrow directly over your board and a plain-language suggestion such as **Pawn to d4**.

<p align="center">
<strong>Point your phone camera at a chess board. Get your next move. No bullshit.</strong>
</p>
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

---
<div align="center">
Built with ❤️ for chess enthusiasts everywhere.
</div>
- [Setup and camera workflow](docs/README.md)
- [API reference](docs/API.md)
- [Performance and operating limits](docs/PERFORMANCE.md)
- [Railway deployment](backend/DEPLOY.md)
80 changes: 42 additions & 38 deletions backend/DEPLOY.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 4 additions & 2 deletions backend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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}"]
32 changes: 30 additions & 2 deletions backend/main.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import os
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

Expand Down Expand Up @@ -36,10 +39,11 @@ async def lifespan(app: FastAPI):

app = FastAPI(
title="Chess Vision Coach API",
version="1.0.0",
version="3.0.0",
description="Lightweight chess move suggester via camera + Stockfish.",
lifespan=lifespan,
)

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
Expand All @@ -49,10 +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"}
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)

# 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")
3 changes: 3 additions & 0 deletions backend/requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-r requirements.txt
pytest>=8,<10
httpx>=0.27,<0.29
Loading
Loading