-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
lib.rs
200 lines (178 loc) · 4.58 KB
/
lib.rs
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
#![deny(clippy::all)]
#![allow(clippy::nonstandard_macro_braces)]
/// Explicit extern crate to use allocator.
extern crate global_alloc;
use std::str;
use jieba_rs::{Jieba, KeywordExtract, TFIDF};
use napi::bindgen_prelude::*;
use napi_derive::*;
use once_cell::sync::OnceCell;
static JIEBA: OnceCell<Jieba> = OnceCell::new();
static TFIDF_INSTANCE: OnceCell<TFIDF> = OnceCell::new();
#[napi]
pub fn load() -> Result<()> {
assert_not_init()?;
let _ = JIEBA.get_or_init(Jieba::new);
Ok(())
}
#[napi]
pub fn load_dict(dict: Buffer) -> Result<()> {
assert_not_init()?;
let mut readable_dict: &[u8] = &dict;
JIEBA.get_or_init(|| {
let mut jieba = Jieba::new();
jieba
.load_dict(&mut readable_dict)
.map_err(|_| {
Error::from_reason("Load dict failed".to_owned());
})
.unwrap();
jieba
});
Ok(())
}
#[inline]
fn assert_not_init() -> Result<()> {
if JIEBA.get().is_some() {
Err(Error::from_reason(
"Jieba was loaded, could not load again".to_owned(),
))
} else {
Ok(())
}
}
#[napi(ts_return_type = "string[]")]
pub fn cut(env: Env, sentence: Either<String, Buffer>, hmm: Option<bool>) -> Result<Array> {
let hmm = hmm.unwrap_or(false);
let jieba = JIEBA.get_or_init(Jieba::new);
let cutted = jieba.cut(
match &sentence {
Either::A(s) => s.as_str(),
Either::B(b) => {
str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))?
}
},
hmm,
);
Array::from_vec(&env, cutted)
}
#[napi(ts_return_type = "string[]")]
pub fn cut_all(env: Env, sentence: Either<String, Buffer>) -> Result<Array> {
let jieba = JIEBA.get_or_init(Jieba::new);
let cutted = jieba.cut_all(match &sentence {
Either::A(s) => s.as_str(),
Either::B(b) => {
str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))?
}
});
Array::from_vec(&env, cutted)
}
#[napi(ts_return_type = "string[]")]
pub fn cut_for_search(
env: Env,
sentence: Either<String, Buffer>,
hmm: Option<bool>,
) -> Result<Array> {
let hmm = hmm.unwrap_or(false);
let jieba = JIEBA.get_or_init(Jieba::new);
let cutted = jieba.cut_for_search(
match &sentence {
Either::A(s) => s.as_str(),
Either::B(b) => {
str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))?
}
},
hmm,
);
Array::from_vec(&env, cutted)
}
#[napi(object)]
pub struct TaggedWord {
pub tag: String,
pub word: String,
}
#[napi]
pub fn tag(sentence: Either<String, Buffer>, hmm: Option<bool>) -> Result<Vec<TaggedWord>> {
let jieba = JIEBA.get_or_init(Jieba::new);
let tagged = jieba.tag(
match &sentence {
Either::A(s) => s.as_str(),
Either::B(b) => {
str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))?
}
},
hmm.unwrap_or(false),
);
Ok(
tagged
.iter()
.map(|t| TaggedWord {
tag: t.tag.to_owned(),
word: t.word.to_owned(),
})
.collect(),
)
}
#[napi(object)]
pub struct Keyword {
pub keyword: String,
pub weight: f64,
}
#[napi]
pub fn extract(
sentence: Either<String, Buffer>,
topn: u32,
allowed_pos: Option<String>,
) -> Result<Vec<Keyword>> {
let allowed_pos_string = allowed_pos.unwrap_or_else(|| "".to_owned());
let allowed_pos: Vec<String> = if allowed_pos_string.is_empty() {
vec![]
} else {
allowed_pos_string
.split(',')
.map(|s| s.to_owned())
.collect()
};
let keyword_extractor = TFIDF_INSTANCE.get_or_init(|| {
let jieba = JIEBA.get_or_init(Jieba::new);
TFIDF::new_with_jieba(jieba)
});
let tags = keyword_extractor.extract_tags(
match &sentence {
Either::A(s) => s.as_str(),
Either::B(b) => {
str::from_utf8(b.as_ref()).map_err(|_| Error::from_status(Status::InvalidArg))?
}
},
topn as usize,
allowed_pos,
);
Ok(
tags
.into_iter()
.map(|tag| Keyword {
keyword: tag.keyword,
weight: tag.weight,
})
.collect::<Vec<Keyword>>(),
)
}
#[napi(js_name = "loadTFIDFDict")]
pub fn load_tfidf_dict(dict: Buffer) -> Result<()> {
let mut readable_dict: &[u8] = &dict;
if TFIDF_INSTANCE.get().is_some() {
return Err(Error::new(
Status::GenericFailure,
"TFIDF has loaded, can not load dict again".to_owned(),
));
}
TFIDF_INSTANCE.get_or_try_init(|| {
let jieba = JIEBA.get_or_init(Jieba::new);
let mut tfidf = TFIDF::new_with_jieba(jieba);
tfidf
.load_dict(&mut readable_dict)
.map(|_| tfidf)
.map_err(|e| Error::new(Status::GenericFailure, format!("{e}")))
})?;
Ok(())
}