-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeybr.py
More file actions
1518 lines (1363 loc) · 71.9 KB
/
Copy pathKeybr.py
File metadata and controls
1518 lines (1363 loc) · 71.9 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Keybr.py v1.1.0 - Terminal-based typing trainer similar to keybr.com
Features:
- Real-time WPM and accuracy tracking
- Progress persistence across sessions
- Multiple practice modes
- Visual feedback for correct/incorrect typing
- Statistics dashboard
Author: johnvexcoder (https://github.com/johnvexcoder)
"""
import curses
import json
import os
import random
import signal
import string
import time
from datetime import datetime
from typing import Dict, List, Tuple, Optional
# ─── Word lists ──────────────────────────────────────────────────────────────
COMMON_WORDS = [
"the", "be", "to", "of", "and", "a", "in", "that", "have", "I",
"it", "for", "not", "on", "with", "he", "as", "you", "do", "at",
"this", "but", "his", "by", "from", "they", "we", "say", "her", "she",
"or", "an", "will", "my", "one", "all", "would", "there", "their", "what",
"so", "up", "out", "if", "about", "who", "get", "which", "go", "me",
"when", "make", "can", "like", "time", "no", "just", "him", "know", "take",
"people", "into", "year", "your", "good", "some", "could", "them", "see",
"other", "than", "then", "now", "look", "only", "come", "its", "over",
"think", "also", "back", "after", "use", "two", "how", "our", "work",
"first", "well", "way", "even", "new", "want", "because", "any", "these",
"give", "day", "most", "us", "great", "between", "need", "large", "often",
"hand", "high", "place", "keep", "last", "let", "thought", "city", "tree",
"cross", "farm", "hard", "start", "might", "story", "saw", "far", "sea",
"draw", "left", "late", "run", "while", "press", "close", "night", "real",
"life", "few", "north", "open", "seem", "together", "next", "white", "children",
"begin", "got", "walk", "example", "ease", "paper", "group", "always", "music",
"those", "both", "mark", "book", "letter", "until", "mile", "river", "car",
"feet", "care", "second", "enough", "plain", "girl", "usual", "young", "ready",
"above", "ever", "red", "list", "though", "feel", "talk", "bird", "soon",
"body", "dog", "family", "direct", "pose", "leave", "song", "measure", "door",
"product", "black", "short", "numeral", "class", "wind", "question", "happen",
"complete", "ship", "area", "half", "rock", "order", "fire", "south", "problem",
"piece", "told", "knew", "pass", "since", "top", "whole", "king", "space",
"heard", "best", "hour", "better", "true", "during", "hundred", "five", "remember",
"step", "early", "hold", "west", "interest", "reach", "fast", "verb", "sing",
"listen", "six", "table", "travel", "less", "morning", "ten", "simple", "several",
"vowel", "toward", "war", "lay", "against", "pattern", "slow", "center", "love",
"person", "money", "serve", "appear", "road", "map", "rain", "rule", "govern",
"pull", "cold", "notice", "voice", "energy", "hunt", "probable", "bed", "brother",
"egg", "ride", "cell", "believe", "perhaps", "pick", "sudden", "count", "square",
"reason", "size", "vary", "settle", "speak", "weight", "general", "ice", "matter",
"circle", "pair", "include", "divide", "syllable", "felt", "grand", "ball", "yet",
"wave", "drop", "heart", "present", "heavy", "dance", "engine", "position", "arm",
"wide", "sail", "material", "fraction", "forest", "sit", "race", "window", "store",
"summer", "train", "sleep", "prove", "lone", "leg", "exercise", "wall", "catch",
"mount", "wish", "sky", "board", "joy", "winter", "sat", "written", "wild",
"instrument", "kept", "glass", "grass", "cow", "job", "edge", "sign", "visit",
"past", "soft", "fun", "bright", "gas", "weather", "month", "million", "bear",
"finish", "happy", "hope", "flower", "clothe", "strange", "gone", "jump", "baby",
"eight", "village", "meet", "root", "buy", "raise", "solve", "metal", "whether",
]
HARD_WORDS = [
"abbreviation", "accommodate", "acquaintance", "aggressive", "allegiance",
"approximately", "belligerent", "bureaucracy", "catastrophe", "circumstance",
"communication", "congratulations", "conscientious", "controversy", "correspondence",
"definitely", "demonstrate", "deteriorate", "disappointment", "distinguish",
"effervescent", "embarrassment", "entrepreneur", "exaggerate", "extraordinary",
"flabbergasted", "guarantee", "hamburger", "hygiene", "idiosyncrasy",
"independently", "infrastructure", "juxtaposition", "kaleidoscope", "knowledgeable",
"legitimately", "maintenance", "millennium", "necessitate", "occasionally",
"parliamentary", "philosophical", "pronunciation", "questionnaire", "recommendation",
"representative", "simultaneously", "sophisticated", "strengthen", "substantial",
"superstitious", "thoroughly", "transformation", "unfortunately", "vulnerability",
"whistleblower", "xenophobia", "youthful", "zealous",
"accomplishment", "acknowledgement", "accountability", "acquisition", "administration",
"adventurous", "ambassador", "antecedent", "appreciation", "architectural",
"authenticity", "bibliography", "biodegradable", "bureaucratic", "calculation",
"calligrapher", "catastrophic", "characteristic", "chronological", "circumscribe",
"comprehensive", "concentration", "confederation", "congratulate", "constellation",
"constipation", "contemporize", "contradiction", "contradictory", "contribution",
"conversation", "counterbalance", "counterfeit", "counterintuitive", "demonstration",
"differentiate", "distinguished", "documentation", "electromagnetic", "encyclopedic",
"entertainment", "entrepreneurial", "environmental", "extraordinary", "furthermore",
"generalization", "hallucination", "hemorrhage", "heterogeneous", "hieroglyphics",
"hypothetical", "illustration", "immigration", "improvisation", "indispensable",
"industrialize", "incompatible", "inconvenience", "interconnected", "interdisciplinary",
"interpretation", "investigation", "irresponsible", "jurisprudence", "justification",
"lexicographer", "magnetosphere", "mathematician", "metamorphosis", "miscellaneous",
"multidisciplinary", "neurotransmitter", "organizational", "overcompensate", "parallelize",
"pharmaceutical", "philosophize", "photosynthesis", "polymorphous", "pronunciation",
"quintessential", "reconnaissance", "rehabilitation", "representative", "revolutionary",
"schizophrenic", "sophistication", "specifications", "standardization", "straightforward",
"surreptitious", "systematically", "technological", "thermodynamics", "tranquility",
"understanding", "unprecedented", "visualization", "vulnerability", "weatherization",
]
SENTENCES = [
"the quick brown fox jumps over the lazy dog and runs across the field before anyone could notice",
"practice makes perfect when you practice every single day without skipping even for a moment",
"typing fast requires both speed and accuracy which can only come from hours of dedicated training",
"the best way to learn any new skill is through consistent practice and never giving up no matter how hard it gets",
"never give up on your dreams and keep typing even when your fingers feel tired and your mind feels slow",
"good programmers are lazy people who find easy solutions to complicated problems by writing clean code",
"the early bird catches the worm but the second mouse gets the cheese so always think before you act",
"in the middle of every difficulty lies a hidden opportunity waiting to be discovered by those who persist",
"life is what happens when you are busy making other plans so enjoy every moment while it lasts",
"the only way to do great work is to love what you do and pour your heart and soul into every task",
"stay hungry stay foolish and never stop learning because knowledge is the one thing that cannot be taken away",
"success is not final failure is not fatal it is the courage to continue that truly counts in the end",
"code is like humor when you have to explain it it is probably bad so keep it simple and clear",
"first solve the problem then write the code because understanding the problem is always the hardest part",
"talk is cheap show me the code and let the results speak louder than any words ever could",
"any fool can write code that a computer can understand but only a good programmer can write code for humans",
"the best error message is the one that never shows up because prevention is always better than debugging",
"simplicity is the soul of efficiency so remove everything that is not essential and focus on what matters",
"make it work make it right make it fast in that specific order because premature optimization is dangerous",
"programs must be written for people to read and only incidentally for machines to execute them afterwards",
"the journey of a thousand miles begins with a single step so start typing today and never look back",
"an investment in knowledge pays the best interest so keep learning new things every single day of your life",
"the only true wisdom is in knowing you know nothing so stay curious and always keep an open mind always",
"it does not matter how slowly you go as long as you do not stop typing and keep improving every day",
"first principles thinking means breaking down complex problems into their simplest components and rebuilding",
]
PUNCTUATION = ".,;:!?-'\"()[]{}"
# Timer limits per mode (seconds)
TIME_LIMITS = {
"common": 45,
"hard": 60,
"sentences": 45,
"symbols": 40,
"capital": 50,
"keybr": 45,
}
SENTENCES_WITH_SYMBOLS = [
"hello! how are you doing today?",
"wait... did you really say that?",
"the answer is: 42, not 41.",
"can you type this sentence; correctly?",
"wow! that was fast, wasn't it?",
"she said \"hello\" and walked away.",
"the price is $5.99, not $6.00!",
"please enter your email (user@domain.com).",
"is this a question? or a statement!",
"he bought [3 apples], [2 oranges], and [1 banana].",
"the meeting is at 3:00 PM, not 2:30 PM!",
"do you know: who, what, when, where, why?",
"type these symbols: ! @ # $ % ^ & * ( )",
"the file is saved as: document_v2.pdf.",
"really? that's amazing! i can't believe it.",
"open the door; close the window; lock the gate.",
"she wrote: \"i love you\" on the note.",
"the formula is: x = (-b +/- sqrt(b^2-4ac)) / 2a.",
"hey! over here. look at this, okay?",
"one plus one equals two; two plus two equals four.",
]
CAPITAL_SENTENCES = [
"The quick brown fox jumps over the lazy dog. It was a beautiful morning in the countryside.",
"Practice makes perfect. Every day you should try to improve your typing speed and accuracy.",
"When life gives you lemons make lemonade. The key is to stay positive no matter what happens.",
"She walked to the store and bought some groceries. Then she went home and cooked dinner.",
"The cat sat on the mat. It was a very comfortable mat and the cat fell asleep immediately.",
"He woke up early in the morning. The sun was shining through the window and birds were singing.",
"They went to the park after lunch. The children played on the swings while the parents watched.",
"The book was very interesting. I could not put it down until I finished reading the last chapter.",
"We should always be kind to others. A small act of kindness can make someone's entire day better.",
"The weather was perfect for a walk. The sky was clear and the temperature was just right outside.",
"Learning to type fast takes time. But with consistent practice you will see great improvements soon.",
"The dog chased its tail in circles. It was the funniest thing I had seen in a very long time.",
"She opened the door and found a surprise. There was a beautiful cake waiting for her on the table.",
"The train arrived at the station right on time. All the passengers quickly got on board the train.",
"He studied hard for the exam. All his effort paid off when he received the highest score in class.",
"The flowers in the garden were blooming. The colors were so vibrant and the scent was wonderful.",
"They decided to go on a road trip. The destination did not matter as long as they were together.",
"The restaurant was packed with people. We had to wait thirty minutes before we could get a table.",
"She looked out the window and smiled. The world was beautiful and full of endless possibilities.",
"The old man sat on the bench. He watched the children play and remembered his own childhood days.",
]
# ─── Statistics file ─────────────────────────────────────────────────────────
STATS_FILE = os.path.join(os.path.expanduser("~"), ".keybr_stats.json")
def load_stats() -> Dict:
"""Load statistics from file."""
if os.path.exists(STATS_FILE):
with open(STATS_FILE, "r") as f:
data = json.load(f)
data.setdefault("category_best", {})
return data
return {
"sessions": 0,
"total_chars_typed": 0,
"total_correct": 0,
"total_time": 0,
"best_wpm": 0,
"category_best": {},
"history": [],
"letter_accuracy": {},
}
def save_stats(stats: Dict) -> None:
"""Save statistics to file."""
with open(STATS_FILE, "w") as f:
json.dump(stats, f, indent=2)
# ─── Keybr Offline Mode ─────────────────────────────────────────────────────
# English letters ordered by frequency (most to least common)
LETTER_FREQUENCY = list("etaoinsrhldcumwfgypbvkjxqz")
# Comprehensive English dictionary for Keybr Offline mode
# ~1500 common English words covering all 26 letters
ENGLISH_DICTIONARY = [
# 3-letter words
"ace", "act", "add", "age", "ago", "aid", "aim", "air", "all", "and",
"ant", "any", "ape", "arc", "are", "ark", "arm", "art", "ash", "ask",
"ate", "awe", "axe", "bad", "bag", "ban", "bar", "bat", "bay", "bed",
"bet", "big", "bin", "bit", "bow", "box", "boy", "bud", "bug", "bus",
"but", "buy", "cab", "can", "cap", "car", "cat", "cop", "cow", "cry",
"cub", "cup", "cut", "dad", "day", "did", "dig", "dim", "dip", "dog",
"dot", "dry", "dub", "dud", "due", "dug", "dye", "ear", "eat", "egg",
"elm", "end", "era", "eve", "ewe", "eye", "fab", "fad", "fan", "far",
"fat", "fax", "fed", "fee", "few", "fig", "fin", "fir", "fit", "fix",
"fly", "fog", "for", "fox", "fry", "fun", "fur", "gag", "gap", "gas",
"gel", "gem", "get", "gin", "god", "got", "gum", "gun", "gut", "guy",
"gym", "had", "ham", "has", "hat", "hay", "hen", "her", "hew", "hid",
"him", "hip", "his", "hit", "hog", "hop", "hot", "how", "hub", "hue",
"hum", "hut", "ice", "icy", "ill", "imp", "ink", "inn", "ion", "ire",
"irk", "ivy", "jab", "jag", "jam", "jar", "jaw", "jay", "jet", "jig",
"job", "jog", "jot", "joy", "jug", "jut", "keg", "ken", "key", "kid",
"kin", "kit", "lab", "lad", "lag", "lap", "law", "lay", "lea", "led",
"leg", "let", "lid", "lie", "lip", "lit", "log", "lot", "low", "lug",
"mad", "man", "map", "mar", "mat", "may", "men", "met", "mid", "mix",
"mob", "mom", "mop", "mud", "mug", "nab", "nag", "nap", "net", "new",
"nil", "nip", "nit", "nod", "nor", "not", "now", "nun", "nut", "oak",
"oar", "oat", "odd", "ode", "off", "oft", "ohm", "oil", "old", "one",
"opt", "orb", "ore", "our", "out", "owe", "owl", "own", "pad", "pal",
"pan", "pap", "par", "pat", "paw", "pay", "pea", "peg", "pen", "pep",
"per", "pet", "pie", "pig", "pin", "pit", "ply", "pod", "pop", "pot",
"pow", "pro", "pry", "pub", "pug", "pun", "pup", "pus", "put", "rag",
"ram", "ran", "rap", "rat", "raw", "ray", "red", "ref", "rep", "rib",
"rid", "rig", "rim", "rip", "rob", "rod", "rot", "row", "rub", "rug",
"rum", "run", "rut", "rye", "sac", "sad", "sag", "sap", "sat", "saw",
"say", "sea", "set", "sew", "shy", "sin", "sip", "sir", "sis", "sit",
"six", "ski", "sky", "sly", "sob", "sod", "son", "sop", "sot", "sow",
"soy", "spa", "spy", "sty", "sub", "sue", "sum", "sun", "sup", "tab",
"tad", "tag", "tan", "tap", "tar", "tat", "tax", "tea", "ten", "the",
"thy", "tie", "tin", "tip", "toe", "ton", "too", "top", "tot", "tow",
"toy", "try", "tub", "tug", "two", "urn", "use", "van", "vat", "vet",
"vex", "via", "vie", "vim", "vow", "wad", "wag", "war", "was", "wax",
"way", "web", "wed", "wet", "who", "why", "wig", "win", "wit", "woe",
"wok", "won", "woo", "wow", "yak", "yam", "yap", "yaw", "yea", "yes",
"yet", "yew", "you", "zap", "zed", "zen", "zig", "zip", "zoo",
# 4-letter words
"able", "acid", "aged", "also", "area", "army", "away", "baby", "back",
"bake", "ball", "band", "bank", "bare", "bark", "barn", "base", "bath",
"bead", "beak", "beam", "bean", "bear", "beat", "been", "beer", "bell",
"belt", "bend", "bent", "best", "bias", "bird", "bite", "blow", "blue",
"blur", "boil", "bold", "bolt", "bomb", "bond", "bone", "book", "boom",
"boot", "bore", "born", "boss", "both", "bowl", "bulk", "bull", "bump",
"burn", "bury", "bush", "busy", "buzz", "cafe", "cage", "cake", "call",
"calm", "came", "camp", "card", "care", "cart", "case", "cash", "cast",
"cave", "cell", "chat", "chip", "chop", "city", "clad", "clam", "clap",
"claw", "clay", "clip", "clod", "clog", "club", "clue", "coal", "coat",
"code", "coil", "coin", "cold", "cole", "colt", "comb", "come", "cone",
"cook", "cool", "cope", "copy", "cord", "core", "cork", "corn", "cost",
"cosy", "coup", "cove", "cozy", "crab", "crop", "crow", "cube", "cult",
"curb", "cure", "curl", "cute", "dale", "dame", "damp", "dare", "dark",
"darn", "dart", "dash", "data", "date", "dawn", "dead", "deaf", "deal",
"dear", "debt", "deck", "deed", "deem", "deep", "deer", "demo", "dent",
"deny", "desk", "dial", "dice", "diet", "dime", "dine", "dire", "dirt",
"disc", "dish", "dock", "does", "dome", "done", "doom", "door", "dose",
"down", "doze", "drab", "drag", "draw", "drew", "drip", "drop", "drum",
"dual", "dub", "duck", "dude", "duel", "duet", "duke", "dull", "dumb",
"dump", "dune", "dung", "dunk", "dusk", "dust", "duty", "each", "earl",
"earn", "ease", "east", "easy", "edge", "edit", "else", "emit", "envy",
"epic", "even", "ever", "evil", "exam", "exec", "exit", "eyed", "face",
"fact", "fade", "fail", "fair", "fake", "fall", "fame", "fang", "fare",
"farm", "fast", "fate", "fawn", "fear", "feat", "feed", "feel", "feet",
"fell", "felt", "fern", "fest", "file", "fill", "film", "find", "fine",
"fire", "firm", "fish", "fist", "five", "flag", "flak", "flap", "flat",
"flaw", "flea", "fled", "flew", "flex", "flip", "flit", "flog", "flop",
"flow", "flux", "foam", "foes", "foil", "fold", "folk", "fond", "font",
"food", "fool", "foot", "ford", "fore", "fork", "form", "fort", "foul",
"four", "fowl", "free", "from", "fuel", "full", "fume", "fund", "furl",
"fury", "fuse", "fuss", "gait", "gale", "gall", "game", "gape", "garb",
"gate", "gave", "gawk", "gaze", "gear", "gene", "germ", "gift", "gild",
"gill", "gist", "give", "glad", "glee", "glen", "glib", "glob", "glow",
"glue", "glum", "glut", "gnat", "gnaw", "goat", "goes", "gold", "golf",
"gone", "good", "gore", "grab", "gram", "gray", "grew", "grid", "grim",
"grin", "grip", "grit", "grow", "grub", "gulf", "gull", "gust", "guts",
"hack", "hail", "hair", "hake", "hale", "half", "hall", "halt", "hand",
"hang", "hare", "hark", "harm", "harp", "hash", "hast", "hate", "haul",
"have", "haze", "hazy", "head", "heal", "heap", "hear", "heat", "heed",
"heel", "held", "hell", "helm", "help", "herb", "herd", "here", "hero",
"hide", "high", "hike", "hill", "hilt", "hind", "hint", "hire", "hiss",
"hive", "hoax", "hold", "hole", "holy", "home", "hone", "hood", "hook",
"hoop", "hope", "horn", "hose", "host", "hour", "howl", "huge", "hull",
"hump", "hung", "hunt", "hurl", "hurt", "hush", "hymn", "icon", "idea",
"idle", "inch", "into", "iron", "isle", "itch", "item", "jack", "jade",
"jail", "jake", "jamb", "jazz", "jean", "jeer", "jerk", "jest", "jilt",
"jinx", "jive", "join", "joke", "jolt", "josh", "jowl", "judo", "juke",
"jump", "june", "junk", "jury", "just", "keen", "keep", "kelp", "kept",
"keys", "kick", "kids", "kill", "kind", "king", "kiss", "kite", "knee",
"knew", "knit", "knob", "knot", "know", "lace", "lack", "lacy", "laid",
"lair", "lake", "lamb", "lame", "lamp", "land", "lane", "lard", "lark",
"lash", "lass", "last", "late", "lawn", "lazy", "lead", "leaf", "leak",
"lean", "leap", "left", "lend", "lens", "less", "lest", "levy", "liar",
"lick", "lied", "lieu", "life", "lift", "like", "limb", "lime", "limp",
"line", "link", "lint", "lion", "list", "live", "load", "loaf", "loan",
"lock", "loft", "lone", "long", "look", "loop", "lord", "lore", "lose",
"loss", "lost", "loud", "love", "luck", "lull", "lump", "lure", "lurk",
"lush", "lust", "lynx", "mace", "made", "mail", "main", "make", "male",
"mall", "malt", "mane", "many", "mare", "mark", "mash", "mask", "mass",
"mast", "mate", "maze", "mead", "meal", "mean", "meat", "meek", "meet",
"meld", "melt", "memo", "mend", "menu", "mere", "mesh", "mess", "mild",
"mile", "milk", "mill", "mime", "mind", "mine", "mint", "mire", "miss",
"mist", "mite", "mitt", "moan", "moat", "mock", "mode", "mold", "mole",
"molt", "monk", "mood", "moon", "moor", "mope", "more", "moss", "most",
"moth", "move", "much", "muck", "mule", "mull", "mump", "murk", "muse",
"mush", "musk", "must", "mute", "myth", "nail", "name", "nape", "navy",
"near", "neat", "neck", "need", "nest", "news", "next", "nice", "nick",
"nine", "node", "none", "noon", "norm", "nose", "note", "noun", "null",
"numb", "oath", "obey", "odds", "odor", "ogle", "omen", "omit", "once",
"only", "onto", "ooze", "opal", "open", "oral", "oven", "over", "owed",
"pace", "pack", "pact", "page", "paid", "pail", "pain", "pair", "pale",
"palm", "pane", "pang", "pant", "pare", "park", "part", "pass", "past",
"path", "pave", "pawn", "peak", "peal", "pear", "peat", "peck", "peel",
"peer", "pelt", "pend", "perk", "perm", "pert", "pest", "pick", "pier",
"pike", "pile", "pill", "pine", "pink", "pint", "pipe", "piss", "pity",
"plan", "plap", "play", "plea", "plod", "plot", "plow", "ploy", "plug",
"plum", "plus", "pock", "poem", "poet", "pole", "poll", "polo", "pond",
"pony", "pool", "poor", "pope", "pore", "pork", "port", "pose", "posh",
"post", "pour", "pray", "prey", "prod", "prop", "prow", "pull", "pulp",
"pump", "punk", "pure", "push", "quay", "quit", "quiz", "race", "rack",
"raft", "rage", "raid", "rail", "rain", "rake", "ramp", "rang", "rank",
"rant", "rare", "rash", "rasp", "rate", "rave", "raze", "read", "real",
"reap", "rear", "reed", "reef", "reel", "rein", "rely", "rent", "rest",
"rice", "rich", "ride", "rife", "rift", "rile", "rill", "rind", "ring",
"riot", "ripe", "rise", "risk", "road", "roam", "roar", "robe", "rock",
"rode", "role", "roll", "romp", "roof", "rook", "room", "root", "rope",
"rose", "rosy", "rout", "rove", "ruin", "rule", "rump", "rung", "ruse",
"rush", "rust", "sack", "safe", "sage", "said", "sail", "sake", "sale",
"salt", "same", "sand", "sane", "sang", "sank", "sash", "save", "scan",
"scar", "seal", "seam", "sear", "seat", "sect", "seed", "seek", "seem",
"seen", "self", "sell", "send", "sent", "sept", "sewn", "shed", "shim",
"shin", "ship", "shoe", "shoo", "shop", "shot", "show", "shut", "sick",
"side", "sift", "sigh", "sign", "silk", "sill", "silo", "silt", "sine",
"sing", "sink", "sire", "site", "size", "skit", "slab", "slag", "slam",
"slap", "slat", "slaw", "slay", "sled", "slew", "slid", "slim", "slit",
"slob", "sloe", "slog", "slop", "slot", "slow", "slug", "slum", "slur",
"smog", "snap", "snag", "snip", "snob", "snot", "snow", "snub", "snug",
"soak", "soap", "soar", "sock", "soda", "sofa", "soft", "soil", "sold",
"sole", "some", "song", "soon", "soot", "sore", "sort", "soul", "soup",
"sour", "span", "spar", "spat", "spec", "sped", "spin", "spit", "spot",
"spur", "stab", "stag", "star", "stay", "stem", "step", "stew", "stir",
"stop", "stub", "stud", "stun", "such", "suck", "suit", "sulk", "sump",
"sung", "sunk", "sure", "surf", "swan", "swap", "swim", "swum", "tack",
"tact", "tail", "take", "tale", "talk", "tall", "tame", "tank", "tape",
"tart", "task", "taxi", "teak", "teal", "team", "tear", "teem", "tell",
"temp", "tend", "tent", "term", "test", "text", "than", "that", "them",
"then", "they", "thin", "this", "tick", "tide", "tidy", "tied", "tier",
"tile", "till", "tilt", "time", "tine", "tiny", "tire", "toad", "toil",
"told", "toll", "tomb", "tome", "tone", "took", "tool", "tops", "tore",
"torn", "toss", "tour", "town", "trap", "tray", "tree", "trek", "trim",
"trio", "trip", "trod", "trot", "true", "tube", "tuck", "tuft", "tuna",
"tune", "turf", "turn", "tusk", "tuft", "twin", "type", "ugly", "undo",
"unit", "unto", "upon", "urge", "used", "user", "vain", "vale", "vane",
"vary", "vase", "vast", "veil", "vein", "vent", "verb", "very", "vest",
"veto", "view", "vile", "vine", "visa", "void", "vole", "volt", "vote",
"wade", "wage", "wail", "wait", "wake", "walk", "wall", "wand", "want",
"ward", "warm", "warn", "warp", "wart", "wary", "wash", "wasp", "wave",
"wavy", "waxy", "weak", "wean", "wear", "weed", "week", "weep", "well",
"welt", "went", "wept", "were", "west", "what", "when", "whim", "whip",
"whom", "wick", "wide", "wife", "wild", "will", "wilt", "wily", "wimp",
"wind", "wine", "wing", "wink", "wipe", "wire", "wise", "wish", "wisp",
"with", "wits", "woke", "wolf", "womb", "wood", "woof", "wool", "word",
"wore", "work", "worm", "worn", "wort", "wove", "wrap", "wren", "yank",
"yard", "yarn", "year", "yell", "yelp", "yoga", "yoke", "your", "zeal",
"zero", "zest", "zinc", "zing", "zone", "zoom",
# 5-letter words
"abide", "about", "above", "abuse", "acted", "acute", "admit", "adopt",
"adult", "after", "again", "agent", "agile", "agree", "alarm", "alert",
"alike", "alive", "allow", "alone", "along", "alter", "among", "ample",
"angel", "anger", "angle", "angry", "ankle", "apart", "apple", "apply",
"arena", "argue", "arise", "armor", "array", "aside", "asset", "atlas",
"attic", "audio", "audit", "avail", "avoid", "await", "awake", "award",
"aware", "awful", "badge", "badly", "bagel", "baker", "basic", "basin",
"basis", "batch", "beach", "beard", "beast", "begin", "being", "below",
"bench", "berry", "birth", "black", "blade", "blame", "bland", "blank",
"blast", "blaze", "bleak", "bleed", "blend", "bless", "blind", "blink",
"bliss", "block", "bloom", "blown", "blues", "bluff", "blunt", "blurt",
"board", "boast", "bonus", "boost", "booth", "bound", "brace", "brain",
"brand", "brass", "brave", "bread", "break", "breed", "brick", "bride",
"brief", "bring", "brink", "brisk", "broad", "broke", "brook", "brood",
"broom", "broth", "brown", "brush", "build", "built", "bunch", "burst",
"buyer", "cabin", "cable", "camel", "candy", "cargo", "carry", "catch",
"cause", "cedar", "chain", "chair", "chalk", "champ", "chaos", "charm",
"chart", "chase", "cheap", "check", "cheek", "cheer", "chess", "chest",
"chief", "child", "chill", "china", "choir", "chord", "chunk", "civic",
"civil", "claim", "clash", "clasp", "class", "clean", "clear", "clerk",
"click", "cliff", "climb", "cling", "cloak", "clock", "clone", "close",
"cloth", "cloud", "coach", "coast", "color", "comet", "comic", "coral",
"couch", "could", "count", "court", "cover", "crack", "craft", "crane",
"crash", "crazy", "cream", "creek", "crest", "crime", "crisp", "cross",
"crowd", "crown", "crude", "cruel", "crush", "curve", "cycle", "daily",
"dance", "death", "debut", "delay", "delta", "dense", "depth", "derby",
"devil", "diary", "dirty", "dizzy", "dodge", "doing", "donor", "doubt",
"dough", "draft", "drain", "drake", "drama", "drank", "drape", "drawn",
"dread", "dream", "dress", "dried", "drift", "drill", "drink", "drive",
"droit", "drone", "drove", "drown", "drunk", "dryer", "dying", "eager",
"eagle", "early", "earth", "eater", "edict", "eight", "elder", "elect",
"elite", "email", "ember", "empty", "ended", "enemy", "enjoy", "enter",
"entry", "equal", "equip", "error", "essay", "event", "every", "exact",
"exalt", "exile", "exist", "expat", "extra", "fable", "facet", "faint",
"fairy", "faith", "false", "fancy", "fatal", "feast", "fence", "ferry",
"fetch", "fever", "fiber", "field", "fiend", "fifth", "fifty", "fight",
"final", "first", "fixed", "flame", "flank", "flare", "flash", "flask",
"fleet", "flesh", "flick", "fling", "flint", "float", "flock", "flood",
"floor", "flora", "flour", "flown", "fluid", "flush", "flute", "focal",
"focus", "force", "forge", "forth", "forty", "forum", "found", "frame",
"frank", "fraud", "fresh", "front", "frost", "froze", "fruit", "fully",
"funny", "gamma", "gauge", "genre", "ghost", "giant", "given", "glare",
"glass", "gleam", "glide", "globe", "gloom", "glory", "gloss", "glove",
"going", "goose", "grace", "grade", "grain", "grand", "grant", "grape",
"graph", "grasp", "grass", "grave", "great", "greed", "green", "greet",
"grief", "grill", "grind", "gripe", "groan", "groom", "grope", "gross",
"group", "grove", "growl", "grown", "guard", "guess", "guest", "guide",
"guild", "guilt", "guise", "habit", "happy", "harsh", "haste", "hasty",
"haunt", "haven", "heart", "heavy", "hedge", "heist", "hence", "herbs",
"hoist", "honey", "honor", "horse", "hotel", "house", "human", "humor",
"hurry", "hyper", "ideal", "image", "imply", "index", "indie", "inner",
"input", "irony", "ivory", "jewel", "joint", "joker", "jolly", "judge",
"juice", "jumbo", "karma", "kayak", "knife", "knock", "known", "label",
"labor", "lance", "large", "laser", "latch", "later", "lathe", "laugh",
"layer", "leach", "learn", "lease", "least", "leave", "ledge", "legal",
"lemon", "level", "light", "limit", "linen", "liner", "liver", "lobby",
"local", "lodge", "logic", "lonely", "loose", "lover", "lower", "loyal",
"lucky", "lunch", "lying", "major", "maker", "manor", "march", "marry",
"marsh", "mason", "match", "mayor", "media", "mercy", "merit", "metal",
"meter", "might", "miner", "minor", "minus", "mirth", "model", "moist",
"money", "month", "moral", "motor", "mound", "mount", "mouse", "mouth",
"moved", "mover", "movie", "music", "naive", "nerve", "never", "night",
"noble", "noise", "north", "noted", "novel", "nurse", "ocean", "offer",
"often", "onset", "opera", "orbit", "order", "other", "ought", "outer",
"outdo", "owner", "oxide", "ozone", "paint", "panel", "panic", "paper",
"patch", "pause", "peace", "peach", "pearl", "penny", "phase", "phone",
"photo", "piano", "piece", "pilot", "pinch", "pitch", "pixel", "pizza",
"place", "plaid", "plain", "plane", "plank", "plant", "plate", "plaza",
"plead", "pleat", "plied", "pluck", "plumb", "plume", "plump", "plush",
"poach", "point", "poise", "polar", "pooch", "pound", "power", "press",
"price", "pride", "prime", "print", "prior", "prism", "prize", "probe",
"prone", "proof", "prose", "proud", "prove", "prude", "prune", "psalm",
"pulse", "punch", "pupil", "purge", "purse", "quake", "queen", "query",
"quest", "queue", "quick", "quiet", "quilt", "quirk", "quota", "quote",
"radar", "radio", "rally", "ranch", "range", "rapid", "ratio", "reach",
"react", "ready", "realm", "rebel", "refer", "reign", "relax", "relay",
"remit", "renew", "repay", "reply", "rider", "ridge", "rifle", "right",
"rigid", "rinse", "risky", "rival", "river", "robin", "robot", "rocky",
"rouge", "rough", "round", "route", "rover", "royal", "rugby", "ruler",
"rural", "saint", "salad", "sauce", "scale", "scare", "scene", "scent",
"scope", "score", "scout", "scrap", "sense", "serve", "seven", "shade",
"shaft", "shake", "shame", "shape", "share", "shark", "sharp", "shave",
"shelf", "shell", "shift", "shine", "shiny", "shirt", "shock", "shore",
"short", "shout", "shove", "shrub", "sight", "sigma", "since", "sixth",
"sixty", "sized", "skill", "skull", "slate", "slave", "sleep", "slice",
"slide", "slope", "small", "smart", "smell", "smile", "smoke", "snake",
"solar", "solid", "solve", "sonic", "south", "space", "spare", "spark",
"speak", "spear", "speed", "spell", "spend", "spent", "spice", "spill",
"spine", "spoke", "spoon", "sport", "spray", "squad", "stack", "staff",
"stage", "stain", "stair", "stake", "stale", "stalk", "stall", "stamp",
"stand", "stare", "stark", "start", "state", "stave", "stays", "steak",
"steal", "steam", "steel", "steep", "steer", "stern", "stick", "stiff",
"still", "sting", "stink", "stock", "stole", "stone", "stood", "stool",
"stoop", "store", "storm", "story", "stout", "stove", "strap", "straw",
"stray", "strip", "stuck", "study", "stuff", "stump", "style", "sugar",
"suite", "sunny", "super", "surge", "swamp", "swarm", "swear", "sweep",
"sweet", "swell", "swept", "swift", "swing", "swirl", "swore", "sworn",
"swung", "table", "taste", "teach", "teeth", "tempo", "tense", "tenth",
"theft", "theme", "there", "thick", "thief", "thing", "think", "third",
"thorn", "those", "three", "threw", "throw", "thumb", "tidal", "tiger",
"tight", "timer", "title", "today", "token", "tooth", "topaz", "topic",
"total", "touch", "tough", "towel", "tower", "toxic", "trace", "track",
"trade", "trail", "train", "trait", "trash", "treat", "trend", "trial",
"tribe", "trick", "tried", "truly", "trump", "trunk", "trust", "truth",
"tumor", "tuned", "twice", "twist", "ultra", "uncle", "under", "union",
"unite", "unity", "until", "upper", "upset", "urban", "usage", "usher",
"usual", "utter", "valid", "value", "valve", "vault", "venue", "verse",
"vigor", "vinyl", "viral", "virus", "visit", "vista", "vital", "vivid",
"vocal", "voice", "voter", "wages", "waste", "watch", "water", "weary",
"weave", "wedge", "weigh", "weird", "wheat", "wheel", "where", "which",
"while", "whine", "white", "whole", "whose", "widen", "width", "witch",
"woman", "world", "worry", "worse", "worst", "worth", "would", "wound",
"wrath", "wreck", "write", "wrong", "wrote", "yacht", "yield", "young",
"youth", "zeros",
]
# ─── Keybr Offline adaptive trainer ───────────────────────────────────────
class KeybrOffline:
"""Keybr.com-style adaptive typing trainer.
Features:
- Progressive letter unlocking (starts with most frequent letters)
- Per-letter confidence scoring (accuracy + speed)
- Dictionary-based text generation targeting weak letters
- Adaptive text targeting weak areas
- Goal-based progress tracking
"""
def __init__(self, stats: Dict):
self.stats = stats
# Ensure keybr_offline section exists
self.stats.setdefault("keybr_offline", {
"unlocked_letters": list(LETTER_FREQUENCY[:9]),
"letter_confidence": {},
"bigram_confidence": {},
"sessions": 0,
"total_wpm": 0.0,
"best_wpm": 0,
"target_wpm": 40,
"history": [],
})
self.kb = self.stats["keybr_offline"]
def get_unlocked(self) -> List[str]:
return self.kb["unlocked_letters"]
def get_target_wpm(self) -> int:
return self.kb["target_wpm"]
def set_target_wpm(self, wpm: int):
self.kb["target_wpm"] = max(10, min(200, wpm))
def _letter_confidence(self, letter: str) -> float:
"""Return confidence 0.0-1.0 for a letter."""
lc = self.kb["letter_confidence"].get(letter)
if not lc or lc["total"] == 0:
return 0.0
accuracy = lc["correct"] / lc["total"]
avg_speed = lc["speed_sum"] / lc["total"]
speed_factor = min(1.0, 80.0 / max(avg_speed, 10))
return accuracy * 0.7 + speed_factor * 0.3
def _bigram_confidence(self, bigram: str) -> float:
bc = self.kb["bigram_confidence"].get(bigram)
if not bc or bc["total"] == 0:
return 0.0
return bc["correct"] / bc["total"]
def should_unlock(self) -> bool:
unlocked = self.get_unlocked()
if len(unlocked) >= 26 or len(unlocked) < 3:
return False
confidences = [self._letter_confidence(l) for l in unlocked]
avg_conf = sum(confidences) / len(confidences) if confidences else 0
return avg_conf >= 0.75
def unlock_next_letter(self) -> Optional[str]:
if not self.should_unlock():
return None
unlocked = set(self.get_unlocked())
for letter in LETTER_FREQUENCY:
if letter not in unlocked:
self.kb["unlocked_letters"].append(letter)
return letter
return None
def _find_focus_key(self) -> Optional[str]:
"""Find the weakest unlocked letter to focus on."""
unlocked = self.get_unlocked()
if not unlocked:
return None
weakest = min(unlocked, key=lambda l: self._letter_confidence(l))
conf = self._letter_confidence(weakest)
if conf >= 0.75:
return None # All letters are doing well
return weakest
def _get_weak_letters(self) -> List[str]:
"""Return unlocked letters sorted by confidence (weakest first)."""
unlocked = self.get_unlocked()
scored = [(l, self._letter_confidence(l)) for l in unlocked]
scored.sort(key=lambda x: x[1])
return [l for l, _ in scored]
def generate_text(self, length: int = 120) -> str:
"""Generate adaptive text using dictionary words targeting weak letters."""
unlocked = self.get_unlocked()
if not unlocked:
unlocked = list(LETTER_FREQUENCY[:9])
self.kb["unlocked_letters"] = unlocked
allowed = set(unlocked)
focused = self._find_focus_key()
weak_letters = self._get_weak_letters()
# Filter dictionary: words that use only unlocked letters
valid_words = [
w for w in ENGLISH_DICTIONARY
if all(c in allowed for c in w)
]
if not valid_words:
valid_words = ["the", "and", "for", "are", "but", "not", "you", "all"]
# Score words: boost those containing weak/focused letters
def word_score(w: str) -> float:
score = 1.0
for ch in w:
if ch == focused:
score += 5.0
elif ch in weak_letters[:3]:
score += 2.0
elif ch in weak_letters:
score += 1.0
# Prefer shorter words for readability
if len(w) <= 5:
score *= 1.2
return score
scored_words = [(w, word_score(w)) for w in valid_words]
words = []
total_len = 0
max_attempts = 200
for _ in range(max_attempts):
if total_len >= length:
break
# Weighted random selection
weights = [s for _, s in scored_words]
word = random.choices([w for w, _ in scored_words], weights=weights, k=1)[0]
candidate = " ".join(words + [word])
if len(candidate) <= length + 20:
words.append(word)
total_len = len(candidate)
return " ".join(words)
def update_keystroke(self, typed_char: str, expected_char: str, correct: bool, elapsed_ms: float):
"""Update per-letter and bigram statistics."""
kb = self.kb
# Per-letter tracking
lc = kb["letter_confidence"].setdefault(expected_char, {"correct": 0, "total": 0, "speed_sum": 0.0})
lc["total"] += 1
if correct:
lc["correct"] += 1
lc["speed_sum"] += elapsed_ms
# Bigram tracking
if len(self.stats.get("_keybr_typed", "")) > 0:
prev = self.stats["_keybr_typed"][-1]
bigram = prev + expected_char
bc = kb["bigram_confidence"].setdefault(bigram, {"correct": 0, "total": 0})
bc["total"] += 1
if correct and prev == typed_char:
bc["correct"] += 1
def finish_session(self, wpm: float, accuracy: float):
"""Record session stats."""
kb = self.kb
kb["sessions"] += 1
kb["total_wpm"] += wpm
if wpm > kb["best_wpm"]:
kb["best_wpm"] = round(wpm, 1)
unlocked_letter = self.unlock_next_letter()
kb["history"].append({
"date": datetime.now().isoformat(),
"wpm": round(wpm, 1),
"accuracy": round(accuracy, 1),
"unlocked_count": len(kb["unlocked_letters"]),
"unlocked_new": unlocked_letter,
})
kb["history"] = kb["history"][-100:]
save_stats(self.stats)
return unlocked_letter
def get_key_map(self) -> List[Tuple[str, float, str]]:
"""Return (letter, confidence, status) for all 26 letters."""
unlocked = set(self.get_unlocked())
result = []
for letter in LETTER_FREQUENCY:
conf = self._letter_confidence(letter)
if letter in unlocked:
if conf >= 0.75:
status = "mastered"
elif conf >= 0.4:
status = "learning"
else:
status = "weak"
else:
status = "locked"
result.append((letter, conf, status))
return result
class TypingTrainer:
"""Main typing trainer class."""
def __init__(self):
self.stats = load_stats()
self.mode = "common"
self.current_text = ""
self.typed_text = ""
self.start_time: Optional[float] = None
self.last_keystroke_time: Optional[float] = None
self.correct_chars = 0
self.incorrect_chars = 0
self.finished = False
self.text_start_pos = 0
self.text_length = 60
self.keybr = KeybrOffline(self.stats)
self.time_limit = TIME_LIMITS.get("common", 45)
self.timer_expired = False
def get_time_remaining(self) -> float:
"""Return seconds remaining, or 0 if expired."""
if not self.start_time:
return float(self.time_limit)
elapsed = time.time() - self.start_time
remaining = self.time_limit - elapsed
return max(0.0, remaining)
def generate_text(self) -> str:
"""Generate text based on current mode."""
if self.mode == "common":
words = random.sample(COMMON_WORDS, min(20, len(COMMON_WORDS)))
return " ".join(words)
elif self.mode == "hard":
words = random.sample(HARD_WORDS, min(15, len(HARD_WORDS)))
return " ".join(words)
elif self.mode == "symbols":
return random.choice(SENTENCES_WITH_SYMBOLS)
elif self.mode == "capital":
return random.choice(CAPITAL_SENTENCES)
elif self.mode == "keybr":
return self.keybr.generate_text()
else: # sentences
return random.choice(SENTENCES)
def calculate_wpm(self) -> float:
"""Calculate words per minute."""
if not self.start_time:
return 0.0
elapsed = time.time() - self.start_time
if elapsed == 0:
return 0.0
# Standard: 1 word = 5 characters
wpm = (len(self.typed_text) / 5) / (elapsed / 60)
return wpm
def calculate_accuracy(self) -> float:
"""Calculate typing accuracy."""
if not self.typed_text:
return 100.0
return (self.correct_chars / len(self.typed_text)) * 100
def update_letter_accuracy(self, typed_char: str, expected_char: str, correct: bool):
"""Update per-letter accuracy statistics."""
if expected_char not in self.stats["letter_accuracy"]:
self.stats["letter_accuracy"][expected_char] = {"correct": 0, "total": 0}
self.stats["letter_accuracy"][expected_char]["total"] += 1
if correct:
self.stats["letter_accuracy"][expected_char]["correct"] += 1
def finish_session(self):
"""Save session statistics."""
self.finished = True
elapsed = time.time() - self.start_time if self.start_time else 0
wpm = self.calculate_wpm()
accuracy = self.calculate_accuracy()
self.stats["sessions"] += 1
self.stats["total_chars_typed"] += len(self.typed_text)
self.stats["total_correct"] += self.correct_chars
self.stats["total_time"] += elapsed
if wpm > self.stats["best_wpm"]:
self.stats["best_wpm"] = round(wpm, 1)
if self.mode not in self.stats["category_best"] or wpm > self.stats["category_best"][self.mode]:
self.stats["category_best"][self.mode] = round(wpm, 1)
self.stats["history"].append({
"date": datetime.now().isoformat(),
"mode": self.mode,
"wpm": round(wpm, 1),
"accuracy": round(accuracy, 1),
"chars": len(self.typed_text),
"correct": self.correct_chars,
"incorrect": self.incorrect_chars,
})
self.stats["history"] = self.stats["history"][-100:] # keep last 100
# Keybr Offline tracking
if self.mode == "keybr":
unlocked_letter = self.keybr.finish_session(wpm, accuracy)
self.stats["_keybr_unlocked_new"] = unlocked_letter
save_stats(self.stats)
def main(stdscr):
"""Main curses loop."""
curses.curs_set(0)
curses.start_color()
curses.use_default_colors()
# Color pairs
curses.init_pair(1, curses.COLOR_GREEN, -1) # correct
curses.init_pair(2, curses.COLOR_RED, -1) # incorrect
curses.init_pair(3, curses.COLOR_YELLOW, -1) # current char
curses.init_pair(4, curses.COLOR_CYAN, -1) # header
curses.init_pair(5, curses.COLOR_WHITE, curses.COLOR_BLUE) # selected menu
curses.init_pair(6, curses.COLOR_MAGENTA, -1) # dim text
curses.init_pair(7, curses.COLOR_GREEN, curses.COLOR_GREEN) # cursor block
curses.init_pair(8, curses.COLOR_WHITE, curses.COLOR_RED) # exit dialog
# ─── SIGINT handler (Ctrl+C) ───────────────────────────────────────
ctrl_c_pressed = [False]
def handle_sigint(sig, frame):
ctrl_c_pressed[0] = True
signal.signal(signal.SIGINT, handle_sigint)
def draw_exit_dialog(stdscr) -> bool:
"""Draw a professional exit confirmation dialog. Returns True to exit."""
h, w = stdscr.getmaxyx()
# Draw dimmed overlay effect
for y in range(h):
try:
stdscr.addnstr(y, 0, " " * w, w, curses.color_pair(0))
except curses.error:
pass
# Dialog box dimensions
box_w = 48
box_h = 9
box_x = max(0, (w - box_w) // 2)
box_y = max(0, (h - box_h) // 2)
# Draw border
try:
# Top border
stdscr.addstr(box_y, box_x, "┌" + "─" * (box_w - 2) + "┐", curses.color_pair(8) | curses.A_BOLD)
# Side borders
for i in range(1, box_h - 1):
stdscr.addstr(box_y + i, box_x, "│", curses.color_pair(8) | curses.A_BOLD)
stdscr.addstr(box_y + i, box_x + box_w - 1, "│", curses.color_pair(8) | curses.A_BOLD)
# Bottom border
stdscr.addstr(box_y + box_h - 1, box_x, "└" + "─" * (box_w - 2) + "┘", curses.color_pair(8) | curses.A_BOLD)
except curses.error:
pass
# Dialog content
lines = [
("", -1),
(" Are you sure you want to exit?", -1),
("", -1),
(" Your progress has been saved.", curses.color_pair(1)),
("", -1),
(" [ Yes ] [ No ]", -1),
("", -1),
(" Press Y to exit, N to continue", curses.color_pair(6)),
]
for i, (line, attr) in enumerate(lines):
y = box_y + 1 + i
if y >= box_y + box_h - 1:
break
try:
x = box_x + max(0, (box_w - len(line)) // 2)
if attr == -1:
stdscr.addstr(y, x, line, curses.color_pair(8) | curses.A_BOLD)
else:
stdscr.addstr(y, x, line, attr)
except curses.error:
pass
stdscr.refresh()
# Wait for Y or N
while True:
stdscr.timeout(-1)
key = stdscr.getch()
if key in (ord("y"), ord("Y")):
return True
elif key in (ord("n"), ord("N"), 27):
return False
trainer = TypingTrainer()
show_stats = False
show_keybr_stats = False
menu_idx = 0
menu_items = ["Common Words", "Hard Words", "Sentences", "Symbols & Punctuation", "Capital Letters", "Keybr Offline", "Statistics", "Quit"]
def draw_menu(stdscr):
nonlocal menu_idx
stdscr.clear()
h, w = stdscr.getmaxyx()
# Title
title = "═" * 3 + " KEYBR TYPING TRAINER " + "═" * 3
try:
stdscr.addstr(2, max(0, (w - len(title)) // 2), title, curses.color_pair(4) | curses.A_BOLD)
except curses.error:
pass
# Overall stats summary
stats = trainer.stats
total_chars = max(stats["total_chars_typed"], 1)
overall_acc = (stats["total_correct"] / total_chars) * 100
total_time = stats["total_time"] / 60
stats_box = [
f"Best WPM: {stats['best_wpm']}",
f"Sessions: {stats['sessions']}",
f"Accuracy: {overall_acc:.0f}%",
f"Practice: {total_time:.1f} min",
]
box_w = max(len(l) for l in stats_box) + 4
box_x = max(0, (w - box_w) // 2)
box_y = 4
try:
stdscr.addstr(box_y, box_x, "┌" + "─" * (box_w - 2) + "┐", curses.color_pair(4))
for bi, line in enumerate(stats_box):
padded = f" {line} ".center(box_w - 2)
stdscr.addstr(box_y + 1 + bi, box_x + 1, padded, curses.color_pair(4))
stdscr.addstr(box_y + len(stats_box) + 1, box_x, "└" + "─" * (box_w - 2) + "┘", curses.color_pair(4))
except curses.error:
pass
# Menu
start_y = 10
for i, item in enumerate(menu_items):
mode_str = ""
if i == 0:
mode_str = " - Practice common English words"
elif i == 1:
mode_str = " - Practice harder vocabulary"
elif i == 2:
mode_str = " - Practice full sentences"
elif i == 3:
mode_str = " - Practice with !, ?, \", and more"
elif i == 4:
mode_str = " - Practice sentence capitalization"
elif i == 5:
mode_str = " - Adaptive learning (keybr.com style)"
elif i == 6:
mode_str = " - View your progress"
elif i == 7:
mode_str = " - Exit the program"
label = f" [{item}]"
text = f"{label}{mode_str}"
x = max(0, (w - len(text)) // 2)
try:
if i == menu_idx:
stdscr.addstr(start_y + i, x, text, curses.color_pair(5) | curses.A_BOLD)
else:
stdscr.addstr(start_y + i, x, text, curses.color_pair(1))
except curses.error:
pass
# Controls
controls = "↑/↓ Navigate Enter Select q Quit"
try:
stdscr.addstr(start_y + len(menu_items) + 2, max(0, (w - len(controls)) // 2), controls, curses.color_pair(6))
except curses.error:
pass
# Category best scores box
cat_best = trainer.stats.get("category_best", {})
mode_map = {
"common": "Common Words", "hard": "Hard Words",
"sentences": "Sentences", "symbols": "Symbols",
"capital": "Capital Letters", "keybr": "Keybr Offline",
}
if cat_best:
# Build data lines first to determine width
data_lines = []