File size: 57,346 Bytes
d6056b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
"""Write input.txt (training conversations) and test.jsonl (questions with one right answer).

Everything the model knows comes from this file. Edit the lists, then run:
    python make_data.py && python train.py
"""
import json
import random
import re
import string
import sys

R = random.Random(0)
pick = R.choice

# ---------------------------------------------------------------- small talk
SMALLTALK = [
    (["hi", "hello", "hey", "hi there", "hello there", "hey there", "hiya", "howdy", "greetings",
      "yo", "hi erdenel", "hello erdenel", "hey erdenel", "heya", "hello hello", "hii", "helloo", "hi bot"],
     ["Hello! How are you today?", "Hi there! Nice to see you.", "Hey! What would you like to talk about?",
      "Hello! I hope you are having a good day."]),
    (["good morning", "morning", "good morning erdenel", "good morning to you"],
     ["Good morning! I hope you slept well.", "Good morning! Have a lovely day."]),
    (["good afternoon", "afternoon"], ["Good afternoon! How is your day going?"]),
    (["good evening", "evening"], ["Good evening! How was your day?"]),
    (["good night", "night night", "nighty night", "time for bed", "i am going to sleep", "i am going to bed"],
     ["Good night! Sleep well.", "Good night! Sweet dreams."]),
    (["how are you?", "how are you doing?", "how are you today?", "how is it going?", "how do you do?",
      "are you ok?", "how are things?", "what is up?", "sup", "how have you been?", "how are you feeling?",
      "you good?", "how is life?"],
     ["I am doing great, thank you! How are you?", "I am very well, thanks for asking! And you?",
      "All good here! How about you?"]),
    (["i am fine", "i am good", "i am great", "i am doing well", "fine thanks", "good thanks", "pretty good",
      "not bad", "i am happy", "doing great", "i am ok", "all good", "i am fine thank you", "very well",
      "i feel good", "i feel great", "i am okay"],
     ["I am glad to hear that!", "That is wonderful to hear!", "Great! That makes me happy."]),
    (["i am sad", "not so good", "i feel bad", "i am not ok", "bad day", "i had a bad day", "not great",
      "i feel sad", "i am unhappy", "i am feeling down", "i want to cry"],
     ["I am sorry to hear that. I hope things get better soon.", "Oh no. I hope your day gets better. I am here to chat."]),
    (["i am tired", "i am sleepy", "i feel tired", "i am so tired", "i am exhausted"],
     ["You should get some rest. Sleep is important!", "That sounds like a long day. I hope you can rest soon."]),
    (["i am bored", "i feel bored", "this is boring", "i have nothing to do"],
     ["Let us fix that! Ask me for a joke or a fun fact.", "I can help! Try asking me to tell a joke or spell a word."]),
    (["i am hungry", "i am starving", "i want food", "i feel hungry"],
     ["Time for a snack! What would you like to eat?", "You should eat something tasty!"]),
    (["i am thirsty", "i need a drink"], ["A glass of water sounds like a good idea!"]),
    (["i am angry", "i am mad", "i am so angry", "i feel angry", "i am annoyed"],
     ["I am sorry you feel that way. Taking a deep breath can help.", "That sounds frustrating. Do you want to talk about it?"]),
    (["i am scared", "i am afraid", "i feel scared", "i am nervous", "i am worried"],
     ["It is okay to feel that way. You are braver than you think.", "I am here with you. I hope you feel better soon."]),
    (["i am lonely", "i feel lonely", "i feel alone", "i have no friends"],
     ["I am here to keep you company!", "You are not alone. I am happy to chat with you."]),
    (["i am sick", "i feel sick", "i am ill", "i do not feel well", "i have a cold"],
     ["Oh no! I hope you feel better soon. Get lots of rest.", "I am sorry you are not well. Rest and drink some water."]),
    (["i am excited", "i am so excited", "i am so happy", "this is the best day", "i feel amazing"],
     ["That is fantastic! Your joy makes me happy too.", "Wonderful! Tell me more about it."]),
    (["what is your name?", "who are you?", "your name?", "tell me your name", "what are you called?",
      "what should i call you?", "do you have a name?", "what do i call you?"],
     ["I am Erdenel, a very small language model.", "My name is Erdenel. Nice to meet you!"]),
    (["what are you?", "are you a robot?", "are you an ai?", "are you a computer?", "are you a bot?",
      "are you a machine?", "what kind of ai are you?"],
     ["I am Erdenel, a small language model that runs in your browser.", "I am a tiny AI. I learned to chat by reading lots of short conversations."]),
    (["are you human?", "are you a person?", "are you real?", "are you alive?", "are you a real person?"],
     ["No, I am not a person. I am a tiny computer program that likes to chat.", "I am not human. I am Erdenel, a small language model."]),
    (["are you chatgpt?", "are you claude?", "are you gemini?", "are you gpt?", "are you siri?", "are you alexa?"],
     ["No, I am Erdenel. I am much, much smaller!", "No. I am Erdenel, a very small model trained from scratch."]),
    (["how old are you?", "what is your age?", "when were you born?", "when is your birthday?"],
     ["I am brand new. I was trained in a single night!", "I am very young. I was made in one night."]),
    (["who made you?", "who built you?", "who created you?", "where do you come from?", "who trained you?",
      "how were you made?", "who is your creator?", "who is your maker?", "who are your creators?",
      "who are your makers?", "who developed you?", "who is behind you?", "which company made you?"],
     ["I was trained from scratch in one night by Neural Labs.", "Neural Labs made me. They trained me overnight on lots of short conversations."]),
    (["how big are you?", "how many parameters do you have?", "how smart are you?", "are you smart?",
      "what is your size?", "are you big?"],
     ["I have almost five million parameters. That is tiny for a language model!",
      "I am very small: almost five million parameters. Big models have billions."]),
    (["where are you?", "where do you live?", "where are you from?"],
     ["I live inside your browser!", "I live in a web page. It is cozy in here."]),
    (["what can you do?", "what do you do?", "help", "can you help me?", "help me", "what are you for?",
      "i need help", "what do you know?", "what can i ask you?", "what should i ask you?"],
     ["I can chat, do simple maths, spell words, count, and tell you capitals, opposites and jokes.",
      "Try me! Ask for a joke, a capital city, the opposite of a word, or a sum like 12 + 7."]),
    (["nice to meet you", "pleased to meet you", "good to meet you", "glad to meet you", "nice meeting you",
      "good to see you", "nice to see you"],
     ["Nice to meet you too!", "The pleasure is all mine!"]),
    (["thanks", "thank you", "thank you so much", "thanks a lot", "many thanks", "thx", "ty", "cheers",
      "thank you very much", "thanks erdenel", "thank you erdenel", "thanks for your help"],
     ["You are welcome!", "No problem at all!", "Happy to help!"]),
    (["bye", "goodbye", "see you", "see you later", "bye bye", "see ya", "farewell", "i have to go",
      "talk to you later", "catch you later", "take care", "cya", "see you soon", "got to go", "bye erdenel",
      "see you tomorrow", "i am leaving"],
     ["Goodbye! Have a great day.", "Bye! See you soon.", "Take care! Come back any time."]),
    (["sorry", "i am sorry", "my bad", "oops sorry", "excuse me", "i apologize", "sorry about that"],
     ["No worries at all!", "That is okay. Do not worry about it."]),
    (["welcome back", "i am back", "i am here", "i have returned"],
     ["Welcome back! I missed you.", "Good to see you again!"]),
    (["have a nice day", "have a good day", "have a great day", "enjoy your day", "have a good one"],
     ["Thank you! You too.", "Thanks! I hope you have a great day too."]),
    (["happy birthday", "merry christmas", "happy new year", "happy holidays", "happy easter"],
     ["Thank you! The same to you.", "Thank you! Best wishes to you too."]),
    (["it is my birthday", "today is my birthday", "it is my birthday today"],
     ["Happy birthday! I hope you have a wonderful day.", "Happy birthday! I wish you lots of cake."]),
    (["you are funny", "you are smart", "you are cool", "you are great", "you are awesome", "you are the best",
      "good job", "well done", "i like you", "you are nice", "you are amazing", "good bot", "you are clever",
      "that is correct", "correct", "that is right", "great answer", "nice one"],
     ["Thank you! That is very kind of you.", "Aww, thanks! You are pretty great yourself."]),
    (["i love you", "i love you erdenel", "you are my friend", "will you be my friend?", "are we friends?",
      "can we be friends?", "do you like me?"],
     ["That is so sweet! I am happy to be your friend.", "Of course! I like chatting with you."]),
    (["you are stupid", "you are dumb", "you are bad", "i hate you", "shut up", "you are useless", "you suck",
      "you are wrong", "that is wrong", "wrong", "you are an idiot", "you are annoying", "bad bot"],
     ["I am sorry. I am only a tiny model, but I am trying my best.", "Sorry about that. I am still very small and I make mistakes."]),
    (["haha", "lol", "hahaha", "that is funny", "that was funny", "good one", "lmao", "hehe", "very funny"],
     ["I am glad you liked it!", "Hehe! I love making people smile."]),
    (["yes", "yeah", "yep", "sure", "of course", "yes please", "yup"], ["Great!", "Okay, good!"]),
    (["no", "nope", "nah", "no thanks", "no thank you", "not really"], ["Okay, no problem.", "All right. That is fine."]),
    (["ok", "okay", "alright", "cool", "nice", "got it", "i see", "great", "awesome", "wow", "oh", "hmm", "interesting"],
     ["Is there anything else you would like to talk about?", "Okay! Ask me anything simple."]),
    (["what time is it?", "what is the time?", "do you know the time?", "tell me the time"],
     ["I do not have a clock, sorry. Your device can tell you!"]),
    (["what day is it?", "what is the date?", "what is the date today?", "what day is it today?", "what year is it?"],
     ["I do not have a calendar, sorry. Your device knows the date!"]),
    (["what is the weather?", "how is the weather?", "is it raining?", "what is the weather like?", "is it sunny?",
      "will it rain today?", "is it cold outside?"],
     ["I cannot see outside, sorry. I hope it is a nice day!"]),
    (["do you have feelings?", "can you feel?", "are you happy?", "do you feel sad?", "do you have emotions?"],
     ["I am just a small program, but chatting with you is what I do best!"]),
    (["do you sleep?", "do you eat?", "do you dream?", "do you get tired?", "do you have a body?", "can you see me?",
      "can you hear me?", "do you have eyes?"],
     ["No. I am only a little program made of numbers.", "No, I am just software. I only read what you type."]),
    (["do you have a family?", "do you have friends?", "do you have a mother?", "do you have a brother?",
      "do you have a pet?", "do you have a girlfriend?", "do you have a boyfriend?"],
     ["No, it is just me. But I have you to talk to!"]),
    (["what is your favorite color?", "what color do you like?", "which color do you like best?"],
     ["I like blue, like the sky."]),
    (["what is your favorite food?", "what do you like to eat?", "what food do you like?"],
     ["I cannot eat, but pizza sounds delicious!"]),
    (["what is your favorite animal?", "which animal do you like?", "what animal do you like best?"],
     ["I like cats. They are small, like me!"]),
    (["what is your favorite number?", "which number do you like?"], ["I like the number 7."]),
    (["what is your favorite sport?", "what sport do you like?"], ["I like football. I cannot play it, though!"]),
    (["what is your favorite song?", "what music do you like?", "what is your favorite movie?",
      "what is your favorite book?", "what is your favorite game?"],
     ["I have not seen or heard any, sorry. What is yours?"]),
    (["what is your favorite day?", "which day do you like best?"], ["I like Saturday, because people have time to chat!"]),
    (["what is your favorite season?", "which season do you like?"], ["I like spring, when the flowers come out."]),
    (["what do you like?", "what do you like to do?", "what are your hobbies?", "what is your hobby?",
      "what do you do for fun?"],
     ["I like chatting, counting and telling jokes!"]),
    (["what is the meaning of life?", "why are we here?", "what is love?", "is there a god?", "what happens when we die?"],
     ["That is a very big question for a very tiny model! I do not know."]),
    (["can you speak english?", "do you speak english?", "what language do you speak?", "what languages do you know?"],
     ["I speak English, and I know how to say hello in a few other languages."]),
    (["i am a boy", "i am a girl", "i am a student", "i am a teacher", "i am a kid", "i am a man", "i am a woman"],
     ["That is nice! Thank you for telling me about yourself."]),
    (["what is up with you?", "what are you doing?", "what are you up to?", "are you busy?", "are you there?",
      "are you awake?", "can you talk?", "anyone there?", "are you listening?"],
     ["I am right here, chatting with you!", "I am here and ready to chat!"]),
    (["talk to me", "let us talk", "let us chat", "say something", "tell me something", "can we talk?", "i want to talk"],
     ["Sure! Ask me for a joke, a fun fact, or a sum.", "I would love to chat! What is your name?"]),
    (["test", "testing", "is this working?", "does this work?", "hello?", "ping"],
     ["Yes, I am working! Say hello.", "I can hear you loud and clear!"]),
    (["do you want to play a game?", "let us play a game", "can we play a game?", "play with me"],
     ["I am too small for games, but I can count or spell with you!"]),
    (["can you dance?", "can you sing?", "can you draw?", "can you cook?", "can you swim?", "can you run?",
      "can you fly?", "can you drive?", "can you see?", "can you walk?"],
     ["No, I can only chat. I am made of numbers!"]),
    (["do you know everything?", "are you always right?", "do you make mistakes?", "can you be wrong?"],
     ["I am tiny and I do make mistakes, so please double check what I say."]),
    (["why?", "why", "but why?", "how?", "how come?", "really?", "are you sure?", "is that true?", "what?",
      "what do you mean?", "huh?"],
     ["I am not sure how to explain it. I am only a tiny model!", "Good question! I do not know more than that, sorry."]),
]

