splintering 1.0.0__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.
splintering/trainer.py ADDED
@@ -0,0 +1,168 @@
1
+ import json
2
+ import os
3
+
4
+ import numpy as np
5
+ from datasets import load_dataset
6
+
7
+ from splintering.utils.corpus_tools import CorpusWordsExtractor
8
+ from splintering.utils.languages import LanguageUtilsInterface
9
+ from splintering.utils.logger import get_logger
10
+ from splintering.utils.path_utils import get_logs_dir, get_raw_data_dir, get_splinter_dir, get_words_dict_dir
11
+ from splintering.utils.misc import get_words_dict_by_length, get_permutation, get_corpus_name
12
+
13
+
14
+ class SplinterTrainer:
15
+ def __init__(self, language_utils: LanguageUtilsInterface):
16
+ self.language_utils = language_utils
17
+
18
+ def train(self, dataset_path: str, dataset_name: str, letters_for_reductions: list[str] = None):
19
+ words_dict = self.get_word_dict(dataset_path, dataset_name)
20
+ pre_process_words_dict = self.pre_process_words(words_dict)
21
+ words_dict_by_length = get_words_dict_by_length(pre_process_words_dict)
22
+ max_length = sorted(words_dict_by_length.keys(), reverse=True)[0]
23
+
24
+ get_logger().info(f"Start first iteration of reductions:")
25
+ reductions = self.initialize_reductions_dict(max_length)
26
+ for word_length in range(4, max_length + 1):
27
+ current_length_words = words_dict_by_length[word_length].keys()
28
+ previous_length_words = words_dict_by_length[word_length - 1].keys()
29
+ for word in current_length_words:
30
+ for position in self.get_position_range_including_negative_indexes(word):
31
+ if letters_for_reductions is None or word[position] in letters_for_reductions:
32
+ permutation = get_permutation(word, position, word_length)
33
+ if permutation in previous_length_words:
34
+ reduction_key = f"{position}:{word[position]}"
35
+ self.increment_value(reductions[word_length], reduction_key)
36
+
37
+ reductions[word_length] = self.normalize_values(self.sort_dictionary(reductions[word_length]))
38
+ get_logger().info(f"Finished reductions for word length {word_length}")
39
+
40
+ with open(f'{get_logs_dir()}/reductions_map_first_iteration.json', 'w') as file:
41
+ json.dump(reductions, file, indent='\t')
42
+
43
+ get_logger().info(f"Start updating reductions:")
44
+ updated_reductions = self.initialize_reductions_dict(max_length)
45
+ for word_length in range(4, max_length + 1):
46
+ previous_length_words = words_dict_by_length[word_length - 1]
47
+ current_length_words = words_dict_by_length[word_length]
48
+ for word, score in list(current_length_words.items()):
49
+ reduction_with_score = self.get_reduction(word, reductions, previous_length_words, 3)
50
+ if reduction_with_score is not None:
51
+ self.increment_value(updated_reductions[word_length], reduction_with_score['reduction'])
52
+ current_length_words[word] = score * reduction_with_score['score']
53
+
54
+ # sort by frequency
55
+ updated_reductions[word_length] = self.normalize_values(self.sort_dictionary(updated_reductions[word_length]))
56
+ # remove word lengths that doesn't have possible reductions
57
+ if len(updated_reductions[word_length]) == 0:
58
+ del updated_reductions[word_length]
59
+ get_logger().info(f"Finished updating reductions for word length {word_length}")
60
+
61
+ with open(f'{get_logs_dir()}/reductions_map_with_frequencies.json', 'w') as file:
62
+ json.dump(updated_reductions, file, indent='\t')
63
+
64
+ self.save_result_file("reductions_map", updated_reductions)
65
+ reduction_to_new_chars_map = self.map_reductions_to_new_chars(updated_reductions)
66
+ self.save_result_file("new_unicode_chars", reduction_to_new_chars_map)
67
+ new_chars_to_reductions_map = {value: key for key, value in reduction_to_new_chars_map.items()}
68
+ self.save_result_file("new_unicode_chars_inverted", new_chars_to_reductions_map)
69
+ return updated_reductions, reduction_to_new_chars_map, new_chars_to_reductions_map
70
+
71
+ def get_word_dict(self, dataset_path, dataset_name):
72
+ corpus_name = get_corpus_name(dataset_path, dataset_name)
73
+ if not os.path.exists(f'{get_words_dict_dir()}/{corpus_name}.json'):
74
+ get_logger().info(f'word dict file was not found - creating it from corpus')
75
+ corpus = load_dataset(dataset_path, dataset_name, split="train", cache_dir=get_raw_data_dir())
76
+ corpus_word_extractor = CorpusWordsExtractor(self.language_utils)
77
+ corpus_word_extractor.convert_corpus_to_words_dict_file(corpus, corpus_name)
78
+
79
+ with open(f'{get_words_dict_dir()}/{corpus_name}.json', 'r') as file:
80
+ words_dict = json.load(file)
81
+ return words_dict
82
+
83
+ def pre_process_words(self, word_counters):
84
+ # Remove words that appeared less than 10 times in the entire corpus
85
+ words = {k: int(v) for k, v in word_counters.items() if int(v) >= 10}
86
+
87
+ words = {self.language_utils.replace_final_letters(k): v for k, v in words.items()}
88
+
89
+ # Remove empty words and single characters words
90
+ words = {k: int(v) for k, v in words.items() if len(k) > 1}
91
+
92
+ # remove words containing characters from other languages.
93
+ words = {k: v for k, v in words.items() if not self.language_utils.is_word_contains_letters_from_other_languages(k)}
94
+
95
+ # normalize values
96
+ max_counter = max(words.values())
97
+ words = {k: (v / max_counter) for k, v in words.items()}
98
+ return words
99
+
100
+ def initialize_reductions_dict(self, max_length):
101
+ # adding single chars to the map, so "root" letters will also be converted when encoding the text
102
+ single_chars = self.language_utils.get_language_alphabet()
103
+ reductions = {1: {single_char: 1 for single_char in single_chars}}
104
+
105
+ for i in range(4, max_length + 1):
106
+ reductions[i] = {}
107
+ return reductions
108
+
109
+ def increment_value(self, dictionary, key):
110
+ if key in dictionary.keys():
111
+ dictionary[key] += 1
112
+ else:
113
+ dictionary[key] = 1
114
+
115
+ def map_reductions_to_new_chars(self, reductions):
116
+ reductions_set = set()
117
+ for word_length, reductions in reductions.items():
118
+ reductions_set.update(reductions.keys())
119
+ reduction_to_new_chars_map = dict()
120
+ unicode_pua_start = 0x5000
121
+ for i, reduction in enumerate(sorted(reductions_set)):
122
+ new_char = chr(unicode_pua_start + i)
123
+ reduction_to_new_chars_map[reduction] = new_char
124
+ return reduction_to_new_chars_map
125
+
126
+ def sort_dictionary(self, dictionary):
127
+ return dict(sorted(dictionary.items(), key=lambda item: (-item[1], item[0])))
128
+
129
+ # change to percents
130
+ def normalize_values(self, dictionary):
131
+ values = np.array(list(dictionary.values()))
132
+ percent_dictionary = {key: value for key, value in zip(dictionary.keys(), (values / np.sum(values)))}
133
+ return percent_dictionary
134
+
135
+ def get_position_range_including_negative_indexes(self, word):
136
+ half_length = len(word) // 2
137
+ return range(-half_length, half_length + len(word) % 2)
138
+
139
+ def get_reduction(self, word, reductions, previous_length_words, max_number_of_candidates):
140
+ word_length = len(word)
141
+ possible_reductions = list()
142
+ if word_length > 3:
143
+ for reduction, reduction_score in reductions[word_length].items():
144
+ position, letter = reduction.split(':')
145
+ position = int(position)
146
+ if word[position] == letter:
147
+ permutation = get_permutation(word, position, word_length)
148
+ if permutation in previous_length_words:
149
+ permutation_score = previous_length_words[permutation]
150
+ possible_reductions.append({"reduction": reduction, "score": reduction_score * permutation_score})
151
+ if len(possible_reductions) >= max_number_of_candidates:
152
+ break
153
+
154
+ max_score_reduction = None
155
+ if len(possible_reductions) > 0:
156
+ max_score_reduction = max(possible_reductions, key=lambda x: x["score"])
157
+ return max_score_reduction
158
+
159
+ def save_result_file(self, file_name, data):
160
+ if not os.path.exists(get_splinter_dir()):
161
+ os.makedirs(get_splinter_dir())
162
+
163
+ with open(f'{get_splinter_dir()}/{file_name}.json', 'w') as file:
164
+ json.dump(data, file, indent='\t')
165
+
166
+ # keep a copy of results in the log dir
167
+ with open(f'{get_logs_dir()}/{file_name}.json', 'w') as file:
168
+ json.dump(data, file, indent='\t')
File without changes
@@ -0,0 +1,134 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ from tqdm import tqdm
7
+
8
+ import sentencepiece as spm
9
+ from datasets import load_dataset
10
+
11
+ from splintering.utils.misc import get_corpus_name
12
+ from splintering.utils.languages import LanguageUtilsInterface
13
+ from splintering.utils.path_utils import get_words_dict_dir, get_raw_data_dir, delete_corpus_file_if_exists, get_corpus_path
14
+ from splintering.utils.logger import get_logger
15
+
16
+
17
+ class CorpusTokenizer:
18
+
19
+ @staticmethod
20
+ def tokenize_corpus_into_file(tokenizer_path, corpus_path, output_path):
21
+ if os.path.exists(output_path):
22
+ os.remove(output_path)
23
+
24
+ get_logger().info(f'start tokenizing corpus {output_path}')
25
+ sp_tokenizer = spm.SentencePieceProcessor(model_file=f'{tokenizer_path}.model')
26
+ with open(corpus_path, 'r', encoding='utf-8') as corpus_file:
27
+ with open(output_path, 'a', encoding='utf-8') as output_file:
28
+ for article_text in tqdm(corpus_file):
29
+ if article_text is not None:
30
+ encoded_article = " ".join([str(token_id) for token_id in sp_tokenizer.encode(article_text)])
31
+ output_file.write(encoded_article + '\n')
32
+ get_logger().info(f'finished tokenizing corpus {output_path}')
33
+
34
+
35
+ class CorpusWordsExtractor:
36
+
37
+ def __init__(self, language_utils: LanguageUtilsInterface):
38
+ self.language_utils = language_utils
39
+
40
+ def convert_corpus_to_words_dict_file(self, corpus, output_filename):
41
+ words = self.get_words_from_corpus(corpus["text"])
42
+ if not os.path.exists(get_words_dict_dir()):
43
+ os.makedirs(get_words_dict_dir())
44
+ with open(f'{get_words_dict_dir()}/{output_filename}.json', 'w') as file:
45
+ json.dump(words, file, indent='\t')
46
+
47
+ def get_words_from_corpus(self, articles_text):
48
+ words = {}
49
+ for index, article_text in enumerate(articles_text):
50
+ article_text = self.language_utils.remove_diacritics(article_text)
51
+ article_words = re.split(r'\.|\s|\n|-|,|:|"|\(|\)', article_text)
52
+
53
+ for word in article_words:
54
+ if word not in words:
55
+ words[word] = 0
56
+ words[word] += 1
57
+
58
+ if (index + 1) % 10000 == 0:
59
+ get_logger().info(f'Finished extracting words from {index + 1} articles out of {len(articles_text)}')
60
+ get_logger().info(f'Finished extracting words from {len(articles_text)} articles out of {len(articles_text)}')
61
+ return words
62
+
63
+
64
+ class TextProcessorInterface(ABC):
65
+
66
+ def __init__(self, language_utils: LanguageUtilsInterface):
67
+ self.language_utils = language_utils
68
+
69
+ @abstractmethod
70
+ def process(self, text: str) -> str:
71
+ pass
72
+
73
+ def save_corpus_as_text_file(self, dataset_path: str, dataset_name: str, batch_size=10000):
74
+ corpus_name = get_corpus_name(dataset_path, dataset_name)
75
+ get_logger().info(f'Start saving {corpus_name} corpus as text file with {self.__class__.__name__}')
76
+ dataset = load_dataset(dataset_path, dataset_name, split="train", cache_dir=get_raw_data_dir())
77
+ delete_corpus_file_if_exists(corpus_name)
78
+ for i, j in enumerate(tqdm(range(0, len(dataset), batch_size))):
79
+ dataset_batch = dataset[j:j + batch_size]
80
+ self.process_batch(dataset_batch, corpus_name)
81
+ get_logger().info(f'Finished saving {corpus_name} corpus')
82
+
83
+ def save_hedc4_corpus(self, batch_size=10000):
84
+ corpus_name = 'HeNLP_HeDC4'
85
+ get_logger().info(f'Start saving {corpus_name} corpus as text file with {self.__class__.__name__}')
86
+ corpus_path = f'{get_raw_data_dir()}/HeNLP-he_dc4-10percent/HeDC4-10percent-seed42-sample.csv'
87
+ if not os.path.exists(corpus_path):
88
+ get_logger().info(f'HeDC4-10percent file was not found - creating it from full corpus')
89
+ full_corpus = load_dataset('HeNLP/HeDC4', split="train", cache_dir=get_raw_data_dir())
90
+ sample_lines_from_corpus_to_csv(full_corpus, corpus_path)
91
+
92
+ dataset = load_dataset("csv", data_files=corpus_path)
93
+ delete_corpus_file_if_exists(corpus_name)
94
+ for i, j in enumerate(tqdm(range(0, len(dataset['train']), batch_size))):
95
+ dataset_batch = dataset['train'][j:j + batch_size]
96
+ self.process_batch(dataset_batch, corpus_name)
97
+ get_logger().info(f'Finished saving {corpus_name} corpus')
98
+
99
+ # hebrew_diacritized repository needs to be git cloned as a prerequisite from
100
+ # https://github.com/elazarg/hebrew_diacritized.git
101
+ # into Splinter/raw_data/hebrew_diacritized folder
102
+ def save_pre_modern_corpus(self):
103
+ corpus_name = 'hebrew_diacritized_pre_modern'
104
+ get_logger().info(f'Start saving {corpus_name} corpus as text file with {self.__class__.__name__}')
105
+ path = f'{get_raw_data_dir()}/hebrew_diacritized/pre_modern'
106
+ files = get_all_files_in_dir(path)
107
+ dataset_batch = {'text': list()}
108
+ for filename in files:
109
+ with open(f'{filename}', 'r', encoding='utf-8') as file:
110
+ dataset_batch['text'].append("\n".join(file.readlines()))
111
+ delete_corpus_file_if_exists(corpus_name)
112
+ self.process_batch(dataset_batch, corpus_name)
113
+ get_logger().info(f'Finished saving {corpus_name} corpus')
114
+
115
+ def process_batch(self, dataset_batch, corpus_name):
116
+ encoded_articles_list = list()
117
+ for article_text in dataset_batch["text"]:
118
+ encoded_article = self.process(article_text)
119
+ encoded_articles_list.append(encoded_article)
120
+ with open(get_corpus_path(corpus_name), 'a', encoding='utf-8') as file:
121
+ file.write("\n".join(encoded_articles_list))
122
+
123
+
124
+ def get_all_files_in_dir(directory):
125
+ return [os.path.join(root, file) for root, _, files in os.walk(directory) for file in files]
126
+
127
+
128
+ def sample_lines_from_corpus_to_csv(full_corpus, output_file):
129
+ get_logger().info(f'Start sample lines from corpus')
130
+ random_seed = 42
131
+ sample_size = int(0.1 * len(full_corpus))
132
+ sampled_dataset = full_corpus.shuffle(seed=random_seed).select(range(sample_size))
133
+ sampled_dataset.to_csv(output_file, index=False)
134
+ get_logger().info(f'Finish sample lines from corpus')
@@ -0,0 +1,332 @@
1
+ import csv
2
+ import json
3
+ import math
4
+ import os
5
+
6
+ FERTILITY_HEADER = "Fertility"
7
+ FERTILITY = "fertility"
8
+ RENYI_HEADER = "Renyi"
9
+ RENYI = "renyi_efficiency"
10
+ TOKENS_PER_WORD_HEADER = "Tokens per word distribution"
11
+ TOKENS_PER_WORD = "tokens_per_word_distribution"
12
+ TOKENS_LENGTH_HEADER = "Tokens length distribution"
13
+ TOKENS_LENGTH = "token_length_distribution"
14
+ DISTINCT_NEIGHBORS_HEADER = "Distinct neighbors distribution"
15
+ DISTINCT_NEIGHBORS = "token_distinct_neighbors_threshold"
16
+ TYPES_LENGTH_HEADER = "Types length distribution"
17
+ TYPES_LENGTH = "types_length_distribution"
18
+ COGNITIVE_EVALUATION_HEADER = "Cognitive evaluation"
19
+ COGNITIVE_EVALUATION = "cognitive_score"
20
+ WORD_CHUNKABILITY_RTS = "Word chunkability rts"
21
+ WORD_CHUNKABILITY_ACCURACY = "Word chunkability accuracy"
22
+ NONWORD_CHUNKABILITY_RTS = "NonWord chunkability rts"
23
+ NONWORD_CHUNKABILITY_ACCURACY = "NonWord chunkability accuracy"
24
+
25
+ HEDC4_HEADER = "HeDC4"
26
+ PRE_MODERN_HEADER = "pre_modern"
27
+ WIKIPEDIA_HEADER = "Wikipedia"
28
+
29
+ VOCAB_SIZES = [128000, 64000, 32000, 10000, 2000, 1000, 800]
30
+
31
+ LANGUAGE = 'hebrew'
32
+ EXPERIMENT_DATE = '2025-01-21'
33
+
34
+ if LANGUAGE == 'hebrew':
35
+ CORPORA = [HEDC4_HEADER, PRE_MODERN_HEADER]
36
+ EXPERIMENT_TYPES = ['all_letters', 'letters_subset', 'baseline']
37
+ else:
38
+ CORPORA = [WIKIPEDIA_HEADER]
39
+ EXPERIMENT_TYPES = ['all_letters', 'baseline']
40
+
41
+ def format_static_checks_results_file(file_paths: list[str], output_path: str):
42
+ results_map = get_empty_results_map()
43
+
44
+ sorted_file_paths = sorted(file_paths)
45
+ for file_path in sorted_file_paths:
46
+ json_data = get_json_data(file_path)
47
+ for result in json_data:
48
+ if FERTILITY in result:
49
+ continue
50
+ # handle_static_check_line(result, results_map)
51
+ elif TYPES_LENGTH in result:
52
+ continue
53
+ # handle_types_length_line(result, results_map)
54
+ elif COGNITIVE_EVALUATION in result:
55
+ handle_cognitive_evaluation_line(result, results_map)
56
+ else:
57
+ raise Exception("Invalid json data")
58
+
59
+ save_as_csv(results_map, output_path)
60
+
61
+
62
+ def get_json_data(file_path):
63
+ with open(file_path, "r") as file:
64
+ data = file.read()
65
+ data = f"[{data}]"
66
+ data = data.replace("}\n{", "},\n{")
67
+ json_data = json.loads(data)
68
+ return json_data
69
+
70
+
71
+ def handle_static_check_line(result, results_map):
72
+ corpus_path = result["corpus"].lower()
73
+ corpus_name = get_corpus_name(corpus_path)
74
+ experiment_type = get_experiment_type(corpus_path)
75
+ tokenizer_type = get_tokenizer_type(corpus_path)
76
+ vocab_size = get_vocab_size(corpus_path)
77
+ vocab_size_int = int(vocab_size)
78
+ line_title = f'{experiment_type} - {tokenizer_type}'
79
+
80
+ line = results_map[f"{FERTILITY_HEADER} - {corpus_name}"][line_title]
81
+ line[vocab_size] = f'{result[FERTILITY]:.3f}'
82
+
83
+ line = results_map[f"{RENYI_HEADER} - {corpus_name}"][line_title]
84
+ line[vocab_size] = f'{result[RENYI]:.3f}'
85
+
86
+ line = results_map[f"{TOKENS_PER_WORD_HEADER} - {corpus_name} - {vocab_size}"][line_title]
87
+ fill_tokens_per_word_distribution(line, vocab_size_int, result[TOKENS_PER_WORD].items())
88
+
89
+ line = results_map[f"{TOKENS_LENGTH_HEADER} - {corpus_name} - {vocab_size}"][line_title]
90
+ fill_tokens_length_distribution(line, vocab_size_int, result[TOKENS_LENGTH].items())
91
+
92
+ line = results_map[f"{DISTINCT_NEIGHBORS_HEADER} - {corpus_name} - {vocab_size}"][line_title]
93
+ fill_distinct_neighbors_distribution(line, vocab_size_int, corpus_name, result[DISTINCT_NEIGHBORS].items())
94
+
95
+
96
+ def fill_tokens_per_word_distribution(line, vocab_size, result_items):
97
+ max_bucket = 4 if (vocab_size > 2000) else 6
98
+ fill_tokens_distributions(line, max_bucket, result_items)
99
+
100
+
101
+ def fill_tokens_length_distribution(line, vocab_size, result_items):
102
+ max_bucket = 8 if (vocab_size > 2000) else 4
103
+ fill_tokens_distributions(line, max_bucket, result_items)
104
+
105
+
106
+ def fill_tokens_distributions(line, max_bucket, result_items):
107
+ if len(line) == 0:
108
+ for i in range(1, max_bucket + 1):
109
+ line[i] = 0
110
+ for key, value in result_items:
111
+ if key == "11+" or int(key) > max_bucket:
112
+ line[max_bucket] += value
113
+ else:
114
+ line[int(key)] = value
115
+
116
+
117
+ def fill_distinct_neighbors_distribution(line, vocab_size, corpus_name, result_items):
118
+ match corpus_name:
119
+ case "pre_modern":
120
+ match vocab_size:
121
+ case 128000 | 64000 | 32000 | 10000:
122
+ min_bucket = 0
123
+ buckets_number = 10
124
+ bucket_width = 50
125
+ case 2000:
126
+ min_bucket = 0
127
+ buckets_number = 10
128
+ bucket_width = 100
129
+ case 1000 | 800:
130
+ min_bucket = 0
131
+ buckets_number = 14
132
+ bucket_width = 50
133
+ case _:
134
+ raise Exception("Invalid vocab_size")
135
+ case _:
136
+ match vocab_size:
137
+ case 128000 | 64000 | 32000 | 10000:
138
+ min_bucket = 0
139
+ buckets_number = 20
140
+ bucket_width = 500
141
+ case 2000:
142
+ min_bucket = 1400
143
+ buckets_number = 6
144
+ bucket_width = 100
145
+ case 1000:
146
+ min_bucket = 750
147
+ buckets_number = 5
148
+ bucket_width = 50
149
+ case 800:
150
+ min_bucket = 600
151
+ buckets_number = 5
152
+ bucket_width = 40
153
+ case _:
154
+ raise Exception("Invalid vocab_size")
155
+
156
+ max_bucket = min_bucket + bucket_width * (buckets_number - 1)
157
+
158
+ if len(line) == 0:
159
+ for key in range(min_bucket, max_bucket + 1, bucket_width):
160
+ line[key] = 0
161
+
162
+ for (_, value) in result_items:
163
+ if value > max_bucket:
164
+ bucket = max_bucket
165
+ elif value < min_bucket:
166
+ bucket = min_bucket
167
+ else:
168
+ bucket = math.floor(int(value - min_bucket) / bucket_width) * bucket_width + min_bucket
169
+ line[bucket] += 1
170
+
171
+
172
+ def handle_types_length_line(result, results_map):
173
+ vocab_path = result["vocab"].lower()
174
+ experiment_type = get_experiment_type(vocab_path)
175
+ tokenizer_type = get_tokenizer_type(vocab_path)
176
+ vocab_size = vocab_path.split("_")[-1]
177
+ line_title = f'{experiment_type} - {tokenizer_type}'
178
+
179
+ line = results_map[f"{TYPES_LENGTH_HEADER} - {vocab_size}"][line_title]
180
+ fill_types_length_distribution(line, int(vocab_size), result[TYPES_LENGTH].items())
181
+
182
+
183
+ def fill_types_length_distribution(line, vocab_size: int, result_items):
184
+ max_bucket = 8 if (vocab_size > 2000) else 6
185
+ if len(line) == 0:
186
+ for i in range(1, max_bucket + 1):
187
+ line[i] = 0
188
+ for key, value in result_items:
189
+ if int(key) == 0:
190
+ continue
191
+ elif int(key) == 1:
192
+ line[int(key)] = value + 1
193
+ elif int(key) > max_bucket:
194
+ line[max_bucket] += value
195
+ else:
196
+ line[int(key)] = value
197
+
198
+
199
+ def handle_cognitive_evaluation_line(result, results_map):
200
+ corpus_path = result["corpus"].lower()
201
+ experiment_type = get_experiment_type(corpus_path)
202
+ tokenizer_type = get_tokenizer_type(corpus_path)
203
+ vocab_size = get_vocab_size(corpus_path)
204
+ line_title = f'{experiment_type} - {tokenizer_type}'
205
+
206
+ line = results_map[COGNITIVE_EVALUATION_HEADER][line_title]
207
+ # line[vocab_size] = (f'{result[COGNITIVE_EVALUATION]:.3f}')
208
+ line[vocab_size] = (f'{result[COGNITIVE_EVALUATION]:.3f}, '
209
+ f'W-RT: {result[WORD_CHUNKABILITY_RTS]:.3f}, '
210
+ f'W-ACC: {result[WORD_CHUNKABILITY_ACCURACY]:.3f}, '
211
+ f'NW-RT: {result[NONWORD_CHUNKABILITY_RTS]:.3f}, '
212
+ f'NW-ACC: {result[NONWORD_CHUNKABILITY_ACCURACY]:.3f}')
213
+
214
+ new_experiment_type = "\\baseline"
215
+ if experiment_type == 'All Letters':
216
+ new_experiment_type = "\\spl"
217
+ elif experiment_type == 'Letters Subset':
218
+ new_experiment_type = "\\ssubset"
219
+
220
+ if tokenizer_type == 'UNIGRAM':
221
+ print(f'{tokenizer_type} - {int(vocab_size):06d}: \t\t\t'
222
+ f'& {new_experiment_type:<10}'
223
+ f'& {result[WORD_CHUNKABILITY_RTS]:.3f} '
224
+ f'& {result[NONWORD_CHUNKABILITY_RTS]:.3f} '
225
+ f'& {result[WORD_CHUNKABILITY_ACCURACY]:.3f} '
226
+ f'& {result[NONWORD_CHUNKABILITY_ACCURACY]:.3f} '
227
+ f'& {result[COGNITIVE_EVALUATION]:.3f} '
228
+ f'\\\\'
229
+ )
230
+
231
+
232
+ def get_experiment_type(corpus_path):
233
+ if "baseline" in corpus_path:
234
+ return "Baseline"
235
+ elif "subset" in corpus_path:
236
+ return "Letters Subset"
237
+ elif "all_letters" in corpus_path:
238
+ return "All Letters"
239
+ else:
240
+ raise ValueError("type not found")
241
+
242
+
243
+ def get_tokenizer_type(corpus_path):
244
+ if "unigram" in corpus_path:
245
+ return "UNIGRAM"
246
+ elif "bpe" in corpus_path:
247
+ return "BPE"
248
+ else:
249
+ raise ValueError("type not found")
250
+
251
+
252
+ def get_corpus_name(corpus_path):
253
+ if "pre_modern" in corpus_path:
254
+ return PRE_MODERN_HEADER
255
+ elif "hedc4" in corpus_path:
256
+ return HEDC4_HEADER
257
+ elif "wikipedia" in corpus_path:
258
+ return WIKIPEDIA_HEADER
259
+ else:
260
+ raise ValueError("type not found")
261
+
262
+
263
+ def get_vocab_size(corpus_path):
264
+ return corpus_path.split("_")[-1].split(".")[0]
265
+
266
+
267
+ def get_empty_results_map():
268
+ results_map = {COGNITIVE_EVALUATION_HEADER: get_empty_result_line()}
269
+ for corpus in CORPORA:
270
+ results_map[f"{FERTILITY_HEADER} - {corpus}"] = get_empty_result_line()
271
+ results_map[f"{RENYI_HEADER} - {corpus}"] = get_empty_result_line()
272
+ for vocab_size in VOCAB_SIZES:
273
+ results_map[f"{TOKENS_PER_WORD_HEADER} - {corpus} - {vocab_size}"] = get_empty_result_line()
274
+ results_map[f"{TOKENS_LENGTH_HEADER} - {corpus} - {vocab_size}"] = get_empty_result_line()
275
+ results_map[f"{DISTINCT_NEIGHBORS_HEADER} - {corpus} - {vocab_size}"] = get_empty_result_line()
276
+ for vocab_size in VOCAB_SIZES:
277
+ results_map[f"{TYPES_LENGTH_HEADER} - {vocab_size}"] = get_empty_result_line()
278
+ return results_map
279
+
280
+ def get_empty_result_line():
281
+ if LANGUAGE == 'hebrew':
282
+ return {
283
+ "All Letters - UNIGRAM": {},
284
+ "Letters Subset - UNIGRAM": {},
285
+ "Baseline - UNIGRAM": {},
286
+ "All Letters - BPE": {},
287
+ "Letters Subset - BPE": {},
288
+ "Baseline - BPE": {},
289
+ }
290
+ else:
291
+ return {
292
+ "All Letters - UNIGRAM": {},
293
+ "Baseline - UNIGRAM": {},
294
+ "All Letters - BPE": {},
295
+ "Baseline - BPE": {},
296
+ }
297
+
298
+ def list_all_files(folder_path):
299
+ all_files = []
300
+ for root, dirs, files in os.walk(folder_path):
301
+ for file in files:
302
+ if file == "static_checks_results.json" and ('log-0-' in root):
303
+ all_files.append(f'{root}/{file}')
304
+ return all_files
305
+
306
+
307
+ def save_as_csv(data, output_path):
308
+ for key, value in data.items():
309
+ csv_lines = []
310
+ for sub_key, sub_value in value.items():
311
+ csv_line = {"experiment_name": sub_key}
312
+ csv_line.update(sub_value)
313
+ csv_lines.append(csv_line)
314
+
315
+ with open(f'{output_path}/{key}.csv', 'w', newline='') as file:
316
+ writer = csv.DictWriter(file, fieldnames=csv_lines[0].keys())
317
+ writer.writeheader()
318
+ writer.writerows(csv_lines)
319
+
320
+
321
+ def main():
322
+ files = []
323
+ for experiment_type in EXPERIMENT_TYPES:
324
+ files.extend(list_all_files(f'./experiments/{EXPERIMENT_DATE}-{LANGUAGE}-{experiment_type}/logs/'))
325
+
326
+ output_path = f'./experiments/{EXPERIMENT_DATE}-{LANGUAGE}-results'
327
+ os.makedirs(output_path, exist_ok=True)
328
+ format_static_checks_results_file(files, output_path)
329
+
330
+
331
+ if __name__ == "__main__":
332
+ main()