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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
use crate::{
types::*,
utils::{parallelism::MaybeParallelRefIterator, regex::SerializeRegex},
Error,
};
use serde::{Deserialize, Serialize};
use std::{
fs::File,
io::{BufReader, Read},
path::Path,
sync::Arc,
};
pub mod chunk;
pub mod multiword;
pub mod tag;
use chunk::Chunker;
use multiword::MultiwordTagger;
use tag::Tagger;
use crate::rule::DisambiguationRule;
fn split<F>(text: &str, split_func: F) -> Vec<&str>
where
F: Fn(char) -> bool,
{
let mut result = Vec::new();
let mut last = 0;
for (index, matched) in text.match_indices(split_func) {
if last != index {
result.push(&text[last..index]);
}
result.push(matched);
last = index + matched.len();
}
if last < text.len() {
result.push(&text[last..]);
}
result
}
pub fn finalize(tokens: Vec<DisambiguatedToken>) -> Vec<Token> {
if tokens.is_empty() {
return Vec::new();
}
let mut finalized = vec![Token::sent_start(tokens[0].0.sentence, tokens[0].0.tagger)];
finalized.extend(tokens.into_iter().map(|x| x.0.into()));
finalized
}
#[derive(Serialize, Deserialize)]
pub struct TokenizerOptions {
pub allow_errors: bool,
pub retain_last: bool,
pub use_compound_split_heuristic: bool,
pub always_add_lower_tags: bool,
#[serde(default)]
pub ids: Vec<String>,
#[serde(default)]
pub ignore_ids: Vec<String>,
#[serde(default)]
pub known_failures: Vec<String>,
#[serde(default)]
pub extra_tags: Vec<String>,
#[serde(default)]
pub extra_split_chars: Vec<char>,
#[serde(default)]
pub extra_join_regexes: Vec<SerializeRegex>,
}
impl Default for TokenizerOptions {
fn default() -> Self {
TokenizerOptions {
allow_errors: false,
retain_last: false,
use_compound_split_heuristic: false,
always_add_lower_tags: false,
ids: Vec::new(),
ignore_ids: Vec::new(),
known_failures: Vec::new(),
extra_tags: Vec::new(),
extra_split_chars: Vec::new(),
extra_join_regexes: Vec::new(),
}
}
}
#[derive(Serialize, Deserialize, Default)]
pub struct Tokenizer {
pub(crate) rules: Vec<DisambiguationRule>,
pub(crate) chunker: Option<Chunker>,
pub(crate) sentencizer: srx::Rules,
pub(crate) multiword_tagger: Option<MultiwordTagger>,
pub(crate) tagger: Arc<Tagger>,
pub(crate) options: Arc<TokenizerOptions>,
}
impl Tokenizer {
pub fn new<P: AsRef<Path>>(p: P) -> Result<Self, Error> {
let reader = BufReader::new(File::open(p)?);
Ok(bincode::deserialize_from(reader)?)
}
pub fn from_reader<R: Read>(reader: R) -> Result<Self, Error> {
Ok(bincode::deserialize_from(reader)?)
}
pub fn rules(&self) -> &Vec<DisambiguationRule> {
&self.rules
}
pub fn tagger(&self) -> &Arc<Tagger> {
&self.tagger
}
pub fn chunker(&self) -> &Option<Chunker> {
&self.chunker
}
pub fn options(&self) -> &Arc<TokenizerOptions> {
&self.options
}
pub(crate) fn disambiguate_up_to_id<'t>(
&'t self,
mut tokens: Vec<IncompleteToken<'t>>,
id: Option<&str>,
) -> Vec<DisambiguatedToken<'t>> {
let n = id.map_or(self.rules.len(), |id| {
self.rules.iter().position(|x| x.id == id).unwrap()
});
let mut i = 0;
while i < n {
let finalized = finalize(tokens.iter().cloned().map(DisambiguatedToken).collect());
let result = self.rules[i..n]
.maybe_par_iter()
.enumerate()
.filter_map(|(j, rule)| {
let changes = rule.apply(&finalized, &self);
if changes.is_empty() {
None
} else {
Some((j + i, changes))
}
})
.find_first(|_| true);
if let Some((index, changes)) = result {
self.rules[index].change(&mut tokens, &self, changes);
i = index + 1;
} else {
i = n;
}
}
tokens.into_iter().map(DisambiguatedToken).collect()
}
pub fn disambiguate<'t>(
&'t self,
tokens: Vec<IncompleteToken<'t>>,
) -> Vec<DisambiguatedToken<'t>> {
self.disambiguate_up_to_id(tokens, None)
}
fn get_token_strs<'t>(&self, text: &'t str) -> Vec<&'t str> {
let mut tokens = Vec::new();
let split_char = |c: char| c.is_whitespace() || crate::utils::splitting_chars().contains(c);
let split_text = |text: &'t str| {
let mut tokens = Vec::new();
for pretoken in split(text, split_char) {
if self.tagger.id_word(pretoken.into()).1.is_some() {
tokens.push(pretoken);
} else {
tokens.extend(split(pretoken, |c| {
split_char(c) || self.options.extra_split_chars.contains(&c)
}));
}
}
tokens
};
let mut joined_mask = vec![false; text.len()];
let mut joins = Vec::new();
for regex in self.options.extra_join_regexes.iter() {
for (start, end) in regex.find_iter(text) {
if !joined_mask[start..end].iter().any(|x| *x) {
joins.push(start..end);
joined_mask[start..end].iter_mut().for_each(|x| *x = true);
}
}
}
joins.sort_by(|a, b| a.start.cmp(&b.start));
let mut prev = 0;
for range in joins {
tokens.extend(split_text(&text[prev..range.start]));
prev = range.end;
tokens.push(&text[range]);
}
tokens.extend(split_text(&text[prev..text.len()]));
tokens
}
pub(crate) fn tokenize<'t>(&'t self, sentence: &'t str) -> Vec<IncompleteToken<'t>> {
let mut current_char = 0;
let token_strs = self.get_token_strs(sentence);
let mut tokens: Vec<_> = token_strs
.iter()
.enumerate()
.map(|(i, x)| {
let char_start = current_char;
let ptr = x.as_ptr() as usize;
current_char += x.chars().count();
let byte_start = ptr - sentence.as_ptr() as usize;
let trimmed = x.trim();
let is_sentence_start = i == 0;
let is_sentence_end = i == token_strs.len() - 1;
IncompleteToken {
word: Word::new_with_tags(
self.tagger.id_word(trimmed.into()),
self.tagger.get_tags(
trimmed,
is_sentence_start || self.options.always_add_lower_tags,
self.options.use_compound_split_heuristic,
),
),
char_span: (char_start, current_char),
byte_span: (byte_start, byte_start + x.len()),
is_sentence_end,
has_space_before: sentence[..byte_start].ends_with(char::is_whitespace),
chunks: Vec::new(),
multiword_data: None,
sentence,
tagger: self.tagger.as_ref(),
}
})
.filter(|token| !token.word.text.as_ref().is_empty())
.collect();
if !tokens.is_empty() {
let last_idx = tokens.len() - 1;
tokens[last_idx].is_sentence_end = true;
if let Some(chunker) = &self.chunker {
chunker.apply(&mut tokens);
}
if let Some(multiword_tagger) = &self.multiword_tagger {
multiword_tagger.apply(&mut tokens, &self.tagger);
}
}
tokens
}
pub fn sentencize<'t>(&'t self, text: &'t str) -> Vec<Vec<IncompleteToken<'t>>> {
self.sentencizer
.split(text)
.into_iter()
.map(|sentence| self.tokenize(sentence))
.collect()
}
pub fn pipe<'t>(&'t self, text: &'t str) -> Vec<Vec<Token<'t>>> {
self.sentencize(text)
.into_iter()
.map(|tokens| finalize(self.disambiguate(tokens)))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::Tokenizer;
use lazy_static::lazy_static;
use quickcheck_macros::quickcheck;
#[quickcheck]
fn can_tokenize_anything(text: String) -> bool {
lazy_static! {
static ref TOKENIZER: Tokenizer =
Tokenizer::new("../storage/en_tokenizer.bin").unwrap();
}
TOKENIZER.tokenize(&text);
true
}
}