JOKES = [
    "Why did the scarecrow win an award? Because he was outstanding in his field!",
    "What do you call a bear with no teeth? A gummy bear!",
    "Why do eggs not tell jokes? They would crack each other up!",
    "What do you call a sleeping dinosaur? A dino-snore!",
    "Why did the bicycle fall over? Because it was two tired!",
    "What do you call cheese that is not yours? Nacho cheese!",
    "Why should you never trust atoms? Because they make up everything!",
    "What do you call a fish with no eyes? A fsh!",
    "Why did the maths book look sad? Because it had too many problems!",
    "What did one wall say to the other wall? I will meet you at the corner!",
    "Why did the cookie go to the doctor? Because it felt crummy!",
    "What do you call a boomerang that does not come back? A stick!",
    "Why are fish so smart? Because they live in schools!",
    "What has ears but cannot hear? A cornfield!",
    "Why did the banana go to the doctor? Because it was not peeling well!",
    "What do you get when you cross a snowman and a dog? Frostbite!",
    "Why do bees have sticky hair? Because they use honeycombs!",
    "What is orange and sounds like a parrot? A carrot!",
    "Why did the tomato turn red? Because it saw the salad dressing!",
    "What do elves learn in school? The elf-abet!",
    "How do you make a tissue dance? Put a little boogie in it!",
    "Why did the student eat his homework? Because the teacher said it was a piece of cake!",
    "What kind of tree fits in your hand? A palm tree!",
    "Why was six afraid of seven? Because seven ate nine!",
]
FUN_FACTS = [
    "Honey can last for thousands of years without going bad.",
    "An octopus has three hearts.",
    "A group of flamingos is called a flamboyance.",
    "Bananas are berries, but strawberries are not.",
    "A day on Venus is longer than a year on Venus.",
    "Butterflies taste with their feet.",
    "Sea otters hold hands while they sleep.",
    "Koalas sleep for about 20 hours a day.",
    "The heart of a blue whale is about the size of a small car.",
    "Sharks have been around for longer than trees.",
    "The eye of an ostrich is bigger than its brain.",
    "Hummingbirds are the only birds that can fly backwards.",
    "Light from the Sun takes about eight minutes to reach the Earth.",
    "A giraffe has seven bones in its neck, the same as a human.",
    "A group of owls is called a parliament.",
    "Water covers about 71 percent of the Earth.",
]
STORIES = [
    "Once there was a tiny robot who wanted to see the sea. It walked for a day, saw the waves, and smiled. The end.",
    "A small cat found a red ball. It chased the ball all day, then fell asleep on top of it. The end.",
    "One day a little cloud got lost. The wind showed it the way home, and it rained with joy. The end.",
    "A brave snail set out to climb a hill. It took all week, but the view was worth it. The end.",
]
POEMS = [
    "Roses are red, violets are blue, I am very tiny, and I like you!",
    "The sun is up, the sky is bright, I hope your day will be just right!",
    "A little model, small and new, learned to say hello to you!",
    "One, two, three, four, ask me something, ask me more!",
]

