LanguageStatisticsLibPy 1.0.3__tar.gz → 1.0.4__tar.gz

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.
Files changed (19) hide show
  1. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/PKG-INFO +4 -2
  2. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/README.md +105 -105
  3. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/pyproject.toml +3 -3
  4. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/LanguageStatisticsFile.py +48 -40
  5. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Tetragrams.py +125 -125
  6. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Trigrams.py +125 -125
  7. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Unigrams.py +110 -110
  8. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/WordTree.py +161 -161
  9. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/test1.py +26 -26
  10. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/test2.py +80 -80
  11. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/LICENSE +0 -0
  12. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Bigrams.py +0 -0
  13. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Grams.py +0 -0
  14. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/GramsType.py +0 -0
  15. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Hexagrams.py +0 -0
  16. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/LanguageStatistics.py +0 -0
  17. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Node.py +0 -0
  18. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/Pentagrams.py +0 -0
  19. {languagestatisticslibpy-1.0.3 → languagestatisticslibpy-1.0.4}/src/languagestatisticslibpy/__init__.py +0 -0
@@ -1,8 +1,9 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: LanguageStatisticsLibPy
3
- Version: 1.0.3
3
+ Version: 1.0.4
4
4
  Summary: Quick and robust Python functions to do cryptanalysis using language statistics data for 15 languages
5
5
  License: Apache-2.0
6
+ License-File: LICENSE
6
7
  Author: Nils Kopal and Bernhard Esslinger
7
8
  Author-email: kopal@cryptool.org
8
9
  Requires-Python: >=3.10,<4.0
@@ -13,6 +14,7 @@ Classifier: Programming Language :: Python :: 3.10
13
14
  Classifier: Programming Language :: Python :: 3.11
14
15
  Classifier: Programming Language :: Python :: 3.12
15
16
  Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
16
18
  Project-URL: Homepage, https://github.com/CrypToolProject/LanguageStatisticsLibPy
17
19
  Description-Content-Type: text/markdown
18
20
 
