sudachi/plugin/oov/mecab_oov/
mod.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
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
/*
 * Copyright (c) 2021-2024 Works Applications Co., Ltd.
 *
 * 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
 *
 *     http://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.
 */

use crate::analysis::created::CreatedWords;
use crate::util::user_pos::{UserPosMode, UserPosSupport};
use serde::Deserialize;
use serde_json::Value;
use std::collections::HashMap;
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;

use crate::analysis::Node;
use crate::config::Config;
use crate::dic::category_type::CategoryType;
use crate::dic::character_category::Error as CharacterCategoryError;
use crate::dic::grammar::Grammar;
use crate::dic::word_id::WordId;
use crate::hash::RoMu;
use crate::input_text::InputBuffer;
use crate::input_text::InputTextIndex;
use crate::plugin::oov::OovProviderPlugin;
use crate::prelude::*;

#[cfg(test)]
mod test;

const DEFAULT_CHAR_DEF_FILE: &str = "char.def";
const DEFAULT_CHAR_DEF_BYTES: &[u8] = include_bytes!("../../../../../resources/char.def");
const DEFAULT_UNK_DEF_FILE: &str = "unk.def";
const DEFAULT_UNK_DEF_BYTES: &[u8] = include_bytes!("../../../../../resources/unk.def");

/// provides MeCab oov nodes
#[derive(Default)]
pub struct MeCabOovPlugin {
    categories: HashMap<CategoryType, CategoryInfo, RoMu>,
    oov_list: HashMap<CategoryType, Vec<Oov>, RoMu>,
}

/// Struct corresponds with raw config json file.
#[allow(non_snake_case)]
#[derive(Deserialize)]
struct PluginSettings {
    charDef: Option<PathBuf>,
    unkDef: Option<PathBuf>,
    #[serde(default)]
    userPOS: UserPosMode,
}

impl MeCabOovPlugin {
    /// Loads character category definition
    ///
    /// See resources/char.def for the syntax
    fn read_character_property<T: BufRead>(
        reader: T,
    ) -> SudachiResult<HashMap<CategoryType, CategoryInfo, RoMu>> {
        let mut categories = HashMap::with_hasher(RoMu::new());
        for (i, line) in reader.lines().enumerate() {
            let line = line?;
            let line = line.trim();
            if line.is_empty()
                || line.starts_with('#')
                || line.chars().take(2).collect::<Vec<_>>() == vec!['0', 'x']
            {
                continue;
            }

            let cols: Vec<_> = line.split_whitespace().collect();
            if cols.len() < 4 {
                return Err(SudachiError::InvalidCharacterCategory(
                    CharacterCategoryError::InvalidFormat(i),
                ));
            }
            let category_type: CategoryType = match cols[0].parse() {
                Ok(t) => t,
                Err(_) => {
                    return Err(SudachiError::InvalidCharacterCategory(
                        CharacterCategoryError::InvalidCategoryType(i, cols[0].to_string()),
                    ))
                }
            };
            if categories.contains_key(&category_type) {
                return Err(SudachiError::InvalidCharacterCategory(
                    CharacterCategoryError::MultipleTypeDefinition(i, cols[0].to_string()),
                ));
            }

            categories.insert(
                category_type,
                CategoryInfo {
                    category_type,
                    is_invoke: cols[1] == "1",
                    is_group: cols[2] == "1",
                    length: cols[3].parse()?,
                },
            );
        }

        Ok(categories)
    }

    /// Load OOV definition
    ///
    /// Each line contains: CategoryType, left_id, right_id, cost, and pos
    fn read_oov<T: BufRead>(
        reader: T,
        categories: &HashMap<CategoryType, CategoryInfo, RoMu>,
        mut grammar: &mut Grammar,
        user_pos: UserPosMode,
    ) -> SudachiResult<HashMap<CategoryType, Vec<Oov>, RoMu>> {
        let mut oov_list: HashMap<CategoryType, Vec<Oov>, RoMu> = HashMap::with_hasher(RoMu::new());
        for (i, line) in reader.lines().enumerate() {
            let line = line?;
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            let cols: Vec<_> = line.split(',').collect();
            if cols.len() < 10 {
                return Err(SudachiError::InvalidDataFormat(
                    i,
                    format!("Invalid number of columns ({})", line),
                ));
            }
            let category_type: CategoryType = cols[0].parse()?;
            if !categories.contains_key(&category_type) {
                return Err(SudachiError::InvalidDataFormat(
                    i,
                    format!("{} is undefined in char definition", cols[0]),
                ));
            }

            let oov = Oov {
                left_id: cols[1].parse()?,
                right_id: cols[2].parse()?,
                cost: cols[3].parse()?,
                pos_id: grammar.handle_user_pos(&cols[4..10], user_pos)?,
            };

            if oov.left_id as usize > grammar.conn_matrix().num_left() {
                return Err(SudachiError::InvalidDataFormat(
                    0,
                    format!(
                        "max grammar left_id is {}, was {}",
                        grammar.conn_matrix().num_left(),
                        oov.left_id
                    ),
                ));
            }

            if oov.right_id as usize > grammar.conn_matrix().num_right() {
                return Err(SudachiError::InvalidDataFormat(
                    0,
                    format!(
                        "max grammar right_id is {}, was {}",
                        grammar.conn_matrix().num_right(),
                        oov.right_id
                    ),
                ));
            }

            match oov_list.get_mut(&category_type) {
                None => {
                    oov_list.insert(category_type, vec![oov]);
                }
                Some(l) => {
                    l.push(oov);
                }
            };
        }

        Ok(oov_list)
    }