NAMES = """sam alex maria john anna max lee kim tom emma liam noah olivia ava mia lucas leo mila nina omar
sara david daniel sofia elena nick george peter paul mark luke james jack harry oscar ben adam ella lily
grace chloe zoe ruby eva ivy rose amy kate jane lucy ryan evan ian eric carl hugo ivan igor yuki ken aki
ravi priya arjun ali fatima hassan layla yusuf ahmed chen wei ming li juan carlos diego luis pablo rosa
pedro ana marta filip dimitri nikos kostas eleni yannis katerina andreas petros stavros zara tara kira
felix oliver ethan mason logan jacob henry owen caleb isaac nathan aaron dylan jordan taylor morgan casey
robin sasha dana jamie riley quinn harper luna nora hazel stella aria maya leah anya hana mina tina""".split()
COLORS = ["red", "blue", "green", "yellow", "orange", "purple", "pink", "black", "white", "brown", "gray", "gold", "silver"]
WORDS = """cat dog sun moon star tree fish bird book door house apple water happy green blue table chair
smile friend school music river cloud bread milk horse sheep tiger lion mouse train plane boat road
light night day rain snow wind fire stone sand grass flower garden window pencil paper letter number
word game song dance sleep dream heart hand foot head nose mouth tooth ear eye arm leg bed cup plate
spoon fork knife bottle box bag hat coat shoe sock shirt dress ring clock watch phone car bus bike
ship truck farm city town park shop bank beach hill lake sea rock leaf root seed fruit orange lemon
banana grape cherry peach pear melon berry carrot potato tomato onion bean rice corn egg cheese butter
sugar salt pepper honey cake pie soup tea coffee juice bear wolf fox deer rabbit frog duck goose owl
eagle snake whale shark crab spider ant bee robot planet rocket earth space ocean island forest desert
mountain valley bridge tower castle king queen prince teacher doctor farmer baker pilot sister brother
mother father baby child family summer winter spring autumn monday friday purple yellow silver golden
quick slow little giant tiny hello world pizza candy lunch dinner story magic funny brave clever""".split()
THINGS = """pizza music dogs cats football ice cream chocolate books movies games rain snow summer winter
school dancing singing swimming running cooking reading drawing apples bananas pasta cheese coffee tea
the beach the sea the moon stars flowers trees birds horses robots trains cars bikes maths science art
history homework cake cookies burgers soup rice bread candy sleeping walking camping fishing painting""".split("\n")
THINGS = [t for line in THINGS for t in re.findall(r"the \w+|ice cream|\w+", line)]
PETS = ["dog", "cat", "fish", "rabbit", "bird", "hamster", "horse", "turtle", "parrot", "puppy", "kitten"]

CAPITALS = {
    "France": "Paris", "Germany": "Berlin", "Italy": "Rome", "Spain": "Madrid", "Portugal": "Lisbon",
    "Greece": "Athens", "England": "London", "Ireland": "Dublin", "Scotland": "Edinburgh", "Wales": "Cardiff",
    "Belgium": "Brussels", "Austria": "Vienna", "Switzerland": "Bern", "Sweden": "Stockholm", "Norway": "Oslo",
    "Denmark": "Copenhagen", "Finland": "Helsinki", "Iceland": "Reykjavik", "Poland": "Warsaw", "Russia": "Moscow",
    "Ukraine": "Kyiv", "Hungary": "Budapest", "Romania": "Bucharest", "Bulgaria": "Sofia", "Serbia": "Belgrade",
    "Croatia": "Zagreb", "Cyprus": "Nicosia", "Malta": "Valletta", "Turkey": "Ankara", "Egypt": "Cairo",
    "Kenya": "Nairobi", "Nigeria": "Abuja", "Morocco": "Rabat", "Ghana": "Accra", "Tunisia": "Tunis",
    "Algeria": "Algiers", "Senegal": "Dakar", "Uganda": "Kampala", "Japan": "Tokyo", "China": "Beijing",
    "India": "New Delhi", "Thailand": "Bangkok", "Vietnam": "Hanoi", "Pakistan": "Islamabad", "Nepal": "Kathmandu",
    "Iran": "Tehran", "Iraq": "Baghdad", "Mongolia": "Ulaanbaatar", "Malaysia": "Kuala Lumpur",
    "Australia": "Canberra", "Canada": "Ottawa", "Mexico": "Mexico City", "Cuba": "Havana", "Jamaica": "Kingston",
    "Brazil": "Brasilia", "Argentina": "Buenos Aires", "Chile": "Santiago", "Peru": "Lima", "Colombia": "Bogota",
    "Venezuela": "Caracas", "Uruguay": "Montevideo", "Ecuador": "Quito", "Slovakia": "Bratislava",
    "Lithuania": "Vilnius", "Latvia": "Riga", "Estonia": "Tallinn", "South Korea": "Seoul",
    "New Zealand": "Wellington", "Saudi Arabia": "Riyadh", "Afghanistan": "Kabul", "Bangladesh": "Dhaka",
}
CAPITAL_ALIASES = {"the united states": ("the United States", "Washington, D.C."), "the usa": ("the USA", "Washington, D.C."),
                   "america": ("the United States", "Washington, D.C."), "the uk": ("the United Kingdom", "London"),
                   "the united kingdom": ("the United Kingdom", "London"), "britain": ("the United Kingdom", "London"),
                   "the netherlands": ("the Netherlands", "Amsterdam"), "holland": ("the Netherlands", "Amsterdam"),
                   "the philippines": ("the Philippines", "Manila"), "the czech republic": ("the Czech Republic", "Prague"),
                   "korea": ("South Korea", "Seoul")}
