diff --git a/backend/routers/analysis.py b/backend/routers/analysis.py index bf559fe..b42c388 100644 --- a/backend/routers/analysis.py +++ b/backend/routers/analysis.py @@ -25,11 +25,17 @@ SESSION_TTL_SEC = 30 * 60 MAX_SESSIONS = 512 MAX_IMAGE_BYTES = 6 * 1024 * 1024 +GEOMETRY_HOLD_SEC = 8.0 @dataclass class CameraSession: previous_fen: Optional[str] = None + board_corners: Optional[list] = None + orientation: Optional[str] = None + corners_source: str = "auto" + geometry_seen: float = 0.0 + tracking_failures: int = 0 cache_key: Optional[tuple] = None result: Optional[dict] = None last_request: float = 0.0 @@ -48,6 +54,7 @@ class AnalyzeRequest(BaseModel): orientation: Literal["w", "b", "auto"] = "auto" side_to_move: Optional[Literal["w", "b"]] = None board_corners: Optional[list[list[float]]] = None + corners_source: Literal["auto", "tracked", "manual"] = "auto" 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) @@ -163,26 +170,92 @@ def square_points(square): def _geometry(detection: Optional[dict], body: AnalyzeRequest) -> dict: + camera_read = detection is not None detection = detection or {} return { "board_detected": bool(detection.get("board_detected", detection.get("fen"))), - "board_corners": detection.get("board_corners", body.board_corners), + # Submitted corners are a hint, not evidence that this frame contains + # a board. Only the detector/session may retain them on a camera read. + "board_corners": detection.get("board_corners") if camera_read else 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"))), + "quality": detection.get("quality"), + "recognition": detection.get("recognition"), + "position_verified": bool(detection.get("fen") and detection.get("position_verified", True)) if camera_read else bool(body.fen), + "lock_state": detection.get("lock_state", "locked" if detection.get("board_detected") else "searching"), + "geometry_held": bool(detection.get("geometry_held", False)), + "corners_source": detection.get("corners_source", body.corners_source), + "lock_age_ms": detection.get("lock_age_ms", 0), + "lock_released": bool(detection.get("lock_released", False)), } 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["board_locked"] = bool(result["board_corners"] and ( + (result["board_detected"] and result["pieces_detected"]) or result["geometry_held"] or + result["corners_source"] == "manual")) result["overlay"] = _overlay( result["fen"], result.get("move_uci"), result["board_corners"], result["orientation"] - ) if result.get("fen") else None + ) if result.get("fen") and result["position_verified"] else None + logger.info("Camera analysis status=%s locked=%s position_verified=%s confidence=%s recognition=%s", + result.get("status"), result["board_locked"], result["position_verified"], + result.get("confidence"), result.get("recognition")) return result +def _remember_geometry(detection: dict, body: AnalyzeRequest, session: CameraSession) -> dict: + """A transient unreadable frame must not erase a verified board boundary. + + Held geometry is explicitly marked and never carries a move or verified FEN. + It is a short-lived alignment aid while the detector reacquires the board. + """ + now = time.monotonic() + if detection.get("board_detected") and detection.get("board_corners"): + source = detection.get("corners_source", "manual" if body.board_corners and + body.corners_source == "manual" else session.corners_source) + # A detector that rejected manual geometry may have found a different + # board automatically. Preserve the provenance of the accepted corners. + session.corners_source = source if source in ("auto", "tracked", "manual") else "auto" + has_pieces = bool(detection.get("pieces_detected", detection.get("fen"))) + if has_pieces or session.corners_source == "manual": + session.board_corners = detection["board_corners"] + session.geometry_seen = now + session.tracking_failures = 0 + else: + # An empty checkerboard can be measured, but it must never acquire + # a held lock on the following unreadable frame. + session.board_corners = None + session.geometry_seen = 0.0 + if detection.get("fen") and detection.get("position_verified", True) and detection.get("orientation") in ("w", "b"): + session.orientation = detection["orientation"] + detection["corners_source"] = session.corners_source + detection["lock_state"] = "locked" + detection["geometry_held"] = False + else: + session.tracking_failures += 1 + age = now - session.geometry_seen + if session.board_corners and age <= GEOMETRY_HOLD_SEC: + detection = {**detection, "fen": None, "position_verified": False, + "board_corners": session.board_corners, + "orientation": session.orientation or detection.get("orientation", "w"), + "geometry_held": True, "lock_state": "held", + "corners_source": session.corners_source, "lock_age_ms": round(age * 1000)} + else: + session.board_corners = None + session.orientation = None + session.corners_source = "auto" + detection["board_corners"] = None + detection["fen"] = None + detection["position_verified"] = False + detection["corners_source"] = "auto" + detection["lock_state"] = "reacquiring" if session.previous_fen else "searching" + detection["lock_released"] = True + return detection + + 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" @@ -249,21 +322,29 @@ async def analyze(request: Request, body: AnalyzeRequest): valid, error = validate_fen(setup_fen) if not valid: return JSONResponse({"status": "invalid_fen", "message": error}, status_code=400) + supplied_corners = body.board_corners or session.board_corners + source = (body.corners_source if body.board_corners else + "manual" if session.board_corners and session.corners_source == "manual" else + "tracked" if session.board_corners else "auto") 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, + orientation=body.orientation, + previous_fen=session.previous_fen, setup_fen=setup_fen, + side_to_move=body.side_to_move, + board_corners=supplied_corners, corners_source=source, ) 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}) + detection = {"status": "detection_error", "error": "Could not read this frame. Keep the full board visible.", + "confidence": 0.0, "board_detected": False, "fen": None} + detection = _remember_geometry(detection, body, session) confidence = detection.get("confidence", 0.0) geometry = _geometry(detection, body) - if detection.get("error") or not detection.get("fen"): + if detection.get("error") or not geometry["position_verified"]: return _attach_geometry({ - "status": detection.get("status", "detection_error"), + "status": ("position_uncertain" if detection.get("status") in ("ok", "no_change") else + 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) @@ -271,6 +352,7 @@ async def analyze(request: Request, body: AnalyzeRequest): geometry = _geometry(detection, body) valid, error = validate_fen(fen) if not valid: + geometry["position_verified"] = False 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) @@ -315,5 +397,9 @@ async def reset_session(session_id: str = "default"): if session: async with session.lock: session.previous_fen = session.cache_key = session.result = None + session.board_corners = session.orientation = None + session.corners_source = "auto" + session.geometry_seen = 0.0 + session.tracking_failures = 0 session.last_request = 0.0 return {"status": "reset", "session_id": session_id} diff --git a/backend/services/board_detector.py b/backend/services/board_detector.py index 1db4498..aff2d77 100644 --- a/backend/services/board_detector.py +++ b/backend/services/board_detector.py @@ -29,7 +29,8 @@ def load(self): 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: + board_corners: list | None = None, setup_fen: str | None = None, + side_to_move: str | None = None, corners_source: str = "auto") -> dict: if not self._ready: return _err("Detector not initialised.") try: @@ -40,7 +41,7 @@ def detect(self, image_bytes: bytes, player_color: str = "w", 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 + corners, corner_confidence, geometry_source = None, 0.0, "auto" if board_corners is not None: try: supplied = np.asarray(board_corners, dtype=np.float32) @@ -51,8 +52,9 @@ def detect(self, image_bytes: bytes, player_color: str = "w", 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: + if score >= 0.60 or corners_source == "manual": corners, corner_confidence = candidate, score + geometry_source = "manual" if corners_source == "manual" else "tracked" except (ValueError, cv2.error): pass if corners is None: @@ -69,6 +71,9 @@ def detect(self, image_bytes: bytes, player_color: str = "w", "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), + "corners_source": geometry_source, + "quality": self._image_quality(warped), + "recognition": "occupancy", "position_verified": False, "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), @@ -93,7 +98,8 @@ def detect(self, image_bytes: bytes, player_color: str = "w", 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) + result.update(fen=fen, turn="w" if chess.Board(fen).turn else "b", orientation=direction, + recognition="setup" if setup_fen else "legal_tracking", position_verified=True) return result if len(unique) > 1: return self._uncertain(result, "position_uncertain", @@ -108,7 +114,14 @@ def detect(self, image_bytes: bytes, player_color: str = "w", 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) + initial = chess.Board() + # The side to move is a user choice, never inferred from the + # player's colour or from pixels. A known tracked FEN retains + # its own turn and chess-rule state above. + if side_to_move in ("w", "b"): + initial.turn = side_to_move == "w" + result.update(fen=initial.fen(), turn="w" if initial.turn else "b", orientation=direction, + recognition="standard_opening", position_verified=True) 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.") @@ -205,6 +218,27 @@ def _find_corners(self, img: np.ndarray): if best_score >= 0.78: return best, round(best_score, 3) + # Real pieces break contour boundaries, and a folding board may have + # no closed outside contour at all. Intersect long, independently + # detected grid/border lines to recover candidate quadrilaterals. + line_candidates = self._line_candidates(gray) + promising = [] + small_dst = np.float32([[0, 0], [159, 0], [159, 159], [0, 159]]) + for candidate in line_candidates: + transform = cv2.getPerspectiveTransform(candidate, small_dst) + preview = cv2.warpPerspective(img, transform, (160, 160)) + score = self._checker_score(preview) + if score >= .58: + promising.append((score, candidate)) + for _, candidate in sorted(promising, key=lambda item: item[0], reverse=True)[:10]: + for inset in (0, .015, .03, .045, .06): + 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 >= .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( @@ -222,6 +256,63 @@ def _find_corners(self, img: np.ndarray): best, best_score = outer, score return (best, round(best_score, 3)) if best_score >= 0.65 else (None, 0.0) + @staticmethod + def _line_candidates(gray: np.ndarray) -> list: + h, w = gray.shape + detected = cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD).detect(gray)[0] + if detected is None: + return [] + lines = detected[:, 0, :] + lengths = np.hypot(lines[:, 2] - lines[:, 0], lines[:, 3] - lines[:, 1]) + keep = lengths >= min(h, w) * .15 + lines, lengths = lines[keep], lengths[keep] + if len(lines) < 4: + return [] + angles = np.mod(np.arctan2(lines[:, 3] - lines[:, 1], lines[:, 2] - lines[:, 0]), np.pi) + hist, edges = np.histogram(angles, bins=36, range=(0, np.pi), weights=lengths) + dominant = (edges[int(np.argmax(hist))] + edges[int(np.argmax(hist)) + 1]) / 2 + distance = lambda a, b: abs((a - b + np.pi / 2) % np.pi - np.pi / 2) + groups = [] + for angle in (dominant, (dominant + np.pi / 2) % np.pi): + group = [] + for index in np.argsort(lengths)[::-1]: + if distance(angles[index], angle) > np.deg2rad(22): + continue + x1, y1, x2, y2 = lines[index] + line = np.cross([x1, y1, 1], [x2, y2, 1]) + line /= max(1e-6, np.linalg.norm(line[:2])) + if line[0] < 0 or abs(line[0]) < 1e-6 and line[1] < 0: + line *= -1 + if any(abs(np.dot(line - old, [w / 2, h / 2, 1])) < min(h, w) * .012 for old in group): + continue + group.append(line) + if len(group) >= 9: + break + groups.append(group) + if min(map(len, groups)) < 2: + return [] + pairs = [] + for group in groups: + pair_group = [] + for i, first in enumerate(group): + for second in group[i + 1:]: + if abs(np.dot(first - second, [w / 2, h / 2, 1])) >= min(h, w) * .22: + pair_group.append((first, second)) + pairs.append(pair_group) + candidates = [] + for first, second in pairs[0]: + for third, fourth in pairs[1]: + intersections = [np.cross(a, b) for a, b in + [(first, third), (first, fourth), (second, fourth), (second, third)]] + if any(abs(p[2]) < 1e-6 for p in intersections): + continue + points = _order_points(np.float32([p[:2] / p[2] for p in intersections])) + if (points[:, 0] < -2).any() or (points[:, 0] > w + 1).any() or (points[:, 1] < -2).any() or (points[:, 1] > h + 1).any(): + continue + if cv2.isContourConvex(points) and cv2.contourArea(points) >= h * w * MIN_BOARD_AREA_FRACTION: + candidates.append(points) + return candidates + @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) @@ -235,7 +326,10 @@ def _backgrounds(board: np.ndarray) -> np.ndarray: 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)): + # Stay clear of square edges: defocus mixes neighbouring colours for + # several pixels. Sampling there makes an empty cell's clean centre + # look like a foreground piece on a blurred phone frame. + for py, px in ((0.18, 0.18), (0.18, 0.82), (0.82, 0.18), (0.82, 0.82)): 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) @@ -243,18 +337,47 @@ def _backgrounds(board: np.ndarray) -> np.ndarray: 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: + yy, xx = np.indices((8, 8)).astype(np.float32) + # A single global light/dark threshold fails when a phone or window + # casts a gradient across the board. Fit illumination and checker + # contrast together; robust weights suppress piece-covered samples. + lighting = np.stack([np.ones(64), xx.ravel() / 7, yy.ravel() / 7], axis=1) + # A shadow scales both the mean square colour and its checker + # contrast. Fit both effects; a constant contrast alone shifts the + # best-scoring boundary inward under uneven illumination. + design = np.concatenate([lighting, lighting * (parity.ravel() * 2 - 1)[:, None]], axis=1) + samples = colours.reshape(64, 3) + weights = np.ones(64) + for _ in range(4): + root = np.sqrt(weights)[:, None] + coeff = np.linalg.lstsq(design * root, samples * root, rcond=None)[0] + errors = np.linalg.norm(samples - design @ coeff, axis=1) + scale = max(4.0, float(np.median(errors)) * 1.4826) + weights = np.minimum(1.0, 2.5 * scale / np.maximum(errors, 1e-3)) + checker = lighting @ coeff[3:] + contrast = float(np.median(np.linalg.norm(checker, axis=1)) * 2) + if contrast < 18: 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: + illumination = lighting @ coeff[:3] + distances = np.stack([np.linalg.norm(samples - illumination + checker, axis=1), + np.linalg.norm(samples - illumination - checker, axis=1)], axis=1) + matching = (np.argmin(distances, axis=1) == parity.ravel()).reshape(8, 8) + agreement = float(np.mean(matching)) + # Require checker evidence across both axes, not just one patch of + # floor tiles, a rectangle, or screen stripes. + if agreement < .80 or np.mean(matching.mean(axis=0) >= .625) < .75 or np.mean(matching.mean(axis=1) >= .625) < .75: return 0.0 - residual = float(np.median(np.min(distances, axis=2))) / contrast + residual = float(np.median(np.min(distances, axis=1))) / contrast return float(np.clip(agreement * (1 - min(residual, 0.35)), 0, 1)) + @staticmethod + def _image_quality(board: np.ndarray) -> dict: + gray = cv2.cvtColor(board, cv2.COLOR_BGR2GRAY) + sharpness = float(cv2.Laplacian(gray, cv2.CV_32F).var()) + contrast = float(np.percentile(gray, 95) - np.percentile(gray, 5)) + return {"sharpness": round(sharpness, 1), "contrast": round(contrast, 1), + "blurred": sharpness < 22, "low_contrast": contrast < 35} + def _classify_squares(self, board: np.ndarray): size = board.shape[0] // 8 backgrounds = self._backgrounds(board) @@ -276,14 +399,26 @@ def _classify_squares(self, board: np.ndarray): 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) + threshold = max(8.0, float(np.percentile(corner_noise, 90)) * 1.5 + 2) 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) + count, labels, stats, centroids = cv2.connectedComponentsWithStats(mask) if count <= 1: entries.append(("empty", None, 0.98)) continue - index = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + # Defocus spreads alternating square edges into the cell. + # Those edge strips must not become phantom pieces. A piece + # footprint has substantial evidence near the cell centre. + mh, mw = mask.shape + central = labels[int(mh * .3):int(mh * .7), int(mw * .3):int(mw * .7)] + candidates = [i for i in range(1, count) + if .18 * mw <= centroids[i, 0] <= .82 * mw + and .18 * mh <= centroids[i, 1] <= .82 * mh + and np.mean(central == i) > .06] + if not candidates: + entries.append(("empty", None, 0.9)) + continue + index = max(candidates, key=lambda i: stats[i, 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)) @@ -341,7 +476,9 @@ def draw_move(self, board_b64: str, uci_move: str, orientation: str = "w") -> st 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} + "requires_setup": False, "board_b64": None, "piece_count": 0, "pieces_detected": False, + "quality": None, "recognition": "unreadable", "position_verified": False, + "corners_source": "auto"} def _occupancy(board: chess.Board) -> list: diff --git a/backend/tests/test_api.py b/backend/tests/test_api.py index d8c48c9..e465ad4 100644 --- a/backend/tests/test_api.py +++ b/backend/tests/test_api.py @@ -1,8 +1,11 @@ +import base64 + import pytest import chess from fastapi.testclient import TestClient from main import app from routers import analysis +from .test_board_detector import board_image, encode @pytest.fixture(autouse=True) @@ -33,9 +36,18 @@ def test_depth_info(client): assert len(data["depths"]) == 13 def test_reset_session(client): + session = analysis._session("test_reset") + session.board_corners = [[0, 0], [1, 0], [1, 1], [0, 1]] + session.orientation = "b" + session.corners_source = "manual" + session.geometry_seen = analysis.time.monotonic() + session.previous_fen = chess.STARTING_FEN res = client.post("/api/reset-session?session_id=test_reset") assert res.status_code == 200 assert res.json() == {"status": "reset", "session_id": "test_reset"} + assert session.board_corners is None and session.orientation is None + assert session.previous_fen is None and session.corners_source == "auto" + assert session.geometry_seen == 0 def test_analyze_fen_valid(client): fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" @@ -200,6 +212,36 @@ def detect(image, **kwargs): assert chess.Move.from_uci(third["move_uci"]) in board.legal_moves +def test_real_camera_reader_accepts_the_api_contract(client): + # Exercise the real detector through HTTP: mocks accepting **kwargs would + # hide a disagreement between router arguments and the detector signature. + image = base64.b64encode(encode(board_image())).decode("ascii") + result = client.post("/api/analyze", json={ + "image_b64": image, "session_id": "real_camera", "orientation": "auto", + }).json() + assert result["status"] == "ok", result + assert result["fen"] == chess.STARTING_FEN + assert result["position_verified"] and result["board_locked"] + assert result["move_uci"] and result["overlay"]["from"] + assert result["quality"] is not None and result["recognition"] + + +def test_playing_color_is_not_used_as_a_turn_override(client, monkeypatch): + calls = [] + + def detect(*args, **kwargs): + calls.append(kwargs) + return {"fen": chess.STARTING_FEN, "status": "ok", "board_detected": True, + "board_corners": [[0, 0], [1, 0], [1, 1], [0, 1]], "orientation": "w"} + + monkeypatch.setattr(app.state.detector, "detect", detect) + result = client.post("/api/analyze", json={ + "image_b64": "ZmFrZQ==", "player_color": "b", "session_id": "black_player", + }).json() + assert calls[0]["side_to_move"] is None + assert result["turn"] == "w" and result["status"] == "opponent_turn" + + 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: { @@ -288,3 +330,101 @@ def test_empty_detected_board_does_not_lock_or_suggest_a_move(client, monkeypatc 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 + + +def test_camera_lock_survives_blurred_frame_without_reusing_stale_move(client, monkeypatch): + corners = [[0.1, 0.1], [0.9, 0.1], [0.9, 0.9], [0.1, 0.9]] + calls = [] + def detect(*args, **kwargs): + calls.append(kwargs) + if len(calls) == 2: + return {"fen": None, "error": "Camera is blurred.", "status": "detection_error", + "board_detected": False, "pieces_detected": False, "confidence": 0.1} + return {"fen": chess.STARTING_FEN, "error": None, "status": "ok", "confidence": 0.9, + "board_detected": True, "board_corners": corners, "orientation": "b", "pieces_detected": True} + monkeypatch.setattr(app.state.detector, "detect", detect) + body = {"image_b64": "ZmFrZQ==", "session_id": "blur_lock", "orientation": "auto"} + first = client.post("/api/analyze", json=body).json() + blurred = client.post("/api/analyze", json=body).json() + recovered = client.post("/api/analyze", json=body).json() + assert first["board_locked"] and first["move_uci"] + assert blurred["board_locked"] and blurred["board_corners"] == corners + assert blurred["geometry_held"] and not blurred["position_verified"] + assert blurred["move_uci"] is None and blurred["overlay"] is None + assert calls[1]["board_corners"] == corners and calls[1]["orientation"] == "auto" + assert calls[1]["corners_source"] == "tracked" + assert recovered["status"] == "no_change" and recovered["move_uci"] == first["move_uci"] + assert not recovered["geometry_held"] and recovered["position_verified"] + + +def test_manual_corners_reach_detector_and_persist_with_session(client, monkeypatch): + corners = [[.1, .1], [.9, .1], [.9, .9], [.1, .9]] + calls = [] + def detect(*args, **kwargs): + calls.append(kwargs) + return {"fen": None, "error": "Read the pieces.", "status": "setup_required", "confidence": .5, + "board_detected": True, "board_corners": corners, "pieces_detected": False} + monkeypatch.setattr(app.state.detector, "detect", detect) + first = client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "manual", + "board_corners": corners, "corners_source": "manual"}).json() + assert first["board_locked"] and first["corners_source"] == "manual" + client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "manual"}) + assert calls[1]["board_corners"] == corners and calls[1]["corners_source"] == "manual" + + +@pytest.mark.parametrize("echoed_source", [None, "auto", "manual"]) +def test_long_missing_board_expires_held_geometry(client, monkeypatch, echoed_source): + session = analysis._session("expired_geometry") + session.board_corners = [[0, 0], [1, 0], [1, 1], [0, 1]] + session.geometry_seen = analysis.time.monotonic() - 9 + session.orientation = "b" + session.previous_fen = chess.STARTING_FEN + monkeypatch.setattr(app.state.detector, "detect", lambda *a, **kw: { + "fen": None, "error": "Board not found.", "status": "detection_error", "board_detected": False}) + body = {"image_b64": "ZmFrZQ==", "session_id": "expired_geometry"} + if echoed_source: + body.update(board_corners=session.board_corners, corners_source=echoed_source) + data = client.post("/api/analyze", json=body).json() + assert not data["board_locked"] and data["lock_state"] == "reacquiring" + assert data["board_corners"] is None and data["overlay"] is None + assert data["lock_released"] and session.orientation is None + + +def test_unverified_fen_never_reaches_engine_or_trusted_position(client, monkeypatch): + monkeypatch.setattr(app.state.detector, "detect", lambda *a, **kw: { + "fen": chess.STARTING_FEN, "status": "ok", "position_verified": False, + "board_detected": True, "board_corners": [[0, 0], [1, 0], [1, 1], [0, 1]], + "orientation": "w", "pieces_detected": True, + }) + monkeypatch.setattr(app.state.stockfish, "get_best_move", lambda *a, **kw: pytest.fail("Unverified position reached engine")) + data = client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "unverified"}).json() + assert data["status"] == "position_uncertain" + assert not data["position_verified"] and data["fen"] is None + assert data["move_uci"] is None and data["overlay"] is None + assert analysis._sessions["unverified"].previous_fen is None + + +def test_auto_reacquisition_does_not_inherit_rejected_manual_provenance(client, monkeypatch): + corners = [[.1, .1], [.9, .1], [.9, .9], [.1, .9]] + monkeypatch.setattr(app.state.detector, "detect", lambda *a, **kw: { + "fen": None, "status": "position_uncertain", "board_detected": True, + "board_corners": corners, "corners_source": "auto", "pieces_detected": True, + }) + result = client.post("/api/analyze", json={"image_b64": "ZmFrZQ==", "session_id": "reacquired", + "board_corners": [[0, 0], [1, 0], [1, 1], [0, 1]], "corners_source": "manual"}).json() + assert result["corners_source"] == "auto" + assert analysis._sessions["reacquired"].corners_source == "auto" + + +def test_empty_board_cannot_turn_into_a_held_lock_on_the_next_frame(client, monkeypatch): + readings = iter([ + {"fen": None, "status": "setup_required", "board_detected": True, + "board_corners": [[0, 0], [1, 0], [1, 1], [0, 1]], "pieces_detected": False}, + {"fen": None, "status": "detection_error", "board_detected": False}, + ]) + monkeypatch.setattr(app.state.detector, "detect", lambda *a, **kw: next(readings)) + body = {"image_b64": "ZmFrZQ==", "session_id": "empty_then_missing"} + assert not client.post("/api/analyze", json=body).json()["board_locked"] + missing = client.post("/api/analyze", json=body).json() + assert not missing["board_locked"] and not missing["geometry_held"] + assert missing["board_corners"] is None diff --git a/backend/tests/test_board_detector.py b/backend/tests/test_board_detector.py index e67d823..76eb2fc 100644 --- a/backend/tests/test_board_detector.py +++ b/backend/tests/test_board_detector.py @@ -312,3 +312,83 @@ def test_warm_wooden_piece_tones_and_camera_noise_are_not_hardcoded_black_white( else: assert result["piece_count"] == 0 assert result["fen"] is None + + +@pytest.mark.parametrize("sigma", [1.5, 3, 6]) +def test_blurred_opening_retains_exact_occupancy_and_board_alignment(detector, sigma): + image = cv2.GaussianBlur(board_image(), (0, 0), sigma) + result = detector.detect(encode(image), corners_source="auto", side_to_move="w") + assert result["status"] == "ok", result["error"] + assert result["fen"] == STARTING_FEN + assert result["piece_count"] == 32 + assert result["position_verified"] + assert result["recognition"] == "standard_opening" + assert result["quality"]["sharpness"] >= 0 + assert np.allclose(result["board_corners"], [[0, 0], [1, 0], [1, 1], [0, 1]], atol=.01) + + +def test_shadow_does_not_shift_board_boundary_or_lose_pieces(detector): + image = np.clip(board_image().astype(float) * np.linspace(.35, 1, 480)[None, :, None], 0, 255).astype(np.uint8) + result = detector.detect(encode(image)) + assert result["fen"] == STARTING_FEN + assert result["piece_count"] == 32 + assert np.allclose(result["board_corners"], [[0, 0], [1, 0], [1, 1], [0, 1]], atol=.01) + + +def test_low_contrast_board_still_calibrates(detector): + image = np.clip(board_image().astype(float) * .24 + 100, 0, 255).astype(np.uint8) + result = detector.detect(encode(image)) + assert result["fen"] == STARTING_FEN + assert result["piece_count"] == 32 + + +def test_blurred_empty_squares_do_not_become_phantom_pieces(detector): + image = cv2.GaussianBlur(board_image(pieces=False), (0, 0), 6) + result = detector.detect(encode(image)) + assert result["board_detected"] + assert result["piece_count"] == 0 + assert result["fen"] is None + assert not result["position_verified"] + + +def test_manual_corner_lock_does_not_invent_a_position_on_blank_frame(detector): + corners = [[.1, .1], [.9, .1], [.9, .9], [.1, .9]] + result = detector.detect(encode(np.full((480, 480, 3), 120, np.uint8)), + board_corners=corners, corners_source="manual", previous_fen=STARTING_FEN) + assert result["board_detected"] + assert result["corners_source"] == "manual" + assert result["fen"] is None + assert not result["position_verified"] + assert result["status"] == "position_uncertain" + + +def test_turn_selection_applies_only_to_new_calibration(detector): + result = detector.detect(encode(board_image()), side_to_move="b") + assert result["turn"] == "b" + assert not chess.Board(result["fen"]).turn + tracked = detector.detect(encode(board_image()), previous_fen=STARTING_FEN, side_to_move="b") + assert tracked["fen"] == STARTING_FEN + assert tracked["recognition"] == "legal_tracking" + + +def test_tracked_corners_are_distinct_from_manual_and_rejected_without_board_evidence(detector): + corners = [[0, 0], [1, 0], [1, 1], [0, 1]] + result = detector.detect(encode(board_image()), board_corners=corners, corners_source="tracked") + assert result["fen"] == STARTING_FEN + assert result["corners_source"] == "tracked" + lost = detector.detect(encode(np.full((480, 480, 3), 120, np.uint8)), + board_corners=corners, corners_source="tracked", previous_fen=STARTING_FEN) + assert not lost["board_detected"] + assert lost["fen"] is None + + +def test_auto_orientation_reacquires_reversed_board_while_tracking(detector): + initial = detector.detect(encode(board_image()), orientation="auto") + board = chess.Board() + board.push_uci("e2e4") + reversed_view = detector.detect(encode(board_image(board, rotation=True)), orientation="auto", + previous_fen=initial["fen"], board_corners=initial["board_corners"], + corners_source="tracked") + assert reversed_view["fen"] == board.fen() + assert reversed_view["orientation"] == "b" + assert reversed_view["position_verified"] diff --git a/docs/API.md b/docs/API.md index 5fe8a55..6c754ed 100644 --- a/docs/API.md +++ b/docs/API.md @@ -43,6 +43,7 @@ Analyzes a camera frame or an authoritative FEN within a tracking session. | `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. | +| `corners_source` | `"auto"` | `auto` or `tracked` corners are revalidated against the checkerboard; `manual` selects a user-defined region. Manual geometry does not verify a position. | | `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. | @@ -107,7 +108,9 @@ All geometry uses the uploaded image coordinate system, normalized to `[0, 1]`. | `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. | -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. +Detected geometry can be returned even when the position needs setup. `board_locked` normally requires a detected board and pieces; a manual region or a temporarily held boundary can also remain locked without a verified position. An empty checkerboard never produces a move. + +Camera responses include `position_verified`, `recognition` (`standard_opening`, `setup`, `legal_tracking`, `occupancy`, or `unreadable`), and `quality` (sharpness, contrast, and blur/low-contrast indicators when a board region was read). These measurements are not calibrated recognition probabilities. `lock_state` is `locked`, `held`, `searching`, or `reacquiring`. A held boundary has `geometry_held: true` and `lock_age_ms`, expires after eight seconds without new board evidence, and carries no FEN, move, or overlay. `lock_released: true` tells clients to discard expired corners. Draw advice only for a verified current position, never for a held boundary. 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. @@ -127,7 +130,7 @@ The endpoint returns `ok`, `game_over`, `invalid_fen`, or `engine_error` and the ## `POST /api/reset-session?session_id=...` -Clears the trusted position, cached result, and request timer for one session: +Clears the trusted position, cached result, board geometry, orientation, and request timer for one session: ```json {"status": "reset", "session_id": "camera-session"} diff --git a/docs/PERFORMANCE.md b/docs/PERFORMANCE.md index af008fc..bd171aa 100644 --- a/docs/PERFORMANCE.md +++ b/docs/PERFORMANCE.md @@ -4,9 +4,9 @@ The application favors prompt, bounded analysis and reliable state transitions. ## Camera and network -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. +The frontend captures a 960-by-960 camera JPEG or a 1280-by-1280 uploaded photo at quality `0.94`. For a camera scan it samples three frames 75 ms apart and sends the one with the most detail. Continuous focus and exposure are requested when the camera supports them. 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. +Camera scans are scheduled after the preceding request completes, with an 850 ms interval. Burst capture and processing add to this interval. This prevents overlapping requests from building a backlog. Requests time out after 15 seconds, and generation checks cancel unfinished captures and discard responses from an old camera, photo, or settings state. 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. @@ -14,7 +14,9 @@ Scanning pauses when the tab is hidden. Camera tracks are stopped when the user ## 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. +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 an automatic candidate, using contours, line intersections, or internal grid corners. Spatial illumination and contrast estimates accommodate uneven lighting; central foreground measurements reduce false pieces caused by blurred square edges. + +A measured board boundary can be held for up to eight seconds after detection fails. Held outlines are marked as refocusing and never justify a move suggestion. The server releases expired geometry even when the client keeps submitting old corners. Manual corners describe a user-selected region and do not prove that its pieces have been read. This pipeline has no learned piece-type model. Its valid operating path is: @@ -23,7 +25,7 @@ This pipeline has no learned piece-type model. Its valid operating path is: 3. Match an unchanged position, one legal move, or two consecutive legal moves. 4. Keep the position uncommitted when no unique match exists. -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. +Clear overhead views and visible square backgrounds work best. Moderate synthetic blur, low contrast, and uneven lighting have regression coverage; this does not guarantee all real camera conditions. Severe blur, glare, 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. diff --git a/docs/README.md b/docs/README.md index 744a50e..f40d160 100644 --- a/docs/README.md +++ b/docs/README.md @@ -28,9 +28,9 @@ The vision pipeline does not independently identify arbitrary midgame pieces. It ## Board alignment -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. +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. A manual region helps alignment but does not identify unreadable pieces. **Unlock** clears the calibration and scans again. -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. +Orientation describes the camera view, independently of whose turn it is or which color you play. Automatic orientation can follow a 180-degree board rotation; a fixed orientation must be changed when switching sides. Use **Whose turn is it?** to correct the active side when necessary. A partial board, severe blur, glare, or a hand over pieces can cause the app to withhold a suggestion until a readable frame returns. During temporary refocusing it keeps a dashed outline for up to eight seconds and hides the previous arrow; after that it releases the lock and searches again. ## Local development diff --git a/frontend/app.js b/frontend/app.js index 7a5d5e7..efd7301 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -1,4 +1,4 @@ -import { fitInside, moveGeometry, validCorners, resolveApiBase } from "./overlay.js"; +import { fitInside, moveGeometry, validCorners, resolveApiBase, frameDetailScore } 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"; @@ -6,7 +6,7 @@ const $ = id => document.getElementById(id); const state = { running: false, starting: false, source: null, facing: "environment", timer: null, generation: 0, controller: null, session: crypto.randomUUID(), corners: null, - cameraAttempt: 0, + cameraAttempt: 0, cornersSource: "auto", lockReading: false, manualCorners: [], locking: false, move: null, fen: null, setupFen: null, player: "w", orientation: "auto", resolvedOrientation: "w", depth: 10, mode: "win", busy: false, }; @@ -56,7 +56,8 @@ function resetTracking({ keepCorners = false } = {}) { state.fen = null; state.setupFen = null; state.resolvedOrientation = state.orientation === "b" ? "b" : "w"; - if (!keepCorners) state.corners = null; + if (!keepCorners) { state.corners = null; state.cornersSource = "auto"; } + state.lockReading = false; state.manualCorners = []; state.locking = false; $("boardStatus").textContent = state.corners ? "Board locked" : "Looking for board"; @@ -77,6 +78,8 @@ function stopCamera({ clear = true } = {}) { if (clear) { state.source = null; state.corners = null; + state.cornersSource = "auto"; + state.lockReading = false; state.locking = false; $("photoPreview").hidden = true; $("cameraOverlay").hidden = false; @@ -100,7 +103,16 @@ async function startCamera() { updateControls(); setStatus("Opening camera…"); try { const stream = await navigator.mediaDevices.getUserMedia({ audio: false, - video: { facingMode: { ideal: state.facing }, width: { ideal: 1280 }, height: { ideal: 1280 } } }); + video: { facingMode: { ideal: state.facing }, width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 24 } } }); + if (attempt !== state.cameraAttempt) { stream.getTracks().forEach(t => t.stop()); return; } + // Supported phones keep refocusing as the board or camera moves. Treat + // these as best-effort hints; unsupported cameras still start normally. + const track = stream.getVideoTracks()[0]; + const capabilities = track?.getCapabilities?.() || {}; + const continuous = {}; + if (capabilities.focusMode?.includes("continuous")) continuous.focusMode = "continuous"; + if (capabilities.exposureMode?.includes("continuous")) continuous.exposureMode = "continuous"; + if (Object.keys(continuous).length) await track.applyConstraints({ advanced: [continuous] }).catch(() => {}); if (attempt !== state.cameraAttempt) { stream.getTracks().forEach(t => t.stop()); return; } $("cameraFeed").srcObject = stream; await $("cameraFeed").play(); @@ -124,19 +136,31 @@ async function startCamera() { } finally { if (attempt === state.cameraAttempt) state.starting = false; updateControls(); } } -function captureFrame() { +async function captureFrame(generation) { 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; + const canvas = $("captureCanvas"), size = state.source === "camera" ? 960 : 1280; 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]; + const samples = state.source === "camera" ? 3 : 1; + const probe = document.createElement("canvas"); probe.width = probe.height = 192; + const probeCtx = probe.getContext("2d", { willReadFrequently: true }); + let bestImage = null, bestScore = -1; + for (let sample = 0; sample < samples; sample++) { + if (generation !== state.generation) return null; + ctx.fillStyle = "#182923"; ctx.fillRect(0, 0, size, size); + ctx.drawImage(source, fit.x, fit.y, fit.width, fit.height); + // Ignore the square frame's letterbox when measuring camera sharpness. + probeCtx.drawImage(source, 0, 0, 192, 192); + const score = frameDetailScore(probeCtx.getImageData(0, 0, 192, 192).data, 192, 192); + if (score > bestScore) { bestScore = score; bestImage = canvas.toDataURL("image/jpeg", .94).split(",")[1]; } + if (sample + 1 < samples) await new Promise(resolve => setTimeout(resolve, 75)); + } + return bestImage; } -function schedule(delay = 1250) { +function schedule(delay = 850) { clearTimeout(state.timer); if (state.running && !state.locking && !document.hidden) state.timer = setTimeout(scanFrame, delay); } @@ -164,21 +188,24 @@ async function apiRequest(path, body, generation) { 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 b64 = await captureFrame(generation); + if (!b64 || generation !== state.generation) return; const data = await apiRequest("/api/analyze", { image_b64: b64, player_color: state.player, orientation: state.orientation, + side_to_move: $("turnSelect").value, depth: state.depth, mode: state.mode, session_id: state.session, - ...(state.corners ? { board_corners: state.corners } : {}), + ...(state.corners ? { board_corners: state.corners, corners_source: state.cornersSource } : {}), ...(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; + if (data.position_verified !== false && !data.geometry_held && data.fen + && ["ok", "no_change", "opponent_turn", "game_over"].includes(data.status) + && state.setupFen === setupFen) state.setupFen = null; } } catch (err) { if (generation === state.generation) { clearMove("Connection interrupted. Retrying…"); setStatus(err.message, "error"); } @@ -189,18 +216,39 @@ async function scanFrame() { function handleResponse(data, elapsed) { const hasPieces = data.pieces_detected !== false; + const goodCorners = validCorners(data.board_corners); + const emptyBoard = data.board_detected === true && !hasPieces && data.status === "setup_required" + && data.corners_source !== "manual" && !data.geometry_held; + const released = data.lock_released === true || (data.board_locked === false && !goodCorners + && ["searching", "reacquiring"].includes(data.lock_state)); + const readingPosition = ["detection_error", "position_uncertain", "tracking_error", "tracking_lost", "recognition_error", "image_blurry", "reacquiring", "recognizing", "reading_position"].includes(data.status) + || data.position_verified === false || data.geometry_held === true; if (["w", "b"].includes(data.orientation)) state.resolvedOrientation = data.orientation; - if (!hasPieces) { + if (released || emptyBoard) { state.corners = null; - $("boardStatus").textContent = "Board found · add pieces"; + state.cornersSource = "auto"; + $("boardStatus").textContent = emptyBoard ? "Board found · add pieces" : "Looking for board"; $("confBadge").hidden = true; } - if (hasPieces && validCorners(data.board_corners)) { + if (goodCorners && !emptyBoard && !released) { state.corners = data.board_corners; - $("boardStatus").textContent = "Board locked"; - $("confBadge").textContent = `${Math.round((data.confidence || 0) * 100)}% confidence`; + if (["manual", "auto", "tracked"].includes(data.corners_source)) state.cornersSource = data.corners_source; + $("boardStatus").textContent = data.geometry_held ? "Board held · refocusing" : readingPosition ? "Board locked · reading pieces" : "Board locked"; + $("confBadge").textContent = data.geometry_held ? "Reading a clearer frame" : `${Math.round((data.confidence || 0) * 100)}% confidence`; + $("confBadge").hidden = false; + } else if (state.corners && readingPosition) { + // A noisy frame must not throw away a previously measured board boundary. + // Retain it as a held outline; advice remains hidden until pieces are read. + $("boardStatus").textContent = "Board held · refocusing"; + $("confBadge").textContent = "Reading a clearer frame"; $("confBadge").hidden = false; } + state.lockReading = Boolean(state.corners && readingPosition); + if (readingPosition && ["ok", "no_change", "opponent_turn", "game_over"].includes(data.status)) { + clearMove("Board locked. Reading the position before suggesting a move…"); + setStatus(data.message || "Waiting for a clear, verified position."); + updateControls(); drawOverlay(); return; + } if (data.fen && ["ok", "no_change", "opponent_turn", "game_over"].includes(data.status)) { state.fen = data.fen; $("customFenInput").value = data.fen; @@ -238,13 +286,18 @@ function handleResponse(data, elapsed) { 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…"); + case "recognition_error": + case "image_blurry": + case "reacquiring": + case "recognizing": + case "reading_position": + if (!state.corners) $("boardStatus").textContent = "Looking for board"; + clearMove(state.corners ? "Board held. Reading a clearer frame before showing the next move…" : "Keep the full board visible. Looking for its four corners…"); setStatus(data.message || "Could not read this frame. Scanning again…"); break; + case "engine_starting": + case "model_loading": + clearMove("The board reader is starting. Analysis will resume automatically…"); + setStatus(data.message || "Preparing the board reader. Please keep the camera steady."); break; default: clearMove(data.message || "Could not analyze this position."); setStatus(data.message || "Analysis failed. Check the position and try again.", "error"); @@ -271,6 +324,7 @@ function drawOverlay() { } if (!state.corners) return; add("polygon", { points: points(state.corners), fill: "none", stroke: "#c3f578", "stroke-width": 3, "stroke-linejoin": "round", opacity: .85 }); + if (state.lockReading) svg.lastElementChild.setAttribute("stroke-dasharray", "12 8"); 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); @@ -318,7 +372,7 @@ $("cameraFrame").addEventListener("click", event => { 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; + state.corners = state.manualCorners; state.cornersSource = "manual"; state.locking = false; $("boardStatus").textContent = "Board locked"; setStatus("Board corners set. Reading the position…"); scanFrame(); } } @@ -422,6 +476,18 @@ $("orientationSelect").addEventListener("change", () => { if (state.source === "demo" && state.fen) { drawDemoBoard(state.fen); drawOverlay(); } else { resetTracking(); if (state.source) scanFrame(); } }); +$("turnSelect").addEventListener("change", () => { + const selected = $("turnSelect").value; + if (state.fen) { + const fields = state.fen.split(/\s+/); fields[1] = selected; + // A user correcting the active side intentionally starts a fresh read. + // Image recognition cannot recover whose turn it is from pixels alone. + if (state.source === "demo") { analyzeFen(fields.join(" ")); return; } + const fen = fields.join(" "); + resetTracking({ keepCorners: true }); state.setupFen = fen; + } + refreshAnalysis("Updating the side to move…"); +}); 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; diff --git a/frontend/index.html b/frontend/index.html index 8ec61e3..e2edf44 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -70,12 +70,12 @@
Keep the full board in view.
We’ll lock i
Starting a game is automatic. For a game already in progress, enter its FEN once to identify the pieces.
Use this position for camera tracking, or analyze it on its own.