-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlearningbase_admin.py
More file actions
263 lines (223 loc) · 8.87 KB
/
Copy pathlearningbase_admin.py
File metadata and controls
263 lines (223 loc) · 8.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
"""Learning-base administration actions (menu-triggered).
Create/update learning bases, unroll PGNs into positions/lessons, import
chess.com games, and register a base as a BrainMaster course. Split out of
chessMain.py; depends only on shared state, app and the domain modules.
"""
import os
import pygame as p
from app_context import app
import BoardScreen as BS
import analyzer
import chess_com_download
import lichess_download
import BrainMaster
import pgngamelist
from LearningBase import LearningBase, learningBases
from state import positionParameters
def _count_games_in_pgn(path: str) -> int:
"""Quickly count games by counting `[Event ...]` lines. 0 on error."""
n = 0
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
if line.startswith("[Event "):
n += 1
except OSError:
return 0
return n
def _make_progress_cb(label: str, total: int):
"""Callback for `analyzer.analyzePgn(progress=...)`: redraws the screen
with N/M and calls event.pump() to avoid Windows' "not responding"."""
def cb(n: int) -> bool:
app.main_background()
msg = f"{label}: analyzing {n}/{total}" if total else f"{label}: analyzing game {n}"
BS.drawEndGameText(app.screen, None, msg + " (ESC to stop)", size=24)
# stop_requested() also drains events, keeping the window responsive.
return BS.stop_requested()
return cb
def createLearningBase():
# Verify that filename is not empty
filename = positionParameters.get("filename", "").strip()
if not filename:
raise ValueError("The 'filename' field in positionParameters is empty.")
learningBase = LearningBase(movesToAnalyze=positionParameters.get("movesToAnalyze",16),
blunderValue=positionParameters.get("blunderValue", 80),
ponderTime=positionParameters.get("ponderTime", 0.5),
useBook=positionParameters.get("useBook", False))
learningBase.setFileName(filename)
learningBases[filename] = learningBase
learningBase.save()
app.main_background()
BS.drawEndGameText(app.screen, None, f"learning base created")
BS.update()
app.delay(2 )
return
# add the games in the pgn file specified in positionParameters["filename"] to the LearningBase specified in positionParameters["base"],
# analyzing them with the parameters specified in positionParameters, and save the updated LearningBase
def updateLearningBase():
pgnFileName = positionParameters.get("filename", None)
learningBaseName = positionParameters.get("base", None)
player = positionParameters.get("player", None)
if pgnFileName is None :
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
if learningBaseName is None:
text = "Please select a base file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
if player is None or player == "":
text = "Please enter a player name"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
learningBase = learningBases.get(learningBaseName, None)
# Quick count for the progress bar (N/M during analysis).
pgn_path = os.path.join(pgngamelist.PGN_FOLDER, pgnFileName + ".pgn")
total = _count_games_in_pgn(pgn_path)
progress = _make_progress_cb(f"Updating '{learningBaseName}'", total)
analyzer.analyzePgn(pgnFileName, player, learningBase, progress=progress)
text = f"Learning base {learningBaseName} updated with {pgnFileName}"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
# Bring back every "Learned" (skip=True) position in the chosen base, so it
# re-enters local review. Non-destructive: only flips skip/serie, keeps stats.
def resetLearned():
learningBaseName = positionParameters.get("base", None)
if not learningBaseName:
app.main_background()
BS.drawEndGameText(app.screen, None, "Please select a base file")
BS.update()
app.delay(2)
return
learningBase = learningBases.get(learningBaseName, None)
if learningBase is None:
app.main_background()
BS.drawEndGameText(app.screen, None, f"Base '{learningBaseName}' not found")
BS.update()
app.delay(2)
return
n = learningBase.reviveLearned()
app.main_background()
BS.drawEndGameText(app.screen, None,
f"Revived {n} learned position(s) in '{learningBaseName}'")
BS.update()
app.delay(2)
return
#transforms a pgn file into a set of positions to use with Brainmaster
def unrollPgnAsLesson():
pgnFileName = positionParameters.get("filename", None)
if pgnFileName is None :
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
learningBaseName = positionParameters.get("base", None)
learningBase = learningBases.get(learningBaseName, None)
analyzer.unrollPgn_as_lesson(pgnFileName+".pgn", learningBase, positionParameters.get("color", "w")=="w")
app.main_background()
BS.drawEndGameText(app.screen, None, f"Unroll {pgnFileName} as a lesson done")
BS.update()
app.delay(2)
return
def unrollPGN():
pgnFileName = positionParameters.get("filename", None)
if pgnFileName is None :
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2 )
return
learningBaseName = positionParameters.get("base", None)
learningBase = learningBases.get(learningBaseName, None)
analyzer.unrollPgn(pgnFileName+".pgn", learningBase, positionParameters.get("color", "w")=="w")
app.main_background()
BS.drawEndGameText(app.screen, None, "Unroll done")
BS.update()
app.delay(2)
return
def readChessComGames():
'''
Reads a file with Chess.com games and creates a LearningBase from it.
The file must be in the format of a Chess.com export, with each game separated by a blank line.
'''
pgnFileName = positionParameters.get("filename", None)
if pgnFileName is None :
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2)
return
n = chess_com_download.load(positionParameters.get("player", None), pgnFileName, positionParameters.get("color",None))
app.main_background()
BS.drawEndGameText(app.screen, None, _download_result_text(n))
BS.update()
app.delay(2)
def _download_result_text(n):
"""Message for the end-of-download screen: real count of games added."""
if n is None:
return "Download failed (see console)"
if n == 0:
return "No new games: file already up to date"
return f"{n} new game{'s' if n != 1 else ''} downloaded"
def readLichessGames():
'''
Incrementally downloads the user's lichess games into the chosen PGN.
Same parameters as readChessComGames (filename, player, color) taken from
positionParameters; automatic dedup in the lichess_download module.
'''
pgnFileName = positionParameters.get("filename", None)
if pgnFileName is None:
text = "Please select a PGN file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2)
return
n = lichess_download.load(
positionParameters.get("lichess_player", None),
pgnFileName,
positionParameters.get("color", None),
)
app.main_background()
BS.drawEndGameText(app.screen, None, _download_result_text(n))
BS.update()
app.delay(2)
def createCourse():
'''
Registers a new BrainMaster base, which is a LearningBase with a specific name.
The name is taken from the positionParameters["base"] variable.
'''
learningBaseName = positionParameters.get("base", None)
if learningBaseName is None or learningBaseName == "":
text = "Please select a base file"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2)
return
if not learningBaseName in learningBases:
text = f"Base {learningBaseName} does not exist"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()
app.delay(2)
return
BrainMaster.add_to_BrainMaster(learningBaseName)
text = f"Base {learningBaseName} added to Brainmaster"
app.main_background()
BS.drawEndGameText(app.screen, None, text)
BS.update()