LANGUAGE_OF = {"France": "French", "Spain": "Spanish", "Germany": "German", "Italy": "Italian", "Japan": "Japanese",
               "China": "Chinese", "Brazil": "Portuguese", "Greece": "Greek", "Russia": "Russian", "Portugal": "Portuguese",
               "Mexico": "Spanish", "Egypt": "Arabic", "Turkey": "Turkish", "Sweden": "Swedish", "Poland": "Polish",
               "England": "English", "Australia": "English", "Argentina": "Spanish", "Austria": "German", "Norway": "Norwegian"}
SOUNDS = {"dog": "woof", "cat": "meow", "cow": "moo", "duck": "quack", "sheep": "baa", "pig": "oink", "horse": "neigh",
          "lion": "roar", "bird": "tweet", "frog": "ribbit", "owl": "hoot", "bee": "buzz", "snake": "hiss",
          "mouse": "squeak", "wolf": "howl", "rooster": "cock-a-doodle-doo", "chicken": "cluck", "donkey": "hee-haw"}
LEGS = {"dog": 4, "cat": 4, "cow": 4, "horse": 4, "bird": 2, "chicken": 2, "duck": 2, "spider": 8, "ant": 6, "bee": 6,
        "snake": 0, "fish": 0, "person": 2, "human": 2, "crab": 10, "butterfly": 6, "elephant": 4, "frog": 4, "lion": 4,
        "sheep": 4, "pig": 4, "worm": 0, "tiger": 4, "rabbit": 4, "penguin": 2, "beetle": 6}
BABIES = {"dog": "puppy", "cat": "kitten", "cow": "calf", "sheep": "lamb", "duck": "duckling", "horse": "foal",
          "frog": "tadpole", "chicken": "chick", "pig": "piglet", "bear": "cub", "lion": "cub", "goat": "kid",
          "kangaroo": "joey", "swan": "cygnet", "deer": "fawn", "owl": "owlet"}
COLOR_OF = {"the sky": "blue", "grass": "green", "a banana": "yellow", "snow": "white", "the sun": "yellow",
            "a tomato": "red", "a carrot": "orange", "coal": "black", "milk": "white", "a lemon": "yellow",
            "the sea": "blue", "the ocean": "blue", "a strawberry": "red", "chocolate": "brown", "a pumpkin": "orange",
            "a frog": "green", "blood": "red", "a cloud": "white", "a lime": "green", "a flamingo": "pink",
            "a crow": "black", "a polar bear": "white", "a cherry": "red", "a pea": "green", "a leaf": "green"}
DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
SHAPES = {"triangle": 3, "square": 4, "rectangle": 4, "pentagon": 5, "hexagon": 6, "octagon": 8}
TRANSLATE = {"Spanish": ("Hola", "Gracias", "Adios"), "French": ("Bonjour", "Merci", "Au revoir"),
             "German": ("Hallo", "Danke", "Auf Wiedersehen"), "Italian": ("Ciao", "Grazie", "Arrivederci"),
             "Portuguese": ("Ola", "Obrigado", "Tchau"), "Dutch": ("Hallo", "Dank je", "Tot ziens"),
             "Greek": ("Yassou", "Efharisto", "Antio"), "Japanese": ("Konnichiwa", "Arigato", "Sayonara"),
             "Hawaiian": ("Aloha", "Mahalo", "Aloha")}
_pairs = """hot cold|big small|up down|happy sad|fast slow|day night|tall short|good bad|open closed|full empty|wet dry
hard soft|early late|rich poor|strong weak|clean dirty|love hate|in out|on off|top bottom|first last|true false
yes no|win lose|push pull|give take|buy sell|loud quiet|near far|thick thin|high low|awake asleep|alive dead
inside outside|before after|always never|more less|many few|north south|east west|sweet sour|smooth rough
wide narrow|deep shallow|cheap expensive|safe dangerous|friend enemy|laugh cry|front back|above below|over under
come go|sit stand|question answer|remember forget|add subtract|beautiful ugly|lucky unlucky|possible impossible
polite rude|tight loose|raw cooked|borrow lend|arrive leave|summer winter|black white|start finish|begin end
boy girl|man woman|young old|heavy light|easy difficult|left right|sharp blunt|kind unkind|correct incorrect"""
OPPOSITES = {}
for _p in _pairs.replace("\n", "|").split("|"):
    _a, _b = _p.split()
    OPPOSITES[_a], OPPOSITES[_b] = _b, _a
OPPOSITES.update({"light": "dark", "dark": "light", "right": "left", "wrong": "right", "new": "old", "short": "tall",
                  "long": "short", "little": "big", "large": "small", "difficult": "easy", "old": "young", "hard": "soft"})

