-
Notifications
You must be signed in to change notification settings - Fork 0
/
dicstrv.py
3369 lines (2676 loc) · 116 KB
/
dicstrv.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
# LIGHTWEIGHT ENGLISH TEXT STREAM COMPRESSION (LETSC)
# (adaptive encoding length 1byte/2byte/3byte based on word dictionary with statistical prevalence ordering - count1_w.txt)
# Huffmann encoding for uknown tokens
# Enforces English syntax rules for punctuation
# Takes into account possessives and contractions
# Has URLs and e-mails processing rules, more to follow
# Second pass compression using a dictionary of the most frequent 4 N-Grams of English fiction.
#GPL 3 License
# www.skynext.tech
# Rodrigo Verissimo
# v0.94
# April 25th, 2024
# Python + packages Requirements
# Python 3.9
# nltk, bitarray, bitstring, re, dahuffmann
# Performance : ratios between x2.6 for Middle to Modern and elaborate English (ex: Shakespeare)
# Up to x3 and more for simple english.
# adapted for text messaging / streaming
# Requires the same dictionary on both channel endpoints.
# ALGORITHM. Very straightforward. (adaptive encoding length based on dictionary with statistical ordering)
#################################################################################
# First byte :
#if MSB is 0, a whole word is encoded on the first 7 bits of one byte only.
#This makes 127 possible words. These are reserved for the first 127 most used
#english words. punctuation also appears as a possible word
# Second byte :
#if MSB of first byte is 1, and MSB of second byte is 0, a whole word is encoded
# with the help of the 7 LSB of byte 1 plus the 7 LSB of byte 2.
# This makes room for the next 16384 most used english words.
# Third byte :
# if MSB of first byte is 1 and MSB of second byte is 1, and the MSB of third byte is 0
# a whole word is encoded
# with the help of the 7 + 7 + 7 = 21 bits (2 097 152 possible words)
# For now, the 3 byte address space is split into two 2 097 152 address spaces
# That is, the case of all 3 bytes MSB being 1 is treated separately.
# In this adress space, only a handful of codes are used as an escape sequence for particular
# Huffmann trees, see below.
#->
#load dictionary of english words from most used to least used.
#punctuation and special characters have been added with order of prevalence.
#punctuation frequency is from wikipedia corpus. (around 1.3 billion words)
#it has been normalized to the frequency of the 1/3 million word list based
#on the google web trillon word corpus. that is, frequencies for special chars have been multiplied by 788.39
#wikipedia punctuation is not optimized for chat, as it lower prevalence of chars like question marks
#that may appear more frequently in chat situations.
# the first tokenizer used does not separate any special character attached (without whitespace) to a word
# this will mostly result in an unknown word in the dictionary
# this key absence in the reverse dict will be catched and treated by another tokenizer (mainly for possessive
# forms and contractions)
#for possessives ex: "dog's bone" or plural "dogs' bones" a separate tokenizer is used to split into
# "dog" , "'s"
# "'s" and "'" also appear in the dictionary.
# ROADMAP
# remove whitespaces left of punctuation DONE
# manage new lines DONE
# manage websites and emails DONE
# TODO
# add spell check !
# TODO
# Remove spurious new lines that appear after encoding special sequences such mails or URLS
# DONE (basic Huffmann, some chars missing in tree)
# add Huffmann encoding for absent words in dictionary (neologisms,colloqualisms,dialects, or misspellings) DONE
# DONE
# TODO : test with more texts such as wikipedia XML and various authors works, to catch as much
# use cases and formatting issues that arise to improve the algorithm
# add adaptive Huffmann. use 4 Huffmann trees. (see below)
# Assuming there are 4 codes for hufmmann : hufmann lower case, hufmann lower + capitals, huffmann
# lower + capitals + numeric, all printable ASCII excluding whitespace : same as preceding category plus
# special chars.
# Chosing the tree to use would be done by string regex.
#DONE
# Detect UTF-8 and transcode to ASCII (potentially lossy)
#DONE
# TODO
# Dictionary Learn over time (re-shuffle the order of tokens)
# Without transmission of any info between parties
# Dangerous if sync is lost between the two parties
# TODO
# TODO
# optimize Huffmann part to remove the need for the chr(0) termination = scan for EOF sequence in Huffmann to get
# the Huffmann byte sequence length. TODO
# DONE
# Add second pass compression using word N-grams lookup table. (4 and 5 N-grams seem to be a good compromize)
# The idea is to encode 4 and 5 token substrings in a line by a single 3 byte code.
# There is plenty of room left in the 3 byte address space. For now, there is 333 333 - 16384 - 128 tokens used = 316821 tokens used
# from 4194304 - 3 total address space.
# DONE using 1 571 125 codes for a 50/50 mix of 4grams and 5grams.
# There is still at least 2million codes left.
# for now we plan 4 escape sequences for the selection of one of the 4 Huffmann trees.
# ngrams processing is first done with the create_ngrams_dic.sh script.
"""
python3 ngrams_format_dic.py 4grams_english-fiction.csv outngrams4.txt #remove counts and process contractions
python3 ngrams_format_dic.py 5grams_english-fiction.csv outngrams5.txt #remove counts and process contractions
python3 dicstrv4.py -d outngrams4.txt outngrams4.bin.dup #convert ngrams txt to compressed form
python3 dicstrv4.py -d outngrams5.txt outngrams5.bin.dup #convert ngrams txt to compressed form
awk '!seen[$0]++' outngrams4.bin.dup > outngrams4.bin #Remove spurious duplicates that may arise
awk '!seen[$0]++' outngrams5.bin.dup > outngrams5.bin #Remove spurious duplicates that may arise
sed -i '786001,$ d' outngrams4.bin # truncate to fit target address space
sed -i '786001,$ d' outngrams5.bin # truncate to fit target address space
cat outngrams4.bin outngrams5.bin > outngrams.bin # concatenate. this is our final form
cat outngrams.bin | awk '{ print length, bash $0 }' | sort -n -s | cut -d" " -f2- > sorted.txt # sort by size to have an idea of distribution
# ngrams that encode as less than 4 bytes have been pruned since the ratio is 1
"""
# DONE
# It is probable that the most used 4 tokens N-grams are based on already frequent words. that individually
# encode as 1 byte or two bytes.
# Worst case : all the 4 tokens are encoded in the 1 to 128 addres space, so they take a total 4 bytes.
# The resulting code will be 3 bytes, a deflate percent of 25%
# If one of the tokens is 2 byte (128 to 16384 -1 address space), then it uses 5 bytes.
# deflate percent is 40%
# The unknown is the statistical prevalence of two million 4 token N-grams.
# (ex: coming from english fiction corpus) in a standard chat text.
# First encode the google most frequent 4 and 5 N-grams csv file to replace the tokens in each N-gram by the corrsponding
# byte sequences from our codes in the count_1w.txt dictionary. This will be another pre-process script.
# The resulting new csv format will be :
# some 3 byte index = x04x09x23.
# The 3 byte index is simply the line number of the compressed ngram.
# read that in ram. Conservative Estimate 4 bytes + 3 bytes per entry 7 bytes * 2 000 000 = 14 Meg memory footprint.
# We already have a 4 MB * 3 12 Meg footprint from count_1w (estimate)
# Generate the inverse map dictionary (mapping sequences to 3 byte indexes)
# x04x09x23' = some 3 byte index
# Should not be a problem since there is a 1 to 1 relationship between the two
# Then perform a first pass compression.
# Then scan the first pass compression file using a 4 token sliding window.
# Contractions is a case that will have to be managed.
# If there are overlapping matches, chose the match that result in the best deflation, if any.
# If the unknown word escape codes appears, stop processing and resume after the escaped word
# Overall, replace the byte sequence by the corrsponding 3 byte sequence.
# DONE
import sys
import os
import pickle
import traceback
from collections import Counter, OrderedDict
import numpy as np
from itertools import cycle,islice
import codecs
import nltk
from nltk.tokenize import TweetTokenizer
tknzr = TweetTokenizer()
import re
import bitstring
from bitarray import bitarray
import struct
import time
from dahuffman import HuffmanCodec
import pycld2 as cld2
from lingua import Language, LanguageDetectorBuilder
from bidict import bidict
#print(len(sys.argv))
#op = (sys.argv[1]).encode("ascii").decode("ascii")
#print(op)
#quit()
interactive = False
no_final_huf = False
if (sys.argv[1] == "-i"):
interactive = True
batch = False
compress = False
gendic = False
huffmann_only = False
elif (sys.argv[1] == "-c"):
interactive = False
batch = False
compress = True
gendic = False
huffmann_only = False
elif (sys.argv[1] == "-bc"):
interactive = False
compress = True
gendic = False
huffmann_only = False
batch = True
if(sys.argv[-1] == "-nfh"):
no_final_huf = True
elif (sys.argv[1] == "-d"):
interactive = False
batch = False
compress = True
gendic = True
huffmann_only = False
elif (sys.argv[1] == "-x"):
interactive = False
batch = False
compress = False
gendic = False
huffmann_only = False
elif (sys.argv[1] == "-hc"): # only use huffmann compression - to compare performance.
interactive = False
batch = False
compress = True
gendic = False
huffmann_only = True
elif (sys.argv[1] == "-hx"): # only yse huffmann decompression - to compare performance.
interactive = False
batch = False
compress = False
gendic = False
huffmann_only = True
else:
print("unknown operation: " + str(sys.argv[0]) + " type 'python3 dicstrv3.py' for help")
if (((len(sys.argv) < 3) or (len(sys.argv) > 5)) and not interactive):
print("Syntax for compression :\n")
print("python3 dicstrv.py -c <txt_inputfile> <compressed_outputfile>")
print("Reads txt_inputfile and writes compressed text stream to compressed_outputfile.\n")
print("python3 dicstrv.py -c <txt_inputfile>")
print("Reads txt_input file and writes compressed output to stdout\n")
print("python3 dicstrv.py -bc folder_path ext")
print("Reads all files recursively in folder_path and generates for each file a compressed file with extension '.ext'")
#print("python3 dicstrv.py -bc <txt_inputfile> <txt_inpputfile2> <txt_inputfile2> ...")
#print("Batch compress : reads txt_input files and writes compressed output to bin files, appending bin extension, filewise\n")
print("Syntax for decompression :\n")
print("python3 dicstrv.py -x <compressed_inputfile> <txt_outputfile>")
print("Reads compressed_inputfile and writes cleartext to txt_outputfile.\n")
print("python3 dicstrv.py -x <compressed_inputfile>\n")
print("Reads compressed_input file and writes cleartext output to stdout\n")
print("NOTE: dictionary file count1_w.txt must be in the same directory as the script.")
quit()
if not interactive:
if (len(sys.argv) == 3):
infile = sys.argv[2]
outfile = ''
if (len(sys.argv) >= 4):
infile = sys.argv[2]
outfile = sys.argv[3]
debug_on = True
debug_ngrams_dic = False
secondpass = True
use_huffmann = False
unknown_token_idx = 16384 + 128 + 2097152
def debugw(strdebug):
if (debug_on):
print(strdebug)
# Huffmann is only used for absent words in count1_w.txt dictionary
# General lower and upper case frequency combined as lowercase
codec_lower = HuffmanCodec.from_frequencies(
{'e' : 56.88, 'm' : 15.36,
'a' : 43.31, 'h' : 15.31,
'r' : 38.64, 'g' : 12.59,
'i' : 38.45, 'b' : 10.56,
'o' : 36.51, 'f' : 9.24,
't' : 35.43, 'y' : 9.06,
'n' : 33.92, 'w' : 6.57,
's' : 29.23, 'k' : 5.61,
'l' : 27.98, 'v' : 5.13,
'c' : 23.13, 'x' : 1.48,
'u' : 18.51, 'z' : 1.39,
'd' : 17.25, 'j' : 1,
'p' : 16.14, 'q' : 1
}
)
#codec_lower.print_code_table()
debugw(codec_lower.get_code_table())
# following is ASCII mixed upper and lower case frequency from an English writer from Palm OS PDA memos in 2002
# Credit : http://fitaly.com/board/domper3/posts/136.html
codec_upperlower = HuffmanCodec.from_frequencies(
{'A' : 0.3132,
'B' : 0.2163,
'C' : 0.3906,
'D' : 0.3151,
'E' : 0.2673,
'F' : 0.1416,
'G' : 0.1876,
'H' : 0.2321,
'I' : 0.3211,
'J' : 0.1726,
'K' : 0.0687,
'L' : 0.1884,
'M' : 0.3529,
'N' : 0.2085,
'O' : 0.1842,
'P' : 0.2614,
'Q' : 0.0316,
'R' : 0.2519,
'S' : 0.4003,
'T' : 0.3322,
'U' : 0.0814,
'V' : 0.0892,
'W' : 0.2527,
'X' : 0.0343,
'Y' : 0.0304,
'Z' : 0.0076,
'a' : 5.1880,
'b' : 1.0195,
'c' : 2.1129,
'd' : 2.5071,
'e' : 8.5771,
'f' : 1.3725,
'g' : 1.5597,
'h' : 2.7444,
'i' : 4.9019,
'j' : 0.0867,
'k' : 0.6753,
'l' : 3.1750,
'm' : 1.6437,
'n' : 4.9701,
'o' : 5.7701,
'p' : 1.5482,
'q' : 0.0747,
'r' : 4.2586,
's' : 4.3686,
't' : 6.3700,
'u' : 2.0999,
'v' : 0.8462,
'w' : 1.3034,
'x' : 0.1950,
'y' : 1.1330,
'z' : 0.0596
})
debugw(codec_upperlower.get_code_table())
# following is ASCII alpha numeric frequency from an English writer from Palm OS PDA memos in 2002
# Credit : http://fitaly.com/board/domper3/posts/136.html
codec_alphanumeric = HuffmanCodec.from_frequencies(
{'0' : 0.5516,
'1' : 0.4594,
'2' : 0.3322,
'3' : 0.1847,
'4' : 0.1348,
'5' : 0.1663,
'6' : 0.1153,
'7' : 0.1030,
'8' : 0.1054,
'9' : 0.1024,
'A' : 0.3132,
'B' : 0.2163,
'C' : 0.3906,
'D' : 0.3151,
'E' : 0.2673,
'F' : 0.1416,
'G' : 0.1876,
'H' : 0.2321,
'I' : 0.3211,
'J' : 0.1726,
'K' : 0.0687,
'L' : 0.1884,
'M' : 0.3529,
'N' : 0.2085,
'O' : 0.1842,
'P' : 0.2614,
'Q' : 0.0316,
'R' : 0.2519,
'S' : 0.4003,
'T' : 0.3322,
'U' : 0.0814,
'V' : 0.0892,
'W' : 0.2527,
'X' : 0.0343,
'Y' : 0.0304,
'Z' : 0.0076,
'a' : 5.1880,
'b' : 1.0195,
'c' : 2.1129,
'd' : 2.5071,
'e' : 8.5771,
'f' : 1.3725,
'g' : 1.5597,
'h' : 2.7444,
'i' : 4.9019,
'j' : 0.0867,
'k' : 0.6753,
'l' : 3.1750,
'm' : 1.6437,
'n' : 4.9701,
'o' : 5.7701,
'p' : 1.5482,
'q' : 0.0747,
'r' : 4.2586,
's' : 4.3686,
't' : 6.3700,
'u' : 2.0999,
'v' : 0.8462,
'w' : 1.3034,
'x' : 0.1950,
'y' : 1.1330,
'z' : 0.0596
})
debugw(codec_alphanumeric.get_code_table())
# following is Whole ASCII printable chars frequency except whitespace from an English writer from Palm OS PDA memos in 2002
# Credit : http://fitaly.com/board/domper3/posts/136.html
codec_all = HuffmanCodec.from_frequencies(
{'!' : 0.0072,
'\"' : 0.2442,
'#' : 0.0179,
'$' : 0.0561,
'%' : 0.0160,
'&' : 0.0226,
'\'' : 0.2447,
'(' : 0.2178,
')' : 0.2233,
'*' : 0.0628,
'+' : 0.0215,
',' : 0.7384,
'-' : 1.3734,
'.' : 1.5124,
'/' : 0.1549,
'0' : 0.5516,
'1' : 0.4594,
'2' : 0.3322,
'3' : 0.1847,
'4' : 0.1348,
'5' : 0.1663,
'6' : 0.1153,
'7' : 0.1030,
'8' : 0.1054,
'9' : 0.1024,
':' : 0.4354,
';' : 0.1214,
'<' : 0.1225,
'=' : 0.0227,
'>' : 0.1242,
'?' : 0.1474,
'@' : 0.0073,
'A' : 0.3132,
'B' : 0.2163,
'C' : 0.3906,
'D' : 0.3151,
'E' : 0.2673,
'F' : 0.1416,
'G' : 0.1876,
'H' : 0.2321,
'I' : 0.3211,
'J' : 0.1726,
'K' : 0.0687,
'L' : 0.1884,
'M' : 0.3529,
'N' : 0.2085,
'O' : 0.1842,
'P' : 0.2614,
'Q' : 0.0316,
'R' : 0.2519,
'S' : 0.4003,
'T' : 0.3322,
'U' : 0.0814,
'V' : 0.0892,
'W' : 0.2527,
'X' : 0.0343,
'Y' : 0.0304,
'Z' : 0.0076,
'[' : 0.0086,
'\\' : 0.0016,
']' : 0.0088,
'^' : 0.0003,
'_' : 0.1159,
'`' : 0.0009,
'a' : 5.1880,
'b' : 1.0195,
'c' : 2.1129,
'd' : 2.5071,
'e' : 8.5771,
'f' : 1.3725,
'g' : 1.5597,
'h' : 2.7444,
'i' : 4.9019,
'j' : 0.0867,
'k' : 0.6753,
'l' : 3.1750,
'm' : 1.6437,
'n' : 4.9701,
'o' : 5.7701,
'p' : 1.5482,
'q' : 0.0747,
'r' : 4.2586,
's' : 4.3686,
't' : 6.3700,
'u' : 2.0999,
'v' : 0.8462,
'w' : 1.3034,
'x' : 0.1950,
'y' : 1.1330,
'z' : 0.0596,
'{' : 0.0026,
'|' : 0.0007,
'}' : 0.0026,
'~' : 0.0003,
})
# following is Whole ASCII printable chars frequency except whitespace from an English writer from Palm OS PDA memos in 2002
# Credit : http://fitaly.com/board/domper3/posts/136.html
codec_all_whitespace = HuffmanCodec.from_frequencies(
{' ' : 17.1662,
'!' : 0.0072,
'\"' : 0.2442,
'#' : 0.0179,
'$' : 0.0561,
'%' : 0.0160,
'&' : 0.0226,
'\'' : 0.2447,
'(' : 0.2178,
')' : 0.2233,
'*' : 0.0628,
'+' : 0.0215,
',' : 0.7384,
'-' : 1.3734,
'.' : 1.5124,
'/' : 0.1549,
'0' : 0.5516,
'1' : 0.4594,
'2' : 0.3322,
'3' : 0.1847,
'4' : 0.1348,
'5' : 0.1663,
'6' : 0.1153,
'7' : 0.1030,
'8' : 0.1054,
'9' : 0.1024,
':' : 0.4354,
';' : 0.1214,
'<' : 0.1225,
'=' : 0.0227,
'>' : 0.1242,
'?' : 0.1474,
'@' : 0.0073,
'A' : 0.3132,
'B' : 0.2163,
'C' : 0.3906,
'D' : 0.3151,
'E' : 0.2673,
'F' : 0.1416,
'G' : 0.1876,
'H' : 0.2321,
'I' : 0.3211,
'J' : 0.1726,
'K' : 0.0687,
'L' : 0.1884,
'M' : 0.3529,
'N' : 0.2085,
'O' : 0.1842,
'P' : 0.2614,
'Q' : 0.0316,
'R' : 0.2519,
'S' : 0.4003,
'T' : 0.3322,
'U' : 0.0814,
'V' : 0.0892,
'W' : 0.2527,
'X' : 0.0343,
'Y' : 0.0304,
'Z' : 0.0076,
'[' : 0.0086,
'\\' : 0.0016,
']' : 0.0088,
'^' : 0.0003,
'_' : 0.1159,
'`' : 0.0009,
'a' : 5.1880,
'b' : 1.0195,
'c' : 2.1129,
'd' : 2.5071,
'e' : 8.5771,
'f' : 1.3725,
'g' : 1.5597,
'h' : 2.7444,
'i' : 4.9019,
'j' : 0.0867,
'k' : 0.6753,
'l' : 3.1750,
'm' : 1.6437,
'n' : 4.9701,
'o' : 5.7701,
'p' : 1.5482,
'q' : 0.0747,
'r' : 4.2586,
's' : 4.3686,
't' : 6.3700,
'u' : 2.0999,
'v' : 0.8462,
'w' : 1.3034,
'x' : 0.1950,
'y' : 1.1330,
'z' : 0.0596,
'{' : 0.0026,
'|' : 0.0007,
'}' : 0.0026,
'~' : 0.0003,
'\n' : 0.06, #wild guess
'\t' : 0.02 #wild guess
})
debugw(codec_all.get_code_table())
#quit()
#
dicts = {}
def load_dicts(lang_id):
#initializing Python dicts
count = 1
onegrams = bidict()
duplicate_onegrams_indexes = []
if (not os.path.isfile('count_1w.pickle')):
debugw("first load of dic")
file1 = open(lang_id + '_1w.txt', 'r')
Lines = file1.readlines()
# special case : byte val 0 is equal to new line.
# TODO : make sure that windows CRLF is taken care of.
onegrams[0] = "\n"
# populating dicts
for line in Lines:
try:
# Strips the newline character of the 1gram
onegrams[count] = line.strip()
except Exception as error:
print(error)
duplicate_onegrams_indexes.append(count)
count += 1
debugw("pickling dictionaries")
with open(lang_id + '_1w.pickle', 'wb') as handle:
pickle.dump(onegrams, handle, protocol=pickle.HIGHEST_PROTOCOL)
else:
debugw("loading pickled dictionaries")
with open(lang_id + '_1w.pickle', 'rb') as handle:
onegrams = pickle.load(handle)
fourgrams = bidict()
duplicate_fourgrams_indexes = []
if (not os.path.isfile(lang_id + '_4w.pickle')):
### populating ngram dict
filengrams = open(lang_id + '_4w.bin', 'rt')
ngramlines = filengrams.readlines()
count = 0
# populating dicts
for ngramline in ngramlines:
# Strips the newline character
#keystr = "".join([f"\\x{byte:02x}" for byte in ngramline.strip()])
#keystr = keystr.replace("\\","")
#if(count == 71374):
keystr = ngramline.strip()
#print(ngramline.strip())
#print(keystr)
#quit()
try:
fourgrams[keystr] = count
except Exception as error:
print(error)
duplicate_fourgrams_indexes.append(count)
count += 1
debugw("pickling ngram dictionaries")
with open(lang_id + '_4w.pickle', 'wb') as handle:
pickle.dump(fourgrams, handle, protocol=pickle.HIGHEST_PROTOCOL)
else:
debugw("loading pickled ngram dictionaries")
with open(lang_id + '_4w.pickle', 'rb') as handle:
fourgrams = pickle.load(handle)
idx = 0
debugw("first ngram in dict:")
test = fourgrams.inverse[0]
debugw(test)
debugw(fourgrams[test])
count = 0
return onegrams , fourgrams
def restore_unused_chars_shiftup(unused_seqs,compressed):
# works in-place
#we need to restore original sequence after bwt_decode, knowing the highest unused char number.
#in our case, simple byte sorting by value, not lexicographic as we are working on the full ASCII range
debugw("unused_seqs_to_shift_up_into:")
debugw(unused_seqs)
if (isinstance(unused_seqs[0],int) and (isinstance(unused_seqs[1],int))):
#handle special case where unused_char is 255 == BWT EOF
if(unused_seqs[0] == 255):
debugw("unused char to shift into is 255 == bwt eof. exiting")
return compressed
debugw("two absent chars")
compzip = zip(range(0,len(compressed)),compressed)
for byte_and_pos in compzip:
if (byte_and_pos[1] >= unused_seqs[0]):
debugw("byte_and_pos[0]")
debugw(byte_and_pos[0])
debugw("byte_and_pos[1]")
debugw(byte_and_pos[1])
compressed[byte_and_pos[0]] += 1
return compressed
# compress bytearray modified in place, no need to return it
elif (isinstance(unused_seqs[0],bytearray) and (isinstance(unused_seqs[1],int))):
debugw("single absent char")
compressed_new = bytearray()
jump = 0
for byte_idx in range(0,len(compressed)):
byte_idx += jump
if(byte_idx>=len(compressed)):
break
if(byte_idx < len(compressed) - 1):
if(compressed[byte_idx:byte_idx+2] == unused_seqs[0]):
debugw("swap absent seq 0 back to 255")
jump += 1
compressed_new.append(255)
# swap back bwt eof.
if(compressed[byte_idx] == unused_seqs[1]):
debugw("swap absent char back to 254")
compressed_new.append(254)
# swap back unused char into rle sep
else:
# all other chars.
debugw("other char, no change")
compressed_new.append(compressed[byte_idx])
return compressed_new
elif (isinstance(unused_seqs[0],bytearray) and (isinstance(unused_seqs[1],bytearray))):
debugw("zero absent char")
compressed_new = bytearray()
jump = 0
for byte_idx in range(0,len(compressed)):
byte_idx += jump
if(byte_idx>=len(compressed)):
break
if(byte_idx < len(compressed) - 1):
if(compressed[byte_idx:byte_idx+2] == unused_seqs[0]):
debugw("swap absent seq 0 back to 255")
jump += 1
compressed_new.append(255)
# swap back bwt eof.
elif(compressed[byte_idx:byte_idx+2] == unused_seqs[1]):
debugw("swap absent seq 1 back to 254")
jump += 1
compressed_new.append(254)
# swap back bwt eof.
else:
# all other chars.
debugw("other char, no change")
compressed_new.append(compressed[byte_idx])
else:
# all other chars.
debugw("other char, no change")
compressed_new.append(compressed[byte_idx])
return compressed_new
def suffixArray(s):
#''' creation du suffixe array avec leurs rangs ordonnés '''
satups = sorted([(s[i:], i) for i in range(0, len(s)+1)])
return map(lambda x: x[1], satups)
def bwt_encode(t,eof):
''' transformation de Burrow-wheeler '''
bw = bytearray()
for si in suffixArray(t):
if si == 0:
bw.extend(eof)
else:
bw.append(t[si-1])
#bw.append(t[si-len(eof)])
return bw
def rankBwt(bw):
''' Retourne les rangs '''
tots = dict()
ranks = []
for c in bw:
if c not in tots:
tots[c] = 0
ranks.append(tots[c])
tots[c] += 1
return ranks, tots
def firstCol(tots):
''' retourne la premiere colonne '''
first = {}
totc = 0
for c, count in sorted(tots.items()):
first[c] = (totc, totc + count)
totc += count
return first # returns dictionary of lexicographic order key = character value, dic val = (index_start,index_end (excluded))
def bwt_decode(bw,eof):
''' Retourne le texte original de la transformation bw '''
ranks, tots = rankBwt(bw)
first = firstCol(tots)
rowi = 0
t= bytearray()
t.extend(eof)
while (int.from_bytes(bw[rowi:rowi+len(eof)],'little') != int.from_bytes(eof,'little')):
c = bw[rowi]
t[:0] = bytearray(c.to_bytes(1,'little'))
rowi = first[c][0] + ranks[rowi] + 1
del(t[-len(eof):])
return t
def reuse_unused_chars_shiftdown(compressed):
# works in-place
#we need to ensure that byte 255 is unused for BWT (used as eof) because of lexicographic constraints
#in our case, simple byte sorting by value, not lexicographic as we are working on the full ASCII range
# we also need another byte to be free as a rle separator, so we return it. - no need to shift for this
# one, just return it in abs_chars
frequency = Counter(compressed).most_common()
frequency_dic = {}
for (ascii_code, count) in frequency:
frequency_dic[ascii_code] = count
abs_chars = []
for charval in range(255,0,-1):
if charval not in frequency_dic.keys():
abs_chars = abs_chars + [charval]
debugw("charval")
debugw(charval)
if (len(abs_chars) >= 2):
if(abs_chars[0] == 255 and abs_chars[1] == 254):
debugw("reversing")
abs_chars.reverse()
return (abs_chars,compressed)
else:
break
if(len(abs_chars) == 2):
#highest_abs_char = abs_chars[0]
lowest_abs_char = abs_chars[1]
# special case where bwt eof is absent and next absent char is not 254.
# then we shift at the second absent char.
#if((highest_abs_char) == 255):
# highest_abs_char = abs_chars[1]
compzip = zip(range(0,len(compressed)),compressed)
for byte_and_pos in compzip:
#if (byte_and_pos[1] > highest_abs_char):
if (byte_and_pos[1] > lowest_abs_char):
compressed[byte_and_pos[0]] -= 1
abs_chars[0] -= 1 # this will be the RLE, bwt will be the 255 freed.
return (abs_chars,compressed)
elif(len(abs_chars) == 1):
tmpchar = abs_chars[0]
# alg :find one absent sequence of two different chars, highest possible,
# that do not contain 255 or 254 or absent char.
# swap 255 (bwt eof) into absent char.
# swap 254 into absent sequence.
abs_seqs = find_absent_sequences(compressed,1,abs_chars[0])
#abs_chars[0] = bytearray((abs_seqs[0]).to_bytes(2,'little'))
abs_chars[0] = abs_seqs[0]
abs_chars.append(tmpchar) # tmpchar is the char in which bwt eof (255) has been swapped into.
debugw("will swap 255 into the lone absent char")
debugw("will swap 254 with found 2 byte escape sequence")
compressed_new = bytearray()
compzip = zip(range(0,len(compressed)),compressed)
for byte_and_pos in compzip:
#if (byte_and_pos[1] > highest_abs_char):
if (byte_and_pos[1] == 255):
debugw("replacing: 255 with: " + str(abs_seqs[0]))
compressed_new.extend(abs_chars[0])
elif (byte_and_pos[1] == 254):
debugw("replacing: 254 with: " + str(tmpchar))
compressed_new.append(tmpchar)
else:
debugw("other character, no change")
compressed_new.append(byte_and_pos[1])
# format : abs_char[0] = absent sequence of two different chars that do not contain 255,254 or absent_char to make room bwt eof 255
# format : abs_char[1] = tmpchar (original absent char). the char in which rle sep (254) has been swapped into.
return (abs_chars,compressed_new)