kabosu 0.7.0.1 → 0.7.0.2
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +118 -0
- data/README.md +151 -65
- data/ext/kabosu/src/dictionary.rs +200 -93
- data/ext/kabosu/src/errors.rs +114 -8
- data/ext/kabosu/src/grouping.rs +44 -92
- data/ext/kabosu/src/lib.rs +73 -23
- data/ext/kabosu/src/morpheme.rs +289 -572
- data/ext/kabosu/src/morpheme_list.rs +204 -0
- data/ext/kabosu/src/nogvl.rs +108 -14
- data/ext/kabosu/src/parsing.rs +104 -118
- data/ext/kabosu/src/splitter.rs +62 -102
- data/ext/kabosu/src/tokenizer.rs +298 -140
- data/ext/kabosu/src/user_dict.rs +47 -22
- data/lib/kabosu/morpheme_list.rb +129 -115
- data/lib/kabosu/pos_matcher.rb +119 -28
- data/lib/kabosu/release.rake +7 -10
- data/lib/kabosu/version.rb +1 -1
- data/lib/kabosu.rb +207 -158
- metadata +12 -5
- data/ext/kabosu/src/token_batch.rs +0 -60
data/ext/kabosu/src/tokenizer.rs
CHANGED
|
@@ -1,198 +1,356 @@
|
|
|
1
|
-
use magnus::{Error, RArray, Ruby};
|
|
2
|
-
use std::
|
|
3
|
-
use std::
|
|
4
|
-
use
|
|
5
|
-
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
6
|
-
use std::sync::Arc;
|
|
1
|
+
use magnus::{gc, DataTypeFunctions, Error, RArray, RString, Ruby, Symbol, TryConvert, TypedData};
|
|
2
|
+
use std::mem::size_of;
|
|
3
|
+
use std::sync::{Mutex, MutexGuard, PoisonError};
|
|
4
|
+
use sudachi::analysis::mlist::MorphemeList;
|
|
7
5
|
use sudachi::analysis::stateful_tokenizer::StatefulTokenizer;
|
|
8
6
|
use sudachi::analysis::Mode;
|
|
9
|
-
use sudachi::dic::dictionary::JapaneseDictionary;
|
|
10
7
|
use sudachi::dic::subset::InfoSubset;
|
|
11
|
-
use sudachi::
|
|
8
|
+
use sudachi::error::{SudachiError, SudachiResult};
|
|
12
9
|
|
|
13
|
-
use crate::
|
|
14
|
-
use crate::
|
|
15
|
-
use crate::
|
|
16
|
-
use crate::
|
|
17
|
-
use crate::
|
|
10
|
+
use crate::dictionary::{Dict, PosTable};
|
|
11
|
+
use crate::errors::tokenization_error;
|
|
12
|
+
use crate::morpheme_list::{Analysis, RbMorphemeList};
|
|
13
|
+
use crate::nogvl::{report_native_memory, without_gvl, Stopped};
|
|
14
|
+
use crate::parsing::{mode_symbol, push_utf8, subset_to_array};
|
|
18
15
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
mode: Mode,
|
|
23
|
-
}
|
|
16
|
+
/// The longest input sudachi.rs accepts, in bytes of UTF-8: its offsets are
|
|
17
|
+
/// 16 bits wide.
|
|
18
|
+
const MAX_INPUT_BYTES: usize = u16::MAX as usize / 4 * 3;
|
|
24
19
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
20
|
+
/// Inputs longer than this get an analyzer of their own kind. An analyzer's
|
|
21
|
+
/// lattice never shrinks, and clearing it costs time proportional to the
|
|
22
|
+
/// longest input it has seen, on every later call: one 40 KB document would
|
|
23
|
+
/// otherwise slow down every short sentence analyzed after it.
|
|
24
|
+
const LARGE_INPUT_BYTES: usize = 4 * 1024;
|
|
25
|
+
|
|
26
|
+
/// How much text `tokenize_batch` analyzes before taking the GVL back to let
|
|
27
|
+
/// Ruby deliver a pending `Timeout`, `Thread#kill` or signal: a few tens of
|
|
28
|
+
/// milliseconds of work.
|
|
29
|
+
const BATCH_CHUNK_BYTES: usize = 64 * 1024;
|
|
30
|
+
|
|
31
|
+
/// What an analyzer is reported to the GC as: its lattice and buffers are
|
|
32
|
+
/// private to sudachi.rs and grow with the longest input it has seen, so this
|
|
33
|
+
/// is an estimate fitted to measurements (about 60 KB after short sentences,
|
|
34
|
+
/// about 11 MB after a 45 KB document), not an exact size.
|
|
35
|
+
const ANALYZER_BASE_BYTES: usize = 48 * 1024;
|
|
36
|
+
const ANALYZER_BYTES_PER_INPUT_BYTE: usize = 240;
|
|
37
|
+
|
|
38
|
+
/// The text of `text` when it has to be transcoded to UTF-8, `None` when it
|
|
39
|
+
/// already is UTF-8.
|
|
40
|
+
fn transcoded(text: RString) -> Result<Option<String>, Error> {
|
|
41
|
+
// SAFETY: the borrowed &str is dropped before any Ruby code can run.
|
|
42
|
+
if unsafe { text.test_as_str() }.is_some() {
|
|
43
|
+
Ok(None)
|
|
44
|
+
} else {
|
|
45
|
+
text.to_string().map(Some)
|
|
32
46
|
}
|
|
33
47
|
}
|
|
34
48
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
49
|
+
/// Refuses input sudachi.rs would refuse, before any of it is copied into an
|
|
50
|
+
/// analyzer that would keep the buffer.
|
|
51
|
+
fn check_length(bytes: usize) -> Result<(), Error> {
|
|
52
|
+
if bytes > MAX_INPUT_BYTES {
|
|
53
|
+
return Err(tokenization_error(SudachiError::InputTooLong(
|
|
54
|
+
bytes,
|
|
55
|
+
MAX_INPUT_BYTES,
|
|
56
|
+
)));
|
|
57
|
+
}
|
|
58
|
+
Ok(())
|
|
40
59
|
}
|
|
41
60
|
|
|
42
|
-
struct
|
|
43
|
-
|
|
44
|
-
|
|
61
|
+
struct Analyzer {
|
|
62
|
+
inner: StatefulTokenizer<Dict>,
|
|
63
|
+
/// The longest input this analyzer has been given, in bytes.
|
|
64
|
+
longest: usize,
|
|
65
|
+
/// What the GC has been told this analyzer holds.
|
|
66
|
+
reported: usize,
|
|
45
67
|
}
|
|
46
68
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
69
|
+
impl Analyzer {
|
|
70
|
+
/// Replaces the text to analyze.
|
|
71
|
+
fn load(&mut self, text: &str) {
|
|
72
|
+
self.longest = self.longest.max(text.len());
|
|
73
|
+
self.inner.reset().push_str(text);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// Analyzes the loaded text and moves the result out. Runs without the
|
|
77
|
+
/// GVL: the list it makes is not shared with anything until it is handed
|
|
78
|
+
/// back to the calling thread.
|
|
79
|
+
fn analyze(&mut self, dict: &Dict) -> SudachiResult<Analysis> {
|
|
80
|
+
self.inner.do_tokenize()?;
|
|
81
|
+
let mut list = MorphemeList::empty(dict.clone());
|
|
82
|
+
list.collect_results(&mut self.inner)?;
|
|
83
|
+
Ok(list)
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
fn estimated_bytes(&self) -> usize {
|
|
87
|
+
ANALYZER_BASE_BYTES + self.longest * ANALYZER_BYTES_PER_INPUT_BYTE
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/// Brings what the GC has been told up to date. Needs the GVL.
|
|
91
|
+
fn report(&mut self) {
|
|
92
|
+
let estimate = self.estimated_bytes();
|
|
93
|
+
if estimate != self.reported {
|
|
94
|
+
report_native_memory(estimate as isize - self.reported as isize);
|
|
95
|
+
self.reported = estimate;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
53
98
|
}
|
|
54
99
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
100
|
+
/// Dropped only while holding the GVL: by the pool, or by a call that got
|
|
101
|
+
/// it back from `without_gvl`.
|
|
102
|
+
impl Drop for Analyzer {
|
|
103
|
+
fn drop(&mut self) {
|
|
104
|
+
report_native_memory(-(self.reported as isize));
|
|
58
105
|
}
|
|
59
106
|
}
|
|
60
107
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
Err(msg)
|
|
108
|
+
#[derive(Default)]
|
|
109
|
+
struct Idle {
|
|
110
|
+
/// Analyzers that have only seen inputs up to `LARGE_INPUT_BYTES`.
|
|
111
|
+
small: Vec<Analyzer>,
|
|
112
|
+
large: Vec<Analyzer>,
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
impl Idle {
|
|
116
|
+
fn for_input(&mut self, bytes: usize) -> &mut Vec<Analyzer> {
|
|
117
|
+
if bytes > LARGE_INPUT_BYTES {
|
|
118
|
+
&mut self.large
|
|
119
|
+
} else {
|
|
120
|
+
&mut self.small
|
|
75
121
|
}
|
|
76
|
-
}
|
|
77
|
-
std::ptr::null_mut()
|
|
122
|
+
}
|
|
78
123
|
}
|
|
79
124
|
|
|
80
|
-
|
|
81
|
-
|
|
125
|
+
/// Idle analyzers owned by one `Kabosu::Tokenizer`. A call checks one out,
|
|
126
|
+
/// analyzes with the GVL released and checks it back in, so threads sharing a
|
|
127
|
+
/// tokenizer run in parallel and the pool never holds more analyzers than the
|
|
128
|
+
/// peak number of concurrent calls. Everything is freed with the tokenizer.
|
|
129
|
+
///
|
|
130
|
+
/// The lock is only ever taken while holding the GVL. That keeps it
|
|
131
|
+
/// uncontended and means no thread can be inside it across a `fork`.
|
|
132
|
+
struct AnalyzerPool {
|
|
133
|
+
dict: Dict,
|
|
134
|
+
mode: Mode,
|
|
82
135
|
subset: InfoSubset,
|
|
83
136
|
debug: bool,
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
TOKENIZER_CACHE.with(|cache| {
|
|
87
|
-
let mut cache = cache.borrow_mut();
|
|
88
|
-
let tokenizer = cache
|
|
89
|
-
.entry(pool.id)
|
|
90
|
-
.or_insert_with(|| StatefulTokenizer::new(pool.dict.clone(), pool.mode));
|
|
91
|
-
|
|
92
|
-
tokenizer.set_debug(debug);
|
|
93
|
-
tokenizer.set_subset(subset);
|
|
94
|
-
tokenizer.reset().push_str(text);
|
|
95
|
-
tokenizer.do_tokenize().map_err(|e| e.to_string())?;
|
|
96
|
-
|
|
97
|
-
let mut mlist = MorphemeList::empty(pool.dict.clone());
|
|
98
|
-
mlist
|
|
99
|
-
.collect_results(tokenizer)
|
|
100
|
-
.map_err(|e| e.to_string())?;
|
|
101
|
-
|
|
102
|
-
let mut morphemes = Vec::with_capacity(mlist.len());
|
|
103
|
-
for i in 0..mlist.len() {
|
|
104
|
-
morphemes.push(build_morpheme_data(&mlist.get(i)));
|
|
105
|
-
}
|
|
137
|
+
idle: Mutex<Idle>,
|
|
138
|
+
}
|
|
106
139
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
140
|
+
impl AnalyzerPool {
|
|
141
|
+
fn idle(&self) -> MutexGuard<'_, Idle> {
|
|
142
|
+
self.idle.lock().unwrap_or_else(PoisonError::into_inner)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/// An analyzer for an input of `bytes` bytes.
|
|
146
|
+
fn check_out(&self, bytes: usize) -> Analyzer {
|
|
147
|
+
let pooled = self.idle().for_input(bytes).pop();
|
|
148
|
+
pooled.unwrap_or_else(|| {
|
|
149
|
+
let mut inner = StatefulTokenizer::create(self.dict.clone(), self.debug, self.mode);
|
|
150
|
+
inner.set_subset(self.subset);
|
|
151
|
+
let mut analyzer = Analyzer {
|
|
152
|
+
inner,
|
|
153
|
+
longest: 0,
|
|
154
|
+
reported: 0,
|
|
155
|
+
};
|
|
156
|
+
analyzer.report();
|
|
157
|
+
analyzer
|
|
110
158
|
})
|
|
111
|
-
}
|
|
112
|
-
}
|
|
159
|
+
}
|
|
113
160
|
|
|
114
|
-
fn
|
|
161
|
+
fn check_in(&self, mut analyzer: Analyzer) {
|
|
162
|
+
analyzer.report();
|
|
163
|
+
let longest = analyzer.longest;
|
|
164
|
+
self.idle().for_input(longest).push(analyzer);
|
|
165
|
+
}
|
|
115
166
|
|
|
116
|
-
fn
|
|
117
|
-
|
|
118
|
-
|
|
167
|
+
fn native_bytes(&self) -> usize {
|
|
168
|
+
let idle = self.idle();
|
|
169
|
+
let reported = |analyzers: &[Analyzer]| -> usize {
|
|
170
|
+
analyzers.iter().map(|analyzer| analyzer.reported).sum()
|
|
171
|
+
};
|
|
172
|
+
reported(&idle.small) + reported(&idle.large)
|
|
173
|
+
}
|
|
119
174
|
}
|
|
120
175
|
|
|
121
|
-
#[
|
|
176
|
+
#[derive(TypedData)]
|
|
177
|
+
#[magnus(class = "Kabosu::Tokenizer", mark, size, free_immediately)]
|
|
122
178
|
pub(crate) struct RbTokenizer {
|
|
123
|
-
pool:
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
179
|
+
pool: AnalyzerPool,
|
|
180
|
+
pos_table: PosTable,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
impl DataTypeFunctions for RbTokenizer {
|
|
184
|
+
fn mark(&self, marker: &gc::Marker) {
|
|
185
|
+
self.pos_table.mark(marker);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
fn size(&self) -> usize {
|
|
189
|
+
size_of::<Self>() + self.pool.native_bytes()
|
|
190
|
+
}
|
|
128
191
|
}
|
|
129
192
|
|
|
130
193
|
impl RbTokenizer {
|
|
131
194
|
pub(crate) fn new(
|
|
132
|
-
dict:
|
|
195
|
+
dict: Dict,
|
|
196
|
+
pos_table: PosTable,
|
|
133
197
|
mode: Mode,
|
|
134
198
|
subset: InfoSubset,
|
|
135
199
|
debug: bool,
|
|
136
200
|
) -> Self {
|
|
137
|
-
|
|
138
|
-
|
|
201
|
+
// What sudachi.rs itself turns the request into: see
|
|
202
|
+
// `StatefulTokenizer::set_subset`.
|
|
203
|
+
let mode_subset = match mode {
|
|
204
|
+
Mode::A => InfoSubset::SPLIT_A,
|
|
205
|
+
Mode::B => InfoSubset::SPLIT_B,
|
|
206
|
+
Mode::C => InfoSubset::empty(),
|
|
207
|
+
};
|
|
139
208
|
Self {
|
|
140
|
-
pool:
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
209
|
+
pool: AnalyzerPool {
|
|
210
|
+
dict,
|
|
211
|
+
mode,
|
|
212
|
+
subset: (subset | mode_subset).normalize(),
|
|
213
|
+
debug,
|
|
214
|
+
idle: Mutex::default(),
|
|
215
|
+
},
|
|
216
|
+
pos_table,
|
|
145
217
|
}
|
|
146
218
|
}
|
|
147
219
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
out: None,
|
|
155
|
-
};
|
|
220
|
+
/// Safe to call from any number of Ruby threads at once: each call works on
|
|
221
|
+
/// its own analyzer, and only the analysis itself runs without the GVL.
|
|
222
|
+
pub(crate) fn tokenize(&self, text: RString) -> Result<RbMorphemeList, Error> {
|
|
223
|
+
let transcoded = transcoded(text)?;
|
|
224
|
+
let bytes = transcoded.as_ref().map_or(text.len(), String::len);
|
|
225
|
+
check_length(bytes)?;
|
|
156
226
|
|
|
157
|
-
|
|
227
|
+
let mut analyzer = self.pool.check_out(bytes);
|
|
228
|
+
match &transcoded {
|
|
229
|
+
Some(utf8) => analyzer.load(utf8),
|
|
230
|
+
// SAFETY: the borrowed &str is copied before any Ruby code runs.
|
|
231
|
+
None => analyzer.load(unsafe { text.as_str() }?),
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// The text has been copied into the analyzer, so nothing in here
|
|
235
|
+
// refers to a Ruby object.
|
|
236
|
+
let dict = &self.pool.dict;
|
|
237
|
+
let analyzed = without_gvl(|| analyzer.analyze(dict));
|
|
238
|
+
let list = self.finish([analyzer], analyzed)?;
|
|
239
|
+
Ok(self.wrap(list))
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/// Tokenizes many texts with the GVL released once per
|
|
243
|
+
/// `BATCH_CHUNK_BYTES` of text, instead of once per text. Worth it for
|
|
244
|
+
/// many short texts tokenized from several threads, where re-acquiring
|
|
245
|
+
/// the GVL after every sentence is what the threads end up waiting for.
|
|
246
|
+
pub(crate) fn tokenize_batch(
|
|
247
|
+
ruby: &Ruby,
|
|
248
|
+
rb_self: &Self,
|
|
249
|
+
texts: RArray,
|
|
250
|
+
) -> Result<RArray, Error> {
|
|
251
|
+
let mut copies = Vec::with_capacity(texts.len());
|
|
252
|
+
for text in texts {
|
|
253
|
+
let mut copy = String::new();
|
|
254
|
+
push_utf8(RString::try_convert(text)?, &mut copy)?;
|
|
255
|
+
check_length(copy.len())?;
|
|
256
|
+
copies.push(copy);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// One analyzer per size class in use, so a long text in the batch
|
|
260
|
+
// does not put the short ones on a large lattice.
|
|
261
|
+
let is_large = |copy: &String| copy.len() > LARGE_INPUT_BYTES;
|
|
262
|
+
let pool = &rb_self.pool;
|
|
263
|
+
let mut small = (copies.iter().any(|copy| !is_large(copy))).then(|| pool.check_out(0));
|
|
264
|
+
let mut large = (copies.iter().any(is_large)).then(|| pool.check_out(usize::MAX));
|
|
158
265
|
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
266
|
+
let results = ruby.ary_new_capa(copies.len());
|
|
267
|
+
let mut rest = copies.as_slice();
|
|
268
|
+
while !rest.is_empty() {
|
|
269
|
+
let mut bytes = 0;
|
|
270
|
+
let count = rest
|
|
271
|
+
.iter()
|
|
272
|
+
.take_while(|copy| {
|
|
273
|
+
let fits = bytes < BATCH_CHUNK_BYTES;
|
|
274
|
+
bytes += copy.len();
|
|
275
|
+
fits
|
|
276
|
+
})
|
|
277
|
+
.count();
|
|
278
|
+
let (chunk, later) = rest.split_at(count);
|
|
279
|
+
rest = later;
|
|
280
|
+
|
|
281
|
+
let dict = &pool.dict;
|
|
282
|
+
let analyzed = without_gvl(|| {
|
|
283
|
+
let mut lists = Vec::with_capacity(chunk.len());
|
|
284
|
+
for copy in chunk {
|
|
285
|
+
let analyzer = if is_large(copy) {
|
|
286
|
+
&mut large
|
|
287
|
+
} else {
|
|
288
|
+
&mut small
|
|
289
|
+
};
|
|
290
|
+
let analyzer = analyzer.as_mut().expect("checked out for this size class");
|
|
291
|
+
analyzer.load(copy);
|
|
292
|
+
lists.push(analyzer.analyze(dict)?);
|
|
293
|
+
}
|
|
294
|
+
Ok(lists)
|
|
295
|
+
});
|
|
296
|
+
let stopped = analyzed.as_ref().map_or(true, |lists| lists.is_err());
|
|
297
|
+
let analyzers = if stopped || rest.is_empty() {
|
|
298
|
+
small.take().into_iter().chain(large.take())
|
|
299
|
+
} else {
|
|
300
|
+
None.into_iter().chain(None)
|
|
301
|
+
};
|
|
302
|
+
for list in rb_self.finish(analyzers, analyzed)? {
|
|
303
|
+
results.push(rb_self.wrap(list))?;
|
|
167
304
|
}
|
|
168
|
-
Err(msg) => Err(sudachi_error(msg)),
|
|
169
305
|
}
|
|
306
|
+
Ok(results)
|
|
170
307
|
}
|
|
171
308
|
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
309
|
+
/// Returns the analyzers to the pool and turns what happened without the
|
|
310
|
+
/// GVL into a result or a Ruby error.
|
|
311
|
+
fn finish<T>(
|
|
312
|
+
&self,
|
|
313
|
+
analyzers: impl IntoIterator<Item = Analyzer>,
|
|
314
|
+
analyzed: Result<SudachiResult<T>, Stopped>,
|
|
315
|
+
) -> Result<T, Error> {
|
|
316
|
+
match analyzed {
|
|
317
|
+
Ok(result) => {
|
|
318
|
+
analyzers.into_iter().for_each(|a| self.pool.check_in(a));
|
|
319
|
+
result.map_err(tokenization_error)
|
|
320
|
+
}
|
|
321
|
+
// The analysis ran to its end, or never started: either way the
|
|
322
|
+
// analyzers are in a state the next call can reset.
|
|
323
|
+
Err(stopped @ Stopped::Raised(_)) => {
|
|
324
|
+
analyzers.into_iter().for_each(|a| self.pool.check_in(a));
|
|
325
|
+
Err(stopped.into_error(|_| unreachable!("not a panic")))
|
|
326
|
+
}
|
|
327
|
+
// An analyzer that panicked mid-analysis is in an unknown state:
|
|
328
|
+
// drop it rather than hand it to the next call.
|
|
329
|
+
Err(stopped @ Stopped::Panic(_)) => {
|
|
330
|
+
analyzers.into_iter().for_each(drop);
|
|
331
|
+
Err(stopped.into_error(|message| {
|
|
332
|
+
tokenization_error(format_args!("panic during tokenization: {message}"))
|
|
333
|
+
}))
|
|
334
|
+
}
|
|
335
|
+
}
|
|
180
336
|
}
|
|
181
337
|
|
|
182
|
-
|
|
183
|
-
|
|
338
|
+
fn wrap(&self, list: Analysis) -> RbMorphemeList {
|
|
339
|
+
let path_cost = list.get_internal_cost();
|
|
340
|
+
RbMorphemeList::new(list, self.pos_table, Some(path_cost))
|
|
184
341
|
}
|
|
185
342
|
|
|
186
|
-
pub(crate) fn
|
|
187
|
-
|
|
188
|
-
subset_to_array(&ruby, self.subset)
|
|
343
|
+
pub(crate) fn mode(ruby: &Ruby, rb_self: &Self) -> Symbol {
|
|
344
|
+
mode_symbol(ruby, rb_self.pool.mode)
|
|
189
345
|
}
|
|
190
346
|
|
|
191
|
-
|
|
192
|
-
|
|
347
|
+
/// The word-info fields this tokenizer loads: the ones it was asked for
|
|
348
|
+
/// plus those they and the split mode depend on.
|
|
349
|
+
pub(crate) fn fields(ruby: &Ruby, rb_self: &Self) -> Result<RArray, Error> {
|
|
350
|
+
subset_to_array(ruby, rb_self.pool.subset)
|
|
193
351
|
}
|
|
194
352
|
|
|
195
|
-
pub(crate) fn
|
|
196
|
-
self.
|
|
353
|
+
pub(crate) fn is_debug(&self) -> bool {
|
|
354
|
+
self.pool.debug
|
|
197
355
|
}
|
|
198
356
|
}
|
data/ext/kabosu/src/user_dict.rs
CHANGED
|
@@ -1,50 +1,75 @@
|
|
|
1
1
|
use std::fs::File;
|
|
2
2
|
use std::io::{BufWriter, Write};
|
|
3
|
+
use std::path::Path;
|
|
3
4
|
|
|
4
|
-
use magnus::
|
|
5
|
+
use magnus::Error;
|
|
5
6
|
use memmap2::Mmap;
|
|
6
7
|
use sudachi::dic::binary_loader::LoadedDictionary;
|
|
7
8
|
use sudachi::dic::build::DictBuilder;
|
|
9
|
+
use sudachi::error::{SudachiError, SudachiResult};
|
|
8
10
|
|
|
9
|
-
use crate::errors::{arg_error,
|
|
11
|
+
use crate::errors::{arg_error, dictionary_error};
|
|
12
|
+
use crate::nogvl::without_gvl;
|
|
10
13
|
|
|
11
14
|
/// Compiles user-dictionary CSV sources against one system dictionary, the
|
|
12
15
|
/// same way `sudachi ubuild` does. The result only loads alongside that exact
|
|
13
16
|
/// system dictionary: sudachi.rs 0.7 records which one it was built with.
|
|
14
17
|
pub(crate) fn build_user_dict(
|
|
15
|
-
inputs:
|
|
18
|
+
inputs: Vec<String>,
|
|
16
19
|
system_dict: String,
|
|
17
20
|
output: String,
|
|
18
21
|
description: Option<String>,
|
|
19
22
|
) -> Result<(), Error> {
|
|
20
|
-
let inputs: Vec<String> = match RArray::from_value(inputs) {
|
|
21
|
-
Some(ary) => ary.to_vec()?,
|
|
22
|
-
None => vec![String::try_convert(inputs)
|
|
23
|
-
.map_err(|_| arg_error("inputs must be a String or an Array of String"))?],
|
|
24
|
-
};
|
|
25
23
|
if inputs.is_empty() {
|
|
26
24
|
return Err(arg_error("inputs must name at least one CSV file"));
|
|
27
25
|
}
|
|
28
26
|
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
// Seconds of pure Rust against a large system dictionary: other threads
|
|
28
|
+
// run meanwhile.
|
|
29
|
+
without_gvl(|| {
|
|
30
|
+
build(
|
|
31
|
+
&inputs,
|
|
32
|
+
&system_dict,
|
|
33
|
+
&output,
|
|
34
|
+
description.unwrap_or_default(),
|
|
35
|
+
)
|
|
36
|
+
})
|
|
37
|
+
.map_err(|stopped| {
|
|
38
|
+
stopped.into_error(|message| {
|
|
39
|
+
dictionary_error(format_args!(
|
|
40
|
+
"panic while building a user dictionary: {message}"
|
|
41
|
+
))
|
|
42
|
+
})
|
|
43
|
+
})?
|
|
44
|
+
.map_err(dictionary_error)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
fn build(
|
|
48
|
+
inputs: &[String],
|
|
49
|
+
system_dict: &str,
|
|
50
|
+
output: &str,
|
|
51
|
+
description: String,
|
|
52
|
+
) -> SudachiResult<()> {
|
|
53
|
+
let context = |what: &str, path: &str| format!("cannot {what} {path}");
|
|
54
|
+
|
|
55
|
+
let system_file = File::open(system_dict).map_err(|e| {
|
|
56
|
+
SudachiError::from(e).with_context(context("open system dictionary", system_dict))
|
|
57
|
+
})?;
|
|
31
58
|
// SAFETY: read-only mapping that outlives every borrow made from it below.
|
|
32
|
-
let system_data = unsafe { Mmap::map(&system_file) }
|
|
33
|
-
let system = LoadedDictionary::load_system(&system_data)
|
|
59
|
+
let system_data = unsafe { Mmap::map(&system_file) }?;
|
|
60
|
+
let system = LoadedDictionary::load_system(&system_data)?;
|
|
34
61
|
|
|
35
62
|
let mut builder = DictBuilder::new_user(&system);
|
|
36
|
-
builder.set_description(description
|
|
37
|
-
for input in
|
|
38
|
-
builder
|
|
39
|
-
.read_lexicon(std::path::Path::new(input))
|
|
40
|
-
.map_err(sudachi_error)?;
|
|
63
|
+
builder.set_description(description);
|
|
64
|
+
for input in inputs {
|
|
65
|
+
builder.read_lexicon(Path::new(input))?;
|
|
41
66
|
}
|
|
42
|
-
builder.resolve()
|
|
67
|
+
builder.resolve()?;
|
|
43
68
|
|
|
44
|
-
let file =
|
|
45
|
-
|
|
69
|
+
let file = File::create(output)
|
|
70
|
+
.map_err(|e| SudachiError::from(e).with_context(context("create", output)))?;
|
|
46
71
|
let mut writer = BufWriter::new(file);
|
|
47
|
-
builder.compile(&mut writer)
|
|
48
|
-
writer.flush()
|
|
72
|
+
builder.compile(&mut writer)?;
|
|
73
|
+
writer.flush()?;
|
|
49
74
|
Ok(())
|
|
50
75
|
}
|