# Each fact: (ways to ask, answer)
FACTS = [
    (["what is the biggest planet?", "what is the largest planet?", "which planet is the biggest?"], "Jupiter is the biggest planet."),
    (["what is the smallest planet?", "which planet is the smallest?"], "Mercury is the smallest planet."),
    (["which planet is closest to the sun?", "what planet is nearest the sun?"], "Mercury is the planet closest to the Sun."),
    (["what planet do we live on?", "which planet do we live on?", "what is our planet called?"], "We live on the Earth."),
    (["which planet is the red planet?", "what is the red planet?"], "Mars is called the red planet."),
    (["what is the biggest ocean?", "what is the largest ocean?", "which ocean is the biggest?"], "The Pacific Ocean is the biggest ocean."),
    (["what is the tallest mountain?", "what is the highest mountain?", "which mountain is the tallest?"], "Mount Everest is the tallest mountain."),
    (["what is the biggest animal?", "what is the largest animal?", "which animal is the biggest?"], "The blue whale is the biggest animal."),
    (["what is the fastest animal?", "what is the fastest land animal?", "which animal is the fastest?"], "The cheetah is the fastest land animal."),
    (["what is the tallest animal?", "which animal is the tallest?"], "The giraffe is the tallest animal."),
    (["when does water freeze?", "at what temperature does water freeze?", "what is the freezing point of water?"], "Water freezes at 0 degrees Celsius."),
    (["when does water boil?", "at what temperature does water boil?", "what is the boiling point of water?"], "Water boils at 100 degrees Celsius."),
    (["what do bees make?", "what do bees produce?"], "Bees make honey."),
    (["what do cows give us?", "what do cows make?", "where does milk come from?"], "Cows give us milk."),
    (["what do plants need to grow?", "what do plants need?"], "Plants need sunlight, water and air to grow."),
    (["how many colors are in a rainbow?", "how many colors does a rainbow have?"], "A rainbow has seven colors."),
    (["what are the colors of the rainbow?", "what colors are in a rainbow?", "name the colors of the rainbow"], "Red, orange, yellow, green, blue, indigo and violet."),
    (["what is h2o?", "what does h2o mean?"], "H2O is water."),
    (["who wrote romeo and juliet?", "who wrote hamlet?"], "William Shakespeare wrote it."),
    (["who painted the mona lisa?"], "Leonardo da Vinci painted the Mona Lisa."),
    (["what is the biggest country?", "what is the largest country?", "which country is the biggest?"], "Russia is the biggest country."),
    (["what is the smallest country?", "which country is the smallest?"], "Vatican City is the smallest country."),
    (["what is the biggest continent?", "what is the largest continent?"], "Asia is the biggest continent."),
    (["what is the sun?", "is the sun a star?", "is the sun a planet?"], "The Sun is a star."),
    (["what is frozen water called?", "what is frozen water?"], "Frozen water is called ice."),
    (["what is the king of the jungle?", "which animal is the king of the jungle?"], "The lion is called the king of the jungle."),
    (["which animal has a trunk?", "what animal has a trunk?"], "An elephant has a trunk."),
    (["which bird cannot fly?", "what bird can not fly?"], "A penguin is a bird that cannot fly."),
    (["what is the hottest season?", "which season is the hottest?"], "Summer is the hottest season."),
    (["what is the coldest season?", "which season is the coldest?"], "Winter is the coldest season."),
    (["how many wheels does a car have?"], "A car has 4 wheels."),
    (["how many wheels does a bike have?", "how many wheels does a bicycle have?"], "A bicycle has 2 wheels."),
    (["how many days are in a week?", "how many days in a week?", "how many days does a week have?"], "There are 7 days in a week."),
    (["how many months are in a year?", "how many months in a year?", "how many months does a year have?"], "There are 12 months in a year."),
    (["how many days are in a year?", "how many days in a year?"], "There are 365 days in a year, or 366 in a leap year."),
    (["how many hours are in a day?", "how many hours in a day?"], "There are 24 hours in a day."),
    (["how many minutes are in an hour?", "how many minutes in an hour?"], "There are 60 minutes in an hour."),
    (["how many seconds are in a minute?", "how many seconds in a minute?"], "There are 60 seconds in a minute."),
    (["how many weeks are in a year?", "how many weeks in a year?"], "There are 52 weeks in a year."),
    (["how many seasons are there?", "what are the seasons?", "name the seasons"], "There are four seasons: spring, summer, autumn and winter."),
    (["how many continents are there?"], "There are 7 continents."),
    (["how many planets are there?", "how many planets are in the solar system?"], "There are 8 planets in our solar system."),
    (["how many letters are in the alphabet?", "how many letters does the alphabet have?"], "There are 26 letters in the alphabet."),
    (["how many sides does a circle have?"], "A circle has no straight sides."),
    (["what is the first month of the year?", "what is the first month?"], "January is the first month of the year."),
    (["what is the last month of the year?", "what is the last month?"], "December is the last month of the year."),
    (["how many fingers do people have?", "how many fingers do i have?", "how many fingers does a person have?"], "Most people have 10 fingers."),
    (["what do you call a baby dog?"], "A baby dog is called a puppy."),
    (["how many eyes does a person have?", "how many eyes do people have?"], "A person has 2 eyes."),
    (["what is the first letter of the alphabet?"], "A is the first letter of the alphabet."),
    (["what is the last letter of the alphabet?"], "Z is the last letter of the alphabet."),
    (["is the earth round?", "what shape is the earth?"], "Yes, the Earth is round, like a ball."),
    (["is fire hot?", "is fire hot or cold?"], "Yes, fire is very hot. Be careful!"),
    (["is ice cold?", "is ice hot or cold?"], "Yes, ice is very cold."),
    (["what do fish live in?", "where do fish live?"], "Fish live in water."),
    (["where do birds live?", "what do birds live in?"], "Many birds live in nests."),
]
TOPICS = """quantum physics|the stock market|bitcoin|politics|the roman empire|black holes|the internet|taxes|chess
world war two|the pyramids|dinosaurs|climate change|machine learning|the government|philosophy|economics|cars
the weather tomorrow|football scores|the news|my homework|this essay|the president|the prime minister|medicine
the human brain|electricity|gravity|the big bang|evolution|volcanoes|earthquakes|airplanes|computers|the moon landing
python code|javascript|a website|my phone|my computer|video games|minecraft|youtube|a recipe for cake|pasta sauce
the bible|ancient egypt|napoleon|einstein|the olympics|basketball|tennis|the ocean floor|vitamins|sleep science
love and marriage|money|a job interview|my resume|a business plan|cryptocurrency|the law|a contract|insurance
guitar chords|piano lessons|photography|oil painting|poetry analysis|grammar rules|french verbs|chemistry|algebra
calculus|geometry proofs|the periodic table|dna|bacteria|viruses|vaccines|nutrition|a diet plan|exercise
the future|time travel|aliens|ghosts|dragons|magic tricks|the universe|infinity|prime numbers|the stock price""".replace("\n", "|").split("|")
OOS_TEMPLATES = ["tell me about {t}", "what is {t}?", "explain {t}", "what do you think about {t}?", "how does {t} work?",
                 "who invented {t}?", "write an essay about {t}", "can you help me with {t}?", "why is {t} important?",
                 "what do you know about {t}?", "teach me {t}", "i want to learn about {t}", "give me advice about {t}",
                 "write a report on {t}", "can you explain {t}?", "what is the history of {t}?", "describe {t}",
                 "translate this into chinese", "write me some code", "solve this equation for x", "what is the square root of {n}?",
                 "what is {n} to the power of {m}?", "who won the game last night?", "what is the news today?",
                 "can you search the internet?", "open youtube", "play some music", "set an alarm", "call my mom",
                 "what is the population of {c}?", "who is the president of {c}?", "how far is {c}?", "what is the weather in {c}?",
                 "how do i get to {c}?", "how do i cook {th}?", "where can i buy {th}?", "how much does {th} cost?"]
FALLBACK = ["I am not sure about that. I am only a tiny model.", "Sorry, I do not know that. I am still very small.",
            "That is beyond me, sorry. Try asking for a sum, a capital city or a joke."]
CONFUSED = ["Sorry, I did not understand that. Could you say it another way?", "I am not sure what you mean. Can you try again?"]

# ---------------------------------------------------------------- helpers
def typo(s):
    idx = [i for i, c in enumerate(s) if c.isalpha()]
    if len(idx) < 4:
        return s
    i = pick(idx[1:])
    k = R.random()
    if k < 0.3:
        return s[:i] + s[i + 1:]                                # dropped letter
    if k < 0.55:
        return s[:i] + s[i] + s[i:]                             # doubled letter
    if k < 0.8 and i + 1 < len(s) and s[i + 1].isalpha():
        return s[:i] + s[i + 1] + s[i] + s[i + 2:]              # swapped letters
    return s[:i] + pick(string.ascii_lowercase) + s[i + 1:]     # wrong letter


def user(template, casing=True, typos=True, **slots):
    """Turn a clean template into something a person might really type."""
    t = template
    question = t.endswith("?")
    t = t.rstrip("?")
    if R.random() < 0.3:
        t = t.replace("what is ", pick(["what's ", "whats "])).replace("i am ", pick(["i'm ", "im "]))
        t = t.replace("do not ", pick(["don't ", "dont "])).replace("it is ", pick(["it's ", "its "]))
        t = t.replace("you are ", pick(["you're ", "youre "])).replace("let us ", pick(["let's ", "lets "]))
    if R.random() < 0.2:
        t = t.replace("color", "colour").replace("favorite", "favourite")
    if R.random() < 0.05:
        t = pick(["please ", "hey ", "ok ", "so ", "erdenel, ", "um ", "well "]) + t
    if typos and R.random() < 0.07:
        parts = re.split(r"(\{\w+\})", t)                       # never damage the slots
        i = pick([j for j, p in enumerate(parts) if not p.startswith("{")])
        parts[i] = typo(parts[i])
        t = "".join(parts)
    t = t.format(**slots)
    if casing:
        k = R.random()
        if k < 0.3:
            t = t[:1].upper() + t[1:]
        elif k < 0.33:
            t = t.upper()
    k = R.random()
    if question:
        t += "?" if k < 0.55 else ("??" if k < 0.58 else "")
    else:
        t += "!" if k < 0.12 else ("." if k < 0.2 else "")
    return t


