forked from hedyorg/hedy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hedy_content.py
428 lines (369 loc) · 11.5 KB
/
hedy_content.py
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
import logging
import os
import static_babel_content
from utils import customize_babel_locale
from website.yaml_file import YamlFile
from safe_format import safe_format
logger = logging.getLogger(__name__)
COUNTRIES = static_babel_content.COUNTRIES
# Define dictionary for available languages. Fill dynamically later.
ALL_LANGUAGES = {}
ALL_KEYWORD_LANGUAGES = {}
# Todo TB -> We create this list manually, but it would be nice if we find
# a way to automate this as well
NON_LATIN_LANGUAGES = ['ar', 'bg', 'bn', 'el', 'fa', 'hi', 'he', 'pa_PK', 'ru', 'zh_Hans']
# Babel has a different naming convention than Weblate and doesn't support some languages -> fix this manually
CUSTOM_BABEL_LANGUAGES = {'pa_PK': 'pa_Arab_PK', 'kmr': 'ku_TR', 'tn': 'en', 'tl': 'en'}
# For the non-existing language manually overwrite the display language to make sure it is displayed correctly
CUSTOM_LANGUAGE_TRANSLATIONS = {'kmr': 'Kurdî (Tirkiye)', 'tn': 'Setswana', 'tl': 'ᜆᜄᜎᜓᜄ᜔'}
customize_babel_locale(CUSTOM_BABEL_LANGUAGES)
KEYWORDS_ADVENTURES = set([
'print_command',
'ask_command',
'is_command',
'sleep_command',
'random_command',
'add_remove_command',
'quotation_marks',
'if_command',
'in_command',
'maths',
'repeat_command',
'repeat_command_2',
'for_command',
'and_or_command',
'while_command',
'elif_command'
])
ADVENTURE_ORDER_PER_LEVEL = {
1: [
'default',
'print_command',
'ask_command',
'parrot',
'rock',
'haunted',
'story',
'turtle',
'restaurant',
'fortune',
],
2: [
'default',
'is_command',
'rock',
'ask_command',
'rock_2',
'haunted',
'sleep_command',
'parrot',
'story',
'restaurant',
'turtle'
],
3: [
'default',
'random_command',
'dice',
'rock',
'fortune',
'restaurant',
'add_remove_command',
'parrot',
'dishes',
'story',
'haunted',
'turtle'
],
4: [
'default',
'quotation_marks',
'rock',
'dice',
'dishes',
'parrot',
'turtle',
'story',
'haunted',
'fortune',
'restaurant'
],
5: [
'default',
'if_command',
'language',
'dice',
'dishes',
'story',
'rock',
'parrot',
'haunted',
'in_command',
'restaurant',
'fortune',
'pressit',
'turtle'
],
6: [
'default',
'maths',
'songs',
'dice',
'dishes',
'turtle',
'calculator',
'fortune',
'restaurant'
],
7: [
'default',
'repeat_command',
'story',
'songs',
'dishes',
'dice',
'repeat_command_2',
'fortune',
'restaurant',
'pressit'
],
8: [
'default',
'repeat_command',
'fortune',
'repeat_command_2',
'songs',
'if_command',
'story',
'haunted',
'restaurant',
'turtle'
],
9: [
'default',
'repeat_command',
'rock',
'story',
'calculator',
'restaurant',
'haunted',
'pressit',
'turtle'
],
10: [
'default',
'for_command',
'dishes',
'dice',
'fortune',
'harry_potter',
'songs',
'story',
'rock',
'calculator',
'restaurant',
],
11: [
'default',
'for_command',
'years',
'calculator',
'songs',
'restaurant',
'haunted'
],
12: [
'default',
'maths',
'quotation_marks',
'story',
'fortune',
'songs',
'restaurant',
'calculator',
'piggybank',
'secret'
],
13: [
'default',
'and_or_command',
'secret',
'story',
'rock',
'restaurant',
'calculator',
'tic'
],
14: [
'default',
'is_command',
'haunted',
'calculator',
'piggybank',
'quizmaster',
'tic'
],
15: [
'default',
'while_command',
'restaurant',
'story',
'dice',
'rock',
'calculator',
'tic'
],
16: [
'default',
'random_command',
'haunted',
'songs',
'language'
],
17: [
'default',
'print_command',
'elif_command',
'tic',
'blackjack'
],
18: [
'default',
'print_command',
'story',
'songs'
]
}
RESEARCH = {}
for paper in sorted(os.listdir('content/research'),
key=lambda x: int(x.split("_")[-1][:-4]),
reverse=True):
# An_approach_to_describing_the_semantics_of_Hedy_2022.pdf -> 2022, An
# approach to describing the semantics of Hedy
name = paper.replace("_", " ").split(".")[0]
name = name[-4:] + ". " + name[:-5]
RESEARCH[name] = paper
# load all available languages in dict
# list_translations of babel does about the same, but without territories.
languages = {}
if not os.path.isdir('translations'):
# should not be possible, but if it's moved someday, EN would still be working.
ALL_LANGUAGES['en'] = 'English'
ALL_KEYWORD_LANGUAGES['en'] = 'EN'
for folder in os.listdir('translations'):
locale_dir = os.path.join('translations', folder, 'LC_MESSAGES')
if not os.path.isdir(locale_dir):
continue
if filter(lambda x: x.endswith('.mo'), os.listdir(locale_dir)):
languages[folder] = CUSTOM_LANGUAGE_TRANSLATIONS.get(folder,
static_babel_content.LANGUAGE_NAMES.get(folder, folder))
for lang in sorted(languages):
ALL_LANGUAGES[lang] = languages[lang]
if os.path.exists('./grammars/keywords-' + lang + '.lark'):
ALL_KEYWORD_LANGUAGES[lang] = lang[0:2].upper() # first two characters
# Load and cache all keyword yamls
KEYWORDS = {}
for lang in ALL_KEYWORD_LANGUAGES.keys():
KEYWORDS[lang] = YamlFile.for_file(f'content/keywords/{lang}.yaml').to_dict()
for k, v in KEYWORDS[lang].items():
if isinstance(v, str) and "|" in v:
# when we have several options, pick the first one as default
# Some keys are ints, turn them into strings
KEYWORDS[lang][k] = v.split('|')[0]
class StructuredDataFile:
"""Base class for all data files in the content directory."""
def __init__(self, filename):
self.filename = filename
self._file = None
@property
def file(self):
"""Lazily load the requested file."""
if not self._file:
self._file = YamlFile.for_file(self.filename)
return self._file
class Commands(StructuredDataFile):
def __init__(self, language):
self.language = language
super().__init__(f'content/cheatsheets/{self.language}.yaml')
def get_commands_for_level(self, level, keyword_lang):
return deep_translate_keywords(self.file.get(int(level), {}), keyword_lang)
def deep_translate_keywords(yaml, keyword_language):
"""Recurse through a data structure and replace keyword placeholders in any strings we encounter."""
if isinstance(yaml, str):
# this is used to localize adventures linked in slides (PR 3860)
yaml = yaml.replace('/raw', f'/raw?keyword_language={keyword_language}')
return safe_format(yaml, **KEYWORDS.get(keyword_language))
if isinstance(yaml, list):
return [deep_translate_keywords(e, keyword_language) for e in yaml]
if isinstance(yaml, dict):
return {k: deep_translate_keywords(v, keyword_language) for k, v in yaml.items()}
return yaml
# Todo TB -> We don't need these anymore as we guarantee with Weblate that
# each language file is there
class NoSuchCommand:
def get_commands_for_level(self, level, keyword_lang):
return {}
class Adventures(StructuredDataFile):
def __init__(self, language):
self.language = language
super().__init__(f'content/adventures/{self.language}.yaml')
def get_adventure_keyname_name_levels(self):
return {aid: {adv['name']: list(adv['levels'].keys())} for aid, adv in self.file.get('adventures', {}).items()}
def get_adventure_names(self):
return {aid: adv['name'] for aid, adv in self.file.get('adventures', {}).items()}
def get_adventures(self, keyword_lang="en"):
return deep_translate_keywords(self.file.get('adventures'), keyword_lang)
def has_adventures(self):
return True if self.file.get('adventures') else False
class NoSuchAdventure:
def get_adventure(self):
return {}
class ParsonsProblem(StructuredDataFile):
def __init__(self, language):
self.language = language
super().__init__(f'content/parsons/{self.language}.yaml')
def get_highest_exercise_level(self, level):
return max(int(lnum) for lnum in self.file.get('levels', {}).get(level, {}).keys())
def get_parsons_data_for_level(self, level, keyword_lang="en"):
return deep_translate_keywords(self.file.get('levels', {}).get(level, None), keyword_lang)
def get_parsons_data_for_level_exercise(self, level, excercise, keyword_lang="en"):
return deep_translate_keywords(self.file.get('levels', {}).get(level, {}).get(excercise), keyword_lang)
class Quizzes(StructuredDataFile):
def __init__(self, language):
self.language = language
super().__init__(f'content/quizzes/{self.language}.yaml')
def get_highest_question_level(self, level):
return max(int(k) for k in self.file.get('levels', {}).get(level, {}))
def get_quiz_data_for_level(self, level, keyword_lang="en"):
return deep_translate_keywords(self.file.get('levels', {}).get(level), keyword_lang)
def get_quiz_data_for_level_question(self, level, question, keyword_lang="en"):
return deep_translate_keywords(self.file.get('levels', {}).get(level, {}).get(question), keyword_lang)
class NoSuchQuiz:
def get_quiz_data_for_level(self, level, keyword_lang):
return {}
class Tutorials(StructuredDataFile):
# Want to parse the keywords only once, they can be cached -> perform this
# action on server start
def __init__(self, language):
self.language = language
super().__init__(f'content/tutorials/{self.language}.yaml')
def get_tutorial_for_level(self, level, keyword_lang="en"):
if level not in ["intro", "teacher"]:
level = int(level)
return deep_translate_keywords(self.file.get(level, None), keyword_lang)
def get_tutorial_for_level_step(self, level, step, keyword_lang="en"):
if level not in ["intro", "teacher"]:
level = int(level)
return deep_translate_keywords(self.file.get(level, {}).get('steps', {}).get(step), keyword_lang)
class NoSuchTutorial:
def get_tutorial_for_level(self, level, keyword_lang):
return {}
class Slides(StructuredDataFile):
def __init__(self, language):
self.language = language
super().__init__(f'content/slides/{self.language}.yaml')
def get_slides_for_level(self, level, keyword_lang="en"):
return deep_translate_keywords(self.file.get('levels', {}).get(level), keyword_lang)
class NoSuchSlides:
def get_slides_for_level(self, level, keyword_lang):
return {}