LanguageStatisticsLibPy 1.0.3__py3-none-any.whl → 1.0.4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- languagestatisticslibpy/LanguageStatisticsFile.py +48 -40
- languagestatisticslibpy/Tetragrams.py +125 -125
- languagestatisticslibpy/Trigrams.py +125 -125
- languagestatisticslibpy/Unigrams.py +110 -110
- languagestatisticslibpy/WordTree.py +161 -161
- languagestatisticslibpy/test1.py +26 -26
- languagestatisticslibpy/test2.py +80 -80
- {languagestatisticslibpy-1.0.3.dist-info → languagestatisticslibpy-1.0.4.dist-info}/METADATA +4 -2
- languagestatisticslibpy-1.0.4.dist-info/RECORD +19 -0
- {languagestatisticslibpy-1.0.3.dist-info → languagestatisticslibpy-1.0.4.dist-info}/WHEEL +1 -1
- languagestatisticslibpy-1.0.3.dist-info/RECORD +0 -19
- {languagestatisticslibpy-1.0.3.dist-info → languagestatisticslibpy-1.0.4.dist-info/licenses}/LICENSE +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
"""
|
|
2
2
|
Copyright 2024 Nils Kopal, Bernhard Esslinger, CrypTool Team
|
|
3
3
|
|
|
4
4
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -12,15 +12,12 @@
|
|
|
12
12
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
13
|
See the License for the specific language governing permissions and
|
|
14
14
|
limitations under the License.
|
|
15
|
-
|
|
16
|
-
import struct
|
|
17
|
-
import numpy as np
|
|
18
|
-
import gzip
|
|
19
|
-
|
|
15
|
+
"""
|
|
20
16
|
import gzip
|
|
21
17
|
import struct
|
|
22
18
|
import numpy as np
|
|
23
19
|
|
|
20
|
+
|
|
24
21
|
class LanguageStatisticsFile:
|
|
25
22
|
"""
|
|
26
23
|
Class for handling the loading of language statistics from a compressed file.
|
|
@@ -28,29 +25,28 @@ class LanguageStatisticsFile:
|
|
|
28
25
|
Attributes:
|
|
29
26
|
- FILE_FORMAT_MAGIC_NUMBER (str): The expected magic number to identify valid language statistics files.
|
|
30
27
|
- file_path (str): The path to the language statistics file.
|
|
31
|
-
- alphabet (str): The alphabet used in the language statistics.
|
|
28
|
+
- alphabet (str): The decoded alphabet used in the language statistics.
|
|
29
|
+
- alphabet_length (int): Number of symbols (characters) in `alphabet` (NOT bytes).
|
|
30
|
+
- alphabet_length_bytes (int): Length prefix from file (= number of bytes used to store the alphabet string).
|
|
32
31
|
- language_code (str): The language code extracted from the statistics file.
|
|
33
32
|
"""
|
|
34
33
|
|
|
35
34
|
FILE_FORMAT_MAGIC_NUMBER = "CTLS"
|
|
36
35
|
|
|
37
|
-
def __init__(self, file_path):
|
|
36
|
+
def __init__(self, file_path: str):
|
|
38
37
|
"""
|
|
39
38
|
Initializes the LanguageStatisticsFile class.
|
|
40
39
|
|
|
41
40
|
Parameters:
|
|
42
41
|
- file_path (str): The path to the language statistics file.
|
|
43
|
-
|
|
44
|
-
Initializes:
|
|
45
|
-
- self.file_path (str): Stores the path to the file.
|
|
46
|
-
- self.alphabet (str): Initially empty, set after file loading.
|
|
47
|
-
- self.language_code (str): Initially empty, set after file loading.
|
|
48
42
|
"""
|
|
49
43
|
self.file_path = file_path
|
|
50
|
-
self.alphabet =
|
|
51
|
-
self.
|
|
44
|
+
self.alphabet = ""
|
|
45
|
+
self.alphabet_length = 0
|
|
46
|
+
self.alphabet_length_bytes = 0
|
|
47
|
+
self.language_code = ""
|
|
52
48
|
|
|
53
|
-
def load_frequencies(self, array_dimensions):
|
|
49
|
+
def load_frequencies(self, array_dimensions: int) -> np.ndarray:
|
|
54
50
|
"""
|
|
55
51
|
Loads the frequency data from the language statistics file.
|
|
56
52
|
|
|
@@ -61,48 +57,60 @@ class LanguageStatisticsFile:
|
|
|
61
57
|
- np.ndarray: A numpy array containing the frequency data.
|
|
62
58
|
|
|
63
59
|
Raises:
|
|
64
|
-
- Exception: If the file format is invalid
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
3. Verifies that the gram length matches the required dimensions.
|
|
70
|
-
4. Reads the frequency data and reshapes it into the appropriate numpy array format.
|
|
71
|
-
5. Copies the data into a new numpy array to allow modification.
|
|
60
|
+
- Exception: If the file format is invalid, gram length mismatches, or the file content size is inconsistent.
|
|
61
|
+
|
|
62
|
+
Notes:
|
|
63
|
+
- The alphabet length stored in the file is a *byte length* (UTF-8). For non-ASCII alphabets (e.g., German ÄÖÜß),
|
|
64
|
+
the number of bytes differs from the number of symbols. We therefore decode first and then compute the symbol count.
|
|
72
65
|
"""
|
|
73
|
-
|
|
66
|
+
if array_dimensions < 1:
|
|
67
|
+
raise Exception("array_dimensions must be >= 1")
|
|
68
|
+
|
|
69
|
+
with gzip.open(self.file_path, "rb") as file:
|
|
74
70
|
# Validate the file format by checking the magic number.
|
|
75
|
-
magic_number = file.read(4).decode(
|
|
71
|
+
magic_number = file.read(4).decode("utf-8")
|
|
76
72
|
if magic_number != self.FILE_FORMAT_MAGIC_NUMBER:
|
|
77
73
|
raise Exception("File does not start with the expected magic number for language statistics.")
|
|
78
74
|
|
|
79
75
|
# Read the language code (length-prefixed string).
|
|
80
76
|
language_code_length_bytes = file.read(1)[0]
|
|
81
|
-
self.language_code = file.read(language_code_length_bytes).decode(
|
|
77
|
+
self.language_code = file.read(language_code_length_bytes).decode("utf-8")
|
|
82
78
|
|
|
83
79
|
# Read the gram length (32-bit signed integer).
|
|
84
|
-
gram_length = struct.unpack(
|
|
80
|
+
gram_length = struct.unpack("<i", file.read(4))[0]
|
|
85
81
|
|
|
86
82
|
# Ensure the gram length matches the required dimensions.
|
|
87
83
|
if gram_length != array_dimensions:
|
|
88
84
|
raise Exception("Gram length of statistics file differs from required dimensions of frequency array.")
|
|
89
85
|
|
|
90
|
-
# Read the alphabet (length-prefixed
|
|
91
|
-
self.
|
|
92
|
-
|
|
86
|
+
# Read the alphabet (length-prefixed BYTES, UTF-8).
|
|
87
|
+
self.alphabet_length_bytes = file.read(1)[0]
|
|
88
|
+
alphabet_bytes = file.read(self.alphabet_length_bytes)
|
|
89
|
+
self.alphabet = alphabet_bytes.decode("utf-8")
|
|
90
|
+
|
|
91
|
+
# IMPORTANT: use number of symbols (characters), not bytes, for frequency tensor dimensions.
|
|
92
|
+
self.alphabet_length = len(self.alphabet)
|
|
93
93
|
|
|
94
94
|
# Calculate the total number of frequency entries.
|
|
95
95
|
frequency_entries = self.alphabet_length ** gram_length
|
|
96
|
+
expected_frequency_bytes = frequency_entries * 4 # float32
|
|
96
97
|
|
|
97
98
|
# Read the frequency data (32-bit float array).
|
|
98
|
-
frequency_data = file.read(
|
|
99
|
-
|
|
100
|
-
#
|
|
99
|
+
frequency_data = file.read(expected_frequency_bytes)
|
|
100
|
+
|
|
101
|
+
# Hard validation: mismatched files should fail with a clear message.
|
|
102
|
+
if len(frequency_data) != expected_frequency_bytes:
|
|
103
|
+
raise Exception(
|
|
104
|
+
f"Frequency data size mismatch. "
|
|
105
|
+
f"Expected {expected_frequency_bytes} bytes ({frequency_entries} float32 values) "
|
|
106
|
+
f"for alphabet_length={self.alphabet_length} and gram_length={gram_length}, "
|
|
107
|
+
f"but got {len(frequency_data)} bytes. "
|
|
108
|
+
f"(alphabet_length_bytes={self.alphabet_length_bytes}, alphabet='{self.alphabet}')"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Convert and reshape.
|
|
112
|
+
data = np.frombuffer(frequency_data, dtype=np.float32)
|
|
101
113
|
if array_dimensions == 1:
|
|
102
|
-
|
|
103
|
-
else:
|
|
104
|
-
frequencies = np.frombuffer(frequency_data, dtype=np.float32).reshape(
|
|
105
|
-
tuple([self.alphabet_length] * array_dimensions)
|
|
106
|
-
).copy()
|
|
114
|
+
return data.copy()
|
|
107
115
|
|
|
108
|
-
return
|
|
116
|
+
return data.reshape(tuple([self.alphabet_length] * array_dimensions)).copy()
|
|
@@ -1,125 +1,125 @@
|
|
|
1
|
-
'''
|
|
2
|
-
Copyright 2024 Nils Kopal, Bernhard Esslinger, CrypTool Team
|
|
3
|
-
|
|
4
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
you may not use this file except in compliance with the License.
|
|
6
|
-
You may obtain a copy of the License at
|
|
7
|
-
|
|
8
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
|
|
10
|
-
Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
See the License for the specific language governing permissions and
|
|
14
|
-
limitations under the License.
|
|
15
|
-
'''
|
|
16
|
-
import numpy as np
|
|
17
|
-
import os
|
|
18
|
-
from languagestatisticslibpy.Grams import Grams
|
|
19
|
-
from languagestatisticslibpy.GramsType import GramsType
|
|
20
|
-
from languagestatisticslibpy.LanguageStatisticsFile import LanguageStatisticsFile
|
|
21
|
-
|
|
22
|
-
class Tetragrams(Grams):
|
|
23
|
-
def __init__(self, language, language_statistics_directory, use_spaces=False):
|
|
24
|
-
"""
|
|
25
|
-
Initializes the Tetragrams class by calling the parent class (Grams) initializer.
|
|
26
|
-
|
|
27
|
-
Parameters:
|
|
28
|
-
- language (str): The language of the tetragram statistics.
|
|
29
|
-
- language_statistics_directory (str): Path to the directory containing language statistics files.
|
|
30
|
-
- use_spaces (bool): Whether to include spaces in the analysis (default: False).
|
|
31
|
-
"""
|
|
32
|
-
super().__init__(language, language_statistics_directory, use_spaces)
|
|
33
|
-
|
|
34
|
-
def load_gz(self, filename, language_statistics_directory):
|
|
35
|
-
"""
|
|
36
|
-
Loads a gzip-compressed file containing tetragram frequencies.
|
|
37
|
-
|
|
38
|
-
Parameters:
|
|
39
|
-
- filename (str): The name of the file to load.
|
|
40
|
-
- language_statistics_directory (str): The directory where the statistics file is located.
|
|
41
|
-
|
|
42
|
-
Sets:
|
|
43
|
-
- self.frequencies (np.ndarray): A 4D array of tetragram frequencies.
|
|
44
|
-
- self.alphabet (list): The alphabet used in the statistics file.
|
|
45
|
-
- self.max_value (float): The maximum value in the frequencies array, or -∞ if the array is empty.
|
|
46
|
-
"""
|
|
47
|
-
file_path = os.path.join(language_statistics_directory, filename)
|
|
48
|
-
language_statistics_file = LanguageStatisticsFile(file_path)
|
|
49
|
-
self.frequencies = language_statistics_file.load_frequencies(4)
|
|
50
|
-
self.alphabet = language_statistics_file.alphabet
|
|
51
|
-
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
52
|
-
|
|
53
|
-
def calculate_cost(self, text):
|
|
54
|
-
"""
|
|
55
|
-
Calculates the cost of a given text based on tetragram frequencies.
|
|
56
|
-
|
|
57
|
-
Parameters:
|
|
58
|
-
- text (str): The text to analyze.
|
|
59
|
-
|
|
60
|
-
Returns:
|
|
61
|
-
- float: The average cost of tetragrams in the text. Returns 0.0 if the text length is less than 4.
|
|
62
|
-
|
|
63
|
-
Notes:
|
|
64
|
-
- Skips tetragrams containing characters outside the defined alphabet.
|
|
65
|
-
- If `add_letter_indices` is defined, modifies the index of the characters before computing the cost.
|
|
66
|
-
"""
|
|
67
|
-
if len(text) < 4:
|
|
68
|
-
return 0.0
|
|
69
|
-
|
|
70
|
-
value = 0.0
|
|
71
|
-
alphabet_length = len(self.alphabet)
|
|
72
|
-
end = len(text) - 3
|
|
73
|
-
|
|
74
|
-
for i in range(end):
|
|
75
|
-
a, b, c, d = text[i:i+4]
|
|
76
|
-
|
|
77
|
-
if self.add_letter_indices:
|
|
78
|
-
a += self.add_letter_indices.get(a, 0)
|
|
79
|
-
b += self.add_letter_indices.get(b, 0)
|
|
80
|
-
c += self.add_letter_indices.get(c, 0)
|
|
81
|
-
d += self.add_letter_indices.get(d, 0)
|
|
82
|
-
|
|
83
|
-
if 0 <= a < alphabet_length and 0 <= b < alphabet_length and \
|
|
84
|
-
0 <= c < alphabet_length and 0 <= d < alphabet_length:
|
|
85
|
-
value += self.frequencies[a, b, c, d]
|
|
86
|
-
|
|
87
|
-
return value / end
|
|
88
|
-
|
|
89
|
-
def gram_size(self):
|
|
90
|
-
"""
|
|
91
|
-
Returns the size of the grams being analyzed (tetragrams in this case).
|
|
92
|
-
|
|
93
|
-
Returns:
|
|
94
|
-
- int: The size of the grams (always 4 for tetragrams).
|
|
95
|
-
"""
|
|
96
|
-
return 4
|
|
97
|
-
|
|
98
|
-
def grams_type(self):
|
|
99
|
-
"""
|
|
100
|
-
Returns the type of grams being analyzed.
|
|
101
|
-
|
|
102
|
-
Returns:
|
|
103
|
-
- GramsType: An enum value representing the type of grams (GramsType.Tetragrams).
|
|
104
|
-
"""
|
|
105
|
-
return GramsType.Tetragrams
|
|
106
|
-
|
|
107
|
-
def normalize(self, max_value):
|
|
108
|
-
"""
|
|
109
|
-
Normalizes the tetragram frequencies based on the provided maximum value.
|
|
110
|
-
|
|
111
|
-
Parameters:
|
|
112
|
-
- max_value (float): The maximum value used for normalization.
|
|
113
|
-
|
|
114
|
-
Notes:
|
|
115
|
-
- Adjusts all frequencies proportionally to the new maximum value.
|
|
116
|
-
- Updates `self.max_value` to the new maximum after normalization.
|
|
117
|
-
"""
|
|
118
|
-
super().normalize(max_value)
|
|
119
|
-
adjust_value = self.max_value * max_value
|
|
120
|
-
for a in range(len(self.alphabet)):
|
|
121
|
-
for b in range(len(self.alphabet)):
|
|
122
|
-
for c in range(len(self.alphabet)):
|
|
123
|
-
for d in range(len(self.alphabet)):
|
|
124
|
-
self.frequencies[a, b, c, d] = adjust_value / self.frequencies[a, b, c, d]
|
|
125
|
-
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
1
|
+
'''
|
|
2
|
+
Copyright 2024 Nils Kopal, Bernhard Esslinger, CrypTool Team
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
'''
|
|
16
|
+
import numpy as np
|
|
17
|
+
import os
|
|
18
|
+
from languagestatisticslibpy.Grams import Grams
|
|
19
|
+
from languagestatisticslibpy.GramsType import GramsType
|
|
20
|
+
from languagestatisticslibpy.LanguageStatisticsFile import LanguageStatisticsFile
|
|
21
|
+
|
|
22
|
+
class Tetragrams(Grams):
|
|
23
|
+
def __init__(self, language, language_statistics_directory, use_spaces=False):
|
|
24
|
+
"""
|
|
25
|
+
Initializes the Tetragrams class by calling the parent class (Grams) initializer.
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
- language (str): The language of the tetragram statistics.
|
|
29
|
+
- language_statistics_directory (str): Path to the directory containing language statistics files.
|
|
30
|
+
- use_spaces (bool): Whether to include spaces in the analysis (default: False).
|
|
31
|
+
"""
|
|
32
|
+
super().__init__(language, language_statistics_directory, use_spaces)
|
|
33
|
+
|
|
34
|
+
def load_gz(self, filename, language_statistics_directory):
|
|
35
|
+
"""
|
|
36
|
+
Loads a gzip-compressed file containing tetragram frequencies.
|
|
37
|
+
|
|
38
|
+
Parameters:
|
|
39
|
+
- filename (str): The name of the file to load.
|
|
40
|
+
- language_statistics_directory (str): The directory where the statistics file is located.
|
|
41
|
+
|
|
42
|
+
Sets:
|
|
43
|
+
- self.frequencies (np.ndarray): A 4D array of tetragram frequencies.
|
|
44
|
+
- self.alphabet (list): The alphabet used in the statistics file.
|
|
45
|
+
- self.max_value (float): The maximum value in the frequencies array, or -∞ if the array is empty.
|
|
46
|
+
"""
|
|
47
|
+
file_path = os.path.join(language_statistics_directory, filename)
|
|
48
|
+
language_statistics_file = LanguageStatisticsFile(file_path)
|
|
49
|
+
self.frequencies = language_statistics_file.load_frequencies(4)
|
|
50
|
+
self.alphabet = language_statistics_file.alphabet
|
|
51
|
+
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
52
|
+
|
|
53
|
+
def calculate_cost(self, text):
|
|
54
|
+
"""
|
|
55
|
+
Calculates the cost of a given text based on tetragram frequencies.
|
|
56
|
+
|
|
57
|
+
Parameters:
|
|
58
|
+
- text (str): The text to analyze.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
- float: The average cost of tetragrams in the text. Returns 0.0 if the text length is less than 4.
|
|
62
|
+
|
|
63
|
+
Notes:
|
|
64
|
+
- Skips tetragrams containing characters outside the defined alphabet.
|
|
65
|
+
- If `add_letter_indices` is defined, modifies the index of the characters before computing the cost.
|
|
66
|
+
"""
|
|
67
|
+
if len(text) < 4:
|
|
68
|
+
return 0.0
|
|
69
|
+
|
|
70
|
+
value = 0.0
|
|
71
|
+
alphabet_length = len(self.alphabet)
|
|
72
|
+
end = len(text) - 3
|
|
73
|
+
|
|
74
|
+
for i in range(end):
|
|
75
|
+
a, b, c, d = text[i:i+4]
|
|
76
|
+
|
|
77
|
+
if self.add_letter_indices:
|
|
78
|
+
a += self.add_letter_indices.get(a, 0)
|
|
79
|
+
b += self.add_letter_indices.get(b, 0)
|
|
80
|
+
c += self.add_letter_indices.get(c, 0)
|
|
81
|
+
d += self.add_letter_indices.get(d, 0)
|
|
82
|
+
|
|
83
|
+
if 0 <= a < alphabet_length and 0 <= b < alphabet_length and \
|
|
84
|
+
0 <= c < alphabet_length and 0 <= d < alphabet_length:
|
|
85
|
+
value += self.frequencies[a, b, c, d]
|
|
86
|
+
|
|
87
|
+
return value / end
|
|
88
|
+
|
|
89
|
+
def gram_size(self):
|
|
90
|
+
"""
|
|
91
|
+
Returns the size of the grams being analyzed (tetragrams in this case).
|
|
92
|
+
|
|
93
|
+
Returns:
|
|
94
|
+
- int: The size of the grams (always 4 for tetragrams).
|
|
95
|
+
"""
|
|
96
|
+
return 4
|
|
97
|
+
|
|
98
|
+
def grams_type(self):
|
|
99
|
+
"""
|
|
100
|
+
Returns the type of grams being analyzed.
|
|
101
|
+
|
|
102
|
+
Returns:
|
|
103
|
+
- GramsType: An enum value representing the type of grams (GramsType.Tetragrams).
|
|
104
|
+
"""
|
|
105
|
+
return GramsType.Tetragrams
|
|
106
|
+
|
|
107
|
+
def normalize(self, max_value):
|
|
108
|
+
"""
|
|
109
|
+
Normalizes the tetragram frequencies based on the provided maximum value.
|
|
110
|
+
|
|
111
|
+
Parameters:
|
|
112
|
+
- max_value (float): The maximum value used for normalization.
|
|
113
|
+
|
|
114
|
+
Notes:
|
|
115
|
+
- Adjusts all frequencies proportionally to the new maximum value.
|
|
116
|
+
- Updates `self.max_value` to the new maximum after normalization.
|
|
117
|
+
"""
|
|
118
|
+
super().normalize(max_value)
|
|
119
|
+
adjust_value = self.max_value * max_value
|
|
120
|
+
for a in range(len(self.alphabet)):
|
|
121
|
+
for b in range(len(self.alphabet)):
|
|
122
|
+
for c in range(len(self.alphabet)):
|
|
123
|
+
for d in range(len(self.alphabet)):
|
|
124
|
+
self.frequencies[a, b, c, d] = adjust_value / self.frequencies[a, b, c, d]
|
|
125
|
+
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
@@ -1,125 +1,125 @@
|
|
|
1
|
-
'''
|
|
2
|
-
Copyright 2024 Nils Kopal, Bernhard Esslinger, CrypTool Team
|
|
3
|
-
|
|
4
|
-
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
-
you may not use this file except in compliance with the License.
|
|
6
|
-
You may obtain a copy of the License at
|
|
7
|
-
|
|
8
|
-
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
-
|
|
10
|
-
Unless required by applicable law or agreed to in writing, software
|
|
11
|
-
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
-
See the License for the specific language governing permissions and
|
|
14
|
-
limitations under the License.
|
|
15
|
-
'''
|
|
16
|
-
import numpy as np
|
|
17
|
-
import os
|
|
18
|
-
from languagestatisticslibpy.Grams import Grams
|
|
19
|
-
from languagestatisticslibpy.GramsType import GramsType
|
|
20
|
-
from languagestatisticslibpy.LanguageStatisticsFile import LanguageStatisticsFile
|
|
21
|
-
|
|
22
|
-
class Trigrams(Grams):
|
|
23
|
-
def __init__(self, language, language_statistics_directory, use_spaces=False):
|
|
24
|
-
"""
|
|
25
|
-
Initializes the Trigrams class by calling the parent class (Grams) initializer.
|
|
26
|
-
|
|
27
|
-
Parameters:
|
|
28
|
-
- language (str): The language of the trigram statistics.
|
|
29
|
-
- language_statistics_directory (str): Path to the directory containing language statistics files.
|
|
30
|
-
- use_spaces (bool): Whether to include spaces in the analysis (default: False).
|
|
31
|
-
"""
|
|
32
|
-
super().__init__(language, language_statistics_directory, use_spaces)
|
|
33
|
-
|
|
34
|
-
def load_gz(self, filename, language_statistics_directory):
|
|
35
|
-
"""
|
|
36
|
-
Loads a gzip-compressed file containing trigram frequencies.
|
|
37
|
-
|
|
38
|
-
Parameters:
|
|
39
|
-
- filename (str): The name of the file to load.
|
|
40
|
-
- language_statistics_directory (str): The directory where the statistics file is located.
|
|
41
|
-
|
|
42
|
-
Sets:
|
|
43
|
-
- self.frequencies (np.ndarray): A 3D array of trigram frequencies.
|
|
44
|
-
- self.alphabet (list): The alphabet used in the statistics file.
|
|
45
|
-
- self.max_value (float): The maximum value in the frequencies array, or -∞ if the array is empty.
|
|
46
|
-
"""
|
|
47
|
-
file_path = os.path.join(language_statistics_directory, filename)
|
|
48
|
-
language_statistics_file = LanguageStatisticsFile(file_path)
|
|
49
|
-
self.frequencies = language_statistics_file.load_frequencies(3)
|
|
50
|
-
self.alphabet = language_statistics_file.alphabet
|
|
51
|
-
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
52
|
-
|
|
53
|
-
def calculate_cost(self, text):
|
|
54
|
-
"""
|
|
55
|
-
Calculates the cost of a given text based on trigram frequencies.
|
|
56
|
-
|
|
57
|
-
Parameters:
|
|
58
|
-
- text (str): The text to analyze.
|
|
59
|
-
|
|
60
|
-
Returns:
|
|
61
|
-
- float: The average cost of trigrams in the text. Returns 0 if the text length is less than 3.
|
|
62
|
-
|
|
63
|
-
Notes:
|
|
64
|
-
- Skips trigrams containing characters outside the defined alphabet.
|
|
65
|
-
- If `add_letter_indices` is defined, modifies indices of the characters before computing the cost.
|
|
66
|
-
"""
|
|
67
|
-
if len(text) < 3:
|
|
68
|
-
return 0
|
|
69
|
-
|
|
70
|
-
value = 0
|
|
71
|
-
alphabet_length = len(self.alphabet)
|
|
72
|
-
end = len(text) - 2
|
|
73
|
-
|
|
74
|
-
for i in range(end):
|
|
75
|
-
a = text[i]
|
|
76
|
-
b = text[i + 1]
|
|
77
|
-
c = text[i + 2]
|
|
78
|
-
|
|
79
|
-
if self.add_letter_indices:
|
|
80
|
-
a += self.add_letter_indices.get(a, 0)
|
|
81
|
-
b += self.add_letter_indices.get(b, 0)
|
|
82
|
-
c += self.add_letter_indices.get(c, 0)
|
|
83
|
-
|
|
84
|
-
if a >= alphabet_length or b >= alphabet_length or c >= alphabet_length or a < 0 or b < 0 or c < 0:
|
|
85
|
-
continue
|
|
86
|
-
value += self.frequencies[a, b, c]
|
|
87
|
-
|
|
88
|
-
return value / end
|
|
89
|
-
|
|
90
|
-
def gram_size(self):
|
|
91
|
-
"""
|
|
92
|
-
Returns the size of the grams being analyzed (trigrams in this case).
|
|
93
|
-
|
|
94
|
-
Returns:
|
|
95
|
-
- int: The size of the grams (always 3 for trigrams).
|
|
96
|
-
"""
|
|
97
|
-
return 3
|
|
98
|
-
|
|
99
|
-
def grams_type(self):
|
|
100
|
-
"""
|
|
101
|
-
Returns the type of grams being analyzed.
|
|
102
|
-
|
|
103
|
-
Returns:
|
|
104
|
-
- GramsType: An enum value representing the type of grams (GramsType.Trigrams).
|
|
105
|
-
"""
|
|
106
|
-
return GramsType.Trigrams
|
|
107
|
-
|
|
108
|
-
def normalize(self, max_value):
|
|
109
|
-
"""
|
|
110
|
-
Normalizes the trigram frequencies based on the provided maximum value.
|
|
111
|
-
|
|
112
|
-
Parameters:
|
|
113
|
-
- max_value (float): The maximum value used for normalization.
|
|
114
|
-
|
|
115
|
-
Notes:
|
|
116
|
-
- Adjusts all frequencies proportionally to the new maximum value.
|
|
117
|
-
- Updates `self.max_value` to the new maximum after normalization.
|
|
118
|
-
"""
|
|
119
|
-
super().normalize(max_value)
|
|
120
|
-
adjust_value = self.max_value * max_value
|
|
121
|
-
for a in range(len(self.alphabet)):
|
|
122
|
-
for b in range(len(self.alphabet)):
|
|
123
|
-
for c in range(len(self.alphabet)):
|
|
124
|
-
self.frequencies[a, b, c] = adjust_value / self.frequencies[a, b, c]
|
|
125
|
-
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
1
|
+
'''
|
|
2
|
+
Copyright 2024 Nils Kopal, Bernhard Esslinger, CrypTool Team
|
|
3
|
+
|
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
5
|
+
you may not use this file except in compliance with the License.
|
|
6
|
+
You may obtain a copy of the License at
|
|
7
|
+
|
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
9
|
+
|
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
13
|
+
See the License for the specific language governing permissions and
|
|
14
|
+
limitations under the License.
|
|
15
|
+
'''
|
|
16
|
+
import numpy as np
|
|
17
|
+
import os
|
|
18
|
+
from languagestatisticslibpy.Grams import Grams
|
|
19
|
+
from languagestatisticslibpy.GramsType import GramsType
|
|
20
|
+
from languagestatisticslibpy.LanguageStatisticsFile import LanguageStatisticsFile
|
|
21
|
+
|
|
22
|
+
class Trigrams(Grams):
|
|
23
|
+
def __init__(self, language, language_statistics_directory, use_spaces=False):
|
|
24
|
+
"""
|
|
25
|
+
Initializes the Trigrams class by calling the parent class (Grams) initializer.
|
|
26
|
+
|
|
27
|
+
Parameters:
|
|
28
|
+
- language (str): The language of the trigram statistics.
|
|
29
|
+
- language_statistics_directory (str): Path to the directory containing language statistics files.
|
|
30
|
+
- use_spaces (bool): Whether to include spaces in the analysis (default: False).
|
|
31
|
+
"""
|
|
32
|
+
super().__init__(language, language_statistics_directory, use_spaces)
|
|
33
|
+
|
|
34
|
+
def load_gz(self, filename, language_statistics_directory):
|
|
35
|
+
"""
|
|
36
|
+
Loads a gzip-compressed file containing trigram frequencies.
|
|
37
|
+
|
|
38
|
+
Parameters:
|
|
39
|
+
- filename (str): The name of the file to load.
|
|
40
|
+
- language_statistics_directory (str): The directory where the statistics file is located.
|
|
41
|
+
|
|
42
|
+
Sets:
|
|
43
|
+
- self.frequencies (np.ndarray): A 3D array of trigram frequencies.
|
|
44
|
+
- self.alphabet (list): The alphabet used in the statistics file.
|
|
45
|
+
- self.max_value (float): The maximum value in the frequencies array, or -∞ if the array is empty.
|
|
46
|
+
"""
|
|
47
|
+
file_path = os.path.join(language_statistics_directory, filename)
|
|
48
|
+
language_statistics_file = LanguageStatisticsFile(file_path)
|
|
49
|
+
self.frequencies = language_statistics_file.load_frequencies(3)
|
|
50
|
+
self.alphabet = language_statistics_file.alphabet
|
|
51
|
+
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|
|
52
|
+
|
|
53
|
+
def calculate_cost(self, text):
|
|
54
|
+
"""
|
|
55
|
+
Calculates the cost of a given text based on trigram frequencies.
|
|
56
|
+
|
|
57
|
+
Parameters:
|
|
58
|
+
- text (str): The text to analyze.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
- float: The average cost of trigrams in the text. Returns 0 if the text length is less than 3.
|
|
62
|
+
|
|
63
|
+
Notes:
|
|
64
|
+
- Skips trigrams containing characters outside the defined alphabet.
|
|
65
|
+
- If `add_letter_indices` is defined, modifies indices of the characters before computing the cost.
|
|
66
|
+
"""
|
|
67
|
+
if len(text) < 3:
|
|
68
|
+
return 0
|
|
69
|
+
|
|
70
|
+
value = 0
|
|
71
|
+
alphabet_length = len(self.alphabet)
|
|
72
|
+
end = len(text) - 2
|
|
73
|
+
|
|
74
|
+
for i in range(end):
|
|
75
|
+
a = text[i]
|
|
76
|
+
b = text[i + 1]
|
|
77
|
+
c = text[i + 2]
|
|
78
|
+
|
|
79
|
+
if self.add_letter_indices:
|
|
80
|
+
a += self.add_letter_indices.get(a, 0)
|
|
81
|
+
b += self.add_letter_indices.get(b, 0)
|
|
82
|
+
c += self.add_letter_indices.get(c, 0)
|
|
83
|
+
|
|
84
|
+
if a >= alphabet_length or b >= alphabet_length or c >= alphabet_length or a < 0 or b < 0 or c < 0:
|
|
85
|
+
continue
|
|
86
|
+
value += self.frequencies[a, b, c]
|
|
87
|
+
|
|
88
|
+
return value / end
|
|
89
|
+
|
|
90
|
+
def gram_size(self):
|
|
91
|
+
"""
|
|
92
|
+
Returns the size of the grams being analyzed (trigrams in this case).
|
|
93
|
+
|
|
94
|
+
Returns:
|
|
95
|
+
- int: The size of the grams (always 3 for trigrams).
|
|
96
|
+
"""
|
|
97
|
+
return 3
|
|
98
|
+
|
|
99
|
+
def grams_type(self):
|
|
100
|
+
"""
|
|
101
|
+
Returns the type of grams being analyzed.
|
|
102
|
+
|
|
103
|
+
Returns:
|
|
104
|
+
- GramsType: An enum value representing the type of grams (GramsType.Trigrams).
|
|
105
|
+
"""
|
|
106
|
+
return GramsType.Trigrams
|
|
107
|
+
|
|
108
|
+
def normalize(self, max_value):
|
|
109
|
+
"""
|
|
110
|
+
Normalizes the trigram frequencies based on the provided maximum value.
|
|
111
|
+
|
|
112
|
+
Parameters:
|
|
113
|
+
- max_value (float): The maximum value used for normalization.
|
|
114
|
+
|
|
115
|
+
Notes:
|
|
116
|
+
- Adjusts all frequencies proportionally to the new maximum value.
|
|
117
|
+
- Updates `self.max_value` to the new maximum after normalization.
|
|
118
|
+
"""
|
|
119
|
+
super().normalize(max_value)
|
|
120
|
+
adjust_value = self.max_value * max_value
|
|
121
|
+
for a in range(len(self.alphabet)):
|
|
122
|
+
for b in range(len(self.alphabet)):
|
|
123
|
+
for c in range(len(self.alphabet)):
|
|
124
|
+
self.frequencies[a, b, c] = adjust_value / self.frequencies[a, b, c]
|
|
125
|
+
self.max_value = np.max(self.frequencies) if self.frequencies.size > 0 else float('-inf')
|