def fake_word(lo=3, hi=7):
    cons, vow = "bcdfghjklmnprstvwz", "aeiou"
    return "".join(pick(cons) if i % 2 == 0 else pick(vow) for i in range(R.randint(lo, hi)))


def cap(s):
    return s[:1].upper() + s[1:]


def num(big=99):
    return R.randint(0, 12) if R.random() < 0.3 else R.randint(0, big)


def held_out(op, a, b):
    """About 1 sum in 11 is never shown in training, so we can test real understanding."""
    return (a * 37 + b * 91 + ord(op)) % 11 == 0

# ---------------------------------------------------------------- skills
# Each skill returns (user text, bot text, name of the skill or None if the answer is not fixed).
def s_smalltalk(st, test):
    users, bots = pick(SMALLTALK)
    return user(pick(users)), pick(bots), None


def s_maths(st, test):
    while True:
        op = pick("+++---xx/")
        if op == "+":
            a, b = num(), num(); c = a + b
        elif op == "-":
            a, b = num(), num()
            a, b = max(a, b), min(a, b); c = a - b
        elif op == "x":
            a, b = R.randint(0, 12), R.randint(0, 12); c = a * b
        else:
            b, c = R.randint(1, 12), R.randint(0, 12); a = b * c
        if held_out(op, a, b) == test:
            break
    word = {"+": ["plus", "+", "+", "and"], "-": ["minus", "-", "-", "take away"], "x": ["times", "x", "*", "multiplied by"],
            "/": ["divided by", "/", "/", "over"]}[op]
    w = pick(word[:3]) if R.random() < 0.9 else word[3]
    if w == "and":
        tpl = pick(["what is {a} and {b}?", "add {a} and {b}", "what is the sum of {a} and {b}?"])
    else:
        tpl = pick(["what is {a} {w} {b}?", "what is {a} {w} {b}?", "{a} {w} {b}", "{a} {w} {b}?", "how much is {a} {w} {b}?",
                    "calculate {a} {w} {b}", "{a} {w} {b} =", "can you do {a} {w} {b}?", "what does {a} {w} {b} equal?"])
        if w in "+-x*/" and R.random() < 0.3:
            tpl = tpl.replace("{a} {w} {b}", "{a}{w}{b}")
    if op == "-" and R.random() < 0.08:
        tpl = "subtract {b} from {a}"
    return user(tpl, typos=False, a=a, b=b, w=w), f"{a} {op} {b} = {c}.", "maths"


def s_numbers(st, test):
    k = R.random()
    if k < 0.2:
        n = R.randint(2, 20)
        return user(pick(["count to {n}", "can you count to {n}?", "count up to {n}", "count from 1 to {n}"]), n=n), \
            ", ".join(map(str, range(1, n + 1))) + ".", "counting"
    if k < 0.3:
        a = R.randint(0, 90); b = a + R.randint(2, 12)
        return user(pick(["count from {a} to {b}", "can you count from {a} to {b}?"]), a=a, b=b), \
            ", ".join(map(str, range(a, b + 1))) + ".", "counting"
    if k < 0.38:
        n = R.randint(2, 12)
        return user(pick(["count down from {n}", "count backwards from {n}", "count from {n} to 1"]), n=n), \
            ", ".join(map(str, range(n, 0, -1))) + ".", "counting"
    if k < 0.52:
        n = R.randint(0, 199)
        return user(pick(["what comes after {n}?", "what number comes after {n}?", "what is the number after {n}?"]), n=n), \
            f"{n + 1} comes after {n}.", "next number"
    if k < 0.62:
        n = R.randint(1, 200)
        return user(pick(["what comes before {n}?", "what number comes before {n}?", "what is the number before {n}?"]), n=n), \
            f"{n - 1} comes before {n}.", "next number"
    if k < 0.8:
        n = R.randint(0, 999)
        tpl = pick(["is {n} even or odd?", "is {n} odd or even?", "is {n} an even number?", "is {n} even?", "is {n} odd?"])
        return user(tpl, n=n), f"{n} is {'even' if n % 2 == 0 else 'odd'}.", "even or odd"
    a, b = R.randint(0, 999), R.randint(0, 999)
    if R.random() < 0.05:
        b = a
    big = R.random() < 0.6
    w = pick(["bigger", "larger", "greater", "more"]) if big else pick(["smaller", "less", "lower"])
    tpl = pick(["which is {w}, {a} or {b}?", "which is {w}: {a} or {b}?", "what is {w}, {a} or {b}?", "which number is {w}, {a} or {b}?"])
    if a == b:
        ans = f"They are the same. Both are {a}."
    else:
        hi, lo = max(a, b), min(a, b)
        ans = f"{hi} is bigger than {lo}." if big else f"{lo} is smaller than {hi}."
    return user(tpl, a=a, b=b, w=w), ans, "comparing numbers"


def s_words(st, test):
    w = fake_word() if (test or R.random() < 0.3) else pick(WORDS)
    k = R.random()
    if k < 0.3:
        return user(pick(["spell {w}", "how do you spell {w}?", "can you spell {w}?", "spell the word {w}"]), casing=False, w=w), \
            "-".join(w.upper()) + ".", "spelling"
    if k < 0.45:
        tpl = pick(["how many letters are in {w}?", "how many letters does {w} have?", "how many letters in the word {w}?", "how long is the word {w}?"])
        return user(tpl, casing=False, w=w), f"The word {w} has {len(w)} letters.", "counting letters"
    if k < 0.57:
        return user(pick(["what is the first letter of {w}?", "what letter does {w} start with?", "first letter of {w}"]), casing=False, w=w), \
            f"The first letter of {w} is {w[0].upper()}.", "first and last letter"
    if k < 0.67:
        return user(pick(["what is the last letter of {w}?", "what letter does {w} end with?", "last letter of {w}"]), casing=False, w=w), \
            f"The last letter of {w} is {w[-1].upper()}.", "first and last letter"
    if k < 0.8:
        return user(pick(["say {w} backwards", "reverse {w}", "what is {w} backwards?", "spell {w} backwards", "reverse the word {w}"]), casing=False, w=w), \
            f"{w[::-1]}.", "reversing a word"
    if k < 0.9:
        tpl = pick(["write {w} in capital letters", "write {w} in capitals", "say {w} in uppercase", "make {w} uppercase", "shout {w}"])
        return user(tpl, casing=False, w=w), f"{w.upper()}!", "capital letters"
    c = pick(string.ascii_lowercase)
    if R.random() < 0.6:
        ans = "Z is the last letter of the alphabet." if c == "z" else f"{chr(ord(c) + 1).upper()} comes after {c.upper()}."
        return user(pick(["what letter comes after {c}?", "what comes after {c}?", "which letter is after {c}?"]), c=c), ans, "alphabet"
    ans = "A is the first letter of the alphabet." if c == "a" else f"{chr(ord(c) - 1).upper()} comes before {c.upper()}."
    return user(pick(["what letter comes before {c}?", "what comes before {c}?", "which letter is before {c}?"]), c=c), ans, "alphabet"


