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/__init__.py +0 -0
- splintering/experiments/__init__.py +0 -0
- splintering/experiments/cognitive_evaluation.py +100 -0
- splintering/experiments/compare_vocabs.py +81 -0
- splintering/experiments/compare_vocabs_for_dicta_bert.py +77 -0
- splintering/experiments/trigram_lm.py +51 -0
- splintering/text_processors.py +239 -0
- splintering/trainer.py +168 -0
- splintering/utils/__init__.py +0 -0
- splintering/utils/corpus_tools.py +134 -0
- splintering/utils/format_static_checks_results_file.py +332 -0
- splintering/utils/languages.py +141 -0
- splintering/utils/logger.py +23 -0
- splintering/utils/misc.py +88 -0
- splintering/utils/path_utils.py +62 -0
- splintering/utils/static_checks.py +196 -0
- splintering-1.0.0.dist-info/METADATA +92 -0
- splintering-1.0.0.dist-info/RECORD +20 -0
- splintering-1.0.0.dist-info/WHEEL +4 -0
- splintering-1.0.0.dist-info/licenses/LICENSE +21 -0
splintering/__init__.py
ADDED
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import os
|
|
3
|
+
|
|
4
|
+
import pandas as pd
|
|
5
|
+
import sentencepiece as spm
|
|
6
|
+
from scipy.stats import pearsonr
|
|
7
|
+
|
|
8
|
+
from splintering.utils.corpus_tools import TextProcessorInterface
|
|
9
|
+
from splintering.utils.logger import get_logger
|
|
10
|
+
from splintering.utils.path_utils import get_corpora_dir, get_raw_data_dir, get_corpus_path, get_tokenized_corpus_path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def save_cognitive_evaluation_corpus(text_processor: TextProcessorInterface):
|
|
14
|
+
get_logger().info(f'Start saving HeLP_The_Hebrew_Lexicon_Project corpus as text file with {text_processor.__class__.__name__}')
|
|
15
|
+
data = pd.read_excel(f'{get_raw_data_dir()}/HeLP_The_Hebrew_Lexicon_Project/raw_LD_data.xlsx')
|
|
16
|
+
filtered_data = filter_data(data) # do the same filtering as in the original HeLP paper
|
|
17
|
+
|
|
18
|
+
aggregated_by_stimuli = filtered_data.groupby("Stimulus", as_index=False).agg(
|
|
19
|
+
Stimulus=("Stimulus", "first"),
|
|
20
|
+
mean_RT=("RT", "mean"),
|
|
21
|
+
mean_Correctness=("Correctness", "mean"),
|
|
22
|
+
n=("RT", "size"),
|
|
23
|
+
Stimulus_type=("Stimulus_type", "first")
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
aggregated_by_stimuli["Stimulus"] = [text_processor.process(stimulus) for stimulus in aggregated_by_stimuli["Stimulus"]]
|
|
27
|
+
aggregated_by_stimuli.to_csv(f'{get_corpora_dir()}/HeLP_cognitive_evaluation.txt', index=False)
|
|
28
|
+
get_logger().info(f'Finished saving HeLP_The_Hebrew_Lexicon_Project corpus')
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# do the same filtering as in the original HeLP paper
|
|
32
|
+
def filter_data(data):
|
|
33
|
+
# remove rows without RT or RT less than 300ms
|
|
34
|
+
filtered_data = data.dropna(subset=["RT"])
|
|
35
|
+
filtered_data = filtered_data[filtered_data["RT"] >= 300]
|
|
36
|
+
aggregated_by_session = (
|
|
37
|
+
filtered_data
|
|
38
|
+
.groupby(["Subject", "Session_date"], as_index=False)
|
|
39
|
+
.agg(
|
|
40
|
+
mean_RT=("RT", "mean"),
|
|
41
|
+
mean_Correct=("Correctness", "mean"),
|
|
42
|
+
n=("RT", "size"),
|
|
43
|
+
Session_date=("Session_date", "first"),
|
|
44
|
+
Subject=("Subject", "first")
|
|
45
|
+
))
|
|
46
|
+
|
|
47
|
+
# Filter sessions with n < 880 or mean_Correct < 0.75
|
|
48
|
+
sessions_to_remove = aggregated_by_session[(aggregated_by_session["n"] < 880) | (aggregated_by_session["mean_Correct"] < 0.75)]
|
|
49
|
+
for _, session in sessions_to_remove.iterrows():
|
|
50
|
+
filtered_data = filtered_data[(filtered_data["Subject"] != session["Subject"]) | (filtered_data["Session_date"] != session["Session_date"])]
|
|
51
|
+
return filtered_data
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def tokenize_cognitive_evaluation_file(tokenizer_path, tokenizer_type, vocab_size):
|
|
55
|
+
corpus_path = get_corpus_path('HeLP_cognitive_evaluation')
|
|
56
|
+
tokenized_corpus_path = get_tokenized_corpus_path('HeLP_cognitive_evaluation', tokenizer_type, vocab_size)
|
|
57
|
+
if os.path.exists(tokenized_corpus_path):
|
|
58
|
+
os.remove(tokenized_corpus_path)
|
|
59
|
+
|
|
60
|
+
get_logger().info(f'cognitive_evaluation: start tokenizing corpus with {tokenizer_type} tokenizer, vocab size {vocab_size}.')
|
|
61
|
+
sp_tokenizer = spm.SentencePieceProcessor(model_file=f'{tokenizer_path}.model')
|
|
62
|
+
df = pd.read_csv(corpus_path)
|
|
63
|
+
df["Stimulus_tokenized"] = [sp_tokenizer.encode(stimulus) for stimulus in df["Stimulus"]]
|
|
64
|
+
df = df[["Stimulus_tokenized"] + [col for col in df.columns if col != "Stimulus_tokenized"]]
|
|
65
|
+
df.to_csv(tokenized_corpus_path, index=False)
|
|
66
|
+
get_logger().info('cognitive_evaluation: finished tokenizing corpus')
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def run_cognitive_evaluation(tokenizer_type, vocab_size):
|
|
70
|
+
tokenized_corpus_path = get_tokenized_corpus_path('HeLP_cognitive_evaluation', tokenizer_type, vocab_size)
|
|
71
|
+
data = pd.read_csv(tokenized_corpus_path)
|
|
72
|
+
data = data.dropna()
|
|
73
|
+
data["wordiness"] = data.apply(get_wordiness, axis=1)
|
|
74
|
+
results = {}
|
|
75
|
+
results.update(get_chunkability("Word", data))
|
|
76
|
+
results.update(get_chunkability("NonWord", data))
|
|
77
|
+
# cognitive score is the average of all the pearson correlations results
|
|
78
|
+
results["cognitive_score"] = sum(abs(value) for value in results.values()) / len(results)
|
|
79
|
+
results["corpus"] = tokenized_corpus_path
|
|
80
|
+
return results
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def get_wordiness(word_data):
|
|
84
|
+
number_of_tokens = len(json.loads(word_data["Stimulus_tokenized"]))
|
|
85
|
+
word_length = len(word_data["Stimulus"])
|
|
86
|
+
wordiness = 1 - (number_of_tokens / word_length)
|
|
87
|
+
return wordiness
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def get_chunkability(category, data):
|
|
91
|
+
results = {}
|
|
92
|
+
category_data = data[data["Stimulus_type"] == category]
|
|
93
|
+
wordiness = list(category_data["wordiness"])
|
|
94
|
+
reaction_times = list(category_data["mean_RT"])
|
|
95
|
+
wordiness_rc_correlation, _ = pearsonr(wordiness, reaction_times)
|
|
96
|
+
results[f'{category} chunkability rts'] = wordiness_rc_correlation
|
|
97
|
+
accuracy = list(category_data["mean_Correctness"])
|
|
98
|
+
wordiness_accuracy_correlation, _ = pearsonr(wordiness, accuracy)
|
|
99
|
+
results[f'{category} chunkability accuracy'] = wordiness_accuracy_correlation
|
|
100
|
+
return results
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from splintering.utils.languages import LanguageUtilsInterface
|
|
4
|
+
from splintering.utils.misc import get_new_unicode_chars_map_from_file
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def compare_vocabs(baseline_vocab: list[str], splinter_decoded_vocab: list[str]):
|
|
8
|
+
baseline_vocab_set = set(baseline_vocab)
|
|
9
|
+
decoded_vocab = [line.split("\t\t") for line in splinter_decoded_vocab]
|
|
10
|
+
possible_full_vocab = [line[0] for line in decoded_vocab if len(line) == 3 and line[0] != line[1]] # BERT differ
|
|
11
|
+
|
|
12
|
+
intersection = {token for token in possible_full_vocab if token in baseline_vocab_set}
|
|
13
|
+
non_complete_words = len(decoded_vocab) - len(possible_full_vocab)
|
|
14
|
+
splinter_unique = len(possible_full_vocab) - len(intersection)
|
|
15
|
+
return [
|
|
16
|
+
f"Full vocab: \t\t\t{len(decoded_vocab)} \t(100.00%)",
|
|
17
|
+
f"Non-complete words: \t{non_complete_words} \t({(non_complete_words / len(decoded_vocab) * 100):.2f}%)",
|
|
18
|
+
f"Intersection: \t\t\t{len(intersection)} \t({(len(intersection) / len(decoded_vocab) * 100):.2f}%)",
|
|
19
|
+
f"Splinter unique: \t\t{splinter_unique} \t({(splinter_unique / len(decoded_vocab) * 100):.2f}%)",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def decode_splintered_vocab(encoded_text, language_utils: LanguageUtilsInterface):
|
|
24
|
+
new_unicode_chars_map = get_new_unicode_chars_map_from_file()
|
|
25
|
+
new_unicode_chars_inverted_map = {value: key for key, value in new_unicode_chars_map.items()}
|
|
26
|
+
decoded_tokens = list()
|
|
27
|
+
for encoded_token in encoded_text:
|
|
28
|
+
encoded_token = encoded_token.split('\t')[0]
|
|
29
|
+
decoded_token = [new_unicode_chars_inverted_map.get(char, char) for char in encoded_token]
|
|
30
|
+
rebuilt_token = rebuild_reduced_word(decoded_token, language_utils)
|
|
31
|
+
decoded_tokens.append(rebuilt_token + "\t\t" + decoded_token_to_str(decoded_token) + "\t\t" + encoded_token)
|
|
32
|
+
return decoded_tokens
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def rebuild_reduced_word(decoded_token, language_utils: LanguageUtilsInterface):
|
|
36
|
+
decoded_token_concat = "".join(decoded_token)
|
|
37
|
+
|
|
38
|
+
if len(decoded_token) == 1 and len(decoded_token[0]) > 1:
|
|
39
|
+
return decoded_token_to_str(decoded_token)
|
|
40
|
+
|
|
41
|
+
if decoded_token_concat.startswith('##') and (len(decoded_token) != 3 or ':' in decoded_token[2]):
|
|
42
|
+
return decoded_token_to_str(decoded_token)
|
|
43
|
+
|
|
44
|
+
is_word_start = False
|
|
45
|
+
if decoded_token[0] == '▁':
|
|
46
|
+
is_word_start = True
|
|
47
|
+
decoded_token = decoded_token[1:] # remove the '▁', and add it later
|
|
48
|
+
|
|
49
|
+
original_word = ""
|
|
50
|
+
for reduction in decoded_token:
|
|
51
|
+
if ':' in reduction and decoded_token_concat not in [':', '##:']:
|
|
52
|
+
position, letter = reduction.split(':')
|
|
53
|
+
position = int(position)
|
|
54
|
+
if position < 0:
|
|
55
|
+
position = len(original_word) + position + 1
|
|
56
|
+
if len(original_word) == position - 1:
|
|
57
|
+
original_word += letter
|
|
58
|
+
else:
|
|
59
|
+
original_word = original_word[:position] + letter + original_word[position:]
|
|
60
|
+
else:
|
|
61
|
+
original_word += reduction
|
|
62
|
+
|
|
63
|
+
original_word = language_utils.replace_final_letters(original_word)
|
|
64
|
+
if is_word_start:
|
|
65
|
+
original_word = '▁' + original_word
|
|
66
|
+
|
|
67
|
+
return original_word
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def decoded_token_to_str(decoded_token):
|
|
71
|
+
return "[" + ",".join([f"'{reduction}'" for reduction in decoded_token]) + "]"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def list_all_vocab_files(folder_path):
|
|
75
|
+
all_files = {}
|
|
76
|
+
for root, dirs, files in os.walk(folder_path):
|
|
77
|
+
for file in files:
|
|
78
|
+
if file.endswith('.vocab') and not file.endswith('_decoded.vocab'):
|
|
79
|
+
all_files[os.path.splitext(file)[0]] = f'{root}/{file}'
|
|
80
|
+
sorted_files = dict(sorted(all_files.items(), key=lambda item: f"{(item[0].split('_')[0])}_{int(item[0].split('_')[1]):06}"))
|
|
81
|
+
return sorted_files
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
from splintering.utils.languages import LanguageUtilsInterface
|
|
2
|
+
from splintering.utils.misc import get_new_unicode_chars_map_from_file
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def compare_vocabs(baseline_vocab: list[str], splinter_decoded_vocab: list[str]):
|
|
6
|
+
baseline_vocab_set = set(baseline_vocab)
|
|
7
|
+
decoded_vocab = [line.split("\t\t") for line in splinter_decoded_vocab]
|
|
8
|
+
possible_full_vocab = [line[0] for line in decoded_vocab if len(line) == 2 and line[0] != line[1]] # BERT differ
|
|
9
|
+
|
|
10
|
+
intersection = {token for token in possible_full_vocab if token in baseline_vocab_set}
|
|
11
|
+
non_complete_words = len(decoded_vocab) - len(possible_full_vocab)
|
|
12
|
+
splinter_unique = len(possible_full_vocab) - len(intersection)
|
|
13
|
+
return [
|
|
14
|
+
f"Full vocab: \t\t\t{len(decoded_vocab)} \t(100.00%)",
|
|
15
|
+
f"Non-complete words: \t{non_complete_words} \t({(non_complete_words / len(decoded_vocab) * 100):.2f}%)",
|
|
16
|
+
f"Intersection: \t\t\t{len(intersection)} \t({(len(intersection) / len(decoded_vocab) * 100):.2f}%)",
|
|
17
|
+
f"Splinter unique: \t\t{splinter_unique} \t({(splinter_unique / len(decoded_vocab) * 100):.2f}%)",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def decode_dicta_bert_splintered_vocab(encoded_text, language_utils: LanguageUtilsInterface):
|
|
22
|
+
new_unicode_chars_map = get_new_unicode_chars_map_from_file()
|
|
23
|
+
new_unicode_chars_inverted_map = {value: key for key, value in new_unicode_chars_map.items()}
|
|
24
|
+
decoded_tokens = list()
|
|
25
|
+
i = 0
|
|
26
|
+
for encoded_token in encoded_text:
|
|
27
|
+
i += 1
|
|
28
|
+
decoded_token = [new_unicode_chars_inverted_map.get(char, char) for char in encoded_token]
|
|
29
|
+
rebuilt_token = rebuild_reduced_word(decoded_token, language_utils)
|
|
30
|
+
decoded_tokens.append(rebuilt_token + "\t\t" + decoded_token_to_str(decoded_token))
|
|
31
|
+
return decoded_tokens
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def rebuild_reduced_word(decoded_token, language_utils: LanguageUtilsInterface):
|
|
35
|
+
decoded_token_concat = "".join(decoded_token)
|
|
36
|
+
|
|
37
|
+
is_middle_of_word = False
|
|
38
|
+
if decoded_token_concat.startswith('##'):
|
|
39
|
+
is_middle_of_word = True
|
|
40
|
+
decoded_token = decoded_token[2:] # remove the '##', and add it later
|
|
41
|
+
|
|
42
|
+
original_word = ""
|
|
43
|
+
for reduction in decoded_token:
|
|
44
|
+
if ':' in reduction and decoded_token_concat not in [':', '##:']:
|
|
45
|
+
position, letter = reduction.split(':')
|
|
46
|
+
position = int(position)
|
|
47
|
+
if position < 0:
|
|
48
|
+
position = len(original_word) + position + 1
|
|
49
|
+
if len(original_word) == position - 1:
|
|
50
|
+
original_word += letter
|
|
51
|
+
else:
|
|
52
|
+
original_word = original_word[:position] + letter + original_word[position:]
|
|
53
|
+
else:
|
|
54
|
+
original_word += reduction
|
|
55
|
+
|
|
56
|
+
original_word = language_utils.replace_final_letters(original_word)
|
|
57
|
+
if is_middle_of_word:
|
|
58
|
+
original_word = '##' + original_word
|
|
59
|
+
|
|
60
|
+
return original_word
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def decoded_token_to_str(decoded_token):
|
|
64
|
+
return "[" + ",".join([f"'{reduction}'" for reduction in decoded_token]) + "]"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def get_dicta_bert_tokens(language_utils: LanguageUtilsInterface):
|
|
68
|
+
baseline_vocab_file = "./experiments/2025-01-06-compare_vocabs_dicta_bert/DictaBert - Vocab.txt"
|
|
69
|
+
with open(baseline_vocab_file, 'r', encoding='utf-8') as file:
|
|
70
|
+
baseline_vocab = file.read().splitlines()
|
|
71
|
+
|
|
72
|
+
splinter_vocab_file = "./experiments/2025-01-06-compare_vocabs_dicta_bert/SplinterDictaBert - Vocab.txt"
|
|
73
|
+
with open(splinter_vocab_file, 'r', encoding='utf-8') as file:
|
|
74
|
+
splinter_vocab = [line.rstrip("\n") for line in file]
|
|
75
|
+
splinter_decoded_vocab = decode_dicta_bert_splintered_vocab(splinter_vocab, language_utils)
|
|
76
|
+
|
|
77
|
+
return baseline_vocab, splinter_decoded_vocab
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import pickle
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from nltk.lm.models import KneserNeyInterpolated
|
|
5
|
+
from nltk.lm.preprocessing import padded_everygram_pipeline
|
|
6
|
+
from sklearn.model_selection import train_test_split
|
|
7
|
+
from tqdm import tqdm
|
|
8
|
+
|
|
9
|
+
from splintering.utils.logger import get_logger, initialize_logger
|
|
10
|
+
from splintering.utils.path_utils import get_trigram_models_dir, get_corpora_tokenized_dir, get_logs_dir
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def test_perplexity(corpus_name, train_model: bool):
|
|
14
|
+
tokenized_corpus_path = f'{get_corpora_tokenized_dir()}/{corpus_name}.txt'
|
|
15
|
+
with open(tokenized_corpus_path, 'r', encoding='utf-8') as file:
|
|
16
|
+
tokenized_text = file.read().split('\n')
|
|
17
|
+
train_data, test_data = train_test_split(tokenized_text, test_size=0.1, random_state=42)
|
|
18
|
+
|
|
19
|
+
n = 3 # For trigram model
|
|
20
|
+
if train_model:
|
|
21
|
+
train_data = [data.split(' ') for data in train_data]
|
|
22
|
+
train_data, padded_vocab = padded_everygram_pipeline(n, train_data)
|
|
23
|
+
model = KneserNeyInterpolated(order=n)
|
|
24
|
+
get_logger().info(f"Start model fit for corpus '{corpus_name}'")
|
|
25
|
+
model.fit(train_data, padded_vocab)
|
|
26
|
+
with open(f'{get_trigram_models_dir()}/trigram_model_{corpus_name}.pkl', 'wb') as file:
|
|
27
|
+
pickle.dump(model, file)
|
|
28
|
+
else:
|
|
29
|
+
get_logger().info(f"Start model load for corpus '{corpus_name}'")
|
|
30
|
+
with open(f'{get_trigram_models_dir()}/trigram_model_{corpus_name}.pkl', 'rb') as file:
|
|
31
|
+
model = pickle.load(file)
|
|
32
|
+
|
|
33
|
+
test_data = [data.split(' ') for data in test_data]
|
|
34
|
+
test_data, _ = padded_everygram_pipeline(n, test_data)
|
|
35
|
+
test_data = [[i for i in item] for item in test_data]
|
|
36
|
+
test_data = [[i for i in item if len(i) == n] for item in test_data]
|
|
37
|
+
perplexity_list = list()
|
|
38
|
+
get_logger().info(f"Start perplexity calculations for {len(test_data)} sentences in '{corpus_name}'.")
|
|
39
|
+
inf_count = 0
|
|
40
|
+
with open(f'{get_logs_dir()}/trigram_model_{corpus_name}_perplexity.txt', 'a', encoding='utf-8') as file:
|
|
41
|
+
for sentence in tqdm(test_data):
|
|
42
|
+
sentence_perplexity = model.perplexity(sentence)
|
|
43
|
+
file.write(f'{sentence_perplexity}\n')
|
|
44
|
+
if np.isinf(sentence_perplexity):
|
|
45
|
+
inf_count += 1
|
|
46
|
+
else:
|
|
47
|
+
perplexity_list.append(sentence_perplexity)
|
|
48
|
+
get_logger().info(f"Finished perplexity calculations for {len(test_data)} sentences in '{corpus_name}'.")
|
|
49
|
+
get_logger().info(f'number of inf: {inf_count}')
|
|
50
|
+
get_logger().info(f'Average perplexity: {sum(perplexity_list) / len(perplexity_list)}')
|
|
51
|
+
return sum(perplexity_list) / len(perplexity_list)
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from splintering.utils.corpus_tools import TextProcessorInterface
|
|
4
|
+
from splintering.utils.misc import get_permutation
|
|
5
|
+
from splintering.utils.languages import LanguageUtilsInterface
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class TextProcessorBaseline(TextProcessorInterface):
|
|
9
|
+
|
|
10
|
+
def __init__(self, language_utils: LanguageUtilsInterface):
|
|
11
|
+
super().__init__(language_utils)
|
|
12
|
+
|
|
13
|
+
def process(self, text):
|
|
14
|
+
if text is None:
|
|
15
|
+
return ''
|
|
16
|
+
|
|
17
|
+
clean_text = self.language_utils.remove_diacritics(text)
|
|
18
|
+
sentences = re.split(r'[.\n]', clean_text)
|
|
19
|
+
processed_sentences = [self.process_sentence(sentence) for sentence in sentences]
|
|
20
|
+
processed_sentences = [sentence for sentence in processed_sentences if sentence != '']
|
|
21
|
+
return "\n".join(processed_sentences)
|
|
22
|
+
|
|
23
|
+
def process_sentence(self, sentence):
|
|
24
|
+
words = re.split(r'\s|-|,|:|"|\(|\)', sentence)
|
|
25
|
+
filtered_words = [word for word in words if word != '']
|
|
26
|
+
processed_words = [self.language_utils.replace_final_letters(word) for word in filtered_words]
|
|
27
|
+
filtered_sentence = " ".join(processed_words)
|
|
28
|
+
return filtered_sentence
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TextProcessorWithEncoding(TextProcessorInterface):
|
|
32
|
+
|
|
33
|
+
def __init__(self, language_utils: LanguageUtilsInterface, reductions_map, new_unicode_chars_map):
|
|
34
|
+
super().__init__(language_utils)
|
|
35
|
+
self.reductions_map = reductions_map
|
|
36
|
+
self.new_unicode_chars_map = new_unicode_chars_map
|
|
37
|
+
self.word_reductions_cache = dict()
|
|
38
|
+
|
|
39
|
+
def process(self, text):
|
|
40
|
+
if text is None:
|
|
41
|
+
return ''
|
|
42
|
+
|
|
43
|
+
clean_text = self.language_utils.remove_diacritics(text)
|
|
44
|
+
sentences = re.split(r'[.\n]', clean_text)
|
|
45
|
+
encoded_sentences_list = list()
|
|
46
|
+
for sentence in sentences:
|
|
47
|
+
encoded_words_list = list()
|
|
48
|
+
words = re.split(r'\s|-|,|:|"|\(|\)', sentence)
|
|
49
|
+
for word in words:
|
|
50
|
+
if len(word) == 0:
|
|
51
|
+
continue
|
|
52
|
+
original_word = word
|
|
53
|
+
if original_word in self.word_reductions_cache:
|
|
54
|
+
encoded_word = self.word_reductions_cache[original_word]
|
|
55
|
+
else:
|
|
56
|
+
word = self.language_utils.replace_final_letters(word)
|
|
57
|
+
# if a word contains letters from other languages, convert only the letters from our language.
|
|
58
|
+
if self.language_utils.is_word_contains_letters_from_other_languages(word):
|
|
59
|
+
encoded_word = self.get_reduction_for_word_with_letters_from_other_languages(word)
|
|
60
|
+
else:
|
|
61
|
+
word_reductions = self.get_word_reductions(word)
|
|
62
|
+
encoded_word = ''.join([self.new_unicode_chars_map[reduction] for reduction in word_reductions])
|
|
63
|
+
encoded_words_list.append(encoded_word)
|
|
64
|
+
self.word_reductions_cache[original_word] = encoded_word
|
|
65
|
+
encoded_sentence = " ".join(encoded_words_list)
|
|
66
|
+
if len(encoded_sentence) == 0:
|
|
67
|
+
continue
|
|
68
|
+
encoded_sentences_list.append(encoded_sentence)
|
|
69
|
+
return "\n".join(encoded_sentences_list)
|
|
70
|
+
|
|
71
|
+
def get_word_reductions(self, word):
|
|
72
|
+
reduced_word = word
|
|
73
|
+
reductions = []
|
|
74
|
+
while len(reduced_word) > 3:
|
|
75
|
+
# if this word length has no known reductions - return what's left of the word as is
|
|
76
|
+
if len(reduced_word) not in self.reductions_map:
|
|
77
|
+
reductions.extend(self.get_single_chars_reductions(reduced_word))
|
|
78
|
+
break
|
|
79
|
+
reduction = self.get_reduction(reduced_word, 3, 3)
|
|
80
|
+
if reduction is not None:
|
|
81
|
+
position = int(reduction.split(':')[0])
|
|
82
|
+
reductions.append(reduction)
|
|
83
|
+
reduced_word = get_permutation(reduced_word, position, len(reduced_word))
|
|
84
|
+
# if we couldn't find a reduction - return what's left of the word as is
|
|
85
|
+
else:
|
|
86
|
+
reductions.extend(self.get_single_chars_reductions(reduced_word))
|
|
87
|
+
break
|
|
88
|
+
|
|
89
|
+
# if we found all reductions and left only with the suspected root - keep it as is
|
|
90
|
+
if len(reduced_word) < 4:
|
|
91
|
+
reductions.extend(self.get_single_chars_reductions(reduced_word))
|
|
92
|
+
|
|
93
|
+
reductions.reverse()
|
|
94
|
+
return reductions
|
|
95
|
+
|
|
96
|
+
def get_reduction(self, word, depth, width):
|
|
97
|
+
curr_step_reductions = [{"word": word, "reduction": None, "root_reduction": None, "score": 1}]
|
|
98
|
+
word_length = len(word)
|
|
99
|
+
i = 0
|
|
100
|
+
while i < depth and len(curr_step_reductions) > 0 and word_length > 3:
|
|
101
|
+
next_step_reductions = list()
|
|
102
|
+
for reduction in curr_step_reductions:
|
|
103
|
+
possible_reductions = self.get_most_frequent_reduction_keys(
|
|
104
|
+
reduction["word"],
|
|
105
|
+
reduction["root_reduction"],
|
|
106
|
+
reduction["score"],
|
|
107
|
+
width,
|
|
108
|
+
word_length
|
|
109
|
+
)
|
|
110
|
+
next_step_reductions += possible_reductions
|
|
111
|
+
curr_step_reductions = list(next_step_reductions)
|
|
112
|
+
i += 1
|
|
113
|
+
word_length -= 1
|
|
114
|
+
|
|
115
|
+
max_score_reduction = None
|
|
116
|
+
if len(curr_step_reductions) > 0:
|
|
117
|
+
max_score_reduction = max(curr_step_reductions, key=lambda x: x["score"])["root_reduction"]
|
|
118
|
+
return max_score_reduction
|
|
119
|
+
|
|
120
|
+
def get_most_frequent_reduction_keys(self, word, root_reduction, parent_score, number_of_reductions, word_length):
|
|
121
|
+
if len(word) not in self.reductions_map:
|
|
122
|
+
return list()
|
|
123
|
+
|
|
124
|
+
possible_reductions = list()
|
|
125
|
+
for reduction, score in self.reductions_map[len(word)].items():
|
|
126
|
+
position, letter = reduction.split(':')
|
|
127
|
+
position = int(position)
|
|
128
|
+
if word[position] == letter:
|
|
129
|
+
permutation = get_permutation(word, position, word_length)
|
|
130
|
+
possible_reductions.append({
|
|
131
|
+
"word": permutation,
|
|
132
|
+
"reduction": reduction,
|
|
133
|
+
"root_reduction": root_reduction if root_reduction is not None else reduction,
|
|
134
|
+
"score": parent_score * score
|
|
135
|
+
})
|
|
136
|
+
if len(possible_reductions) >= number_of_reductions:
|
|
137
|
+
break
|
|
138
|
+
return possible_reductions
|
|
139
|
+
|
|
140
|
+
def get_reduction_for_word_with_letters_from_other_languages(self, word):
|
|
141
|
+
return ''.join(self.new_unicode_chars_map[char] if self.language_utils.is_letter_in_language(char) else char for char in word)
|
|
142
|
+
|
|
143
|
+
@staticmethod
|
|
144
|
+
def get_single_chars_reductions(reduced_word):
|
|
145
|
+
reductions = []
|
|
146
|
+
for char in reduced_word[::-1]:
|
|
147
|
+
reductions.append(char)
|
|
148
|
+
return reductions
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
class TextProcessorForDemo(TextProcessorWithEncoding):
|
|
152
|
+
|
|
153
|
+
def __init__(self, language_utils: LanguageUtilsInterface, reductions_map, new_unicode_chars_map, new_unicode_chars_inverted_map):
|
|
154
|
+
super().__init__(language_utils, reductions_map, new_unicode_chars_map)
|
|
155
|
+
self.new_unicode_chars_inverted_map = new_unicode_chars_inverted_map
|
|
156
|
+
|
|
157
|
+
def process(self, text):
|
|
158
|
+
if text is None:
|
|
159
|
+
return ''
|
|
160
|
+
|
|
161
|
+
clean_text = self.language_utils.remove_diacritics(text)
|
|
162
|
+
sentences = re.split(r'[.\n]', clean_text)
|
|
163
|
+
reduced_sentences_list = list()
|
|
164
|
+
encoded_sentences_list = list()
|
|
165
|
+
for sentence in sentences:
|
|
166
|
+
word_reductions_list = list()
|
|
167
|
+
encoded_words_list = list()
|
|
168
|
+
words = re.split(r'\s|-|,|:|"|\(|\)', sentence)
|
|
169
|
+
for word in words:
|
|
170
|
+
if len(word) == 0:
|
|
171
|
+
continue
|
|
172
|
+
word = self.language_utils.replace_final_letters(word)
|
|
173
|
+
# if a word contains letters from other languages, convert only the letters from our language.
|
|
174
|
+
if self.language_utils.is_word_contains_letters_from_other_languages(word):
|
|
175
|
+
word_reductions = self.get_single_chars_reductions(word)
|
|
176
|
+
encoded_word = self.get_reduction_for_word_with_letters_from_other_languages(word)
|
|
177
|
+
else:
|
|
178
|
+
word_reductions = self.get_word_reductions(word)
|
|
179
|
+
encoded_word = ''.join([self.new_unicode_chars_map[reduction] for reduction in word_reductions])
|
|
180
|
+
word_reductions_list.append(f'{word_reductions}')
|
|
181
|
+
encoded_words_list.append(encoded_word)
|
|
182
|
+
reduced_sentence = " ".join(word_reductions_list)
|
|
183
|
+
encoded_sentence = " ".join(encoded_words_list)
|
|
184
|
+
if len(encoded_sentence) == 0:
|
|
185
|
+
continue
|
|
186
|
+
reduced_sentences_list.append(reduced_sentence)
|
|
187
|
+
encoded_sentences_list.append(encoded_sentence)
|
|
188
|
+
return (
|
|
189
|
+
"\n".join(reduced_sentences_list),
|
|
190
|
+
"\n".join(encoded_sentences_list)
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
def undo_process(self, encoded_text):
|
|
194
|
+
if encoded_text is None:
|
|
195
|
+
return ''
|
|
196
|
+
|
|
197
|
+
encoded_sentences = re.split(r'[.\n]', encoded_text)
|
|
198
|
+
decoded_sentences_list = list()
|
|
199
|
+
original_sentences_list = list()
|
|
200
|
+
for encoded_sentence in encoded_sentences:
|
|
201
|
+
decoded_words_list = list()
|
|
202
|
+
original_words_list = list()
|
|
203
|
+
encoded_words = encoded_sentence.split()
|
|
204
|
+
for encoded_word in encoded_words:
|
|
205
|
+
if len(encoded_word) == 0:
|
|
206
|
+
continue
|
|
207
|
+
decoded_word = [self.new_unicode_chars_inverted_map.get(char, char) for char in encoded_word]
|
|
208
|
+
original_word = self.rebuild_reduced_word(decoded_word)
|
|
209
|
+
decoded_words_list.append(f'{decoded_word}')
|
|
210
|
+
original_words_list.append(original_word)
|
|
211
|
+
|
|
212
|
+
reduced_sentence = " ".join(decoded_words_list)
|
|
213
|
+
original_sentence = " ".join(original_words_list)
|
|
214
|
+
if len(original_sentence) == 0:
|
|
215
|
+
continue
|
|
216
|
+
decoded_sentences_list.append(reduced_sentence)
|
|
217
|
+
original_sentences_list.append(original_sentence)
|
|
218
|
+
return (
|
|
219
|
+
"\n".join(decoded_sentences_list),
|
|
220
|
+
"\n".join(original_sentences_list)
|
|
221
|
+
)
|
|
222
|
+
|
|
223
|
+
def rebuild_reduced_word(self, decoded_word):
|
|
224
|
+
original_word = ""
|
|
225
|
+
for reduction in decoded_word:
|
|
226
|
+
if ':' in reduction:
|
|
227
|
+
position, letter = reduction.split(':')
|
|
228
|
+
position = int(position)
|
|
229
|
+
if position < 0:
|
|
230
|
+
position = len(original_word) + position + 1
|
|
231
|
+
if len(original_word) == position - 1:
|
|
232
|
+
original_word += letter
|
|
233
|
+
else:
|
|
234
|
+
original_word = original_word[:position] + letter + original_word[position:]
|
|
235
|
+
else:
|
|
236
|
+
original_word += reduction
|
|
237
|
+
|
|
238
|
+
original_word = self.language_utils.replace_final_letters(original_word)
|
|
239
|
+
return original_word
|