    /// Creates a new oov node
    fn get_oov_node(&self, oov: &Oov, start: usize, end: usize) -> Node {
        Node::new(
            start as u16,
            end as u16,
            oov.left_id as u16,
            oov.right_id as u16,
            oov.cost,
            WordId::oov(oov.pos_id as u32),
        )
    }

    fn provide_oov_gen<T: InputTextIndex>(
        &self,
        input: &T,
        offset: usize,
        other_words: CreatedWords,
        nodes: &mut Vec<Node>,
    ) -> SudachiResult<usize> {
        let char_len = input.cat_continuous_len(offset);
        if char_len == 0 {
            return Ok(0);
        }
        let mut num_created = 0;

        for ctype in input.cat_at_char(offset).iter() {
            let cinfo = match self.categories.get(&ctype) {
                Some(ci) => ci,
                None => continue,
            };

            if !cinfo.is_invoke && other_words.not_empty() {
                continue;
            }

            let mut llength = char_len;
            let oovs = match self.oov_list.get(&cinfo.category_type) {
                Some(v) => v,
                None => continue,
            };

            if cinfo.is_group {
                for oov in oovs {
                    nodes.push(self.get_oov_node(oov, offset, offset + char_len));
                    num_created += 1;
                }
                llength -= 1;
            }
            for i in 1..=cinfo.length {
                let sublength = input.char_distance(offset, i as usize);
                if sublength > llength {
                    break;
                }
                for oov in oovs {
                    nodes.push(self.get_oov_node(oov, offset, offset + sublength));
                    num_created += 1;
                }
            }
        }
        Ok(num_created)
    }
}

impl OovProviderPlugin for MeCabOovPlugin {
    fn set_up(
        &mut self,
        settings: &Value,
        config: &Config,
        grammar: &mut Grammar,
    ) -> SudachiResult<()> {
        let settings: PluginSettings = serde_json::from_value(settings.clone())?;

        let char_def_path = config.complete_path(
            settings
                .charDef
                .unwrap_or_else(|| PathBuf::from(DEFAULT_CHAR_DEF_FILE)),
        );

        let categories = if char_def_path.is_ok() {
            let reader = BufReader::new(fs::File::open(char_def_path?)?);
            MeCabOovPlugin::read_character_property(reader)?
        } else {
            let reader = BufReader::new(DEFAULT_CHAR_DEF_BYTES);
            MeCabOovPlugin::read_character_property(reader)?
        };

        let unk_def_path = config.complete_path(
            settings
                .unkDef
                .unwrap_or_else(|| PathBuf::from(DEFAULT_UNK_DEF_FILE)),
        );

        let oov_list = if unk_def_path.is_ok() {
            let reader = BufReader::new(fs::File::open(unk_def_path?)?);
            MeCabOovPlugin::read_oov(reader, &categories, grammar, settings.userPOS)?
        } else {
            let reader = BufReader::new(DEFAULT_UNK_DEF_BYTES);
            MeCabOovPlugin::read_oov(reader, &categories, grammar, settings.userPOS)?
        };

        self.categories = categories;
        self.oov_list = oov_list;

        Ok(())
    }

    fn provide_oov(
        &self,
        input_text: &InputBuffer,
        offset: usize,
        other_words: CreatedWords,
        result: &mut Vec<Node>,
    ) -> SudachiResult<usize> {
        self.provide_oov_gen(input_text, offset, other_words, result)
    }
}

/// The character category definition
#[derive(Debug)]
struct CategoryInfo {
    category_type: CategoryType,
    is_invoke: bool,
    is_group: bool,
    length: u32,
}

/// The OOV definition
#[derive(Debug, Default, Clone)]
struct Oov {
    left_id: i16,
    right_id: i16,
    cost: i16,
    pos_id: u16,
}