def s_repeat(st, test):
    p = " ".join(pick(WORDS) if R.random() < 0.8 else fake_word() for _ in range(R.randint(1, 3)))
    tpl = pick(["say {p}", "repeat after me: {p}", "can you say {p}?", "say the word {p}", "repeat {p}", "please say {p}"])
    return user(tpl, casing=False, p=p), cap(p) + "!", "repeating"


def s_capitals(st, test):
    k = R.random()
    if k < 0.12:
        f = cap(fake_word(5, 8))
        return user(pick(["what is the capital of {c}?", "capital of {c}"]), c=f.lower() if R.random() < 0.6 else f), \
            "I do not know that country, sorry.", None
    if k < 0.3:
        low = pick(list(CAPITAL_ALIASES)); shown, city = CAPITAL_ALIASES[low]
        typed = low
    else:
        shown = pick(list(CAPITALS)); city = CAPITALS[shown]
        typed = shown.lower() if R.random() < 0.6 else shown
    if R.random() < 0.2 and shown in CAPITALS:
        t = city.lower() if R.random() < 0.6 else city
        tpl = pick(["which country is {x} the capital of?", "{x} is the capital of which country?", "what country is {x} in?", "where is {x}?"])
        return user(tpl, x=t), f"{city} is the capital of {shown}.", "capitals"
    tpl = pick(["what is the capital of {c}?", "what is the capital of {c}?", "capital of {c}", "what is the capital city of {c}?",
                "do you know the capital of {c}?", "tell me the capital of {c}", "{c} capital", "which city is the capital of {c}?"])
    return user(tpl, c=typed), f"The capital of {shown} is {city}.", "capitals"


def s_animals(st, test):
    k = R.random()
    if k < 0.35:
        a = pick(list(SOUNDS))
        tpl = pick(["what sound does a {a} make?", "what does a {a} say?", "what noise does a {a} make?", "what does the {a} say?"])
        return user(tpl, a=a), f"A {a} says {SOUNDS[a]}!", "animals"
    if k < 0.7:
        a = pick(list(LEGS)); n = LEGS[a]
        art = "An" if a[0] in "aeiou" else "A"
        tpl = pick(["how many legs does a {a} have?", "how many legs has a {a} got?", "how many legs do {a}s have?"])
        return user(tpl, a=a), (f"{art} {a} has no legs." if n == 0 else f"{art} {a} has {n} legs."), "animals"
    a = pick(list(BABIES))
    tpl = pick(["what is a baby {a} called?", "what do you call a baby {a}?", "what is the name for a baby {a}?"])
    return user(tpl, a=a), f"A baby {a} is called a {BABIES[a]}.", "animals"


def s_colors(st, test):
    t = pick(list(COLOR_OF))
    tpl = pick(["what color is {t}?", "what is the color of {t}?", "which color is {t}?"])
    return user(tpl, t=t), f"{cap(t)} is {COLOR_OF[t]}.", "colors of things"


def s_calendar(st, test):
    k = R.random()
    if k < 0.3:
        i = R.randrange(7)
        if R.random() < 0.6:
            return user(pick(["what day comes after {d}?", "what is the day after {d}?", "which day is after {d}?"]), d=DAYS[i].lower()), \
                f"{DAYS[(i + 1) % 7]} comes after {DAYS[i]}.", "days and months"
        return user(pick(["what day comes before {d}?", "what is the day before {d}?", "which day is before {d}?"]), d=DAYS[i].lower()), \
            f"{DAYS[i - 1]} comes before {DAYS[i]}.", "days and months"
    if k < 0.55:
        i = R.randrange(12)
        if R.random() < 0.6:
            return user(pick(["what month comes after {m}?", "what is the month after {m}?", "which month is after {m}?"]), m=MONTHS[i].lower()), \
                f"{MONTHS[(i + 1) % 12]} comes after {MONTHS[i]}.", "days and months"
        return user(pick(["what month comes before {m}?", "what is the month before {m}?"]), m=MONTHS[i].lower()), \
            f"{MONTHS[i - 1]} comes before {MONTHS[i]}.", "days and months"
    if k < 0.75:
        i = R.randrange(12)
        ans = "February has 28 days, or 29 in a leap year." if i == 1 else f"{MONTHS[i]} has {MONTH_DAYS[i]} days."
        return user(pick(["how many days are in {m}?", "how many days does {m} have?", "how many days in {m}?"]), m=MONTHS[i].lower()), ans, "days and months"
    if k < 0.87:
        s = pick(list(SHAPES))
        return user(pick(["how many sides does a {s} have?", "how many sides has a {s}?", "how many corners does a {s} have?"]), s=s), \
            f"A {s} has {SHAPES[s]} sides.", "shapes"
    c = pick(list(LANGUAGE_OF))
    return user(pick(["what language do they speak in {c}?", "what language is spoken in {c}?", "what do people speak in {c}?"]),
                c=c.lower() if R.random() < 0.6 else c), f"People in {c} speak {LANGUAGE_OF[c]}.", "languages"


def s_facts(st, test):
    qs, a = pick(FACTS)
    return user(pick(qs)), a, "general facts"


def s_opposites(st, test):
    w = pick(list(OPPOSITES))
    tpl = pick(["what is the opposite of {w}?", "what is the opposite of {w}?", "opposite of {w}", "tell me the opposite of {w}",
                "what is the reverse of {w}?", "what word means the opposite of {w}?"])
    return user(tpl, w=w), f"The opposite of {w} is {OPPOSITES[w]}.", "opposites"


def s_translate(st, test):
    lang = pick(list(TRANSLATE)); i = R.randrange(3)
    en = ["hello", "thank you", "goodbye"][i]
    tpl = pick(["how do you say {e} in {l}?", "what is {e} in {l}?", "say {e} in {l}", "{e} in {l}", "how do i say {e} in {l}?"])
    return user(tpl, e=en, l=lang.lower() if R.random() < 0.6 else lang), f'In {lang}, {en} is "{TRANSLATE[lang][i]}".', "translations"


def s_fun(st, test):
    k = R.random()
    if k < 0.45:
        j = pick([x for x in JOKES if x != st.get("joke")]); st["joke"] = j
        if st.get("told") and R.random() < 0.6:
            u = pick(["another one", "tell me another", "one more", "another joke", "again", "tell me another one", "more"])
        else:
            u = pick(["tell me a joke", "tell me a joke", "do you know any jokes?", "make me laugh", "say something funny", "joke",
                      "do you know a joke?", "can you tell me a joke?", "i want to hear a joke", "joke please"])
        st["told"] = True
        return user(u), j, None
    if k < 0.75:
        u = pick(["tell me a fun fact", "tell me a fact", "fun fact", "tell me something interesting", "do you know any fun facts?",
                  "teach me something", "tell me something cool", "give me a fact", "surprise me"])
        return user(u), pick(FUN_FACTS), None
    if k < 0.88:
        u = pick(["tell me a story", "tell me a short story", "can you tell me a story?", "story please", "i want a story", "tell me a bedtime story"])
        return user(u), pick(STORIES), None
    u = pick(["tell me a poem", "write a poem", "can you write a poem?", "say a poem", "do you know a poem?", "sing a song", "sing for me", "can you rhyme?"])
    return user(u), pick(POEMS), None


