Python API Reference
Auto-generated from source code docstrings.
Command-line interface for chess-self-coach.
Entry point for the CLI. Dispatches to subcommands: setup, train, update, syzygy.
main(argv=None)
Main CLI entry point.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
argv
|
list[str] | None
|
Command-line arguments (defaults to sys.argv[1:]). |
None
|
Source code in src/chess_self_coach/cli.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
Configuration loading for chess-self-coach.
Loads config.json (Stockfish path, player usernames) and .env (Lichess token). Every error produces a clear message with the exact command to fix it.
ConfigError
Bases: Exception
Raised when config.json is missing, invalid, or unreadable.
Attributes:
| Name | Type | Description |
|---|---|---|
hint |
Optional fix suggestion for the user. |
Source code in src/chess_self_coach/config.py
20 21 22 23 24 25 26 27 28 29 | |
analysis_data_path()
Return the path to analysis_data.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/analysis_data.json. |
Source code in src/chess_self_coach/config.py
83 84 85 86 87 88 89 | |
check_stockfish_version(sf_path, expected=None)
Check the Stockfish version and warn if it doesn't match expected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sf_path
|
Path
|
Path to the Stockfish binary. |
required |
expected
|
str | None
|
Expected version string (e.g. "Stockfish 18"). |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The detected version string. |
Source code in src/chess_self_coach/config.py
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 | |
classifications_data_path()
Return the path to classifications_data.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/classifications_data.json. |
Source code in src/chess_self_coach/config.py
119 120 121 122 123 124 125 | |
config_path()
Return the path to config.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/config.json. |
Source code in src/chess_self_coach/config.py
74 75 76 77 78 79 80 | |
data_dir()
Return the data directory path.
Returns:
| Type | Description |
|---|---|
Path
|
Path to the data/ directory in the project root. |
Source code in src/chess_self_coach/config.py
65 66 67 68 69 70 71 | |
error_exit(message, hint=None, debug_cmd=None)
Print a formatted error and exit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
What went wrong. |
required |
hint
|
str | None
|
How to fix it. |
None
|
debug_cmd
|
str | None
|
A shell command the user can run to debug. |
None
|
Source code in src/chess_self_coach/config.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
fetched_games_path()
Return the path to fetched_games.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/fetched_games.json. |
Source code in src/chess_self_coach/config.py
101 102 103 104 105 106 107 | |
find_stockfish(config=None)
Find a working Stockfish binary.
Search order: config.json path → common install locations → system → $PATH.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any] | None
|
Optional loaded config dict. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the Stockfish binary. |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If no Stockfish binary is found. |
Source code in src/chess_self_coach/config.py
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
load_config()
Load config.json from the data directory.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Parsed config dictionary. |
Raises:
| Type | Description |
|---|---|
ConfigError
|
If config.json is missing or invalid. |
Source code in src/chess_self_coach/config.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
load_lichess_token(required=True)
Load the Lichess API token from .env or environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
required
|
bool
|
If True, exit on missing token. If False, return None. |
True
|
Returns:
| Type | Description |
|---|---|
str | None
|
The API token string, or None if not found and not required. |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If required=True and no token is found or it looks invalid. |
Source code in src/chess_self_coach/config.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | |
save_config(config)
Write config back to config.json atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any]
|
The config dictionary to save. |
required |
Source code in src/chess_self_coach/config.py
183 184 185 186 187 188 189 190 191 192 193 194 | |
tactics_data_path()
Return the path to tactics_data.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/tactics_data.json. |
Source code in src/chess_self_coach/config.py
110 111 112 113 114 115 116 | |
training_data_path()
Return the path to training_data.json.
Returns:
| Type | Description |
|---|---|
Path
|
Path to data/training_data.json. |
Source code in src/chess_self_coach/config.py
92 93 94 95 96 97 98 | |
Phase 1: collect raw per-move data from Stockfish, tablebase, and opening explorer.
Stores all evaluation data in analysis_data.json with maximum granularity. Phase 2 (training_data.py) annotates and filters this data into training_data.json.
AnalysisInterrupted
Bases: Exception
Raised when analysis is cancelled via the interrupt signal.
Source code in src/chess_self_coach/analysis.py
927 928 | |
AnalysisSettings
dataclass
Engine and analysis configuration for full game analysis.
Attributes:
| Name | Type | Description |
|---|---|---|
threads |
int
|
Number of Stockfish threads. 0 means auto (cpu_count - 1). |
hash_mb |
int
|
Stockfish hash table size in megabytes. |
limits |
dict[str, dict[str, float | int]]
|
Depth/time limits per piece-count bracket. |
Source code in src/chess_self_coach/analysis.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
resolved_threads
property
Actual thread count (resolves 0/auto to cpu_count - 1).
from_config(config)
classmethod
Build settings from a config dict (from config.json).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict
|
Full config dict. Reads the 'analysis_engine' key. |
required |
Returns:
| Type | Description |
|---|---|
AnalysisSettings
|
AnalysisSettings with values from config, defaults for missing keys. |
Source code in src/chess_self_coach/analysis.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
to_dict()
Serialize to a dict suitable for JSON storage.
Returns:
| Type | Description |
|---|---|
dict
|
Dict with threads (resolved to actual count), hash_mb, limits. |
Source code in src/chess_self_coach/analysis.py
84 85 86 87 88 89 90 91 92 93 94 | |
analyze_games(*, game_ids=None, max_games=10, reanalyze_all=False, settings=None, engine_path=None, on_progress=None, on_game_done=None, cancel=None)
Fetch games, analyze with Stockfish + APIs, write analysis_data.json.
Phase 1 orchestrator: sequential analysis with one multi-threaded Stockfish. Caller is responsible for invoking generate_training_data() (Phase 2) afterwards.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_ids
|
list[str] | None
|
Specific game IDs to analyze from the cache. When set, skips the fetch phase and reads from fetched_games.json. When None or empty, fetches from APIs (original behavior). |
None
|
max_games
|
int
|
Maximum total games in the dataset (default: 10). |
10
|
reanalyze_all
|
bool
|
If True, re-analyze games (skip only same-settings). |
False
|
settings
|
AnalysisSettings | None
|
Override analysis settings. None = load from config. |
None
|
engine_path
|
str | None
|
Override path to Stockfish binary. |
None
|
on_progress
|
Callable[[dict], None] | None
|
Optional callback for structured progress events. |
None
|
cancel
|
Event | None
|
Threading event for cancellation. |
None
|
Source code in src/chess_self_coach/analysis.py
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 | |
collect_game_data(game, engine, player_color, settings, lichess_token=None, game_id='', existing_moves=None, on_wait=None)
Collect full per-move analysis data for one game (Phase 1).
Source hierarchy per move
- Tablebase (priority if ≤7 pieces — perfect information)
- Masters opening explorer (in_opening=True, cp_loss=0)
- Cloud eval (depth 50-70, cp_loss computed)
- Stockfish (fallback, always re-run on re-analysis)
When existing_moves is provided (re-analysis), API data (masters, cloud eval, tablebase) is preserved and only breakpoints are re-tested. Stockfish positions are always re-run regardless.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game
|
Game
|
Parsed PGN game. |
required |
engine
|
SimpleEngine
|
Running Stockfish engine (already configured with threads/hash). |
required |
player_color
|
Color
|
Which color the player was. |
required |
settings
|
AnalysisSettings
|
Analysis settings (for limits and storage). |
required |
lichess_token
|
str | None
|
Lichess API token for Opening Explorer. None to skip. |
None
|
game_id
|
str
|
Unique game identifier. Passed to engine.analyse() so python-chess sends ucinewgame between different games (hash table reset). |
''
|
existing_moves
|
list[dict[str, Any]] | None
|
Previous per-move data from a prior analysis. When set, preserves API data and only re-tests breakpoints + re-runs Stockfish. |
None
|
on_wait
|
Callable[[int, float], None] | None
|
Optional callback(attempt, delay_seconds) called when an API request is retrying after a transient error (429, 5xx). |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with game headers, settings, and moves[] array ready for |
dict[str, Any]
|
storage in analysis_data.json. |
Source code in src/chess_self_coach/analysis.py
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 | |
load_analysis_data(path=None)
Load analysis_data.json, returning empty structure if not found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Path to analysis_data.json. Defaults to data directory. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Parsed dict with at least {version, player, games}. |
Source code in src/chess_self_coach/analysis.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
save_analysis_data(data, path=None)
Atomically write analysis_data.json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Full analysis data dict. |
required |
path
|
Path | None
|
Target path. Defaults to data directory. |
None
|
Source code in src/chess_self_coach/analysis.py
118 119 120 121 122 123 124 125 126 127 128 | |
settings_match(stored, current)
Check if stored analysis settings match current settings.
Used to skip re-analysis of games already analyzed with identical settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stored
|
dict
|
Settings dict from a previously analyzed game. |
required |
current
|
dict
|
Current settings dict. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if settings are equivalent. |
Source code in src/chess_self_coach/analysis.py
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 | |
Training mode: explanation generation, move classification, and training data utilities.
Pure functions for generating rule-based explanations, classifying mistakes by centipawn loss, and managing training_data.json (stats, refresh). The heavy analysis pipeline lives in analysis.py (Phase 1: collection, Phase 2: derivation).
classify_mistake(cp_loss)
Classify a move by centipawn loss.
Returns:
| Type | Description |
|---|---|
str | None
|
Category string or None if the move is acceptable. |
Source code in src/chess_self_coach/trainer.py
42 43 44 45 46 47 48 49 50 51 52 53 54 | |
format_score_cp(cp)
Format centipawn value as score string like '+0.32'.
Source code in src/chess_self_coach/trainer.py
32 33 34 35 36 37 38 | |
generate_context(category, cp_loss, was_mate, score_after_cp, fen='', score_before_cp=None, player_color='white')
Generate a short context sentence shown BEFORE the player answers.
Includes game phase, advantage context, and what went wrong.
Source code in src/chess_self_coach/trainer.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 | |
generate_explanation(board, actual_san, best_san, cp_loss, category, was_mate=False, score_after_cp=None)
Generate a rule-based explanation for a mistake.
Detects basic patterns: missed captures, missed checks/checkmates, hanging pieces, stalemate. Falls back to a generic template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
board
|
Board
|
Board position BEFORE the move was played. |
required |
actual_san
|
str
|
The move the player made (SAN). |
required |
best_san
|
str
|
The best move according to Stockfish (SAN). |
required |
cp_loss
|
int
|
Centipawn loss. |
required |
category
|
str
|
Mistake category string. |
required |
was_mate
|
bool
|
True if the position before was a forced mate. |
False
|
score_after_cp
|
int | None
|
Score after the move (white perspective), for context. |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Explanation string. |
Source code in src/chess_self_coach/trainer.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
get_stats_data()
Compute training statistics from training_data.json.
Returns:
| Type | Description |
|---|---|
dict
|
Dict with keys: generated, total, by_category, by_source. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If training_data.json does not exist. |
Source code in src/chess_self_coach/trainer.py
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 | |
print_stats()
Show training progress from training_data.json.
Source code in src/chess_self_coach/trainer.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 | |
refresh_explanations()
Regenerate explanations in training_data.json without re-running Stockfish.
Reads existing positions, rebuilds explanations using generate_explanation(), and writes back. SRS progress and all other fields are preserved.
Source code in src/chess_self_coach/trainer.py
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | |
time_pressure_context(player_clock, opponent_clock)
Generate time pressure context string, or empty if not relevant.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
player_clock
|
float | None
|
Player's remaining time in seconds, or None. |
required |
opponent_clock
|
float | None
|
Opponent's remaining time in seconds, or None. |
required |
Source code in src/chess_self_coach/trainer.py
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | |
FastAPI backend server for Chess Self-Coach [App] mode.
Serves the PWA with API endpoints for native Stockfish analysis. Replaces the old static-file-only serve_pwa() from trainer.py.
Key design decisions: - No temp dir: PWA files served directly from source, sw.js and training_data.json via dynamic routes (always fresh, no copy needed). - Single Stockfish engine instance with asyncio.Lock for thread safety. - Engine crash recovery: auto-restart on EngineTerminatedError. - Port scanning: tries 8000-8010 if default port is busy.
AnalysisSettingsResponse
Bases: BaseModel
Response body for GET /api/analysis/settings.
Source code in src/chess_self_coach/server.py
223 224 225 226 227 228 | |
AnalysisStartRequest
Bases: BaseModel
Request body for POST /api/analysis/start.
Source code in src/chess_self_coach/server.py
231 232 233 234 235 236 | |
BestMoveRequest
Bases: BaseModel
Request body for /api/stockfish/bestmove.
Source code in src/chess_self_coach/server.py
166 167 168 169 170 | |
BestMoveResponse
Bases: BaseModel
Response body for /api/stockfish/bestmove.
Source code in src/chess_self_coach/server.py
173 174 175 176 | |
ConfigResponse
Bases: BaseModel
Response body for GET /api/config.
Source code in src/chess_self_coach/server.py
187 188 189 190 191 | |
ConfigUpdateRequest
Bases: BaseModel
Request body for POST /api/config.
Source code in src/chess_self_coach/server.py
194 195 196 197 198 | |
GameListResponse
Bases: BaseModel
Response body for GET /api/games.
Source code in src/chess_self_coach/server.py
216 217 218 219 220 | |
GameSummaryResponse
Bases: BaseModel
One game in the game list.
Source code in src/chess_self_coach/server.py
201 202 203 204 205 206 207 208 209 210 211 212 213 | |
JobStartResponse
Bases: BaseModel
Response body for job start endpoints.
Source code in src/chess_self_coach/server.py
239 240 241 242 | |
StatusResponse
Bases: BaseModel
Response body for /api/status.
Source code in src/chess_self_coach/server.py
179 180 181 182 183 184 | |
analysis_data()
async
Serve analysis data directly from project root (always fresh).
Source code in src/chess_self_coach/server.py
645 646 647 648 649 650 651 | |
analysis_start(req)
async
Start a background full game analysis job.
Source code in src/chess_self_coach/server.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | |
bestmove(req)
async
Compute the best move for a position using native Stockfish.
Source code in src/chess_self_coach/server.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
classifications_data()
async
Serve pre-computed move classifications (always fresh).
Source code in src/chess_self_coach/server.py
654 655 656 657 658 659 660 | |
games_fetch(max_games=200)
async
Fetch games from Lichess/chess.com and cache locally.
Source code in src/chess_self_coach/server.py
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
games_list(limit=20)
async
Return unified game list (cached + analyzed), sorted by date.
Source code in src/chess_self_coach/server.py
360 361 362 363 364 365 366 367 368 369 370 371 | |
get_analysis_settings()
async
Return current analysis engine settings (with 'auto' resolved).
Source code in src/chess_self_coach/server.py
377 378 379 380 381 382 383 384 385 386 387 388 389 390 | |
get_config()
async
Return editable config fields (players, analysis).
Source code in src/chess_self_coach/server.py
290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
job_cancel(job_id)
async
Request cancellation of a running job.
Source code in src/chess_self_coach/server.py
622 623 624 625 626 627 628 629 630 | |
job_current()
async
Return the current job ID and status, if any.
Source code in src/chess_self_coach/server.py
613 614 615 616 617 618 619 | |
job_events(job_id)
async
Stream job progress events via SSE.
Source code in src/chess_self_coach/server.py
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | |
lifespan(app)
async
Manage Stockfish engine lifecycle.
Source code in src/chess_self_coach/server.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | |
run_server()
Start the FastAPI server and open the browser.
Called by cli.py when user runs chess-self-coach (no subcommand)
or chess-self-coach train --serve.
Source code in src/chess_self_coach/server.py
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | |
service_worker()
async
Serve service worker with version injected on-the-fly.
Source code in src/chess_self_coach/server.py
663 664 665 666 667 668 669 670 671 672 | |
status()
async
Return app status for mode detection by the PWA.
Source code in src/chess_self_coach/server.py
248 249 250 251 252 253 254 | |
training_data()
async
Serve training data directly from project root (always fresh).
Source code in src/chess_self_coach/server.py
636 637 638 639 640 641 642 | |
update_analysis_settings(req)
async
Save analysis engine settings to config.json.
Source code in src/chess_self_coach/server.py
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | |
update_config(req)
async
Update editable config fields (players, analysis). Preserves other fields.
Source code in src/chess_self_coach/server.py
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 | |
Game fetching from Lichess and chess.com.
fetch_chesscom_games(username, max_games=100)
Fetch rated rapid+ games from chess.com public API.
Uses the chessdotcom package (installed as chess.com) to access the chess.com public API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
Chess.com username. |
required |
max_games
|
int
|
Maximum number of games to fetch. |
100
|
Returns:
| Type | Description |
|---|---|
list[Game]
|
List of parsed chess.pgn.Game objects. |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If fetching fails. |
Source code in src/chess_self_coach/importer.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
fetch_lichess_games(username, max_games=100)
Fetch rated rapid+ games from Lichess.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
username
|
str
|
Lichess username. |
required |
max_games
|
int
|
Maximum number of games to fetch. |
100
|
Returns:
| Type | Description |
|---|---|
list[Game]
|
List of parsed chess.pgn.Game objects. |
Raises:
| Type | Description |
|---|---|
SystemExit
|
If fetching fails. |
Source code in src/chess_self_coach/importer.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
Game cache: fetch games from APIs and cache locally for later analysis.
Decouples game fetching (fast, API-only) from Stockfish analysis (slow). The cache stores raw PGN text so games can be deserialized on demand.
GameSummary
dataclass
Summary of a game for the game list UI.
Attributes:
| Name | Type | Description |
|---|---|---|
game_id |
str
|
Unique game identifier (URL from PGN headers). |
white |
str
|
White player name. |
black |
str
|
Black player name. |
player_color |
str
|
Color the player was playing ("white" or "black"). |
result |
str
|
Game result ("1-0", "0-1", "1/2-1/2"). |
date |
str
|
Game date string (YYYY.MM.DD). |
opening |
str
|
Opening name if known. |
move_count |
int
|
Number of half-moves in the game. |
source |
str
|
Platform ("lichess" or "chess.com"). |
analyzed |
bool
|
Whether the game has been analyzed with Stockfish. |
Source code in src/chess_self_coach/game_cache.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
to_dict()
Serialize to dict for JSON API response.
Source code in src/chess_self_coach/game_cache.py
51 52 53 | |
fetch_and_cache_games(lichess_user, chesscom_user, max_games=200)
Fetch games from Lichess and chess.com, cache locally.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lichess_user
|
str
|
Lichess username. |
required |
chesscom_user
|
str | None
|
Optional chess.com username. |
required |
max_games
|
int
|
Maximum games to fetch per source. |
200
|
Returns:
| Type | Description |
|---|---|
list[GameSummary]
|
List of GameSummary for all fetched games. |
Source code in src/chess_self_coach/game_cache.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 | |
get_cached_game(game_id)
Deserialize a single game from the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
game_id
|
str
|
Game URL identifier. |
required |
Returns:
| Type | Description |
|---|---|
Game | None
|
Parsed chess.pgn.Game, or None if not in cache. |
Source code in src/chess_self_coach/game_cache.py
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
get_unified_game_list(limit=20)
Merge fetched games cache with analysis data into a unified list.
Analysis data takes precedence (richer info, marked as analyzed). Sorted by date descending, capped at limit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum number of games to return. |
20
|
Returns:
| Type | Description |
|---|---|
list[GameSummary]
|
List of GameSummary, most recent first. |
Source code in src/chess_self_coach/game_cache.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
load_game_cache()
Load the fetched games cache.
Returns:
| Type | Description |
|---|---|
dict
|
Cache dict with 'fetched_at' and 'games' keys, or empty structure. |
Source code in src/chess_self_coach/game_cache.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
Lichess Masters Opening Explorer API client.
Queries the Lichess Masters opening explorer (FIDE 2200+ OTB games) to identify opening names, ECO codes, and move popularity statistics for each position. Used during Phase 1 analysis to detect when players depart from known theory.
A move is considered "in opening" (in_opening=True) only if it appears in the Masters database.
ExplorerAPIError
Bases: Exception
Raised when the Opening Explorer API is unavailable or rate-limited.
Source code in src/chess_self_coach/opening_explorer.py
37 38 | |
query_opening(fen, token)
Query the Lichess Masters Opening Explorer for a position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fen
|
str
|
FEN string of the position to query. |
required |
token
|
str
|
Lichess API personal access token. |
required |
Returns:
| Type | Description |
|---|---|
dict | None
|
Dict with {opening, white, draws, black, moves[]} or None if position |
dict | None
|
has zero games in Masters database. |
Raises:
| Type | Description |
|---|---|
ExplorerAPIError
|
If both primary/fallback endpoints fail. |
Source code in src/chess_self_coach/opening_explorer.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
query_opening_sequence(fens_and_moves, token, *, existing_results=None)
Query the Masters Opening Explorer for a sequence of positions.
Queries Masters until the played move is not found (theory departure).
Each returned dict has _source="masters".
When existing_results is provided (re-analysis), positions that already have Masters data are preserved without API calls. Querying resumes from the first position without Masters data (breakpoint re-testing).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fens_and_moves
|
list[tuple[str, str]]
|
List of (fen_before, move_uci) tuples for each ply. |
required |
token
|
str
|
Lichess API personal access token. |
required |
existing_results
|
list[dict | None] | None
|
Previous opening_explorer data per ply (from a prior
analysis). Entries with |
None
|
Returns:
| Type | Description |
|---|---|
list[dict | None]
|
List of explorer responses (same length as input). None entries mean |
list[dict | None]
|
the position was past theory departure. |
Source code in src/chess_self_coach/opening_explorer.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 | |
refresh_opening_data(path=None, token=None)
Re-query Masters for existing games to update in_opening flags.
For each game, iterates through moves that currently have in_opening=True. Queries Masters for each position until Masters departs, then sets in_opening=False for that move and all subsequent moves.
Does NOT re-run Stockfish or touch eval data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Path to analysis_data.json. Defaults to config. |
None
|
token
|
str | None
|
Lichess API token. Required for API calls. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with stats: {games_updated, moves_changed, total_masters}. |
Source code in src/chess_self_coach/opening_explorer.py
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
Lichess tablebase API client for perfect endgame analysis.
Probes the public Lichess tablebase API (no token required) for positions with <= 7 pieces. Returns mathematically exact Win/Draw/Loss verdicts instead of heuristic Stockfish evaluations.
Transient errors (429, 5xx, timeouts) are retried with exponential backoff. Only a genuine 404 (position not in database) returns None.
API: https://tablebase.lichess.ovh/standard?fen=
RateLimitExhaustedError
Bases: Exception
Raised when the API rate limit persists after maximum backoff (128 min).
Source code in src/chess_self_coach/tablebase.py
46 47 | |
TablebaseResult
dataclass
Result from a tablebase probe.
Source code in src/chess_self_coach/tablebase.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | |
tier
property
WDL tier: WIN, DRAW, or LOSS.
format_verdict()
Human-readable verdict, e.g. 'win, mate in 23' or 'draw'.
Source code in src/chess_self_coach/tablebase.py
79 80 81 82 83 84 85 86 | |
probe_position(fen)
Probe the Lichess tablebase API for a position.
Retries indefinitely on transient errors (429, 5xx, network) with exponential backoff. Only returns None for too many pieces or 404.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fen
|
str
|
FEN string of the position. |
required |
Returns:
| Type | Description |
|---|---|
TablebaseResult | None
|
TablebaseResult if the position has <= 7 pieces and is in the |
TablebaseResult | None
|
tablebase, None otherwise. |
Source code in src/chess_self_coach/tablebase.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
probe_position_full(fen, on_wait=None)
Probe the Lichess tablebase API and return the complete response.
Unlike probe_position() which returns a simplified TablebaseResult, this returns the raw API response including all legal moves with their WDL/DTM/DTZ data — suitable for storing in analysis_data.json.
Retries indefinitely on transient errors (429, 5xx, network) with exponential backoff. Only returns None for too many pieces or 404.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fen
|
str
|
FEN string of the position. |
required |
on_wait
|
Callable[[int, float], None] | None
|
Optional callback(attempt, delay_seconds) called before each retry sleep, so callers can surface the wait to the UI. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
Full API response dict (category, dtm, dtz, precise_dtz, dtw, dtc, |
dict[str, Any] | None
|
checkmate, stalemate, moves[]) or None if unavailable. |
Source code in src/chess_self_coach/tablebase.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
tablebase_context(before, piece_count, player_color='white')
Generate context string for a tablebase-resolved position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
before
|
TablebaseResult
|
Tablebase result for the position before the move. |
required |
piece_count
|
int
|
Number of pieces on the board. |
required |
player_color
|
str
|
"white" or "black". |
'white'
|
Returns:
| Type | Description |
|---|---|
str
|
Context string shown before the player answers. |
Source code in src/chess_self_coach/tablebase.py
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
tablebase_explanation(before, after, actual_san, best_san)
Generate explanation for a tablebase-detected mistake.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
before
|
TablebaseResult
|
Tablebase result before the move. |
required |
after
|
TablebaseResult
|
Tablebase result after the move. |
required |
actual_san
|
str
|
The move the player made. |
required |
best_san
|
str | None
|
The best move according to the tablebase. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Explanation string. |
Source code in src/chess_self_coach/tablebase.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 | |
Lichess Cloud Evaluation API client.
Queries the Lichess cloud database for pre-computed Stockfish analysis. Opening positions have near-perfect coverage at depth 50-70, making this much faster than running Stockfish locally.
Transient errors (429, 5xx, timeouts) are retried with exponential backoff. Only a genuine 404 (position not in database) returns None.
API: https://lichess.org/api#tag/Analysis
RateLimitExhaustedError
Bases: Exception
Raised when the API rate limit persists after maximum backoff (128 min).
Source code in src/chess_self_coach/cloud_eval.py
40 41 | |
query_cloud_eval(fen, multi_pv=1, on_wait=None, log_label='')
Query the Lichess Cloud database for a position.
Retries on transient errors (429, 5xx, network) with exponential backoff up to 128 minutes. Raises RateLimitExhaustedError if still failing after a retry at max backoff. Only returns None for a genuine cache miss (404).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fen
|
str
|
FEN string of the position to query. |
required |
multi_pv
|
int
|
Number of principal variations to request. |
1
|
on_wait
|
Callable[[int, float], None] | None
|
Optional callback(attempt, delay_seconds) called before each retry sleep, so callers can surface the wait to the UI. |
None
|
log_label
|
str
|
Optional prefix for log messages (e.g. "[ply 12 after] ") to identify which step triggered the query. |
''
|
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
API response dict with {fen, knodes, depth, pvs[]} or None if |
dict[str, Any] | None
|
the position is not in the database (404). |
Raises:
| Type | Description |
|---|---|
RateLimitExhaustedError
|
If rate limit persists after max backoff. |
Source code in src/chess_self_coach/cloud_eval.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
Syzygy endgame tablebase management.
Download, locate, and validate local Syzygy tablebases (3-5 pieces) for use by Stockfish via the SyzygyPath UCI option.
download_syzygy(target_dir=None)
Download 3-5 piece Syzygy tablebases (~1 GB).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_dir
|
Path | None
|
Where to store tables. Defaults to ~/.local/share/syzygy/. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the download directory. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If wget is not installed. |
CalledProcessError
|
If download fails. |
Source code in src/chess_self_coach/syzygy.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
find_syzygy(config=None)
Find a directory containing Syzygy tablebase files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict | None
|
Optional config dict. Reads config["syzygy"]["path"] first. |
None
|
Returns:
| Type | Description |
|---|---|
Path | None
|
Path to a directory with .rtbw files, or None if not found. |
Source code in src/chess_self_coach/syzygy.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
syzygy_status(config=None)
Report status of local Syzygy tablebases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict | None
|
Optional config dict for custom path lookup. |
None
|
Returns:
| Type | Description |
|---|---|
dict
|
Dict with path, found (bool), wdl_count, dtz_count, total_size_mb. |
Source code in src/chess_self_coach/syzygy.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | |
Self-update mechanism for chess-self-coach.
check_stockfish_update()
Check GitHub for a newer Stockfish release.
Compares the locally installed Stockfish version against the latest GitHub release of official-stockfish/Stockfish.
Returns:
| Type | Description |
|---|---|
bool
|
Tuple of (update_available, installed_version, latest_version). |
str | None
|
On any error, returns (False, None, None) — never crashes. |
Source code in src/chess_self_coach/updater.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | |
check_update()
Check PyPI for a newer version.
Returns:
| Type | Description |
|---|---|
bool
|
Tuple of (update_available, latest_version). On network error, |
str | None
|
returns (False, None) — never crashes. |
Source code in src/chess_self_coach/updater.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
update()
Update chess-self-coach to the latest version via uv, pipx, or pip.
Source code in src/chess_self_coach/updater.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
Shared constants and types for chess analysis engine.
Single source of truth for values used across multiple modules (analysis.py, trainer.py, tablebase.py).
EvalDict
Bases: TypedDict
Standard evaluation dictionary returned by all eval extraction functions.
Used by _extract_eval (Stockfish), _tb_to_eval (tablebase), and _cloud_eval_to_eval (Lichess Cloud Eval).
Source code in src/chess_self_coach/constants.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |