Repository navigation
Expand file tree
/
Copy pathencode_data.py
More file actions
207 lines (172 loc) · 6.09 KB
/
Copy pathencode_data.py
File metadata and controls
207 lines (172 loc) · 6.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Encodes the training data with extracted features."""
import argparse
import functools
import itertools
import multiprocessing
import os
import sys
from collections.abc import Iterable
# module hack
LIB_PATH = os.path.join(os.path.dirname(__file__), '..')
sys.path.insert(0, os.path.abspath(LIB_PATH))
from budoux import utils
ArgList = list[str] | None
DEFAULT_OUTPUT_FILENAME = 'encoded_data.txt'
INVALID = '▔'
"""The invalid feature string."""
def get_feature(w1: str, w2: str, w3: str, w4: str, w5: str, w6: str) -> list[str]:
"""Generates a feature from characters around (w1-6).
Args:
w1 (str): The character 3 characters before the break point.
w2 (str): The character 2 characters before the break point.
w3 (str): The character right before the break point.
w4 (str): The character right after the break point.
w5 (str): The character 2 characters after the break point.
w6 (str): The character 3 characters after the break point.
Returns:
The feature (list[str]).
"""
raw_feature = {
'UW1': w1,
'UW2': w2,
'UW3': w3,
'UW4': w4,
'UW5': w5,
'UW6': w6,
'BW1': w2 + w3,
'BW2': w3 + w4,
'BW3': w4 + w5,
'TW1': w1 + w2 + w3,
'TW2': w2 + w3 + w4,
'TW3': w3 + w4 + w5,
'TW4': w4 + w5 + w6,
}
for key, value in list(raw_feature.items()):
if INVALID in value:
del raw_feature[key]
return [f'{item[0]}:{item[1]}' for item in raw_feature.items()]
def get_features_at(sentence: str, i: int) -> list[str]:
"""Generates features around the break point at index `i` in `sentence`.
Args:
sentence (str): A character sequence without separator markers.
i (int): Break point index (`1 <= i <= len(sentence)`).
Returns:
The extracted features (`list[str]`).
"""
return get_feature(
sentence[i - 3] if i > 2 else INVALID,
sentence[i - 2] if i > 1 else INVALID,
sentence[i - 1],
sentence[i] if i < len(sentence) else INVALID,
sentence[i + 1] if i + 1 < len(sentence) else INVALID,
sentence[i + 2] if i + 2 < len(sentence) else INVALID,
)
def reconstruct_context(features: Iterable[str]) -> str:
"""Reconstructs a readable 6-character context string from unigram features.
Args:
features: An iterable of feature strings (e.g. `'UW1:a'`, `'UW2:b'`, ...).
Returns:
A formatted 6-character context string (`"<left> | <right>"`).
"""
unigrams: dict[int, str] = {}
for feat in features:
if feat.startswith('UW'):
parts = feat.split(':', 1)
if len(parts) == 2 and parts[0][2:].isdigit():
unigrams[int(parts[0][2:])] = parts[1]
left = ''.join(unigrams.get(i, ' ') for i in range(1, 4))
right = ''.join(unigrams.get(i, ' ') for i in range(4, 7))
return f'{left} | {right}'
def parse_args(test: ArgList = None) -> argparse.Namespace:
"""Parses commandline arguments.
Args:
test (typing.Optional[typing.List[str]], optional): Commandline args for testing. Defaults to None.
Returns:
argparse.Namespace: Parsed data of args.
"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'source_data', help='''File path of the source training data to extract features.'''
)
parser.add_argument(
'-o',
'--outfile',
help='''Output file path for the encoded training data.
(default: encoded_data.txt)''',
default=DEFAULT_OUTPUT_FILENAME,
)
parser.add_argument(
'--processes',
type=int,
help='''Number of processes to use.
(default: the number of CPUs in the system)''',
default=None,
)
parser.add_argument(
'--scale',
type=int,
help='''Weight scale for the entries. The value should be a unsigned
integer. (default: 1)''',
default=1,
)
if test is None:
return parser.parse_args()
else:
return parser.parse_args(test)
def process(i: int, sentence: str, sep_indices: set[int], scale: int) -> str:
"""Outputs an encoded line of features from the given index.
Args:
i (int): index
sentence (str): A sentence
sep_indices (typing.Set[int]): A set of separator indices.
scale (int): A weight scale for the entries.
"""
feature = get_features_at(sentence, i)
positive = i in sep_indices
line = '\t'.join([f'{scale}' if positive else f'{-scale}', *feature])
return line
def normalize_input(data: str) -> tuple[str, set[int]]:
"""Normalizes the input to one line with separators.
Args:
data(str): Source input
Returns:
typing.Tuple[str, typing.Set[int]]: A tuple of the sentence and the
separator indices.
"""
chunks = data.replace('\n', utils.SEP).strip().split(utils.SEP)
chunk_lengths = [len(chunk) for chunk in chunks]
sep_indices = set(itertools.accumulate(chunk_lengths, lambda x, y: x + y))
sentence = ''.join(chunks)
return (sentence, sep_indices)
def main(test: ArgList = None) -> None:
args = parse_args(test)
source_filename: str = args.source_data
entries_filename: str = args.outfile
processes = None if args.processes is None else int(args.processes)
scale: int = args.scale
with open(source_filename, encoding='utf-8') as f:
data = f.read()
sentence, sep_indices = normalize_input(data)
with multiprocessing.Pool(processes) as p:
func = functools.partial(
process, sentence=sentence, sep_indices=sep_indices, scale=scale
)
lines = p.map(func, range(1, len(sentence) + 1))
with open(entries_filename, 'w', encoding='utf-8') as f:
f.writelines(line + '\n' for line in lines)
print(f'\033[92mEncoded training data is out at: {entries_filename}\033[0m')
if __name__ == '__main__':
main()