-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathngrams.py
executable file
·1288 lines (1105 loc) · 54.3 KB
/
ngrams.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
# encoding: utf-8
"""Calculating ngram distributions (letters, bigrams, trigrams) from text or getting them from precomputed files."""
import collections
import hashlib
from config import MODIFIERS_PER_LAYER
from layout_base import POS_TO_FINGER, Layout, Layouts
from textcheck import occurrence_dict_difference as diffdict
### Constants
# shorthand: ngrams in these are more seldomly between word-parts.
#: shorthand pre and suffixes
_steno_fix = "all ant ander bis da dar ent er es ge gegen hab her hin hint ich in könn konnt keit kon lich mit rück schaft sei seid seine selbst so sollst sonders sondern tum tüm über übr un ung unser unter ver voll völl voll völl wenn werd wieder widr wiedr wider willst zer zu zurück zum zur"
#: shorthand words
_steno_short = "als also auf aus das dass deine dem den der des dessen deutsch die dies doch durch eine fort für hast hat haft hatt hätt heit ist kannst keine meine miss nicht nichts nieder noch nur ohne schon sich sie sind solch und usw vom woll wir wird wirst wo worden wurde würde"
#: shorthand, too much
_steno_short_too_long = "besonders zusammen zwischen vielleicht"
#: shorthand ngram-letters
_steno_letters = "pf cht ng h ch eit tr br gr kr rr dr fr pr pfr wr uhr ur au eu rs ss tz sch st nd ndr rd mp mpf sp spr str schr zw schw schm schn st cr qu ex ion"
#: shorthand, higher level letters
_steno_eil_letters = "en es ge ber ger ter ker rer der fer per wer pfer igkeit ung du st est pro frag fall fahr zahl hand man männ dis bot isch istisch ie bar sam ial iell"
#: shorthand, higher level words → these are likely too much.
_steno_eil_short = "ismus ismen stadt statt nach richt bitt biet trag jahr herr komm kömm schließ kauf käuf tisch immer nimmer gleich wachs selb stell schreib schrieb schrift zeit tag groß etwa etwas wer jetzt größ geschäft mensch punkt tausend million mindestens wenigstens einzeln volk völk prozentual darauf gesamt insgesamt sonst forder förder konto selbstverständlich kunst zunächst gesetz allgemein angenehm ungefähr gesellschaft möglich wirtschaft versicher genossenschaft kapital sozial beschäftig person fabrik finanz organisation"
### Functions
def read_file(path):
"""Get the data from a file.
>>> read_file("testfile")[:2]
'ui'
"""
f = open(path, encoding="utf-8")
data = f.read()
f.close()
return data
def _split_uppercase_repeat(rep, num, layout=Layouts.NEO2,
mods=MODIFIERS_PER_LAYER):
"""Split a single bigram.
>>> reps = _split_uppercase_repeat("AB", 5)
>>> list(reversed(sorted([(j,i) for i, j in reps.items()])))
[(10, 'a⇧'), (5, '⇧b'), (5, '⇗⇧'), (5, '⇗a'), (5, 'ab'), (2.5, '⇗b')]
"""
# first check whether we really have a bigram and whether we need to split it.
try:
r2 = rep[1] # second first to error out early.
r1 = rep[0]
except IndexError:
# this is no repeat but at most a single key.
return {}
pos1 = layout.char_to_pos(r1)
pos2 = layout.char_to_pos(r2)
# if any key isn’t found, the repeat doesn’t need splitting.
if pos1 is None or pos2 is None:
# caught all repeats for which one key isn’t in the layout. We
# don’t need to change anything for these.
return {rep: num}
# same is true if all keys are layer 0.
layer1 = pos1[2]
layer2 = pos2[2]
if layer1 == 0 and layer2 == 0:
# caught all lowercase repeats. We don’t need to change
# anything for these.
return {rep: num}
#: Adjustment of the weight of two modifiers on the same hand, because we can’t yet simulate moving the hand to use a different finger for M4/M3 when the pinky is needed on M3/shift. 2 * WEIGHT_FINGER_REPEATS * mods_on_same_hand_adjustment should be lower than (COST_PER_KEY_NOT_FOUND - max(COST_LAYER_ADDITION) - the most expensive key), because a key with M3-shift brings 2 finger repeats: one as first part in a bigram and the second as second part.
mods_on_same_hand_adjustment = 1/32
repeats = collections.Counter()
# now get the base keys.
if layer1 == 0:
base1 = r1
else:
base1 = layout.pos_to_char(pos1[:2] + (0, ))
if layer2 == 0:
base2 = r2
else:
base2 = layout.pos_to_char(pos2[:2] + (0, ))
# add the base keys as repeat
try: repeats[base1+base2] += num
except KeyError: repeats[base1+base2] = num
# now check for the mods which are needed to get the key
# if the pos is left, we need the modifiers on the right.
if layout.pos_is_left(pos1):
mods1 = mods[layer1][1]
else:
mods1 = mods[layer1][0]
if layout.pos_is_left(pos2):
mods2 = mods[layer2][1]
else:
mods2 = mods[layer2][0]
# now we have the mods, so we do the splitting by mods.
for m1 in mods1:
# each of the mods with the key itself
try: repeats[m1+base1] += num
except KeyError: repeats[m1+base1] = num
# each mod of the first with each mod of the second
for m2 in mods2:
try: repeats[m1+m2] += num
except KeyError: repeats[m1+m2] = num
# each of the first mods with the second base key
# counted only 0.5 as strong, because the mod is normally hit and released short before the key is.
try: repeats[m1+base2] += 0.5*num
except KeyError: repeats[m1+base2] = 0.5*num
# the first base key with the second mods.
# counted 2x as strong, because the mod is normally hit and released short before the key is.
for m2 in mods2:
try: repeats[base1+m2] += 2*num
except KeyError: repeats[base1+m2] = 2*num
# also the second mod with the second base key
try: repeats[m2+base2] += num
except KeyError: repeats[m2+base2] = num
# the mods of the first with each other
# 0123 → 01 02 03 12 13 23
if mods1[1:]:
for i in range(len(mods1)):
for m2 in mods1[i+1:]:
try: repeats[mods1[i]+m2] += num*mods_on_same_hand_adjustment
except KeyError: repeats[mods1[i]+m2] = num*mods_on_same_hand_adjustment
# the mods of the second with each other
# 0123 → 01 02 03 12 13 23
if mods2[1:]:
for i in range(len(mods2)):
for m2 in mods2[i+1:]:
try: repeats[mods2[i]+m2] += num*mods_on_same_hand_adjustment
except KeyError: repeats[mods2[i]+m2] = num*mods_on_same_hand_adjustment
return repeats
def split_uppercase_repeats(reps, layout=Layouts.NEO2):
"""Split bigrams with uppercase letters (or others with any mod) into several lowercase bigrams by adding bigrams with mods and the base key.
Note: Using a collections.Counter() does not make this faster -- neither for pypy nor for cPython.
Ab -> shift-a, shift-b, a-b.
aB -> a-shift, shift-b, a-b.
AB -> shift-a, shift-b, a-b, 0.5*(shift_L-shift_R, shift_R-shift_L)
(a -> mod3-n, mod3-a, n-a.
() -> mod3L-n, mod3L-r, n-r, 0.5*(mod3L-mod3L, mod3L-mod3L)
(} -> mod3L-n, mod3R-e, n-e, 0.5*(mod3L-mod3R, mod3R-mod3L)
∃ℕ -> mod3R-e, mod4R-e, mod3L-n, mod4L-n,
mod3R-n, mod4R-n, e-mod3L, e-mod4L,
mod3R-mod3L, mod3R-mod4L, mod4R-mod3L, mod4R-mod4L,
0.5*(mod3R-mod4R, mod4R-mod3R, mod3L-mod4L, mod4L-mod3L)
Ψ∃:
# Modifiers from different keys
'⇩⇙', M3L + M4R
'⇩⇘', M3L + M3R
'⇚⇙', M4L + M4R # TODO: M4L is hit with the ringfinger, here. Take that into account.
'⇚⇘', M4L + M3R # TODO: M4L is hit with the ringfinger, here. Take that into account.
# The different Modifiers of one of the keys with each other
# sorted – should that be (m3-m4, m4-m3)/64?
'⇩⇚', M3L + M4L / 32 (because this mistakenly gives a finger repeat, since we can’t yet simulate hitting M4 with the ringfinger and M3 with the pinky. # TODO: M4L is hit with the ringfinger, here. Take that into account.
'⇘⇙', M3R + M4R / 32
# Modifiers with the corresponding base keys
'⇩h', M3L + h
'⇚h', M4L + h
'⇙e', M4R + e
'⇘e', M3R + e
# Modifiers with the other base key
'⇩e', shiftL + e
'⇚e', M4L + e # TODO: M4L is hit with the ringfinger, here. Take that into account.
'h⇙', h + M4R
'h⇘', h + M3R
# The base keys on the base layer
'he'
>>> reps = [(36, "ab"), (24, "Ab"), (16, "aB"), (10, "AB"), (6, "¾2"), (4, "(}"), (2, "Ψ∃"), (1, "q")]
>>> list(reversed(sorted([(j,i) for i, j in split_uppercase_repeats(reps).items()])))
[(86, 'ab'), (52, 'a⇧'), (34, '⇗a'), (26, '⇧b'), (17.0, '⇗b'), (10, '⇗⇧'), (8, 'n⇘'), (6, '⇩⇘'), (6, '⇘e'), (6, '¾2'), (4, '⇩n'), (4, 'ne'), (4, 'h⇙'), (4, 'h⇘'), (3.0, '⇩e'), (2, '⇩⇙'), (2, '⇩h'), (2, '⇚⇙'), (2, '⇚⇘'), (2, '⇚h'), (2, '⇙e'), (2, 'he'), (1.0, '⇚e'), (0.0625, '⇩⇚'), (0.0625, '⇘⇙')]
>>> reps = [(1, ", ")]
>>> from layout_base import Layout, Layouts
>>> layout = Layout.from_string("äuobp kglmfx+\\naietc hdnrsß\\n⇚.,üpö qyzwv", base_layout=Layouts.NEO2)
>>> list(reversed(sorted([(j,i) for i, j in split_uppercase_repeats(reps, layout=layout).items()])))
[(1, ', ')]
"""
# replace uppercase by ⇧ + char1 and char1 + char2 and ⇧ + char2
# char1 and shift are pressed at the same time
#: The resulting bigrams after splitting.
repeats = collections.Counter()
_sur = _split_uppercase_repeat
_mods = MODIFIERS_PER_LAYER
for num, rep in reps:
# this function gets called 100k times. Microoptimize the hell out of it.
for key, val in _sur(rep, num, layout=layout, mods=_mods,).items():
try:
repeats[key] += val
except KeyError:
repeats[key] = val
return repeats
#reps = [(num, rep) for rep, num in repeats.items()]
#reps.sort()
#reps.reverse()
#return reps
def repeats_in_file(data):
"""Sort the repeats in a file by the number of occurrances.
>>> data = read_file("testfile")
>>> repeats_in_file(data)[:3]
[(2, 'a\\n'), (2, 'Aa'), (1, 'ui')]
"""
repeats = collections.Counter()
for i in range(len(data)-1):
rep = data[i] + data[i+1]
try:
repeats[rep] += 1
except KeyError:
repeats[rep] = 1
sorted_repeats = [(repeats[i], i) for i in repeats]
sorted_repeats.sort(reverse=True)
#reps = split_uppercase_repeats(sorted_repeats) # wrong place
return sorted_repeats
def split_uppercase_letters(reps, layout):
"""Split uppercase letters (or others with any mod) into two lowercase letters (with the mod).
>>> letters = [(4, "a"), (3, "A")]
>>> split_uppercase_letters(letters, layout=Layouts.NEO2)
[(4, 'a'), (3, '⇗'), (3, 'a')]
"""
# replace uppercase by ⇧ and char1
upper = []
repeats = []
for num, rep in reps:
pos = layout.char_to_pos(rep)
if pos and pos[2]:
upper.append((num, rep, pos))
else:
repeats.append((num, rep))
reps = repeats
up = []
for num, rep, pos in upper:
layer_mods = MODIFIERS_PER_LAYER[pos[2]]
if layout.pos_is_left(pos):
for m in layer_mods[1]: # left keys use the right mods
up.append((num, m))
else:
for m in layer_mods[0]: # right keys use the left mods
up.append((num, m))
# also append the base layer key.
up.append((num, layout.pos_to_char((pos[0], pos[1], 0),)))
reps.extend(up)
reps = [(int(num), r) for num, r in reps]
reps.sort(reverse=True)
return reps
def letters_in_file(data):
"""Sort the repeats in a file by the number of occurrances.
>>> data = read_file("testfile")
>>> letters_in_file(data)[:3]
[(5, 'a'), (4, '\\n'), (2, 'r')]
"""
letters = collections.Counter()
for letter in data:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
sort = [(letters[i], i) for i in letters]
sort.sort(reverse=True)
return sort
def unique_sort(liste):
"""Count the occurrence of each item in a list.
>>> unique_sort([1, 2, 1])
[(1, 2), (2, 1)]
"""
counter = collections.Counter()
for i in liste:
if i in counter:
counter[i] += 1
else:
counter[i] = 1
sorted_repeats = [(counter[i], i) for i in counter]
sorted_repeats.sort()
return sorted_repeats
def repeats_in_file_sorted(data):
"""Sort the repeats in a file by the number of occurrances.
>>> data = read_file("testfile")
>>> repeats_in_file_sorted(data)[:2]
[(1, '\\na'), (1, '\\ne')]
"""
repeats = repeats_in_file(data)
repeats.reverse()
return repeats
def _unescape_ngram_list(ngrams):
"""unescape \n and \ in an ngram list."""
for i in range(len(ngrams)):
if "\\" in ngrams[i][1]:
ngrams[i] = (ngrams[i][0], ngrams[i][1].replace("\\\\", "\\"))
ngrams[i] = (ngrams[i][0], ngrams[i][1].replace("\\n", "\n"))
return ngrams
def repeats_in_file_precalculated(data, only_existing=True):
"""Get the repeats from a precalculated file.
>>> data = read_file("2gramme.txt")
>>> repeats_in_file_precalculated(data)[:3]
[(10159250, 'en'), (10024681, 'er'), (9051717, 'n ')]
"""
md5 = hashlib.md5(data.encode("utf-8")).hexdigest()
if ( 'reps_repeats_in_file_precalculated' not in repeats_in_file_precalculated.__dict__ or
md5 not in repeats_in_file_precalculated.reps_repeats_in_file_precalculated):
if 'reps_repeats_in_file_precalculated' not in repeats_in_file_precalculated.__dict__:
repeats_in_file_precalculated.reps_repeats_in_file_precalculated = {}
reps = [line.lstrip().split(" ", 1) for line in data.splitlines() if line.lstrip().split(" ", 1)[1:]]
if only_existing:
all_keys = Layouts.NEO2.get_all_chars()
try:
reps = [(int(num), r) for num, r in reps if r[1:] and r[0] in all_keys and r[1] in all_keys]
except ValueError: # we got floats
reps = [(float(num), r) for num, r in reps if r[1:] and r[0] in all_keys and r[1] in all_keys]
else:
try:
reps = [(int(num), r) for num, r in reps if r[1:]]
except ValueError: # we got floats
reps = [(float(num), r) for num, r in reps if r[1:]]
# cleanup
_unescape_ngram_list(reps)
repeats_in_file_precalculated.reps_repeats_in_file_precalculated[md5] = reps
return repeats_in_file_precalculated.reps_repeats_in_file_precalculated[md5]
else:
return repeats_in_file_precalculated.reps_repeats_in_file_precalculated[md5]
def split_uppercase_trigrams(trigs):
"""Split uppercase repeats into two to three lowercase repeats.
Here we don’t care about shift-collisions with the “second” letter, because we only use it for handswitching and the shift will always mean a handswitch afterwards (opposing shift). ⇒ Ab → Sh-ab, ignoring a-Sh-b. ⇒ for handswitching ignore trigrams with any of the shifts.
>>> trigs = [(8, "abc"), (7, "Abc"), (6, "aBc"), (5, "abC"), (4, "ABc"), (3, "aBC"), (2, "AbC"), (1, "ABC")]
>>> split_uppercase_trigrams(trigs)
[(15, 'abc'), (7, 'a⇧b'), (7, 'a⇗b'), (5, '⇧bc'), (5, '⇗bc'), (5, 'b⇧c'), (5, 'b⇗c'), (4, '⇧ab'), (4, '⇗ab'), (3, 'ab⇧'), (3, 'ab⇗'), (2, '⇧b⇧'), (2, '⇧b⇗'), (2, '⇧a⇧'), (2, '⇧a⇗'), (2, '⇗b⇧'), (2, '⇗b⇗'), (2, '⇗a⇧'), (2, '⇗a⇗')]
"""
# replace uppercase by ⇧ + char1 and char1 + char2
upper = [(num, trig) for num, trig in trigs if not trig == trig.lower() and trig[2:]]
# and remove them temporarily from the list of trigrams - don’t compare list with list, else this takes ~20min!
trigs = [(num, trig) for num, trig in trigs if trig == trig.lower() and trig[2:]]
up = []
# since this gets a bit more complex and the chance to err is high,
# we do this dumbly, just checking for the exact cases.
# TODO: Do it more elegantly: Replace every uppercase letter by "⇧"+lowercase
# and then turn the x-gram into multiple 3grams (four[:-1], four[1:]; five… ).
for num, trig in upper:
# Abc
if not trig[0] == trig[0].lower() and trig[1] == trig[1].lower() and trig[2] == trig[2].lower():
up.append((max(1, num//2), "⇧"+trig[:2].lower()))
up.append((max(1, num//2), "⇗"+trig[:2].lower()))
up.append((num, trig.lower()))
# aBc
elif trig[0] == trig[0].lower() and not trig[1] == trig[1].lower() and trig[2] == trig[2].lower():
up.append((max(1, num//2), "⇧"+trig[1:].lower()))
up.append((max(1, num//2), "⇗"+trig[1:].lower()))
up.append((max(1, num//2), trig[0].lower()+"⇧"+trig[1].lower()))
up.append((max(1, num//2), trig[0].lower()+"⇗"+trig[1].lower()))
# abC
elif trig[0] == trig[0].lower() and trig[1] == trig[1].lower() and not trig[2] == trig[2].lower():
up.append((max(1, num//2), trig[:2].lower() + "⇧"))
up.append((max(1, num//2), trig[:2].lower() + "⇗"))
up.append((max(1, num//2), trig[1].lower()+"⇧"+trig[2].lower()))
up.append((max(1, num//2), trig[1].lower()+"⇗"+trig[2].lower()))
# ABc (4, '⇧a⇧'), (4, 'a⇧b'), (4, '⇧bc')
elif not trig[0] == trig[0].lower() and not trig[1] == trig[1].lower() and trig[2] == trig[2].lower():
up.append((max(1, num//4), "⇧"+trig[0].lower()+"⇧"))
up.append((max(1, num//2), trig[0].lower()+"⇧"+trig[1].lower()))
up.append((max(1, num//2), "⇧" + trig[1:].lower()))
up.append((max(1, num//4), "⇗"+trig[0].lower()+"⇧"))
up.append((max(1, num//4), "⇧"+trig[0].lower()+"⇗"))
up.append((max(1, num//4), "⇗"+trig[0].lower()+"⇗"))
up.append((max(1, num//2), trig[0].lower()+"⇗"+trig[1].lower()))
up.append((max(1, num//2), "⇗" + trig[1:].lower()))
# aBC (3, 'a⇧b'), (3, '⇧b⇧'), (3, 'b⇧c')
elif trig[0] == trig[0].lower() and not trig[1] == trig[1].lower() and not trig[2] == trig[2].lower():
up.append((max(1, num//4), "⇧"+trig[1].lower()+"⇧"))
up.append((max(1, num//2), trig[0].lower()+"⇧"+trig[1].lower()))
up.append((max(1, num//2), trig[1].lower()+"⇧"+trig[2].lower()))
up.append((max(1, num//4), "⇗"+trig[1].lower()+"⇧"))
up.append((max(1, num//4), "⇧"+trig[1].lower()+"⇗"))
up.append((max(1, num//4), "⇗"+trig[1].lower()+"⇗"))
up.append((max(1, num//2), trig[0].lower()+"⇗"+trig[1].lower()))
up.append((max(1, num//2), trig[1].lower()+"⇗"+trig[2].lower()))
# AbC (2, '⇧ab'), (2, 'ab⇧'), (2, 'b⇧c')
elif not trig[0] == trig[0].lower() and trig[1] == trig[1].lower() and not trig[2] == trig[2].lower():
up.append((max(1, num//2), "⇧" + trig[:2].lower()))
up.append((max(1, num//2), trig[:2].lower() + "⇧"))
up.append((max(1, num//2), trig[1].lower()+"⇧"+trig[2].lower()))
up.append((max(1, num//2), "⇗" + trig[:2].lower()))
up.append((max(1, num//2), trig[:2].lower() + "⇗"))
up.append((max(1, num//2), trig[1].lower()+"⇗"+trig[2].lower()))
# ABC (1, '⇧a⇧'), (1, 'a⇧b'), (1, '⇧b⇧'), (1, 'b⇧c')
elif not trig[0] == trig[0].lower() and not trig[1] == trig[1].lower() and not trig[2] == trig[2].lower():
up.append((max(1, num//4), "⇧"+trig[0].lower()+"⇧"))
up.append((max(1, num//2), trig[0].lower()+"⇧"+trig[1].lower()))
up.append((max(1, num//4), "⇧"+trig[1].lower()+"⇧"))
up.append((max(1, num//2), trig[1].lower()+"⇧"+trig[2].lower()))
up.append((max(1, num//4), "⇗"+trig[0].lower()+"⇧"))
up.append((max(1, num//4), "⇧"+trig[0].lower()+"⇗"))
up.append((max(1, num//4), "⇗"+trig[0].lower()+"⇗"))
up.append((max(1, num//4), "⇗"+trig[1].lower()+"⇧"))
up.append((max(1, num//4), "⇧"+trig[1].lower()+"⇗"))
up.append((max(1, num//4), "⇗"+trig[1].lower()+"⇗"))
up.append((max(1, num//2), trig[0].lower()+"⇗"+trig[1].lower()))
up.append((max(1, num//2), trig[1].lower()+"⇗"+trig[2].lower()))
trigs.extend(up)
trigs = [(num, r) for num, r in trigs if r[1:]]
t = collections.Counter()
for num, r in trigs:
try: t[r] += num
except KeyError: t[r] = num
trigs = [(num, r) for r, num in t.items()]
trigs.sort(reverse=True)
return trigs
def split_uppercase_trigrams_correctly(trigs, layout, just_record_the_mod_key=False):
"""Split uppercase repeats into two to three lowercase repeats.
Definition:
a → b → c
| × | × |
sa→ sb→ sc
senkrechte nur nach oben. Kreuze und Pfeile nur nach vorne. Alle Trigramme, die du aus dem Bild basteln kannst.
>>> trigs = [(8, "abc"), (7, "∀bC"), (6, "aBc"), (5, "abC"), (4, "ABc"), (3, "aBC"), (2, "AbC"), (1, "ABC")]
>>> # split_uppercase_trigrams_correctly(trigs, Layouts.NEO2)
"""
# kick out any who don’t have a position
pos_trig = [(num, [layout.char_to_pos(char) for char in trig], trig) for num, trig in trigs]
pos_trig = [(num, pos, trig) for num, pos, trig in pos_trig if not None in pos]
# get all trigrams with non-baselayer-keys
upper = [(num, pos, trig) for num, pos, trig in pos_trig if True in [p[2]>0 for p in pos]]
# and remove them temporarily from the list of trigrams - don’t compare list with list, else this takes ~20min!
trigs = [(num, trig) for num, pos, trig in pos_trig if not True in [p[2]>0 for p in pos]]
#: The trigrams to add to the baselayer trigrams
up = []
mod = MODIFIERS_PER_LAYER
for num, pos, trig in upper:
print(trig)
# lower letters
l0 = layout.pos_to_char((pos[0][0], pos[0][1], 0))
l1 = layout.pos_to_char((pos[1][0], pos[1][1], 0))
l2 = layout.pos_to_char((pos[2][0], pos[2][1], 0))
# mods
m0 = mod[pos[0][2]]
m1 = mod[pos[1][2]]
m2 = mod[pos[2][2]]
### Algorithm
algo = """
a → b → c
| × | × |
sa→ sb→ sc
| × | × | ; seperate dimension. ma is connected to a and sa.
ma→ mb→ mc
"""
#: Matrix der Tasten und Modifikatoren
m = []
for p, c in zip(pos, (l0, l1, l2)):
mx = mod[p[2]] # liste mit bis zu 2 mods
if just_record_the_mod_key:
mx = [i+c for i in mx[0]]
elif layout.pos_is_left(p):
mx = mx[1]
else: mx = mx[0]
col = [c]
if mx:
col.append(mx[0])
else: col.append(None)
if mx[1:]:
col.append(mx[1])
else: col.append(None)
m.append(col)
# Matrix created
#: All possible starting positions for trigrams in that matrix
sp = [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2), (2,1), (2,2)] # not last letter
# reduce the starting positions to the actually existing letters.
sp = [p for p in sp if m[p[0]][p[1]] is not None]
#: All possible paths in the matrix for letters
paths = [(1,0), (1,1), (1,2)]
#: Additional possible paths for modifiers
mod_paths = [(0,1), (0,2)]
#: The new trigrams which get created due to splitting.
new_trigs = [] # option: take a set to avoid double entries.
# move all paths
for s in sp:
#: trigrams of matrix positions [(p0, p1, p2), …]
tri = []
#: bigrams of matrix positions [(p0, p1), …]
tr = []
# try all possible path for two steps.
#: the paths
p = paths[:]
# modifiers get extra options
if s[1]: p.extend(mod_paths)
# try all paths, append to tr if not None
for n in p:
new_pos = (s[0] + n[0], (s[1] + n[1])%3)
try:
if m[new_pos[0]][new_pos[1]] is not None:
tr.append((s, new_pos))
except IndexError: # left the matrix
pass
# now try all paths, starting from the positions in tr.
for s,t in tr:
#: the paths
p = paths[:]
# modifiers get extra options
if t[1]: p.extend(mod_paths)
for n in p:
new_pos = (t[0]+n[0], (t[1] + n[1])%3)
try:
if m[new_pos[0]][new_pos[1]] is not None:
tri.append((s, t, new_pos))
except IndexError: # left the matrix
pass
print([m[s[0]][s[1]]+m[t[0]][t[1]]+m[n[0]][n[1]] for s,t,n in tri])
new_trigs.extend([m[s[0]][s[1]]+m[t[0]][t[1]]+m[n[0]][n[1]] for s,t,n in tri])
for tri in new_trigs:
up.append((num, tri))
print (up)
trigs.extend(up)
trigs = [(int(num), r) for num, r in trigs if r[1:]]
trigs.sort(reverse=True)
return trigs
def trigrams_in_file(data, only_existing=True):
"""Sort the trigrams in a file by the number of occurrances.
>>> data = read_file("testfile")
>>> trigrams_in_file(data)[:4]
[(4, '⇧aa'), (4, '⇗aa'), (2, 't⇧a'), (2, 't⇗a')]
"""
trigs = collections.Counter()
for i in range(len(data)-2):
trig = data[i] + data[i+1] + data[i+2]
if trig in trigs:
trigs[trig] += 1
else:
trigs[trig] = 1
if only_existing:
all_keys = Layouts.NEO2.get_all_chars()
sorted_trigs = [(trigs[i], i) for i in trigs if i[2:] and i[0] in all_keys and i[1] in all_keys and i[2] in all_keys]
else:
sorted_trigs = [(trigs[i], i) for i in trigs if i[2:]]
sorted_trigs.sort(reverse=True)
trigs = split_uppercase_trigrams(sorted_trigs)
return trigs
def ngrams_in_filepath(datapath, slicelength=1000000):
"""Sort the trigrams in a file by the number of occurrances.
>>> lett, big, trig = ngrams_in_filepath("testfile")
>>> lett[:3]
[(5, 'a'), (4, '\\n'), (2, 'r')]
>>> big[:3]
[(2, 'a\\n'), (2, 'Aa'), (1, 'ui')]
>>> trig[:10]
[(4, '⇧aa'), (4, '⇗aa'), (2, 't⇧a'), (2, 't⇗a'), (2, 'a⇧a'), (2, 'a⇗a'), (2, 'aa\\n'), (1, 'uia'), (1, 'rt⇧'), (1, 'rt⇗')]
"""
f = open(datapath, encoding="utf-8", errors="ignore")
letters = collections.Counter()
repeats = collections.Counter()
trigs = collections.Counter()
data = f.read(slicelength)
step = 0
while data[2:]:
if step == 1:
print("reading ngrams from", datapath)
if step:
print("read ~", int(f.tell()/10000)/100, "MiB")
step += 1
for i in range(len(data)-2):
letter = data[i]
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
rep = data[i] + data[i+1]
if rep in repeats:
repeats[rep] += 1
else:
repeats[rep] = 1
trig = data[i] + data[i+1] + data[i+2]
if trig in trigs:
trigs[trig] += 1
else:
trigs[trig] = 1
data = data[-2:] + f.read(slicelength)
# final two letters
for letter in data:
if letter in letters:
letters[letter] += 1
else:
letters[letter] = 1
# final bigram
rep = data[-2] + data[-1]
if rep in repeats:
repeats[rep] += 1
else:
repeats[rep] = 1
letters = [(letters[i], i) for i in letters]
letters.sort(reverse=True)
repeats = [(repeats[i], i) for i in repeats]
repeats.sort(reverse=True)
trigs = [(trigs[i], i) for i in trigs]
trigs.sort(reverse=True)
# split uppercase trigrams here, because we really want to do that only *once*.
trigs = split_uppercase_trigrams(trigs)
return letters, repeats, trigs
def trigrams_in_file_precalculated(data, only_existing=True):
"""Get the repeats from a precalculated file.
CAREFUL: SLOW!
>>> data = read_file("3gramme.txt")
>>> trigrams_in_file_precalculated(data)[:6]
[(5678553, 'en '), (4467769, 'er '), (2891228, ' de'), (2493088, 'der'), (2304026, 'sch'), (2272028, 'ie ')]
"""
md5 = hashlib.md5(data.encode("utf-8")).hexdigest()
if ( 'trigs_trigrams_in_file_precalculated' not in trigrams_in_file_precalculated.__dict__ or
md5 not in trigrams_in_file_precalculated.trigs_trigrams_in_file_precalculated):
if 'trigs_trigrams_in_file_precalculated' not in trigrams_in_file_precalculated.__dict__:
trigrams_in_file_precalculated.trigs_trigrams_in_file_precalculated = {}
trigs = [line.lstrip().split(" ", 1) for line in data.splitlines() if line.split()[1:]]
if only_existing:
all_keys = Layouts.NEO2.get_all_chars()
try:
trigs = [(int(num), r) for num, r in trigs if r[2:] and r[0] in all_keys and r[1] in all_keys and r[2] in all_keys]
except ValueError: # we got floats
trigs = [(float(num), r) for num, r in trigs if r[2:] and r[0] in all_keys and r[1] in all_keys and r[2] in all_keys]
else:
try:
trigs = [(int(num), r) for num, r in trigs if r[2:]]
except ValueError: # we got floats
trigs = [(float(num), r) for num, r in trigs if r[2:]]
# cleanup
_unescape_ngram_list(trigs)
trigs = split_uppercase_trigrams(trigs)
trigrams_in_file_precalculated.trigs_trigrams_in_file_precalculated[md5] = trigs
return trigs
else:
return trigrams_in_file_precalculated.trigs_trigrams_in_file_precalculated[md5]
def letters_in_file_precalculated(data, only_existing=True):
"""Get the repeats from a precalculated file.
>>> data = read_file("1gramme.txt")
>>> letters_in_file_precalculated(data)[:3]
[(46474641, ' '), (44021504, 'e'), (26999087, 'n')]
"""
md5 = hashlib.md5(data.encode("utf-8")).hexdigest()
if ( 'ret_letters_in_file_precalculated' not in letters_in_file_precalculated.__dict__ or
md5 not in letters_in_file_precalculated.__dict__['ret_letters_in_file_precalculated']):
if 'ret_letters_in_file_precalculated' not in letters_in_file_precalculated.__dict__:
letters_in_file_precalculated.ret_letters_in_file_precalculated = {}
letters = [line.lstrip().split(" ", 1) for line in data.splitlines() if line.split()[1:] or line[-2:] == " "]
# cleanup
_unescape_ngram_list(letters)
try:
if only_existing:
all_keys = Layouts.NEO2.get_all_chars()
letters_in_file_precalculated.ret_letters_in_file_precalculated[md5] = [(int(num), let) for num, let in letters if let in all_keys]
return letters_in_file_precalculated.ret_letters_in_file_precalculated[md5]
else:
letters_in_file_precalculated.ret_letters_in_file_precalculated[md5] = [(int(num), let) for num, let in letters if let]
return letters_in_file_precalculated.ret_letters_in_file_precalculated[md5]
except ValueError: # floats in there
if only_existing:
all_keys = Layouts.NEO2.get_all_chars()
letters_in_file_precalculated.ret_letters_in_file_precalculated[md5] = [(float(num), let) for num, let in letters if let in all_keys]
return letters_in_file_precalculated.ret_letters_in_file_precalculated[md5]
else:
letters_in_file_precalculated.ret_letters_in_file_precalculated[md5] = [(float(num), let) for num, let in letters if let]
return letters_in_file_precalculated.ret_letters_in_file_precalculated[md5]
else:
return letters_in_file_precalculated.ret_letters_in_file_precalculated[md5]
def clean_data(data):
"""Remove cruft from loaded data"""
if data[:1] == "\ufeff":
data = data[1:]
return data
def fix_impossible_ngrams(data, layout=None):
"""Make sure that we get the best possible data:
1. Correct the representation of some symbols. (Tabs can be "⇥" or "\\t")
2. Remove the ngrams that can't be typed using a specified layout
If no layout is specified, the ngrams aren't changed.
"""
if layout:
# The list of possible inputs in a given layout
keys = layout.get_all_chars()
# Make sure the correct tab-syntax is shown in the ngrams
if ("⇥" in keys) and not ("\t" in keys):
# Replace all "\t" with "⇥"
for tuple_idx, (num, ngram) in enumerate(data):
if "\t" in ngram:
corrected_ngram = ngram.replace("\t", "⇥")
data[tuple_idx] = (num, corrected_ngram)
elif ("\t" in keys) and not ("⇥" in keys):
# Replace all "⇥" with "\t"
for tuple_idx, (num, ngram) in enumerate(data):
if "⇥" in ngram:
corrected_ngram = ngram.replace("⇥", "\t")
data[tuple_idx] = (num, corrected_ngram)
# def can_be_typed(ngram_tuple):
# """Check if a ngram can be typed"""
# ngram = ngram_tuple[1]
# for letter in ngram:
# if letter not in keys:
# #print("filtered trig:", ngram)
# #print("crucial letter:", letter.encode("unicode_escape"))
# #print()
# return False
# return True
# data = list(filter(can_be_typed, data))
return data
else:
# Do nothing
return data
def ngrams_in_data(data):
"""Get ngrams from a dataset."""
letters = letters_in_file(data)
repeats = bigrams = repeats_in_file(data)
trigrams = trigrams_in_file(data)
return letters, repeats, trigrams
### Classes
class FileNotFoundException(Exception):
def __str__(self):
return repr(self.parameter)
class ParseException(Exception):
def __str__(self):
return repr(self.parameter)
class NGrams(object):
"""
NGrams contains ngrams from various sources in raw and weighted
form and can export them to the simple (1gramme.txt, 2gramme.txt,
3gramme.txt) form with a given number of total keystrokes.
self.one, self.two and self.three are dictionaries of 1grams, 2grams and threegrams with their respective probability of occurring.
"""
def __init__(self, config):
"""Create an ngrams object.
config: plain text file (utf-8 encoded).
# ngrams source v0.1
weight type filepath
# comment
weight type filepath
…
>>> ngrams = NGrams('ngrams_test.config')
Reading text testfile
Reading bla errortest
unrecognized filetype bla errortest
>>> ngrams.raw
[(1.0, ([(5, 'a'), (4, '\\n'), (2, 'r'), (2, 'e'), (2, 'A'), (1, 'u'), (1, 't'), (1, 'o'), (1, 'n'), (1, 'i'), (1, 'g'), (1, 'd')], [(2, 'a\\n'), (2, 'Aa'), (1, 'ui'), (1, 'tA'), (1, 'rt'), (1, 'rg'), (1, 'od'), (1, 'nr'), (1, 'ia'), (1, 'g\\n'), (1, 'eo'), (1, 'en'), (1, 'd\\n'), (1, 'ae'), (1, 'aa'), (1, 'aA'), (1, '\\nr'), (1, '\\ne'), (1, '\\na')], [(4, '⇧aa'), (4, '⇗aa'), (2, 't⇧a'), (2, 't⇗a'), (2, 'a⇧a'), (2, 'a⇗a'), (2, 'aa\\n'), (1, 'uia'), (1, 'rt⇧'), (1, 'rt⇗'), (1, 'rg\\n'), (1, 'od\\n'), (1, 'nrt'), (1, 'iae'), (1, 'g\\na'), (1, 'eod'), (1, 'enr'), (1, 'd\\nr'), (1, 'aen'), (1, 'aa⇧'), (1, 'aa⇗'), (1, 'a\\ne'), (1, '\\nrg'), (1, '\\neo'), (1, '\\naa')]))]
"""
# read the config.
try:
with open(config, encoding="utf-8") as f:
self.config = f.read()
except IOError:
raise FileNotFoundException("File", config, "can’t be read.")
if self.config.startswith("# ngrams source v0.0"):
self.parse_config_0_0()
elif self.config.startswith("# ngrams source v0.1"):
self.parse_config_0_1()
else:
raise ParseException("ngrams config has no version header. Please start it with # ngrams source v<version>")
self.normalize_raw() # gets one, two and three
def finalize(self):
"""Do ngrams adjustments for ngram-files which are going to be used directly, but which are not suitable for intermediate files (must be done only once)."""
# increases the weight for ngrams which are shorts in steno: profit from 100 years of professional writing experience.
self.weight_steno()
self.weight_punctuation()
def diff(self, other):
"""Compare two ngram distributions.
>>> n = NGrams('ngrams_test_diff.config')
Reading pregenerated 1-gramme.arne.txt;2-gramme.arne.txt;3-gramme.arne.txt
>>> from copy import deepcopy
>>> m = deepcopy(n)
>>> m.one["a"] += 0
>>> n.diff(m)
[{}, {}, {}]
>>> m.one["a"] += 3
>>> n.diff(m)[1:]
[{}, {}]
>>> str(n.diff(m)[0]["a"])[:7]
'-2.8652'
@return the differences of the normalized 1-, 2- and 3grams as dicts.
"""
def _normalize_dict(d):
"""Normalize a dict to have a valuesum of 1"""
s = sum(d.values())
# no zero division
if s == 0:
return d
return {key: num/s for key, num in d.items()}
def _diffdict(d1, d2):
"""All different keys with the difference."""
diff = {key: d1[key] - d2[key] for key in d1 if key in d2 and abs(d1[key] - d2[key]) > 1.0e-14}
# python floats normally should have binary precision 53,
# but with 1.0e-15 I still get stray results when diffing
# the same dictionary.
for key in d1:
if key in d2: continue
diff[key] = d1[key]
for key in d2:
if key in d1: continue
diff[key] = -d2[key]
return diff
# normalized
one = _normalize_dict(self.one)
two = _normalize_dict(self.two)
three = _normalize_dict(self.three)
o1 = _normalize_dict(other.one)
o2 = _normalize_dict(other.two)
o3 = _normalize_dict(other.three)
return [_diffdict(s, o) for s, o in ((one, o1), (two, o2), (three, o3))]
def parse_config_0_1(self):
lines = self.config.splitlines()
# the raw list of included ngrams.
self.raw = []
for l in lines[1:]:
# # start a comment
if l.startswith("#"):
continue
parts = l.split()
weight, typ = parts[:2]
weight = float(weight)
datapath = l[l.index(typ)+len(typ)+1:]
print ("Reading", typ, datapath)
if typ=="text":
one, two, three = ngrams_in_filepath(datapath=datapath)
self.raw.append((weight, (one, two, three)))
elif typ=="pykeylogger":
one, two, three = self.read_pykeylogger_logfile(datapath)
self.raw.append((weight, (one, two, three)))
elif typ=="pregenerated":
onegrams, twograms, threegrams = datapath.split(";")
letterdata = clean_data(read_file(onegrams))
one = letters_in_file_precalculated(letterdata)
bigramdata = clean_data(read_file(twograms))
two = repeats_in_file_precalculated(bigramdata)
trigramdata = clean_data(read_file(threegrams))
three = trigrams_in_file_precalculated(trigramdata)
self.raw.append((weight, (one, two, three)))
elif typ=="maildir":
one, two, three = self.read_maildir_dir(datapath)
self.raw.append((weight, (one, two, three)))
elif typ=="chatlog":
one, two, three = self.read_mirc_chatlog(datapath)
self.raw.append((weight, (one, two, three)))
else: print("unrecognized filetype", typ, datapath)
def read_maildir_dir(self, folderpath):
"""Read all message contents from within a maildir folder.
see http://docs.python.org/library/mailbox.html#mailbox.Maildir
"""
text = ""
from mailbox import Maildir
from termctrl import home, erase
m = Maildir(folderpath)
num = 0
for message in m.itervalues():
home()
print (num, "/", len(m), end="")
text += self._maildir_message_own_content(message)
num += 1
home()
erase()
one, two, three = ngrams_in_data(data=text)
return one, two, three
def _maildir_message_own_content(self, message):
"""Remove all quotes and headers from the message.
@return string of the content which was written by the author."""
import quopri
text = ""
for t in message.walk():
if t.get_content_type() == "text/plain":
# remove quoted printable
# the following should work, but does not.
# body = quopri.decodestring(t.as_string())
# fix directly from quopri:
from io import BytesIO
infp = BytesIO(t.as_string().encode("utf-8"))
outfp = BytesIO()
quopri.decode(infp, outfp, header=False)
try:
body = outfp.getvalue().decode("utf-8")
except UnicodeDecodeError:
try: body = outfp.getvalue().decode("iso-8859-1")