Repository navigation
Expand file tree
/
Copy pathBrainMaster.py
More file actions
439 lines (375 loc) · 14.7 KB
/
Copy pathBrainMaster.py
File metadata and controls
439 lines (375 loc) · 14.7 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
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
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import requests
import json_helper
import os
import LearningBase
from datetime import datetime
from dataclasses import dataclass,fields
from typing import Optional, Union,List,Dict, Tuple, Iterator, Any
import json
from config import config, save_config
import sys
def get_base_path():
"""Return the path of the folder where the executable or the script is located"""
if getattr(sys, 'frozen', False): # If it is a PyInstaller executable
return os.path.dirname(sys.executable)
else:
return os.path.dirname(os.path.abspath(__file__))
BASE_PATH = get_base_path()
DATA_FOLDER = os.path.join(BASE_PATH, "data")
# Name of the configuration file
# URL of your Flask service
#base_url = 'http://localhost:5000/api/'
#id_student = 'gaetano.lazzo'
# --- Authentication -------------------------------------------------------
# When the server runs with require_auth on, the student endpoints need the
# X-Student-Id / X-Api-Key headers (credentials obtained once from /register),
# and the authoring endpoints need X-Admin-Token (only the maintainer has it).
# When the server runs open (private/LAN) these headers are simply ignored.
def _student_headers() -> Dict[str, str]:
"""Auth headers for the student endpoints (empty until registered)."""
headers: Dict[str, str] = {}
sid = getattr(config, "id_student", "")
key = getattr(config, "api_key", "")
if sid:
headers["X-Student-Id"] = sid
if key:
headers["X-Api-Key"] = key
return headers
def _admin_headers() -> Dict[str, str]:
"""Auth header for the authoring endpoints. Only the maintainer has an
admin_token configured; ordinary users send nothing (and cannot author)."""
token = getattr(config, "admin_token", "")
return {"X-Admin-Token": token} if token else {}
def ensure_registered() -> bool:
"""Register this installation with the BrainMaster service the first time it
is actually needed.
LAZY: call it only when the user enters a BrainMaster feature -- never at
startup (most users never touch BrainMaster, and registering everyone would
flood the server). No-op when there is no `base_url` configured or when we
already hold credentials (id_student + api_key). On success it stores the
generated `id_student` + `api_key` in config.json. Returns True iff usable
credentials exist.
"""
base_url = getattr(config, "base_url", "")
if not base_url:
return False
if getattr(config, "id_student", "") and getattr(config, "api_key", ""):
return True
try:
response = requests.post(f"{base_url}register", json={}, timeout=10)
if response.status_code == 200:
data = response.json()
config.id_student = data["id_student"]
config.api_key = data["api_key"]
save_config()
print(f"Registered with BrainMaster as {config.id_student}")
return True
print('Registration error:', response.status_code, response.text)
except Exception as e:
print('Registration request failed:', str(e))
return False
def create_course(id_course:str):
'''
Create a course in the Brain Master service.
Args:
id_course(str): unique identifier for the course, e.g. 'openings', 'C42_white', etc.
'''
url = f"{config.base_url}create_course"
payload = {
'id_course': id_course,
'description': 'Chess course'
}
try:
response = requests.post(url, json=payload, headers=_admin_headers())
# Check the result
if response.status_code == 200:
print('Course created successfully!')
#print('Response:', response.json()) # If you return a JSON from the backend
else:
print('Error:', response.status_code, response.text)
except Exception as e:
print('Error in request:', str(e))
def create_lesson(id_lesson:str, id_course:str, title:str, description:str):
'''
Create a lesson in the Brain Master service.
Args:
id_lesson(str): unique identifier for the lesson, e.g. 'C44_black', 'C42_white', etc.
id_course(str): unique identifier for the course
title(str): title of the lesson
description(str): description of the lesson
'''
url = f'{config.base_url}create_lesson'
payload = {
'id_lesson': id_lesson,
'id_course': id_course,
'title': title,
'description': description
}
try:
response = requests.post(url, json=payload, headers=_admin_headers())
# Check the result
if response.status_code == 200:
print(f'Lesson {id_lesson} created successfully!')
#print('Response:', response.json()) # If you return a JSON from the backend
else:
print('Error:', response.status_code, response.text)
except Exception as e:
print('Error in request:', str(e))
def add_question(id_course:str, id_test:str, id_lesson:str, id_question:str,
lesson_name:str, lesson_descr:str,
question:str, explanation:str, rightAnswer:str):
url = f'{config.base_url}add_question_OpenAnswer'
payload = {
'id_course': id_course,
'id_test': id_test,
'id_lesson': id_lesson,
'id_question': id_question,
'lesson_name': lesson_name,
'lesson_description': lesson_descr,
'question': question,
'explanation': explanation,
'rightAnswer': rightAnswer
}
try:
response = requests.post(url, json=payload, headers=_admin_headers())
# Check the result
if response.status_code == 200:
print(f'Question {id_question} {id_lesson} created successfully!')
#print('Response:', response.json()) # If you return a JSON from the backend
else:
print('Error:', response.status_code, response.text)
except Exception as e:
print('Error in request:', str(e))
def unlock_lesson(id_course:str, id_student:str, id_lesson:str)->bool:
'''
Unlock a lesson for a student
Args:
id_course(str) key of the mdl_course table
id_student(str) key of the mdl_user table
id_lesson(str) key of the mdl_course_modules table
'''
url = f'{config.base_url}unlock_lesson'
payload = {
'id_lesson': id_lesson,
'id_student': id_student,
'id_course': id_course
}
try:
response = requests.post(url, json=payload, headers=_student_headers())
# Check the result
if response.status_code == 200:
result = response.json()
return result
else:
print('Error:', response.status_code, response.text)
return False
except Exception as e:
print('Error in request:', str(e))
return False
@dataclass
class AnswerData:
adate:datetime # when the question was asked
id_question:str
result:int
timeElapsed:int
notesTime:int
def to_dict(self):
return {
"adate": self.adate.isoformat() ,
"id_question": self.id_question ,
"result": self.result ,
"timeElapsed": self.timeElapsed ,
"notesTime": self.notesTime
}
@dataclass
class QuestionData:
id_question:str
id_test:str
id_type: int
explanation: str
question:str
rightAnswer:str
@classmethod
def from_dict(cls, data: dict[str,Any]) -> "QuestionData":
# Explicitly convert the data
return cls(
id_question=data['id_question'],
id_test=data['id_test'],
id_type=data['id_type'],
explanation=data['explanation'],
question=data['question'],
rightAnswer=data['rightAnswer'],
)
def ask_for_quiz(id_course:str, id_student:str):
'''
Ask the Brain Master to suggest a quiz for a student in a course.
Args:
id_course(str): unique identifier for the course, e.g. 'openings', 'C42_white', etc.
id_student(str): unique identifier for the student, e.g. 'gaetano.lazzo'
Returns:
A dictionary with the suggested quiz, containing:
{"action":action.value,
"description":Submitter.get_action_description(action),
"questions": Submitter.get_test(id_course, id_student, action)
}
'''
url = f'{config.base_url}suggest_action'
# The data you want to send to the service
payload = {
'id_course': id_course,
'id_student': id_student
}
try:
response = requests.post(url, json=payload, headers=_student_headers())
# Check the result
if response.status_code == 200:
res = response.json()
# The server replies 200 + {"error": ...} when there is no suggestion
# available (e.g. nothing left to review for this course). It's a valid
# outcome, not a failure: return it so the caller can tell it apart
# from a real service error (which yields None below).
if isinstance(res, dict) and "error" in res:
print('No suggestion available:', res["error"])
return res
print(f'Quiz received: {res["action"]} {res["description"]}')
return res
else:
print('Error:', response.status_code, response.text)
except Exception as e:
print('Error in request:', str(e))
def give_answers(id_course:str, action:int, answers:List[AnswerData]):
'''
Send answer to the Brain Master to train it
Args:
id_course(str): unique identifier for the course, e.g. 'openings', 'C42_white', etc.
id_student(str): unique identifier for the student, e.g. 'gaetano.lazzo'
action(int): action taken by the student
answers(List[AnswerData]): list of answers given by the student
'''
url = f'{config.base_url}give_answers'
# The data you want to send to the service
payload = {
'id_course': id_course,
'id_student': config.id_student,
'action': action,
'answers': [a.to_dict() for a in answers]
}
try:
response = requests.post(url, json=payload, headers=_student_headers())
# Check the result
if response.status_code == 200:
print('Data sent successfully.')
return response.json()
else:
print('Error:', response.status_code, response.text)
except Exception as e:
print('Error in request:', str(e))
def add_all_lessons(learnBase:str):
'''
Add all lessons for a given learning base to the Brain Master.
Args:
learnBase(str): unique identifier for the learning base, e.g. 'openings', 'C42_white', etc.
'''
quizNames = json_helper.read_struct(os.path.join(DATA_FOLDER,f"lessons_{learnBase}.json"))
lessons = set()
for idtest, idlesson in quizNames.items():
if idlesson in lessons:
continue
lessons.add(idlesson)
id_brainMasterLesson = f'{learnBase}{idlesson}'
create_lesson(id_brainMasterLesson, learnBase, idlesson, idlesson)
def add_all_questions(learnBase:str):
'''
Add all questions for a given learning base to the Brain Master.
Args:
learnBase(str): unique identifier for the learning base, e.g. 'openings', 'C42_white', etc.
'''
quizNames = json_helper.read_struct(os.path.join(DATA_FOLDER,f"lessons_{learnBase}.json"))
base = LearningBase.learningBases[learnBase]
for pos in base.positions:
position = base.positions[pos]
id_test = f'{learnBase}-{position.idquiz}'
idlesson = quizNames[str(position.idquiz)]
id_brainMasterLesson = f'{learnBase}{idlesson}'
add_question(learnBase, id_test, id_brainMasterLesson, str(position.zobrist),
idlesson, idlesson,
position.moves, 'no', position.ok)
def list_courses() -> List[str]:
'''
List all courses in the Brain Master service.
Returns:
A list of course identifiers.
'''
url = f'{config.base_url}list_courses'
try:
response = requests.get(url)
# Check the result
if response.status_code == 200:
res = response.json()
return res
else:
print('Error:', response.status_code, response.text)
return []
except Exception as e:
print('Error in request:', str(e))
return []
def unlock_new_lesson(id_course:str)->str:
'''
Unlock a new lesson for a student in a course.
Args:
id_course(str): unique identifier for the course, e.g. 'openings', 'C42_white', etc.
'''
url = f'{config.base_url}suggest_new_lesson'
payload = {
'id_course': id_course,
'id_student': config.id_student
}
try:
response = requests.post(url, json=payload, headers=_student_headers())
# Check the result
if response.status_code == 200:
res = response.json()["result"]
if not res: return False
print('New lesson to unlock')
else:
print('Error:', response.status_code, response.text)
return None
except Exception as e:
print('Error in request:', str(e))
return None
lesson_unlocks:Dict[str,datetime] = {}
fname =os.path.join(DATA_FOLDER,f'unlock_{id_course}.json')
if os.path.exists(fname):
lesson_unlocks = json_helper.read_struct(fname)
quizNames = json_helper.read_struct(os.path.join(DATA_FOLDER,f"lessons_{id_course}.json"))
for idtest, idlesson in quizNames.items():
if idlesson in lesson_unlocks:
continue
id_brainMasterLesson:str = f'{id_course}{idlesson}'
print(f"Course: {id_course} Unlocking lesson {id_brainMasterLesson}")
if unlock_lesson(id_course, config.id_student, id_brainMasterLesson):
print(f"Course: {id_course} lesson {id_brainMasterLesson} unlocked")
lesson_unlocks[idlesson]= datetime.now()
json_helper.write_struct(fname, lesson_unlocks)
return idlesson
else:
print(f"Course: {id_course} lesson {idlesson} was not unlocked")
return None
print(f"No lesson to unlock in course {id_course}")
return None
def add_to_BrainMaster(id_course:str):
'''
Add a course to the Brain Master
'''
create_course(id_course)
add_all_lessons(id_course)
add_all_questions(id_course)
print(f"Course: {id_course} registered")
if __name__ == "__main__":
'''
Main function to add all courses, lessons, and questions to the Brain Master.
'''
for id_course in LearningBase.learningBases:
create_course(id_course)
add_all_lessons(id_course)
add_all_questions(id_course)