@@ -1,106 +1,106 @@
1
- # LanguageStatisticsLibPy
2
-
3
- LanguageStatisticsLibPy is a Python library designed to facilitate the fast analysis and manipulation of language statistics data. It originates from a C# library that was first used in the widespread cryptography e-learning software CrypTool 2. From now on "CrypTool 2" is abbreviated "CT2". CT2 is an open-source e-learning program for Windows to do cryptography and cryptanalysis (https://www.cryptool.org/en/ct2/).
4
-
5
- This Python library supports 15 different languages and offers functionality for generating and handling n-gram data, specifically for calculating n-gram frequencies using the language statistics files from CT2.
6
- Additionally, it facilitates the use of CT2's dictionaries through a "Word Tree", an efficient data structure for rapid word searches within a language.
7
-
8
- The language statistics files (for example, `en-5gram-nocs.gz` indicates an English 5-gram file that is not case-sensitive and excludes spaces) can be found in the "LanguageStatistics" subdirectory of CT2, if you have installed CT2 on Windows.
9
- If you don't have a Windows machine or you don't want to install CT2, you may download the language statistics files and dictionaries from the CT2 Github repo: [Language Statistics](https://github.com/CrypToolProject/CrypTool-2/tree/main/LanguageStatistics).
10
-
11
- Remark: This package contains the implemented algorithms without the language statistics files. These files have to be downloaded separately as they occupy many megabytes.
12
-
13
- ## Features
14
-
15
- - **Support for multiple languages**: The library includes predefined support for 15 languages, including English, German, Spanish, French -- each with its own set of unigram frequencies and alphabets.
16
-
17
- - **N-gram loading**: Users can load unigrams, bigrams, trigrams, tetragrams, pentagrams, and hexagrams as n-gram objects in supported languages, with the option to include or exclude spaces. The n-grams delivered in the language statistics files range from 1 to 5 (we don't deliver 6-grams within CT2, since these files are too big). All language statistics files delivered are case-insensitive, denoted as "nocs" in the filename. Each language statistics is available in two forms: with space/blank ("sp" in the filename) and without space/blank (indicated by the absence of "sp" in the filename) within the alphabet.
18
-
19
- - **Index of Coincidence calculation**: It offers a method to calculate the index of coincidence (IoC) for a given plaintext, which is useful for cryptanalysis and language pattern recognition.
20
-
21
- - **Alphabet and number mapping**: The library provides functionality to map characters to their respective positions in a language's alphabet and vice versa, supporting operations on encoded messages or language data.
22
-
23
- - **Dynamic n-gram support**: Depending on the available data, the library dynamically supports various n-gram types.
24
- - **Word tree data structure**: It supports a word tree data structure for fast word lookups (true = part of language, false = not part of language) of a specific language.
25
-
26
- ## Usage
27
-
28
- Prerequisites: LanguageStatisticsLibPy is installed on your computer via
29
- **$ pip3 install LanguageStatisticsLibPy**
30
-
31
- 1. **Initialization**: Start by importing the `LanguageStatistics` class and specify the language code for your analysis.
32
- 2. **Loading n-grams**: To load n-grams of your chosen type (e.g., unigrams, bigrams) for a specific language, use the `create_grams` method with the appropriate .gz file from the LanguageStatistics directory in CT2. For instance, to load English 4-grams that are case-insensitive and include the space/blank symbol, use the file named `en-4gram-nocs-sp.gz`.
33
- 3. **Calculating IoC**: Calculate the index of coincidence for a given plaintext using the `calculate_ioc` method.
34
- 4. **Word tree loading**: For advanced language analysis, load a pre-built word tree for a specific language using the `load_word_tree` method.
35
-
36
- Sample usage (from file `test1.py`):
37
-
38
- ```python
39
- from languagestatisticslibpy.LanguageStatistics import LanguageStatistics as LS
40
-
41
- plaintext = LS.map_text_into_number_space("HELLOWORD", LS.alphabets['en'])
42
- ioc = LS.calculate_ioc(plaintext)
43
-
44
- print(ioc)
45
- ```
46
-
47
- You can find further example usages in the file `test2.py` within the package.
48
-
49
- ## Supported languages
50
-
51
- The library includes predefined configurations for the following languages:
52
- - English (en)
53
- - German (de)
54
- - Spanish (es)
55
- - French (fr)
56
- - Italian (it)
57
- - Hungarian (hu)
58
- - Russian (ru)
59
- - Czech (cs)
60
- - Greek (el)
61
- - Latin (la)
62
- - Dutch (nl)
63
- - Swedish (sv)
64
- - Portuguese (pt)
65
- - Polish (pl)
66
- - Turkish (tr)
67
-
68
-
69
- ## Some more technical details
70
-
71
- ### Where are the package files stored after installing the package and how to find this out
72
-
73
- ```bash
74
- % pip3 list | grep LanguageStatisticsLibPy
75
- % pip3 show LanguageStatisticsLibPy
76
-
77
- # show package content (including the test files) for example on Mac
78
- % tree /Users/be/Library/Python/3.13/lib/python/site-packages/LanguageStatisticsLibPy
79
- # on Linux this could be in:
80
- # /home/user/.local/lib/python3.10/site-packages/LanguageStatisticsLibPy/
81
- ...
82
- # show content of a directory where the statistics files had been copied to
83
- tree /Users/be/Documents/Python/LanguageStatisticsLibPy_PIP-Test/LSLP
84
- ...
85
- ```
86
-
87
- ### How to call the test files
88
- ```bash
89
- % pwd
90
- /Users/be/Documents/Python/LanguageStatisticsLibPy_PIP-Test/testen2
91
-
92
- % ls -l
93
- -rwx------ 1 be staff 956 27 Dez 09:44 test1.py
94
- -rwx------ 1 be staff 2944 27 Dez 09:42 test2.py
95
-
96
- % python3 test1.py
97
- 0.08333333333333333
98
-
99
- % python3 test2.py
100
- Grams size: 1
101
- Grams loaded in 0:00:00.000097
102
- Grams normalized in 0:00:00.000007
103
- Text: HELLOWORLDTHISISATEST
104
- Cost value: 771793.56
105
- ...
1
+ # LanguageStatisticsLibPy
2
+
3
+ LanguageStatisticsLibPy is a Python library designed to facilitate the fast analysis and manipulation of language statistics data. It originates from a C# library that was first used in the widespread cryptography e-learning software CrypTool 2. From now on "CrypTool 2" is abbreviated "CT2". CT2 is an open-source e-learning program for Windows to do cryptography and cryptanalysis (https://www.cryptool.org/en/ct2/).
4
+
5
+ This Python library supports 15 different languages and offers functionality for generating and handling n-gram data, specifically for calculating n-gram frequencies using the language statistics files from CT2.
6
+ Additionally, it facilitates the use of CT2's dictionaries through a "Word Tree", an efficient data structure for rapid word searches within a language.
7
+
8
+ The language statistics files (for example, `en-5gram-nocs.gz` indicates an English 5-gram file that is not case-sensitive and excludes spaces) can be found in the "LanguageStatistics" subdirectory of CT2, if you have installed CT2 on Windows.
9
+ If you don't have a Windows machine or you don't want to install CT2, you may download the language statistics files and dictionaries from the CT2 Github repo: [Language Statistics](https://github.com/CrypToolProject/CrypTool-2/tree/main/LanguageStatistics).
10
+
11
+ Remark: This package contains the implemented algorithms without the language statistics files. These files have to be downloaded separately as they occupy many megabytes.
12
+
13
+ ## Features
14
+
15
+ - **Support for multiple languages**: The library includes predefined support for 15 languages, including English, German, Spanish, French -- each with its own set of unigram frequencies and alphabets.
16
+
17
+ - **N-gram loading**: Users can load unigrams, bigrams, trigrams, tetragrams, pentagrams, and hexagrams as n-gram objects in supported languages, with the option to include or exclude spaces. The n-grams delivered in the language statistics files range from 1 to 5 (we don't deliver 6-grams within CT2, since these files are too big). All language statistics files delivered are case-insensitive, denoted as "nocs" in the filename. Each language statistics is available in two forms: with space/blank ("sp" in the filename) and without space/blank (indicated by the absence of "sp" in the filename) within the alphabet.
18
+
19
+ - **Index of Coincidence calculation**: It offers a method to calculate the index of coincidence (IoC) for a given plaintext, which is useful for cryptanalysis and language pattern recognition.
20
+
21
+ - **Alphabet and number mapping**: The library provides functionality to map characters to their respective positions in a language's alphabet and vice versa, supporting operations on encoded messages or language data.
22
+
23
+ - **Dynamic n-gram support**: Depending on the available data, the library dynamically supports various n-gram types.
24
+ - **Word tree data structure**: It supports a word tree data structure for fast word lookups (true = part of language, false = not part of language) of a specific language.
25
+
26
+ ## Usage
27
+
28
+ Prerequisites: LanguageStatisticsLibPy is installed on your computer via
29
+ **$ pip3 install LanguageStatisticsLibPy**
30
+
31
+ 1. **Initialization**: Start by importing the `LanguageStatistics` class and specify the language code for your analysis.
32
+ 2. **Loading n-grams**: To load n-grams of your chosen type (e.g., unigrams, bigrams) for a specific language, use the `create_grams` method with the appropriate .gz file from the LanguageStatistics directory in CT2. For instance, to load English 4-grams that are case-insensitive and include the space/blank symbol, use the file named `en-4gram-nocs-sp.gz`.
33
+ 3. **Calculating IoC**: Calculate the index of coincidence for a given plaintext using the `calculate_ioc` method.
34
+ 4. **Word tree loading**: For advanced language analysis, load a pre-built word tree for a specific language using the `load_word_tree` method.
35
+
36
+ Sample usage (from file `test1.py`):
37
+
38
+ ```python
39
+ from languagestatisticslibpy.LanguageStatistics import LanguageStatistics as LS
40
+
41
+ plaintext = LS.map_text_into_number_space("HELLOWORD", LS.alphabets['en'])
42
+ ioc = LS.calculate_ioc(plaintext)
43
+
44
+ print(ioc)
45
+ ```
46
+
47
+ You can find further example usages in the file `test2.py` within the package.
48
+
49
+ ## Supported languages
50
+
51
+ The library includes predefined configurations for the following languages:
52
+ - English (en)
53
+ - German (de)
54
+ - Spanish (es)
55
+ - French (fr)
56
+ - Italian (it)
57
+ - Hungarian (hu)
58
+ - Russian (ru)
59
+ - Czech (cs)
60
+ - Greek (el)
61
+ - Latin (la)
62
+ - Dutch (nl)
63
+ - Swedish (sv)
64
+ - Portuguese (pt)
65
+ - Polish (pl)
66
+ - Turkish (tr)
67
+
68
+
69
+ ## Some more technical details
70
+
71
+ ### Where are the package files stored after installing the package and how to find this out
72
+
73
+ ```bash
74
+ % pip3 list | grep LanguageStatisticsLibPy
75
+ % pip3 show LanguageStatisticsLibPy
76
+
77
+ # show package content (including the test files) for example on Mac
78
+ % tree /Users/be/Library/Python/3.13/lib/python/site-packages/LanguageStatisticsLibPy
79
+ # on Linux this could be in:
80
+ # /home/user/.local/lib/python3.10/site-packages/LanguageStatisticsLibPy/
81
+ ...
82
+ # show content of a directory where the statistics files had been copied to
83
+ tree /Users/be/Documents/Python/LanguageStatisticsLibPy_PIP-Test/LSLP
84
+ ...
85
+ ```
86
+
87
+ ### How to call the test files
88
+ ```bash
89
+ % pwd
90
+ /Users/be/Documents/Python/LanguageStatisticsLibPy_PIP-Test/testen2
91
+
92
+ % ls -l
93
+ -rwx------ 1 be staff 956 27 Dez 09:44 test1.py
94
+ -rwx------ 1 be staff 2944 27 Dez 09:42 test2.py
95
+
96
+ % python3 test1.py
97
+ 0.08333333333333333
98
+
99
+ % python3 test2.py
100
+ Grams size: 1
101
+ Grams loaded in 0:00:00.000097
102
+ Grams normalized in 0:00:00.000007
103
+ Text: HELLOWORLDTHISISATEST
104
+ Cost value: 771793.56
105
+ ...
106
106
  ```
@@ -1,9 +1,9 @@
1
1
  [tool.poetry]
2
2
  name = "LanguageStatisticsLibPy"
3
- version = "1.0.3"
3
+ version = "1.0.4"
4
4
  description = "Quick and robust Python functions to do cryptanalysis using language statistics data for 15 languages"
5
5
  readme = "README.md"
6
- authors = ["Nils Kopal and Bernhard Esslinger <kopal@cryptool.org>"]
6
+ authors = ["Nils Kopal and Bernhard Esslinger <kopal@cryptool.org>"]
7
7
  license = "Apache-2.0"
8
8
  classifiers = [
9
9
  "Programming Language :: Python :: 3",
@@ -24,4 +24,4 @@ dependencies = [
24
24
 
25
25
  [build-system]
26
26
  requires = ["poetry-core>=1.0.0"]
27
- build-backend = "poetry.core.masonry.api"
27
+ build-backend = "poetry.core.masonry.api"
@@ -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.language_code = ''
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 or the dimensions of the frequency array do not match the expected value.
65
-
66
- Process:
67
- 1. Validates the file by checking the magic number.
68
- 2. Reads the language code, gram length, and alphabet.
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
- with gzip.open(self.file_path, 'rb') as file:
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('utf-8')
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('utf-8')
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('<i', file.read(4))[0]
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 string).
91
- self.alphabet_length = file.read(1)[0]
92
- self.alphabet = file.read(self.alphabet_length).decode('utf-8')
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(frequency_entries * 4)
99
-
100
- # Reshape the data into the correct dimensionality and copy it for mutability.
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
- frequencies = np.frombuffer(frequency_data, dtype=np.float32).copy()
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 frequencies
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')