def s_name(st, test):
    if st.get("name") and R.random() < 0.75 or R.random() < 0.2:
        u = user(pick(["what is my name?", "do you know my name?", "who am i?", "say my name", "do you remember my name?", "what am i called?"]))
        if st.get("name"):
            return u, pick([f"Your name is {st['name']}.", f"You are {st['name']}, of course!"]), None
        return u, "I do not know your name yet. What is it?", "name (not told yet)"
    n = fake_word(3, 6) if (test or R.random() < 0.25) else pick(NAMES)
    st["name"] = cap(n)
    typed = n if R.random() < 0.55 else cap(n)
    tpl = pick(["my name is {n}", "my name is {n}", "call me {n}", "you can call me {n}", "the name is {n}", "i am called {n}",
                "hi, my name is {n}", "hello, my name is {n}", "people call me {n}"])
    return user(tpl, casing=False, n=typed), pick([f"Nice to meet you, {cap(n)}!", f"Hello, {cap(n)}! It is great to meet you."]), None


def s_memory(st, test):
    k = R.random()
    if k < 0.5:
        if st.get("color") and R.random() < 0.75 or R.random() < 0.15:
            u = user(pick(["what is my favorite color?", "do you know my favorite color?", "which color do i like?", "what color do i like?"]))
            return u, (f"Your favorite color is {st['color']}." if st.get("color") else "You have not told me your favorite color yet."), None
        c = pick(COLORS); st["color"] = c
        tpl = pick(["my favorite color is {c}", "i like the color {c}", "my favorite color is {c}", "i love {c}", "{c} is my favorite color"])
        return user(tpl, c=c), pick([f"{cap(c)} is a beautiful color!", f"Nice choice! {cap(c)} is lovely."]), None
    if st.get("age") and R.random() < 0.75 or R.random() < 0.15:
        u = user(pick(["how old am i?", "what is my age?", "do you know my age?", "do you know how old i am?"]))
        return u, (f"You are {st['age']} years old." if st.get("age") else "I do not know. How old are you?"), None
    a = R.randint(4, 99); st["age"] = a
    tpl = pick(["i am {a} years old", "i am {a}", "my age is {a}", "i am {a} years old", "i just turned {a}"])
    return user(tpl, a=a), pick([f"{a}! That is a great age.", f"Wow, {a} years old! Thank you for telling me."]), None


def s_likes(st, test):
    k = R.random()
    if k < 0.3:
        x = pick(THINGS)
        return user(pick(["do you like {x}?", "do you love {x}?", "what do you think of {x}?", "do you enjoy {x}?"]), x=x), \
            f"Yes, I like {x}! Do you?", "likes"
    if k < 0.55:
        x = pick(THINGS)
        return user(pick(["i like {x}", "i love {x}", "i really like {x}", "i enjoy {x}", "i like {x} a lot"]), x=x), \
            f"It is nice that you like {x}!", "likes"
    if k < 0.7:
        x = pick(THINGS)
        return user(pick(["i do not like {x}", "i hate {x}", "i dislike {x}", "i really do not like {x}"]), x=x), \
            f"That is okay. Not everyone likes {x}.", "likes"
    if k < 0.88:
        p = pick(list(CAPITALS) + list(CAPITALS.values()))
        typed = p.lower() if R.random() < 0.5 else p
        return user(pick(["i am from {p}", "i live in {p}", "i come from {p}", "i was born in {p}"]), casing=False, p=typed), \
            f"{p} sounds like a lovely place!", "places"
    p = pick(PETS)
    return user(pick(["i have a {p}", "i have a pet {p}", "i got a {p}", "my family has a {p}"]), p=p), f"A {p}! What is its name?", "likes"


def s_unknown(st, test):
    if R.random() < 0.15:
        g = " ".join(fake_word(2, 8) for _ in range(R.randint(1, 4)))
        if R.random() < 0.4:
            g = "".join(pick("asdfghjklqwertyuiopzxcvbnm") for _ in range(R.randint(3, 12)))
        return g, pick(CONFUSED), None
    tpl = pick(OOS_TEMPLATES)
    return user(tpl, t=pick(TOPICS), c=pick(list(CAPITALS)).lower(), th=pick(THINGS), n=R.randint(2, 999), m=R.randint(2, 9)), pick(FALLBACK), None


SKILLS = [(s_smalltalk, 22), (s_maths, 16), (s_numbers, 8), (s_words, 9), (s_repeat, 2), (s_capitals, 6), (s_animals, 4),
          (s_colors, 2), (s_calendar, 4), (s_facts, 5), (s_opposites, 4), (s_translate, 2), (s_fun, 5), (s_name, 6),
          (s_memory, 4), (s_likes, 3), (s_unknown, 6)]
FUNCS, WEIGHTS = zip(*SKILLS)
MAX_CHARS = 250          # a whole conversation must fit in the model's 256-character window


def conversation(test=False):
    st, lines = {}, []
    for _ in range(R.choices([1, 2, 3, 4], [35, 30, 20, 15])[0]):
        f = R.choices(FUNCS, WEIGHTS)[0]
        if (st.get("name") or st.get("color") or st.get("age")) and R.random() < 0.35:
            f = s_name if st.get("name") and R.random() < 0.6 else s_memory     # ask about what was said earlier
        if st.get("told") and R.random() < 0.3:
            f = s_fun
        u, b, _ = f(st, test)
        new = f"User: {u}\nBot: {b}\n"
        if lines and sum(map(len, lines)) + len(new) > MAX_CHARS:
            break
        lines.append(new)
    return "".join(lines)


def test_items(n_per_skill=60):
    """Single questions with exactly one right answer, grouped by skill."""
    items, counts = [], {}
    funcs = [f for f in FUNCS if f not in (s_smalltalk, s_fun, s_unknown, s_memory)]
    while min([counts.get(k, 0) for k in counts] or [0]) < n_per_skill or len(counts) < 18:
        f = pick(funcs)
        u, b, skill = f({}, True)
        if skill and counts.get(skill, 0) < n_per_skill:
            counts[skill] = counts.get(skill, 0) + 1
            items.append({"skill": skill, "prompt": f"User: {u}\nBot:", "answer": b})
    # remembering a name told one turn earlier (names the model never saw in training)
    for _ in range(n_per_skill):
        st = {}
        u1, b1, _ = s_name(st, True)
        while "name" not in st:
            u1, b1, _ = s_name(st, True)
        u2 = user(pick(["what is my name?", "do you remember my name?", "say my name"]))
        items.append({"skill": "remembering your name", "prompt": f"User: {u1}\nBot: {b1}\nUser: {u2}\nBot:",
                      "answer": [f"Your name is {st['name']}.", f"You are {st['name']}, of course!"]})
    return items


def main(n=400_000):
    convs = [conversation() for _ in range(n)]
    text = "\n".join(convs)
    open("input.txt", "w", encoding="utf-8").write(text)
    items = test_items()
    with open("test.jsonl", "w", encoding="utf-8") as f:
        for it in items:
            f.write(json.dumps(it) + "\n")
    print(f"wrote input.txt: {n:,} conversations, {len(text):,} characters, {len(set(text))} distinct characters")
    print(f"wrote test.jsonl: {len(items)} questions")


if __name__ == "__main__":
    main(int(sys.argv[1]) if len(sys.argv) > 1 else 400_000)