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.
@@ -0,0 +1,141 @@
1
+ from abc import ABC, abstractmethod
2
+
3
+ import re
4
+
5
+ from splintering.experiments.cognitive_evaluation import save_cognitive_evaluation_corpus
6
+ from splintering.utils.corpus_tools import TextProcessorInterface
7
+
8
+
9
+ class LanguageUtilsInterface(ABC):
10
+
11
+ @abstractmethod
12
+ def remove_diacritics(self, text: str) -> str:
13
+ pass
14
+
15
+ @abstractmethod
16
+ def is_letter_in_language(self, char: str) -> bool:
17
+ pass
18
+
19
+ @abstractmethod
20
+ def is_word_contains_letters_from_other_languages(self, word: str) -> bool:
21
+ pass
22
+
23
+ @abstractmethod
24
+ def get_language_alphabet(self) -> range:
25
+ pass
26
+
27
+ @abstractmethod
28
+ def replace_final_letters(self, text: str) -> str:
29
+ pass
30
+
31
+ @abstractmethod
32
+ def save_additional_corpora_for_evaluation(self, text_processor: TextProcessorInterface) -> None:
33
+ pass
34
+
35
+ @staticmethod
36
+ def replace_last_letter(text, replacement):
37
+ return text[:-1] + replacement
38
+
39
+
40
+ class ArabicUtils(LanguageUtilsInterface):
41
+ def remove_diacritics(self, text: str) -> str:
42
+ # text = text.replace('\u0622', '\u0627')
43
+ # text = text.replace('\u0623', '\u0627')
44
+ # text = text.replace('\u0624', '\u0648')
45
+ # text = text.replace('\u0625', '\u0627')
46
+ # text = text.replace('\u0626', '\u064A')
47
+ return re.sub(r'[\u064B-\u065F]', '', text)
48
+
49
+ def is_letter_in_language(self, char: str) -> bool:
50
+ return '\u0621' <= char <= '\u064A'
51
+
52
+ def is_word_contains_letters_from_other_languages(self, word: str) -> bool:
53
+ return re.search(r'[^\u0621-\u064A]', word) is not None
54
+
55
+ def get_language_alphabet(self) -> list[str]:
56
+ return [chr(char) for char in range(0x0621, 0x064A + 1)]
57
+
58
+ def replace_final_letters(self, text: str) -> str:
59
+ return text
60
+
61
+ def save_additional_corpora_for_evaluation(self, text_processor) -> None:
62
+ pass
63
+
64
+
65
+ class HebrewUtils(LanguageUtilsInterface):
66
+ def remove_diacritics(self, text: str) -> str:
67
+ return re.sub(r'[\u0590-\u05CF]', '', text)
68
+
69
+ def is_letter_in_language(self, char: str) -> bool:
70
+ return '\u05D0' <= char <= '\u05EA'
71
+
72
+ def is_word_contains_letters_from_other_languages(self, word: str) -> bool:
73
+ return re.search(r'[^\u05D0-\u05EA]', word) is not None
74
+
75
+ def get_language_alphabet(self) -> list[str]:
76
+ return [chr(char) for char in range(0x05D0, 0x05EA + 1)]
77
+
78
+ def replace_final_letters(self, text: str) -> str:
79
+ if text == '':
80
+ return text
81
+ elif text[-1] == 'ך':
82
+ return self.replace_last_letter(text, 'כ')
83
+ elif text[-1] == 'כ':
84
+ return self.replace_last_letter(text, 'ך')
85
+ elif text[-1] == 'ם':
86
+ return self.replace_last_letter(text, 'מ')
87
+ elif text[-1] == 'מ':
88
+ return self.replace_last_letter(text, 'ם')
89
+ elif text[-1] == 'ן':
90
+ return self.replace_last_letter(text, 'נ')
91
+ elif text[-1] == 'נ':
92
+ return self.replace_last_letter(text, 'ן')
93
+ elif text[-1] == 'ף':
94
+ return self.replace_last_letter(text, 'פ')
95
+ elif text[-1] == 'פ':
96
+ return self.replace_last_letter(text, 'ף')
97
+ elif text[-1] == 'ץ':
98
+ return self.replace_last_letter(text, 'צ')
99
+ elif text[-1] == 'צ':
100
+ return self.replace_last_letter(text, 'ץ')
101
+ else:
102
+ return text
103
+
104
+ def save_additional_corpora_for_evaluation(self, text_processor: TextProcessorInterface) -> None:
105
+ text_processor.save_hedc4_corpus()
106
+ text_processor.save_pre_modern_corpus()
107
+ save_cognitive_evaluation_corpus(text_processor=text_processor)
108
+
109
+
110
+ class MalayUtils(LanguageUtilsInterface):
111
+ def remove_diacritics(self, text: str) -> str:
112
+ return text
113
+
114
+ def is_letter_in_language(self, char: str) -> bool:
115
+ return ('A' <= char <= 'Z') or ('a' <= char <= 'z')
116
+
117
+ def is_word_contains_letters_from_other_languages(self, word: str) -> bool:
118
+ return re.search(r'[^a-zA-Z]', word) is not None
119
+
120
+ def get_language_alphabet(self) -> list[str]:
121
+ return [chr(i) for i in range(97, 123)] + [chr(i) for i in range(65, 91)]
122
+
123
+ def replace_final_letters(self, text: str) -> str:
124
+ return text
125
+
126
+ def save_additional_corpora_for_evaluation(self, text_processor) -> None:
127
+ pass
128
+
129
+
130
+ ########################################################################################################################
131
+
132
+
133
+ class LanguageUtilsFactory:
134
+ @staticmethod
135
+ def get_by_language(language: str) -> LanguageUtilsInterface:
136
+ switch = {
137
+ 'he': HebrewUtils(),
138
+ 'ar': ArabicUtils(),
139
+ 'ms': MalayUtils(),
140
+ }
141
+ return switch.get(language)
@@ -0,0 +1,23 @@
1
+ import logging
2
+
3
+ from splintering.utils.path_utils import get_logs_dir
4
+
5
+ logger = None
6
+
7
+ def initialize_logger():
8
+ global logger
9
+ logging.basicConfig(
10
+ filename=f'{get_logs_dir()}/log.log',
11
+ level=logging.INFO,
12
+ format="%(asctime)s - %(levelname)s - %(message)s"
13
+ )
14
+ logger = logging.getLogger()
15
+ console_handler = logging.StreamHandler()
16
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
17
+ console_handler.setFormatter(formatter)
18
+ logger.addHandler(console_handler)
19
+
20
+
21
+ def get_logger():
22
+ global logger
23
+ return logger
@@ -0,0 +1,88 @@
1
+ import json
2
+ import re
3
+ from collections import Counter
4
+
5
+ from splintering.utils.path_utils import get_splinter_dir, get_logs_dir
6
+
7
+
8
+ def add_static_result_to_file(result):
9
+ with open(f'{get_logs_dir()}/static_checks_results.json', 'a', encoding='utf-8') as file:
10
+ file.write('\n')
11
+ json.dump(result, file, indent='\t')
12
+
13
+
14
+ def get_reductions_map_from_file():
15
+ with open(f'{get_splinter_dir()}/reductions_map.json', 'r') as file:
16
+ data = json.load(file)
17
+ data = {int(key): value for key, value in data.items()}
18
+ return data
19
+
20
+
21
+ def get_new_unicode_chars_map_from_file():
22
+ with open(f'{get_splinter_dir()}/new_unicode_chars.json', 'r') as file:
23
+ data = json.load(file)
24
+ return data
25
+
26
+
27
+ def get_new_unicode_chars_inverted_map_from_file():
28
+ with open(f'{get_splinter_dir()}/new_unicode_chars_inverted.json', 'r') as file:
29
+ data = json.load(file)
30
+ return data
31
+
32
+
33
+ def get_permutation(word, position, word_length):
34
+ if position < 0:
35
+ permutation = word[:word_length + position] + word[(word_length + position + 1):]
36
+ else:
37
+ permutation = word[:position] + word[(position + 1):]
38
+ return permutation
39
+
40
+
41
+ def get_words_dict_by_length(words):
42
+ words_dict_by_length = {}
43
+ max_length = len(max(words.keys(), key=len))
44
+
45
+ # initialize the dict with keys from 2 to max_length
46
+ for i in range(2, max_length + 1):
47
+ words_dict_by_length[i] = dict()
48
+ # fill the dict with words
49
+ for word in words.keys():
50
+ words_dict_by_length[len(word)][word] = words[word]
51
+ return words_dict_by_length
52
+
53
+
54
+ def get_letters_frequency(words):
55
+ words_letters_frequency = [dict(Counter(word)) for word, _ in words.items()]
56
+ letters_frequency = dict()
57
+ for word_letter_frequency in words_letters_frequency:
58
+ for letter in word_letter_frequency.keys():
59
+ letters_frequency[letter] = letters_frequency.get(letter, 0) + word_letter_frequency[letter]
60
+ letters_frequency = dict(sorted(letters_frequency.items(), key=lambda item: item[1], reverse=True))
61
+ return letters_frequency
62
+
63
+
64
+ def decode_tokens_vocab_file(tokens_vocab_file):
65
+ with open(f'{tokens_vocab_file}.vocab', 'r', encoding='utf-8') as file:
66
+ encoded_text = file.read()
67
+
68
+ new_unicode_chars_inverted_map = get_new_unicode_chars_inverted_map_from_file()
69
+ encoded_tokens = encoded_text.splitlines()
70
+ decoded_tokens = list()
71
+ for encoded_token in encoded_tokens:
72
+ decoded_words_list = decode_sentence(encoded_token, new_unicode_chars_inverted_map)
73
+ decoded_tokens.append("\t".join(decoded_words_list))
74
+ with open(f'{tokens_vocab_file}_decoded.vocab', 'a', encoding='utf-8') as file:
75
+ file.write("\n".join(decoded_tokens))
76
+
77
+
78
+ def decode_sentence(text, new_unicode_chars_inverted_map):
79
+ decoded_words_list = list()
80
+ encoded_words = text.split()
81
+ for encoded_word in encoded_words:
82
+ decoded_word = [new_unicode_chars_inverted_map.get(char, char) for char in encoded_word]
83
+ decoded_words_list.append("".join(decoded_word))
84
+ return decoded_words_list
85
+
86
+
87
+ def get_corpus_name(dataset_path, dataset_name):
88
+ return re.sub(r'\W', '_', f'{dataset_path}_{dataset_name}')
@@ -0,0 +1,62 @@
1
+ import os
2
+ import shutil
3
+
4
+ from scripts.params import get_run_params
5
+
6
+
7
+ def get_raw_data_dir():
8
+ return './raw_data'
9
+
10
+
11
+ def get_words_dict_dir():
12
+ return './data/word_dict'
13
+
14
+
15
+ def get_logs_dir():
16
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/logs/log-{get_run_params("TASK_ID")}-{get_run_params("TIMESTAMP")}'
17
+
18
+
19
+ def get_corpora_dir():
20
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/corpora'
21
+
22
+
23
+ def get_corpora_tokenized_dir():
24
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/corpora_tokenized'
25
+
26
+
27
+ def get_tokenizers_dir():
28
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/results/tokenizers'
29
+
30
+
31
+ def get_splinter_dir():
32
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/results/splinter'
33
+
34
+
35
+ def get_trigram_models_dir():
36
+ return f'./experiments/{get_run_params("EXPERIMENT_NAME")}/results/trigram_models'
37
+
38
+
39
+ def get_tokenizer_path(tokenizer_type, vocab_size) -> str:
40
+ return f'{get_tokenizers_dir()}/{tokenizer_type}_{vocab_size}'
41
+
42
+
43
+ def get_corpus_path(corpus_name) -> str:
44
+ return f'{get_corpora_dir()}/{corpus_name}.txt'
45
+
46
+
47
+ def get_tokenized_corpus_path(corpus_name, tokenizer_type, vocab_size) -> str:
48
+ return f'{get_corpora_tokenized_dir()}/{corpus_name}_{tokenizer_type}_{vocab_size}.txt'
49
+
50
+
51
+ def create_experiment_dirs():
52
+ os.makedirs(get_logs_dir(), exist_ok=True)
53
+ os.makedirs(get_corpora_dir(), exist_ok=True)
54
+ os.makedirs(get_corpora_tokenized_dir(), exist_ok=True)
55
+ os.makedirs(get_tokenizers_dir(), exist_ok=True)
56
+ os.makedirs(get_splinter_dir(), exist_ok=True)
57
+
58
+
59
+ def delete_corpus_file_if_exists(corpus_name):
60
+ corpus_path = get_corpus_path(corpus_name)
61
+ if os.path.exists(corpus_path):
62
+ os.remove(corpus_path)
@@ -0,0 +1,196 @@
1
+ import gc
2
+ from collections import Counter
3
+
4
+ import numpy as np
5
+ import scipy.sparse as sp
6
+ import sentencepiece as spm
7
+ import tokenization_scorer
8
+ from tqdm import tqdm
9
+
10
+ from splintering.utils.logger import get_logger
11
+ from splintering.utils.path_utils import get_tokenizer_path
12
+
13
+
14
+ # ------------------------------------------------------------------------
15
+ # taken from https://github.com/MeLeLBGU/tokenizers_intrinsic_benchmark/
16
+ # ------------------------------------------------------------------------
17
+
18
+
19
+ def run_static_checks(corpus_path, tokenized_corpus_path, tokenizer_path, vocab_size):
20
+ lines_number = get_lines_number(corpus_path)
21
+ results = dict()
22
+ results['corpus'] = tokenized_corpus_path
23
+ results['fertility'] = fertility_score(corpus_path, tokenized_corpus_path, lines_number)
24
+ results['renyi_efficiency'] = renyi_efficiency_score(tokenized_corpus_path)
25
+ results['tokens_per_word_distribution'] = tokens_per_word_distribution(tokenizer_path, tokenized_corpus_path, lines_number)
26
+ results['token_length_distribution'] = token_length_distribution(tokenizer_path, tokenized_corpus_path, lines_number)
27
+ results['token_distinct_neighbors_threshold'] = token_distinct_neighbors_number(tokenized_corpus_path, lines_number, vocab_size)
28
+ return results
29
+
30
+
31
+ def get_lines_number(corpus_path):
32
+ get_logger().info('get_lines_number - START')
33
+ with open(corpus_path, 'r', encoding='utf-8') as file:
34
+ lines_number = sum(1 for _ in file)
35
+ get_logger().info('get_lines_number - END')
36
+ get_logger().info(f'Lines number: {lines_number}')
37
+ return lines_number
38
+
39
+
40
+ def fertility_score(corpus_path, tokenized_corpus_path, lines_number):
41
+ get_logger().info('fertility_score - START')
42
+
43
+ with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
44
+ num_of_tokens = sum([len(text.split(" ")) for text in tqdm(file, total=lines_number)])
45
+ get_logger().info(f'num_of_tokens: {num_of_tokens}')
46
+
47
+ with open(corpus_path, 'r', encoding='utf-8') as file:
48
+ num_of_words = sum([len(sentence.split(" ")) for sentence in tqdm(file, total=lines_number)])
49
+ get_logger().info(f'num_of_words: {num_of_words}')
50
+
51
+ fertility = num_of_tokens / num_of_words
52
+ get_logger().info('fertility_score - END')
53
+ get_logger().info(f'Fertility score: {fertility}')
54
+ return fertility
55
+
56
+
57
+ def renyi_efficiency_score(tokenized_corpus_path):
58
+ get_logger().info('renyi_efficiency_score - START')
59
+ with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
60
+ file_generator = (line for line in file)
61
+ score = tokenization_scorer.score(file_generator, power=2.5)
62
+ get_logger().info('renyi_efficiency_score - END')
63
+ get_logger().info(f'Renyi efficiency score: {score}')
64
+ return score
65
+
66
+
67
+ def tokens_per_word_distribution(tokenizer_path, tokenized_corpus_path, lines_number):
68
+ get_logger().info('tokens_per_word_distribution - START')
69
+ tokenizer = spm.SentencePieceProcessor(model_file=f'{tokenizer_path}.model')
70
+
71
+ distribution = dict()
72
+ with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
73
+ for text in tqdm(file, total=lines_number):
74
+ if text == '\n':
75
+ continue
76
+ proto = tokenizer.decode([int(token_id) for token_id in text.split()], out_type='immutable_proto')
77
+ tokenized_text = " ".join([piece.piece for piece in proto.pieces]) + " "
78
+ text_split_by_words = tokenized_text.split("▁")
79
+ tokens_per_word_in_text = [word.count(' ') for word in text_split_by_words]
80
+ for tokens_per_word in tokens_per_word_in_text:
81
+ if tokens_per_word not in distribution:
82
+ distribution[tokens_per_word] = 0
83
+ distribution[tokens_per_word] += 1
84
+ cleaned_distribution = merge_keys_above_ten(distribution)
85
+ get_logger().info('tokens_per_word_distribution - END')
86
+ get_logger().info(f'Tokens per word distribution: {cleaned_distribution}')
87
+ return cleaned_distribution
88
+
89
+
90
+ def token_length_distribution(tokenizer_path, tokenized_corpus_path, lines_number):
91
+ get_logger().info('token_length_distribution - START')
92
+ tokenizer = spm.SentencePieceProcessor(model_file=f'{tokenizer_path}.model')
93
+ token_occurrence = get_token_occurrence_in_corpus(tokenized_corpus_path, lines_number)
94
+ distribution = dict()
95
+ for (token_id, count) in token_occurrence.items():
96
+ proto = tokenizer.decode([int(token_id)], out_type='immutable_proto')
97
+ token = proto.pieces[0].piece
98
+ token_length = get_token_length(token)
99
+ if token_length not in distribution:
100
+ distribution[token_length] = 0
101
+ distribution[token_length] += count
102
+ cleaned_distribution = merge_keys_above_ten(distribution)
103
+ get_logger().info('token_length_distribution - END')
104
+ get_logger().info(f'Token length distribution: {cleaned_distribution}')
105
+ return cleaned_distribution
106
+
107
+
108
+ def get_token_length(token: str):
109
+ return len(token.replace('▁', ''))
110
+
111
+
112
+ def get_token_occurrence_in_corpus(tokenized_corpus_path, lines_number):
113
+ token_occurrence = dict()
114
+ with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
115
+ for text in tqdm(file, total=lines_number):
116
+ token_occurrence_in_text = get_token_occurrence_in_text(text)
117
+ for token, count in token_occurrence_in_text.items():
118
+ if token not in token_occurrence:
119
+ token_occurrence[token] = 0
120
+ token_occurrence[token] = token_occurrence[token] + count
121
+ return token_occurrence
122
+
123
+
124
+ def get_token_occurrence_in_text(text: str):
125
+ text_tokens = text.split()
126
+ return Counter(text_tokens)
127
+
128
+
129
+ # sum all the 11+ keys together in a special "11+" key
130
+ def merge_keys_above_ten(distribution):
131
+ keys_above_ten_counter = sum(v for (k, v) in distribution.items() if int(k) > 10)
132
+ clean_distribution = {k: v for (k, v) in distribution.items() if int(k) <= 10}
133
+ clean_distribution.pop(0, None)
134
+ clean_distribution = dict(sorted(clean_distribution.items()))
135
+ clean_distribution = {str(k): v for (k, v) in clean_distribution.items()}
136
+ clean_distribution["11+"] = keys_above_ten_counter
137
+ return clean_distribution
138
+
139
+
140
+ def run_types_length_distribution(tokenizer_type, vocab_size):
141
+ get_logger().info('types_length_distribution - START')
142
+ tokens = get_vocab_tokens(tokenizer_type, vocab_size)
143
+ token_lengths = [get_token_length(token) for token in tokens]
144
+ distribution = dict(sorted(Counter(token_lengths).items()))
145
+ get_logger().info('types_length_distribution - END')
146
+ get_logger().info(f'Types length distribution: {distribution}')
147
+
148
+ return {
149
+ 'vocab': get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size),
150
+ 'types_length_distribution': distribution
151
+ }
152
+
153
+
154
+ def get_vocab_tokens(tokenizer_type, vocab_size):
155
+ vocab_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
156
+ with open(f'{vocab_path}.vocab', 'r', encoding='utf-8') as file:
157
+ tokens = [token.split('\t')[0] for token in tqdm(file)]
158
+ return tokens
159
+
160
+
161
+ def token_distinct_neighbors_number(tokenized_corpus_path, lines_number, vocab_size:int, window_size=2, threshold=1):
162
+ get_logger().info('distinct_neighbors - START')
163
+
164
+ distinct_neighbors = sp.lil_matrix((vocab_size, vocab_size), dtype=int)
165
+ with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
166
+ for text in tqdm(file, total=lines_number):
167
+ add_distinct_neighbors_from_text(text, distinct_neighbors, window_size)
168
+
169
+ distinct_neighbors_bool = sp.lil_matrix((vocab_size, vocab_size), dtype=bool)
170
+ distinct_neighbors_bool[distinct_neighbors >= threshold] = True
171
+
172
+ del distinct_neighbors
173
+ gc.collect()
174
+
175
+ distinct_neighbors_bool = distinct_neighbors_bool.tocsr()
176
+ distinct_neighbors_bool = (distinct_neighbors_bool + distinct_neighbors_bool.T).astype(bool).tocsr()
177
+
178
+ neighbors_number = np.array(distinct_neighbors_bool.sum(axis=1)).flatten()
179
+ neighbors_number = {str(i): int(neighbors_number[i]) for i in range(vocab_size) if neighbors_number[i] != 0}
180
+ neighbors_number = dict(sorted(neighbors_number.items(), key=lambda item: item[1], reverse=True))
181
+
182
+ get_logger().info('distinct_neighbors - END')
183
+ return neighbors_number
184
+
185
+
186
+ def add_distinct_neighbors_from_text(text: str, distinct_neighbors, window_size: int):
187
+ token_ids = [int(token_id) for token_id in text.split()]
188
+ length = len(token_ids)
189
+ for i, token_id in enumerate(token_ids[:-1]):
190
+ neighbors = token_ids[(i + 1):min(length,(i + window_size + 1))]
191
+ for neighbor in neighbors:
192
+ if neighbor >= token_id:
193
+ distinct_neighbors[token_id, neighbor] += 1
194
+ else:
195
+ distinct_neighbors[neighbor, token_id] += 1
196
+ return distinct_neighbors
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: splintering
3
+ Version: 1.0.0
4
+ Summary: Splinter is a text pre-processing step which rearranges characters into a linear form that better represents nonconcatenative morphologies, enabling meaningful contiguous segments to be found by a subword tokenizer.
5
+ Project-URL: Source, https://github.com/MeLeLBGU/Splintering
6
+ Project-URL: Issues, https://github.com/MeLeLBGU/Splintering/issues
7
+ Author-email: Bar Gazit <bargazi@post.bgu.ac.il>, Shaltiel Shmidman <shaltieltzion@gmail.com>, Avi Shmidman <avi.shmidman@biu.ac.il>, Yuval Pinter <uvp@cs.bgu.ac.il>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: datasets
14
+ Requires-Dist: nltk
15
+ Requires-Dist: numpy<2.0.0
16
+ Requires-Dist: openpyxl~=3.1.5
17
+ Requires-Dist: pandas
18
+ Requires-Dist: scikit-learn
19
+ Requires-Dist: scipy
20
+ Requires-Dist: sentencepiece
21
+ Requires-Dist: tokenization-scorer~=1.1.6
22
+ Requires-Dist: tqdm
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Splintering
26
+ This repository contains the code used in [Splintering Nonconcatenative Languages for Better Tokenization](https://aclanthology.org/2025.findings-acl.1151/).
27
+
28
+ It contains the Splinter algorithm as well as the intrinsic evaluation code.
29
+
30
+ The downstream evaluation DictaBERT-Splinter models can be found [here](https://huggingface.co/dicta-il/dictabert-splinter).
31
+
32
+ The following example trains Splinter on Hebrew Wikipedia, encodes the training corpus, and uses it to train a BPE tokenizer:
33
+
34
+ ```python
35
+ # Training:
36
+ from splintering.trainer import SplinterTrainer
37
+ from splintering.text_processors import TextProcessorWithEncoding
38
+ from splintering.utils.languages import LanguageUtilsFactory
39
+ from splintering.utils.path_utils import get_tokenizer_path, get_corpus_path
40
+ from splintering.utils.misc import get_corpus_name
41
+
42
+ language = 'he'
43
+ train_dataset_path = 'wikimedia/wikipedia'
44
+ train_dataset_name = f'20231101.{language}'
45
+ language_utils = LanguageUtilsFactory.get_by_language(language)
46
+
47
+ # - Create the reductions map, and map the reductions in it into new Unicode characters
48
+ splinter_trainer = SplinterTrainer(language_utils)
49
+ reductions_map, new_unicode_chars_map, _ = splinter_trainer.train(train_dataset_path, train_dataset_name, None)
50
+
51
+ # Application:
52
+ # - Splinter the corpus
53
+ text_processor = TextProcessorWithEncoding(language_utils, reductions_map, new_unicode_chars_map)
54
+ text_processor.save_corpus_as_text_file(train_dataset_path, train_dataset_name)
55
+
56
+ # - Train tokenizer on the splintered corpus
57
+ tokenizer_corpus_path = get_corpus_path(get_corpus_name(train_dataset_path, train_dataset_name))
58
+ tokenizer_type = 'bpe'
59
+ vocab_size = 128_000
60
+
61
+ from scripts.train_tokenizer import train_tokenizer # Thin wrapper around SentencePiece; you can use any package that takes a string corpus.
62
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
63
+ train_tokenizer(tokenizer_type=tokenizer_type, vocab_size=vocab_size, input_path=tokenizer_corpus_path,
64
+ output_path=tokenizer_path)
65
+ ```
66
+
67
+ ## Citation
68
+
69
+ If you use Splinter in your research, please cite ```Splintering Nonconcatenative Languages for Better Tokenization```:
70
+
71
+ ```
72
+ @inproceedings{gazit-etal-2025-splintering,
73
+ title = "Splintering Nonconcatenative Languages for Better Tokenization",
74
+ author = "Gazit, Bar and
75
+ Shmidman, Shaltiel and
76
+ Shmidman, Avi and
77
+ Pinter, Yuval",
78
+ editor = "Che, Wanxiang and
79
+ Nabende, Joyce and
80
+ Shutova, Ekaterina and
81
+ Pilehvar, Mohammad Taher",
82
+ booktitle = "Findings of the {A}ssociation for {C}omputational {L}inguistics: {ACL} 2025",
83
+ month = jul,
84
+ year = "2025",
85
+ address = "Vienna, Austria",
86
+ publisher = "Association for Computational Linguistics",
87
+ url = "https://aclanthology.org/2025.findings-acl.1151/",
88
+ doi = "10.18653/v1/2025.findings-acl.1151",
89
+ pages = "22405--22417",
90
+ ISBN = "979-8-89176-256-5"
91
+ }
92
+ ```
@@ -0,0 +1,20 @@
1
+ splintering/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ splintering/text_processors.py,sha256=TIkmlifAy9Xm9i8pN5LxebeJsgvnJMegeGDrDPMx0fU,10790
3
+ splintering/trainer.py,sha256=2O5dXefV7rGNtdXFMMkLHM-pKwjo8Xgju26UDX6l_zY,8750
4
+ splintering/experiments/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ splintering/experiments/cognitive_evaluation.py,sha256=AcH8rZEF8JfGOQDZhLO4rRhHdOyoJ8nMJ6OuuCTAnlo,4718
6
+ splintering/experiments/compare_vocabs.py,sha256=FJJL6qdsVX1GW-V-cJWs50C53GTeFhdXcRpu_9sXsbA,3677
7
+ splintering/experiments/compare_vocabs_for_dicta_bert.py,sha256=qLZ2TkFl--N6b3gHoU0punX5IoM_FvF4CYQJR9SxyKM,3606
8
+ splintering/experiments/trigram_lm.py,sha256=WYjHnqfeXnEFgergTxdVelRsPcfpVX0f-VjJf7S2gVg,2570
9
+ splintering/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
10
+ splintering/utils/corpus_tools.py,sha256=Kxhq0LuGuZH0IzHERVJ4R5Xr2Ry1DMPmFISRLmdxDSs,6250
11
+ splintering/utils/format_static_checks_results_file.py,sha256=TcJyy7_f6daD_rJwxxDFWBpmM6ovjJdX4IsiL1N9b10,11956
12
+ splintering/utils/languages.py,sha256=J0ucodnIadMyL0tGuQtBIz0LwCDWU7bmdtZEkA3Av0c,4727
13
+ splintering/utils/logger.py,sha256=t3vq3bBDEpI8xo2Wnw3BePf5Imbb6BglOuYVTlLNiTQ,590
14
+ splintering/utils/misc.py,sha256=LUL8aJL0Sg-llKCRhzY0GDSL8hLnUJtPulVOfCqP-jQ,3177
15
+ splintering/utils/path_utils.py,sha256=w_yUAl9YjGQwhfKGF2V6QB4hQn-8E39Vjg3si2TPZy8,1731
16
+ splintering/utils/static_checks.py,sha256=fPdEiGbQP19POIks6FHSz71JsGRAq1dY8CjIrnI9vbk,8813
17
+ splintering-1.0.0.dist-info/METADATA,sha256=bCEbJ_x3g1YTNdab4T7PstgLMHL3pitP9HmaDLkDBdE,4024
18
+ splintering-1.0.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
19
+ splintering-1.0.0.dist-info/licenses/LICENSE,sha256=FGckSlBuwH7fieULvv-0gZgQBF-IDKjJ5Xp_JnOJv2E,1089
20
+ splintering-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MeLeL lab, Ben-Gurion University
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.