Fix changes for blunder analysis
a
This commit is contained in:
1 parent
86569d4098
commit
9c5c599a26
12 files changed
+142
-74
No files matched your search
@@ -1,2 +1,4 @@
|
||||
app/__pycache__
|
||||
*.db
|
||||
data/
|
||||
docker-compose.yml
|
||||
@@ -18,4 +18,7 @@ ENV DATA_DIR=/app/data
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
|
||||
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/api/health', timeout=4)"
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
+21
-12
@@ -1,5 +1,6 @@
|
||||
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
import shutil
|
||||
|
||||
@@ -15,14 +16,21 @@ MAX_PLIES = int(os.environ.get("MAX_PLIES", "500"))
|
||||
MATE_SCORE_CP = 100_000
|
||||
|
||||
|
||||
def classify(loss_cp: int) -> str:
|
||||
if loss_cp <= 10:
|
||||
def _win_pct(cp: int) -> float:
|
||||
return 50 + 50 * (2 / (1 + math.exp(-0.00368208 * cp)) - 1)
|
||||
|
||||
|
||||
def classify(eval_before: int, eval_after: int, mover_is_white: bool) -> str:
|
||||
before = _win_pct(eval_before)
|
||||
after = _win_pct(eval_after)
|
||||
drop = (before - after) if mover_is_white else (after - before)
|
||||
if drop <= 2:
|
||||
return "best"
|
||||
if loss_cp <= 50:
|
||||
if drop <= 10:
|
||||
return "good"
|
||||
if loss_cp <= 100:
|
||||
if drop <= 20:
|
||||
return "inaccuracy"
|
||||
if loss_cp <= 200:
|
||||
if drop <= 30:
|
||||
return "mistake"
|
||||
return "blunder"
|
||||
|
||||
@@ -34,6 +42,9 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
|
||||
|
||||
white = game.headers.get("White", "")
|
||||
black = game.headers.get("Black", "")
|
||||
white_rating = game.headers.get("WhiteElo", "")
|
||||
black_rating = game.headers.get("BlackElo", "")
|
||||
link = game.headers.get("Link", "")
|
||||
user_color = None
|
||||
if username:
|
||||
if username.lower() == white.lower():
|
||||
@@ -78,11 +89,6 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
|
||||
san_best = board.san(best_move) if best_move and best_move in board.legal_moves else None
|
||||
uci_best = best_move.uci() if best_move else None
|
||||
|
||||
loss_cp = None
|
||||
if eval_before is not None and eval_after is not None:
|
||||
loss_cp = (eval_before - eval_after) if mover_is_white else (eval_after - eval_before)
|
||||
loss_cp = max(0, loss_cp)
|
||||
|
||||
board.push(move)
|
||||
|
||||
is_user_move = None
|
||||
@@ -97,8 +103,8 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
|
||||
"best_move_san": san_best,
|
||||
"best_move_uci": uci_best,
|
||||
"eval_cp": eval_after,
|
||||
"loss_cp": loss_cp,
|
||||
"classification": classify(loss_cp) if loss_cp is not None else "unknown",
|
||||
"classification": classify(eval_before, eval_after, mover_is_white)
|
||||
if eval_before is not None and eval_after is not None else "unknown",
|
||||
"is_user_move": is_user_move,
|
||||
"fen_after": board.fen(),
|
||||
})
|
||||
@@ -106,6 +112,9 @@ async def analyze_pgn(pgn_text: str, username: str | None = None, depth: int = D
|
||||
return {
|
||||
"white": white,
|
||||
"black": black,
|
||||
"white_rating": white_rating if white_rating.isdigit() else None,
|
||||
"black_rating": black_rating if black_rating.isdigit() else None,
|
||||
"game_url": link if link.startswith("https://www.chess.com/") else None,
|
||||
"result": game.headers.get("Result", ""),
|
||||
"initial_eval_cp": white_pov_evals[0],
|
||||
"initial_fen": game.headers.get("FEN", chess.STARTING_FEN),
|
||||
|
||||
@@ -31,10 +31,6 @@ def init_db() -> None:
|
||||
CREATE TABLE IF NOT EXISTS games (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT,
|
||||
white TEXT,
|
||||
black TEXT,
|
||||
result TEXT,
|
||||
depth INTEGER,
|
||||
created_at REAL,
|
||||
analysis_json TEXT NOT NULL
|
||||
)
|
||||
@@ -60,25 +56,15 @@ def get_game(game_id: str) -> dict | None:
|
||||
return analysis
|
||||
|
||||
|
||||
def save_game(game_id: str, username: str | None, depth: int, analysis: dict) -> None:
|
||||
def save_game(game_id: str, username: str | None, analysis: dict) -> None:
|
||||
conn = _connect()
|
||||
try:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO games
|
||||
(id, username, white, black, result, depth, created_at, analysis_json)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT OR REPLACE INTO games (id, username, created_at, analysis_json)
|
||||
VALUES (?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
game_id,
|
||||
username,
|
||||
analysis.get("white"),
|
||||
analysis.get("black"),
|
||||
analysis.get("result"),
|
||||
depth,
|
||||
time.time(),
|
||||
json.dumps(analysis),
|
||||
),
|
||||
(game_id, username, time.time(), json.dumps(analysis)),
|
||||
)
|
||||
_purge_old(conn)
|
||||
conn.commit()
|
||||
|
||||
+15
-6
@@ -5,15 +5,24 @@ from fastapi import HTTPException
|
||||
|
||||
BASE_URL = "https://api.chess.com/pub"
|
||||
HEADERS = {"User-Agent": os.environ.get("CHESSCOM_USER_AGENT", "chess.sistav.com")}
|
||||
UPSTREAM_ERROR = "chess.com isn't responding right now. Try again in a minute."
|
||||
|
||||
|
||||
async def _get(url: str, timeout: float) -> httpx.Response:
|
||||
try:
|
||||
async with httpx.AsyncClient(headers=HEADERS, timeout=timeout) as client:
|
||||
return await client.get(url)
|
||||
except httpx.HTTPError:
|
||||
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
|
||||
|
||||
|
||||
async def get_archives(username: str) -> list[str]:
|
||||
url = f"{BASE_URL}/player/{quote(username, safe='')}/games/archives"
|
||||
async with httpx.AsyncClient(headers=HEADERS, timeout=15) as client:
|
||||
resp = await client.get(url)
|
||||
resp = await _get(url, timeout=15)
|
||||
if resp.status_code == 404:
|
||||
raise HTTPException(status_code=404, detail=f"No chess.com player found for '{username}'")
|
||||
resp.raise_for_status()
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
|
||||
archive_urls = resp.json().get("archives", [])
|
||||
months = []
|
||||
for archive_url in archive_urls:
|
||||
@@ -26,10 +35,10 @@ async def get_archives(username: str) -> list[str]:
|
||||
|
||||
async def get_games(username: str, year: str, month: str) -> list[dict]:
|
||||
url = f"{BASE_URL}/player/{quote(username, safe='')}/games/{quote(year, safe='')}/{quote(month, safe='')}"
|
||||
async with httpx.AsyncClient(headers=HEADERS, timeout=30) as client:
|
||||
resp = await client.get(url)
|
||||
resp = await _get(url, timeout=30)
|
||||
if resp.status_code == 404:
|
||||
return []
|
||||
resp.raise_for_status()
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=502, detail=UPSTREAM_ERROR)
|
||||
games = resp.json().get("games", [])
|
||||
return list(reversed(games))
|
||||
+4
-12
@@ -11,7 +11,7 @@ from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app import db, fetch
|
||||
from app.analysis import analyze_pgn
|
||||
from app.analysis import DEFAULT_DEPTH, analyze_pgn
|
||||
|
||||
logger = logging.getLogger("chess_analyzer")
|
||||
|
||||
@@ -28,7 +28,6 @@ STATIC_DIR = Path(__file__).parent / "static"
|
||||
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
|
||||
|
||||
ANALYSIS_CONCURRENCY = int(os.environ.get("ANALYSIS_CONCURRENCY", "2"))
|
||||
MAX_DEPTH = int(os.environ.get("MAX_DEPTH", "20"))
|
||||
analysis_semaphore = asyncio.Semaphore(ANALYSIS_CONCURRENCY)
|
||||
|
||||
|
||||
@@ -45,7 +44,6 @@ def _game_id(pgn: str, username: str | None, depth: int) -> str:
|
||||
class AnalyzeRequest(BaseModel):
|
||||
pgn: str = Field(max_length=65536)
|
||||
username: str | None = Field(default=None, max_length=64)
|
||||
depth: int | None = None
|
||||
|
||||
|
||||
@app.get("/")
|
||||
@@ -82,11 +80,8 @@ async def games(username: str, year: str, month: str):
|
||||
white = g.get("white", {})
|
||||
black = g.get("black", {})
|
||||
games_out.append({
|
||||
"url": g.get("url"),
|
||||
"end_time": g.get("end_time"),
|
||||
"time_class": g.get("time_class"),
|
||||
"time_control": g.get("time_control"),
|
||||
"rated": g.get("rated"),
|
||||
"white": {"username": white.get("username"), "rating": white.get("rating"), "result": white.get("result")},
|
||||
"black": {"username": black.get("username"), "rating": black.get("rating"), "result": black.get("result")},
|
||||
"pgn": g.get("pgn"),
|
||||
@@ -104,14 +99,11 @@ async def get_game(game_id: str):
|
||||
|
||||
@app.post("/api/analyze")
|
||||
async def analyze(req: AnalyzeRequest):
|
||||
depth = req.depth or int(os.environ.get("ANALYSIS_DEPTH", "14"))
|
||||
depth = max(1, min(depth, MAX_DEPTH))
|
||||
|
||||
# chess.com usernames are case-insensitive; normalize so "Foo" and "foo"
|
||||
# hit the same cache entry.
|
||||
username = req.username.strip().lower() if req.username else None
|
||||
|
||||
game_id = _game_id(req.pgn, username, depth)
|
||||
game_id = _game_id(req.pgn, username, DEFAULT_DEPTH)
|
||||
|
||||
cached = await asyncio.to_thread(db.get_game, game_id)
|
||||
if cached is not None:
|
||||
@@ -123,7 +115,7 @@ async def analyze(req: AnalyzeRequest):
|
||||
if cached is not None:
|
||||
return {"id": game_id, **cached}
|
||||
try:
|
||||
result = await analyze_pgn(req.pgn, username=username, depth=depth)
|
||||
result = await analyze_pgn(req.pgn, username=username)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
except Exception:
|
||||
@@ -133,5 +125,5 @@ async def analyze(req: AnalyzeRequest):
|
||||
detail="Analysis failed. Check server logs — this is usually a missing/misconfigured Stockfish binary.",
|
||||
)
|
||||
|
||||
await asyncio.to_thread(db.save_game, game_id, username, depth, result)
|
||||
await asyncio.to_thread(db.save_game, game_id, username, result)
|
||||
return {"id": game_id, **result}
|
||||
@@ -26,10 +26,12 @@
|
||||
<section class="panel" id="analysis-panel" hidden>
|
||||
<div class="analysis-layout">
|
||||
<div class="board-column">
|
||||
<div id="top-player" class="player-plate"></div>
|
||||
<div id="board-wrap">
|
||||
<div id="board"></div>
|
||||
<svg id="arrows" viewBox="0 0 100 100" preserveAspectRatio="none"></svg>
|
||||
</div>
|
||||
<div id="bottom-player" class="player-plate"></div>
|
||||
<div class="nav-row">
|
||||
<button id="prev-btn">← Prev</button>
|
||||
<span id="ply-label"></span>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const STARTING_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR";
|
||||
// Mirrors MATE_SCORE_CP in app/analysis.py: mate in N plies arrives as ±(100000 − N).
|
||||
const MATE_SCORE_CP = 100000;
|
||||
|
||||
// CBurnett piece set by Colin M.L. Burnett (GPLv2+/BSD/CC BY-SA),
|
||||
// via https://github.com/lichess-org/lila/tree/master/public/piece/cburnett
|
||||
@@ -13,7 +14,7 @@ const CLASS_COLORS = {
|
||||
blunder: "#d64545",
|
||||
unknown: "#888888",
|
||||
};
|
||||
const BEST_MOVE_ARROW_COLOR = "#23242a"; // the editor's ink line
|
||||
const BEST_MOVE_ARROW_COLOR = CLASS_COLORS.best;
|
||||
|
||||
const el = (id) => document.getElementById(id);
|
||||
|
||||
@@ -41,9 +42,8 @@ async function apiPost(url, payload) {
|
||||
|
||||
function formatEval(cp) {
|
||||
if (cp === null || cp === undefined) return "n/a";
|
||||
// Server encodes "mate in N plies" as ±(100000 - N); render as chess notation.
|
||||
if (Math.abs(cp) > 90000) {
|
||||
const plies = 100000 - Math.abs(cp);
|
||||
if (Math.abs(cp) > MATE_SCORE_CP - 10000) {
|
||||
const plies = MATE_SCORE_CP - Math.abs(cp);
|
||||
const label = plies <= 0 ? "#" : `M${Math.ceil(plies / 2)}`;
|
||||
return (cp > 0 ? "+" : "-") + label;
|
||||
}
|
||||
@@ -52,7 +52,7 @@ function formatEval(cp) {
|
||||
}
|
||||
|
||||
function renderBoard(fen, flip) {
|
||||
const placement = fen.split(" ")[0] || STARTING_FEN;
|
||||
const placement = fen.split(" ")[0];
|
||||
const rows = placement.split("/"); // rows[0] = rank 8 ... rows[7] = rank 1
|
||||
|
||||
const board = el("board");
|
||||
|
||||
+38
-8
@@ -17,8 +17,10 @@ async function init() {
|
||||
setStatus("Loading analysis...");
|
||||
try {
|
||||
analysis = await apiGet(`/api/game/${id}`);
|
||||
el("game-title").textContent = `${analysis.white} vs ${analysis.black}`;
|
||||
document.title = `${analysis.white} vs ${analysis.black}`;
|
||||
const title = `${analysis.white} vs ${analysis.black}`;
|
||||
document.title = title;
|
||||
el("game-title").replaceChildren(gameLink(title));
|
||||
renderPlayerPlates();
|
||||
const back = document.querySelector(".back-link");
|
||||
if (back && analysis.username) {
|
||||
back.href = `/u/${encodeURIComponent(analysis.username)}`;
|
||||
@@ -36,6 +38,31 @@ async function init() {
|
||||
}
|
||||
}
|
||||
|
||||
// Wraps text in an unstyled link to the game on chess.com when we have one.
|
||||
// Built with createElement/textContent — player names come from the API.
|
||||
function gameLink(text) {
|
||||
if (!analysis.game_url) return document.createTextNode(text);
|
||||
const a = document.createElement("a");
|
||||
a.className = "quiet-link";
|
||||
a.href = analysis.game_url;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener";
|
||||
a.textContent = text;
|
||||
return a;
|
||||
}
|
||||
|
||||
// Name plates hug the board: whoever owns the pieces at the top of the board
|
||||
// gets the top plate, so they follow the flip when the user played black.
|
||||
function renderPlayerPlates() {
|
||||
const name = (n, rating) => (rating ? `${n} (${rating})` : n);
|
||||
const plate = (id, text) => el(id).replaceChildren(gameLink(text));
|
||||
const flip = analysis.user_color === "black";
|
||||
plate(flip ? "bottom-player" : "top-player",
|
||||
name(analysis.black, analysis.black_rating));
|
||||
plate(flip ? "top-player" : "bottom-player",
|
||||
name(analysis.white, analysis.white_rating));
|
||||
}
|
||||
|
||||
function renderSummary() {
|
||||
const counts = { best: 0, good: 0, inaccuracy: 0, mistake: 0, blunder: 0 };
|
||||
for (const m of analysis.moves) {
|
||||
@@ -150,12 +177,15 @@ function renderEvalGraph() {
|
||||
|
||||
// Ink on paper, like a stock listing: the faint shaded area is White's
|
||||
// share of the game, the ink line is the story, red dots mark the sins.
|
||||
const PAPER = "#f7f3e8";
|
||||
const INK = "#23242a";
|
||||
// Colors come from the stylesheet's :root variables so the palette has one home.
|
||||
const theme = getComputedStyle(document.documentElement);
|
||||
const PAPER = theme.getPropertyValue("--paper").trim();
|
||||
const INK = theme.getPropertyValue("--ink").trim();
|
||||
const GOLD = theme.getPropertyValue("--gold").trim();
|
||||
const RED = theme.getPropertyValue("--red").trim();
|
||||
const HAIRLINE = theme.getPropertyValue("--rule").trim();
|
||||
const MUTED = theme.getPropertyValue("--muted").trim();
|
||||
const AREA = "#e7dfc9";
|
||||
const GOLD = "#a8892e";
|
||||
const RED = "#9c2b23";
|
||||
const HAIRLINE = "#c9c2ac";
|
||||
|
||||
let curve = "";
|
||||
for (const p of graphPts) {
|
||||
@@ -189,7 +219,7 @@ function renderEvalGraph() {
|
||||
// Hover crosshair + current-position marker.
|
||||
svg.appendChild(svgEl("line", {
|
||||
id: "eval-hover-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H,
|
||||
stroke: "#6b6656", "stroke-width": 1.5, visibility: "hidden",
|
||||
stroke: MUTED, "stroke-width": 1.5, visibility: "hidden",
|
||||
}));
|
||||
svg.appendChild(svgEl("line", {
|
||||
id: "eval-marker-line", x1: 0, y1: 0, x2: 0, y2: GRAPH.H,
|
||||
|
||||
+34
-9
@@ -19,6 +19,13 @@ el("month-select").addEventListener("change", () => {
|
||||
});
|
||||
el("older-month-btn").addEventListener("click", () => stepMonth(1));
|
||||
el("newer-month-btn").addEventListener("click", () => stepMonth(-1));
|
||||
document.addEventListener("keydown", (e) => {
|
||||
// Leave the arrow keys alone while the user is moving the caret in the search box.
|
||||
if (document.activeElement === el("player-search")) return;
|
||||
if (el("games-panel").hidden) return;
|
||||
if (e.key === "ArrowLeft") stepMonth(1);
|
||||
if (e.key === "ArrowRight") stepMonth(-1);
|
||||
});
|
||||
|
||||
function monthLabel(value) {
|
||||
const [year, month] = value.split("-");
|
||||
@@ -143,9 +150,13 @@ function renderGamesTable() {
|
||||
tbody.innerHTML = "";
|
||||
currentGames.forEach((game) => {
|
||||
const tr = document.createElement("tr");
|
||||
const date = game.end_time ? new Date(game.end_time * 1000).toLocaleDateString() : "";
|
||||
const cell = (text) => {
|
||||
const td = document.createElement("td");
|
||||
td.textContent = text;
|
||||
tr.appendChild(td);
|
||||
return td;
|
||||
};
|
||||
|
||||
// Everything from the searched player's point of view.
|
||||
const whiteIsUser = (game.white.username || "").toLowerCase() === currentUsername;
|
||||
const me = whiteIsUser ? game.white : game.black;
|
||||
const opponent = whiteIsUser ? game.black : game.white;
|
||||
@@ -162,13 +173,19 @@ function renderGamesTable() {
|
||||
}
|
||||
const why = me.result === "win" ? "" : (RESULT_REASONS[me.result] || me.result);
|
||||
|
||||
tr.innerHTML = `
|
||||
<td>${date}</td>
|
||||
<td>${opponent.username} (${opponent.rating ?? "?"})</td>
|
||||
<td>${whiteIsUser ? "White" : "Black"}</td>
|
||||
<td class="${resultClass}">${verdict}${why ? ` <span class="res-why">${why}</span>` : ""}</td>
|
||||
<td>${formatTimeControl(game.time_control)}</td>
|
||||
`;
|
||||
cell(game.end_time ? new Date(game.end_time * 1000).toLocaleDateString() : "");
|
||||
cell(`${opponent.username} (${opponent.rating ?? "?"})`);
|
||||
cell(whiteIsUser ? "White" : "Black");
|
||||
const resultTd = cell(verdict);
|
||||
resultTd.className = resultClass;
|
||||
if (why) {
|
||||
const span = document.createElement("span");
|
||||
span.className = "res-why";
|
||||
span.textContent = why;
|
||||
resultTd.append(" ", span);
|
||||
}
|
||||
cell(formatTimeControl(game.time_control));
|
||||
|
||||
tr.addEventListener("click", () => analyzeGame(game, tr));
|
||||
tbody.appendChild(tr);
|
||||
});
|
||||
@@ -182,6 +199,14 @@ if (bookmarkedUsername) {
|
||||
|
||||
let analyzing = false;
|
||||
|
||||
// Safari restores this page from the back/forward cache exactly as it was when
|
||||
// we navigated away — busy overlay up and clicks locked out. Reset on return.
|
||||
window.addEventListener("pageshow", () => {
|
||||
analyzing = false;
|
||||
el("busy-overlay").hidden = true;
|
||||
document.querySelectorAll("tr.analyzing").forEach((tr) => tr.classList.remove("analyzing"));
|
||||
});
|
||||
|
||||
async function analyzeGame(game, row) {
|
||||
if (analyzing) return;
|
||||
analyzing = true;
|
||||
|
||||
+12
-2
@@ -19,7 +19,7 @@
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
html { overflow-y: scroll; scrollbar-gutter: stable; }
|
||||
html { scrollbar-gutter: stable; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
@@ -59,7 +59,9 @@ h1 {
|
||||
text-wrap: balance;
|
||||
}
|
||||
.subtitle { margin: 0; color: var(--muted); font-style: italic; font-size: 1rem; }
|
||||
.subtitle b, .subtitle strong { color: var(--gold); font-style: normal; }
|
||||
|
||||
.quiet-link { color: inherit; text-decoration: none; }
|
||||
.quiet-link:hover { color: var(--gold); }
|
||||
|
||||
.back-link {
|
||||
display: inline-block;
|
||||
@@ -196,6 +198,14 @@ tbody tr.analyzing { background: var(--paper-shade); font-style: italic; cursor:
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
.player-plate {
|
||||
width: 560px;
|
||||
max-width: 90vw;
|
||||
font-size: 1rem;
|
||||
}
|
||||
#top-player { margin-bottom: 0.4rem; }
|
||||
#bottom-player { margin-top: 0.4rem; }
|
||||
|
||||
#board {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
fastapi==0.115.6
|
||||
uvicorn[standard]==0.32.1
|
||||
httpx==0.28.1
|
||||
python-chess==1.999
|
||||
chess==1.11.2
|
||||
Reference in new issue
Block a user