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.
@@ -1,11 +1,13 @@
1
- use magnus::{Error, RArray, Ruby};
2
- use std::ffi::c_void;
1
+ use magnus::value::ReprValue;
2
+ use magnus::{Error, RArray, Ruby, TryConvert, Value};
3
3
  use sudachi::config::Config;
4
4
  use sudachi::dic::dictionary::JapaneseDictionary;
5
+ use sudachi::error::SudachiResult;
5
6
  use sudachi::sentence_splitter::{SentenceSplitter, SplitSentences};
6
7
 
7
- use crate::errors::sudachi_error;
8
- use crate::nogvl::run_without_gvl;
8
+ use crate::dictionary::{Dict, RbDictionary};
9
+ use crate::errors::{arg_error, sentence_split_error};
10
+ use crate::nogvl::without_gvl;
9
11
 
10
12
  struct SentenceChunk {
11
13
  start: usize,
@@ -13,124 +15,82 @@ struct SentenceChunk {
13
15
  sentence: String,
14
16
  }
15
17
 
16
- struct SplitSentencesJob {
17
- text: String,
18
- limit: Option<usize>,
19
- dict_path: Option<String>,
20
- out: Option<Result<Vec<SentenceChunk>, String>>,
18
+ /// The dictionary consulted so that a boundary does not fall inside a word.
19
+ enum Checker {
20
+ None,
21
+ /// An already loaded dictionary.
22
+ Loaded(Dict),
23
+ /// A system dictionary to load for this call.
24
+ Path(String),
21
25
  }
22
26
 
23
- impl SplitSentencesJob {
24
- fn run(&self) -> Result<Vec<SentenceChunk>, String> {
25
- let mut chunks = Vec::new();
26
-
27
- let mut push = |start: usize, end: usize, sentence: &str| {
28
- chunks.push(SentenceChunk {
29
- start,
30
- end,
31
- sentence: sentence.to_string(),
32
- });
27
+ impl Checker {
28
+ fn from_value(value: Option<Value>) -> Result<Self, Error> {
29
+ let Some(value) = value.filter(|value| !value.is_nil()) else {
30
+ return Ok(Self::None);
33
31
  };
34
-
35
- match &self.dict_path {
36
- Some(path) => {
37
- let cfg = Config::new(None, None, Some(path.clone().into()))
38
- .map_err(|e| e.to_string())?;
39
- let dict = JapaneseDictionary::from_cfg(&cfg).map_err(|e| e.to_string())?;
40
- let base = match self.limit {
41
- Some(lim) => SentenceSplitter::with_limit(lim),
42
- None => SentenceSplitter::new(),
43
- };
44
- let splitter = base.with_checker(dict.lexicon());
45
- for (range, sentence) in splitter.split(&self.text) {
46
- push(range.start, range.end, sentence);
47
- }
48
- }
49
- None => {
50
- let splitter = match self.limit {
51
- Some(lim) => SentenceSplitter::with_limit(lim),
52
- None => SentenceSplitter::new(),
53
- };
54
- for (range, sentence) in splitter.split(&self.text) {
55
- push(range.start, range.end, sentence);
56
- }
57
- }
32
+ if let Ok(dictionary) = <&RbDictionary>::try_convert(value) {
33
+ return Ok(Self::Loaded(dictionary.shared()));
58
34
  }
59
-
60
- Ok(chunks)
35
+ String::try_convert(value)
36
+ .map(Self::Path)
37
+ .map_err(|_| arg_error("dictionary must be a Kabosu::Dictionary or a path"))
61
38
  }
62
39
  }
63
40
 
64
- unsafe extern "C" fn split_without_gvl(ptr: *mut c_void) -> *mut c_void {
65
- let job = unsafe { &mut *(ptr as *mut SplitSentencesJob) };
66
- let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| job.run()));
67
- job.out = Some(match outcome {
68
- Ok(result) => result,
69
- Err(panic_payload) => {
70
- let msg = if let Some(s) = panic_payload.downcast_ref::<&str>() {
71
- format!("panic during sentence split: {s}")
72
- } else if let Some(s) = panic_payload.downcast_ref::<String>() {
73
- format!("panic during sentence split: {s}")
74
- } else {
75
- "panic during sentence split".to_string()
76
- };
77
- Err(msg)
41
+ fn split(text: &str, limit: Option<usize>, checker: &Checker) -> SudachiResult<Vec<SentenceChunk>> {
42
+ let splitter = match limit {
43
+ Some(limit) => SentenceSplitter::with_limit(limit),
44
+ None => SentenceSplitter::new(),
45
+ };
46
+ let chunk = |(range, sentence): (std::ops::Range<usize>, &str)| SentenceChunk {
47
+ start: range.start,
48
+ end: range.end,
49
+ sentence: sentence.to_string(),
50
+ };
51
+
52
+ Ok(match checker {
53
+ Checker::None => splitter.split(text).map(chunk).collect(),
54
+ Checker::Loaded(dict) => {
55
+ let splitter = splitter.with_checker(dict.lexicon());
56
+ splitter.split(text).map(chunk).collect()
57
+ }
58
+ Checker::Path(path) => {
59
+ let cfg = Config::new(None, None, Some(path.into()))?;
60
+ let dict = JapaneseDictionary::from_cfg(&cfg)?;
61
+ let splitter = splitter.with_checker(dict.lexicon());
62
+ splitter.split(text).map(chunk).collect()
78
63
  }
79
- });
80
- std::ptr::null_mut()
64
+ })
81
65
  }
82
66
 
83
- fn split_sentences_impl(
67
+ /// Splits `text` into sentences, with the GVL released. Answers with the
68
+ /// sentences, or with `[start, end, sentence]` triples (byte offsets) when
69
+ /// `with_ranges` is set.
70
+ pub(crate) fn split_sentences(
71
+ ruby: &Ruby,
84
72
  text: String,
85
73
  limit: Option<usize>,
86
- dict_path: Option<String>,
74
+ checker: Option<Value>,
87
75
  with_ranges: bool,
88
76
  ) -> Result<RArray, Error> {
89
- let mut job = SplitSentencesJob {
90
- text,
91
- limit,
92
- dict_path,
93
- out: None,
94
- };
95
- run_without_gvl(&mut job, split_without_gvl);
96
- let chunks = match job
97
- .out
98
- .take()
99
- .unwrap_or_else(|| Err("sentence split job did not produce a result".to_string()))
100
- {
101
- Ok(chunks) => chunks,
102
- Err(msg) => return Err(sudachi_error(msg)),
103
- };
77
+ let checker = Checker::from_value(checker)?;
78
+ let chunks = without_gvl(|| split(&text, limit, &checker))
79
+ .map_err(|stopped| {
80
+ stopped.into_error(|message| {
81
+ sentence_split_error(format_args!("panic during sentence split: {message}"))
82
+ })
83
+ })?
84
+ .map_err(sentence_split_error)?;
104
85
 
105
- let ruby = Ruby::get().unwrap();
106
86
  let result = ruby.ary_new_capa(chunks.len());
107
87
  for chunk in chunks {
88
+ let sentence = ruby.str_new(&chunk.sentence);
108
89
  if with_ranges {
109
- let entry = ruby.ary_new_capa(3);
110
- entry.push(chunk.start)?;
111
- entry.push(chunk.end)?;
112
- entry.push(ruby.str_new(&chunk.sentence))?;
113
- result.push(entry)?;
90
+ result.push((chunk.start, chunk.end, sentence))?;
114
91
  } else {
115
- result.push(ruby.str_new(&chunk.sentence))?;
92
+ result.push(sentence)?;
116
93
  }
117
94
  }
118
-
119
95
  Ok(result)
120
96
  }
121
-
122
- pub(crate) fn split_sentences(
123
- text: String,
124
- limit: Option<usize>,
125
- dict_path: Option<String>,
126
- ) -> Result<RArray, Error> {
127
- split_sentences_impl(text, limit, dict_path, false)
128
- }
129
-
130
- pub(crate) fn split_sentences_with_ranges(
131
- text: String,
132
- limit: Option<usize>,
133
- dict_path: Option<String>,
134
- ) -> Result<RArray, Error> {
135
- split_sentences_impl(text, limit, dict_path, true)
136
- }