mod crfpp;
mod svm;
use crate::chunker::{ChunkerModel, Column, Template};
use crate::error::{Error, Result};
use crate::model::ModelBuilder;
use crate::parser::{FeatureSet, PairWeights, ParserModel, Quantization};
use crate::schema::{HeadRule, Marks, Normalization, Pattern, Schema, SurfaceRule, Symbols};
const NORMALIZER_RULE: &str = include_str!("cabocha/normalizer.rule");
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PartOfSpeechSet {
Ipa,
Juman,
Unidic,
}
impl PartOfSpeechSet {
pub fn from_name(name: &str) -> Result<Self> {
match name {
"IPA" => Ok(PartOfSpeechSet::Ipa),
"JUMAN" => Ok(PartOfSpeechSet::Juman),
"UNIDIC" => Ok(PartOfSpeechSet::Unidic),
other => Err(Error::Cabocha(format!(
"the model is for the part-of-speech set {other:?}, which is not one of CaboCha"
))),
}
}
pub fn dictionary(self) -> &'static str {
self.dictionaries()[0]
}
pub fn dictionaries(self) -> &'static [&'static str] {
match self {
PartOfSpeechSet::Ipa => &["ipadic"],
PartOfSpeechSet::Juman => &["jumandic"],
PartOfSpeechSet::Unidic => &["unidic", "unidic-cwj", "unidic-csj"],
}
}
pub fn feature_set(self) -> FeatureSet {
match self {
PartOfSpeechSet::Ipa | PartOfSpeechSet::Juman => FeatureSet::cabocha(),
PartOfSpeechSet::Unidic => FeatureSet::cabocha()
.with_part_of_speech_levels(2)
.expect("two levels are a limit"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Options {
pub sigma: f64,
pub min_support: usize,
pub frequent_features: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
sigma: 0.0001,
min_support: 2,
frequent_features: 3000,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Report {
pub chunker_features: usize,
pub support_vectors: usize,
pub positives: usize,
pub parser_features: usize,
pub all_pairs: usize,
pub kept_pairs: usize,
pub pairs: usize,
pub unit: f64,
}
#[derive(Debug, Clone)]
pub struct Converted {
pub part_of_speech_set: PartOfSpeechSet,
pub chunker: ChunkerModel,
pub parser: ParserModel,
pub report: Report,
}
impl Converted {
pub fn to_bytes(&self) -> Result<Vec<u8>> {
self.to_bytes_for(self.part_of_speech_set.dictionary())
}
pub fn to_bytes_for(&self, dictionary: &str) -> Result<Vec<u8>> {
let dictionaries = self.part_of_speech_set.dictionaries();
if !dictionaries.contains(&dictionary) {
return Err(Error::Cabocha(format!(
"the model is not one for the dictionary {dictionary}: its part-of-speech set is that of {}",
dictionaries.join(", ")
)));
}
Ok(
ModelBuilder::new(dictionary, self.chunker.schema().clone())?
.chunker(&self.chunker)?
.parser(&self.parser, Quantization::F32)?
.to_bytes(),
)
}
}
pub fn normalization() -> Normalization {
let rules: Vec<(&str, &str)> = NORMALIZER_RULE
.lines()
.filter_map(|line| line.split_once('\t'))
.collect();
Normalization::new(&rules).expect("the table of CaboCha is a table")
}
pub fn schema(part_of_speech_set: PartOfSpeechSet) -> Schema {
match part_of_speech_set {
PartOfSpeechSet::Ipa => Schema {
part_of_speech: 0..4,
conjugation_type: Some(4),
conjugation_form: Some(5),
base_form: Some(6),
function_words: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["助動詞"]),
Pattern::new(&["動詞", "非自立"]),
Pattern::new(&["動詞", "接尾"]),
Pattern::new(&["形容詞", "非自立"]),
Pattern::new(&["形容詞", "接尾"]),
],
not_heads: Vec::new(),
particles: vec![Pattern::new(&["助詞"])],
lexicalized: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["副詞"]),
Pattern::new(&["連体詞"]),
Pattern::new(&["接続詞"]),
],
symbols: Symbols {
others: Marks::new(&[&["記号"]], ""),
commas: Marks::new(&[], "、"),
periods: Marks::new(&[], "。"),
open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
close_brackets: Marks::new(&[], "))’”》」』]〉}"),
surface: SurfaceRule::OneCharacter,
},
normalization: normalization(),
head_rule: HeadRule::FunctionWordsApart,
},
PartOfSpeechSet::Juman => Schema {
part_of_speech: 0..2,
conjugation_type: Some(2),
conjugation_form: Some(3),
base_form: Some(4),
function_words: Vec::new(),
not_heads: vec![Pattern::new(&["助詞"]), Pattern::new(&["接尾辞"])],
particles: vec![Pattern::new(&["助詞"])],
lexicalized: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["副詞"]),
Pattern::new(&["連体詞"]),
Pattern::new(&["接続詞"]),
],
symbols: Symbols {
others: Marks::new(&[&["特殊"]], ""),
commas: Marks::new(&[], "、"),
periods: Marks::new(&[], "。"),
open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
close_brackets: Marks::new(&[], "))’”》」』]〉}"),
surface: SurfaceRule::OneCharacter,
},
normalization: normalization(),
head_rule: HeadRule::LastWords,
},
PartOfSpeechSet::Unidic => Schema {
part_of_speech: 0..4,
conjugation_type: Some(4),
conjugation_form: Some(3),
base_form: Some(7),
function_words: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["助動詞"]),
Pattern::new(&["接尾辞", "形容詞的"]),
Pattern::new(&["接尾辞", "形状詞的"]),
Pattern::new(&["接尾辞", "動詞的"]),
],
not_heads: Vec::new(),
particles: vec![Pattern::new(&["助詞"])],
lexicalized: vec![
Pattern::new(&["助詞"]),
Pattern::new(&["副詞"]),
Pattern::new(&["連体詞"]),
Pattern::new(&["接続詞"]),
],
symbols: Symbols {
others: Marks::new(&[&["空白"], &["補助記号"], &["記号"]], ""),
commas: Marks::new(&[], "、"),
periods: Marks::new(&[], "。"),
open_brackets: Marks::new(&[], "((‘“《「『[〈{"),
close_brackets: Marks::new(&[], "))’”》」』]〉}"),
surface: SurfaceRule::OneCharacter,
},
normalization: normalization(),
head_rule: HeadRule::FunctionWordsApart,
},
}
}
fn check_header(model: &svm::SvmModel, key: &str, accepted: &[&str]) -> Result<()> {
let value = model
.header
.get(key)
.ok_or_else(|| Error::Cabocha(format!("the parser model has no `{key}` in its header")))?;
if accepted
.iter()
.any(|one| one.eq_ignore_ascii_case(value.trim()))
{
Ok(())
} else {
Err(Error::Cabocha(format!(
"the parser model has `{key}: {value}`, and only {} is supported",
accepted.join(" or ")
)))
}
}
pub fn convert(chunker: &str, parser: &str, options: &Options) -> Result<Converted> {
if !options.sigma.is_finite() || options.sigma < 0.0 {
return Err(Error::Cabocha(format!(
"sigma is {}, and has to be 0 or more",
options.sigma
)));
}
let support = svm::read(parser)?;
let name = support.header.get("posset").ok_or_else(|| {
Error::Cabocha("the parser model has no `posset` in its header".to_string())
})?;
let part_of_speech_set = PartOfSpeechSet::from_name(name.trim())?;
check_header(&support, "degree", &["2"])?;
check_header(&support, "charset", &["UTF8", "UTF-8"])?;
if let Some(kind) = support.header.get("type")
&& kind.trim() != "dep"
{
return Err(Error::Cabocha(format!(
"the parser model has `type: {kind}`, and a parser model has `dep`"
)));
}
let bias = support
.header
.get("bias")
.and_then(|bias| bias.trim().parse::<f64>().ok());
if bias != Some(0.0) {
return Err(Error::Cabocha(
"the parser model has no `bias: 0` in its header, and only a model without a bias is supported".to_string(),
));
}
let schema = schema(part_of_speech_set);
let crf = crfpp::read(chunker)?;
if crf.columns != 2 {
return Err(Error::Cabocha(format!(
"the chunker model has {} columns, and the chunker of CaboCha has 2: the surface and the part of speech",
crf.columns
)));
}
let chunker_features = crf.features.len();
let chunker = ChunkerModel::new(
schema.clone(),
vec![Column::Surface, Column::PartOfSpeech],
Template::parse(&crf.template)?,
crf.transitions,
crf.features,
)?;
let expansion = svm::expand(&support, options)?;
let mut order: Vec<u32> = (0..support.names.len() as u32)
.filter(|number| !support.names[*number as usize].is_empty())
.collect();
order.sort_unstable_by_key(|number| support.names[*number as usize].as_bytes());
let mut numbers = vec![u32::MAX; support.names.len()];
for (index, number) in order.iter().enumerate() {
numbers[*number as usize] = index as u32;
}
let features: Vec<(String, f32)> = order
.iter()
.map(|number| {
let weight = expansion
.weights
.get(*number as usize)
.copied()
.unwrap_or(0);
(support.names[*number as usize].clone(), weight as f32)
})
.collect();
let mut pairs: Vec<((u32, u32), f32)> = expansion
.pairs
.iter()
.map(|((one, other), weight)| {
let (one, other) = (numbers[*one as usize], numbers[*other as usize]);
((one.min(other), one.max(other)), *weight as f32)
})
.collect();
pairs.sort_unstable_by_key(|(pair, _)| *pair);
let unit = f64::from(expansion.unit);
let report = Report {
chunker_features,
support_vectors: support.vectors.len(),
positives: expansion.positives,
parser_features: features.len(),
all_pairs: expansion.all_pairs,
kept_pairs: expansion.kept_pairs,
pairs: pairs.len(),
unit,
};
let parser = ParserModel::new(
schema,
part_of_speech_set.feature_set(),
f64::from(expansion.bias) * unit,
features,
PairWeights::Exact(pairs),
)?
.with_unit(unit)?;
Ok(Converted {
part_of_speech_set,
chunker,
parser,
report,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::lattice::LatticeMorpheme;
use crate::model::Model;
use crate::parser::Classifier;
#[test]
fn the_table_is_the_one_of_cabocha() {
let table = normalization();
assert_eq!(NORMALIZER_RULE.lines().count(), 182);
assert_eq!(table.rules().count(), 181);
for (surface, expected) in [
("ガイド", "ガイド"),
("ABC123", "ABC123"),
("(株)", "(株)"),
("「ヲ」", "「ヲ」"),
("ヴ", "ヴ"),
(" ", "___"),
(" ", "___"),
("―", "-"),
("-", "-"),
(",.読ん、。", ",.読ん、。"),
] {
assert_eq!(table.apply(surface), expected, "{surface}");
}
}
#[test]
fn the_schema_is_the_rule_of_cabocha_for_ipa() {
let schema = schema(PartOfSpeechSet::Ipa);
let morpheme = |surface: &str, features: &str| LatticeMorpheme::new(surface, features);
let bunsetsu = [
morpheme("利用", "名詞,サ変接続,*,*,*,*,利用,リヨウ,リヨー"),
morpheme("し", "動詞,自立,*,*,サ変・スル,連用形,する,シ,シ"),
morpheme("た", "助動詞,*,*,*,特殊・タ,基本形,た,タ,タ"),
morpheme("。", "記号,句点,*,*,*,*,。,。,。"),
];
assert_eq!(schema.positions(&bunsetsu), Some((1, 2)));
assert_eq!(Schema::ipadic().positions(&bunsetsu), Some((0, 2)));
let bunsetsu = [
morpheme("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
morpheme("こと", "名詞,非自立,一般,*,*,*,こと,コト,コト"),
morpheme("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ"),
];
assert_eq!(schema.positions(&bunsetsu), Some((1, 2)));
assert_eq!(schema.positions(&bunsetsu[..2]), Some((1, 1)));
let noun = "名詞,サ変接続,*,*,*,*,*";
assert!(schema.is_comma(&morpheme("、", noun)));
assert!(schema.is_period(&morpheme("。", noun)));
assert!(!schema.is_comma(&morpheme(",", noun)));
assert!(!schema.is_comma(&morpheme(",", noun)));
assert!(!schema.is_period(&morpheme(".", noun)));
for open in ["(", "(", "‘", "“", "《", "「", "『", "[", "〈", "「"] {
assert!(schema.is_open_bracket(&morpheme(open, noun)), "{open}");
}
for close in [")", ")", "》", "」", "』", "]", "〉", "」"] {
assert!(schema.is_close_bracket(&morpheme(close, noun)), "{close}");
}
for other in ["[", "【", "((", "「「", ""] {
assert!(!schema.is_open_bracket(&morpheme(other, noun)), "{other}");
}
assert!(!schema.is_open_bracket(&morpheme("{", noun)));
assert!(!schema.is_open_bracket(&morpheme("{", noun)));
for close in ["}", "}", "’", "”", "'", "\""] {
assert!(!schema.is_close_bracket(&morpheme(close, noun)), "{close}");
}
assert!(!schema.is_symbol(&morpheme("(", noun)));
assert!(schema.is_symbol(&morpheme("x", "記号,一般,*,*,*,*,*")));
assert!(schema.is_particle(&[morpheme("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ")], 0));
assert_eq!(schema.width(), 7);
}
#[test]
fn converts_the_two_models_into_one() {
let converted = convert(
crfpp::tests::MODEL,
svm::tests::MODEL,
&svm::tests::unpruned(),
)
.unwrap();
assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Ipa);
assert_eq!(
converted.report,
Report {
chunker_features: 3,
support_vectors: 4,
positives: 2,
parser_features: 5,
all_pairs: 7,
kept_pairs: 7,
pairs: 7,
unit: f64::from(2.25f32 / 1_048_575.0),
}
);
let parser = &converted.parser;
let unit = converted.report.unit;
let whole = |weight: f32| f64::from((weight / (2.25f32 / 1_048_575.0)) as i32);
let id = |name: &str| parser.id(name).unwrap();
assert_eq!(parser.id("DIST:6-"), None);
assert_eq!(parser.score(&[]), whole(0.375) * unit);
assert_eq!(
parser.score(&[id("DHS:読む")]),
(whole(0.375) + 1_048_575.0) * unit
);
let mut both = [id("DIST:1"), id("DHS:読む")];
both.sort_unstable();
assert_eq!(
parser.score(&both),
(whole(0.375) + whole(0.375) + 1_048_575.0 + whole(1.0)) * unit
);
let mut negative = [id("DIST:1"), id("GNB:1"), id("SHS:本")];
negative.sort_unstable();
let score = parser.score(&negative);
assert!((score + 0.375).abs() < 8.0 * unit, "{score}");
assert_eq!(parser.feature_set(), &FeatureSet::cabocha());
assert_eq!(parser.schema(), &schema(PartOfSpeechSet::Ipa));
let model = Model::new(converted.to_bytes().unwrap()).unwrap();
assert_eq!(model.dictionary(), "ipadic");
assert_eq!(model.schema(), &schema(PartOfSpeechSet::Ipa));
assert!(model.chunker().is_some());
let part = model.parser().unwrap();
let classifier = part.classifier();
for features in [vec![], negative.to_vec(), both.to_vec()] {
assert_eq!(classifier.score(&features), parser.score(&features));
}
}
#[test]
fn the_converted_model_analyzes_with_the_features_of_cabocha() {
let chunker = "version: 100\ncost-factor: 1\nmaxid: 8\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:助詞-格助詞-一般/名詞-一般\n6 U01:助詞-格助詞-一般/動詞-自立\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n";
let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: IPA\n\n0 SHS:ABC\n1 DIST:1\n\n1 0\n-0.25 1\n";
let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
let model = Model::new(converted.to_bytes().unwrap()).unwrap();
let sentence = |first: &str| {
vec![
LatticeMorpheme::new(first, "名詞,一般,*,*,*,*,*"),
LatticeMorpheme::new("が", "助詞,格助詞,一般,*,*,*,が,ガ,ガ"),
LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
]
};
let bunsetsu = model.analyze(&sentence("ABC")).unwrap();
let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
assert_eq!(heads, [Some(1), Some(2), None]);
let bunsetsu = model.analyze(&sentence("彼")).unwrap();
let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
assert_eq!(heads, [Some(2), Some(2), None]);
}
#[test]
fn a_model_for_juman_is_converted_with_the_schema_of_juman() {
let chunker = "version: 100\ncost-factor: 1\nmaxid: 10\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:助詞-格助詞/動詞\n6 U01:助詞-格助詞/名詞-普通名詞\n8 U01:接尾辞-動詞性接尾辞/名詞-普通名詞\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n5\n-5\n";
let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: JUMAN\n\n0 SFF:基本形\n1 DIST:1\n\n1 0\n-0.25 1\n";
let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Juman);
let juman = schema(PartOfSpeechSet::Juman);
assert_eq!(juman.part_of_speech, 0..2);
assert_eq!(juman.conjugation_form, Some(3));
assert_eq!(juman.head_rule, HeadRule::LastWords);
assert_eq!(converted.parser.schema(), &juman);
assert_ne!(juman, schema(PartOfSpeechSet::Ipa));
let model = Model::new(converted.to_bytes().unwrap()).unwrap();
assert_eq!(model.dictionary(), "jumandic");
assert_eq!(model.schema(), &juman);
let sentence = vec![
LatticeMorpheme::new("彼", "名詞,普通名詞,*,*,彼,かれ,*"),
LatticeMorpheme::new("が", "助詞,格助詞,*,*,が,が,*"),
LatticeMorpheme::new("読んで", "動詞,*,子音動詞マ行,タ系連用テ形,読む,よんで,*"),
LatticeMorpheme::new("いる", "接尾辞,動詞性接尾辞,母音動詞,基本形,いる,いる,*"),
LatticeMorpheme::new("本", "名詞,普通名詞,*,*,本,ほん,*"),
LatticeMorpheme::new("を", "助詞,格助詞,*,*,を,を,*"),
LatticeMorpheme::new("買う", "動詞,*,子音動詞ワ行,基本形,買う,かう,*"),
LatticeMorpheme::new("。", "特殊,句点,*,*,。,。,*"),
];
let bunsetsu = model.analyze(&sentence).unwrap();
let ranges: Vec<_> = bunsetsu.iter().map(|one| one.morphemes.clone()).collect();
assert_eq!(ranges, [0..2, 2..4, 4..6, 6..8]);
let positions: Vec<_> = bunsetsu.iter().map(|one| one.positions).collect();
assert_eq!(
positions,
[Some((0, 1)), Some((0, 1)), Some((0, 1)), Some((0, 0))]
);
let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
assert_eq!(heads, [Some(2), Some(2), Some(3), None]);
let score = bunsetsu[1].score.unwrap();
assert!((score - 3.0).abs() < 1e-6, "{score}");
}
#[test]
fn a_model_for_unidic_is_converted_with_two_levels_for_the_parser() {
let chunker = "version: 100\ncost-factor: 1\nmaxid: 8\nxsize: 2\n\nB\nI\n\nU00:%x[0,0]\nU01:%x[-1,1]/%x[0,1]\nB\n\n0 B\n4 U01:名詞-固有名詞-人名-名/名詞-普通名詞-一般\n6 U01:助詞-格助詞/動詞-一般\n\n-1\n1\n-1\n1\n5\n-5\n5\n-5\n";
let parser = "degree: 2\nbias: 0.000000\ncharset: UTF8\nposset: UNIDIC\n\n0 SFF:名\n1 DIST:1\n\n1 0\n-0.25 1\n";
let converted = convert(chunker, parser, &svm::tests::unpruned()).unwrap();
assert_eq!(converted.part_of_speech_set, PartOfSpeechSet::Unidic);
let unidic = schema(PartOfSpeechSet::Unidic);
assert_eq!(unidic.part_of_speech, 0..4);
assert_eq!(unidic.conjugation_form, Some(3));
assert_eq!(unidic.head_rule, HeadRule::FunctionWordsApart);
assert_eq!(converted.parser.schema(), &unidic);
let two = FeatureSet::cabocha().with_part_of_speech_levels(2).unwrap();
assert_eq!(converted.parser.feature_set(), &two);
assert_eq!(PartOfSpeechSet::Unidic.feature_set(), two);
for set in [PartOfSpeechSet::Ipa, PartOfSpeechSet::Juman] {
assert_eq!(set.feature_set(), FeatureSet::cabocha());
}
let model = Model::new(converted.to_bytes().unwrap()).unwrap();
assert_eq!(model.dictionary(), "unidic");
assert_eq!(model.schema(), &unidic);
assert_eq!(model.parser().unwrap().feature_set(), &two);
let sentence = vec![
LatticeMorpheme::new("太郎", "名詞,固有名詞,人名,名,*,*,タロウ,タロウ"),
LatticeMorpheme::new("本", "名詞,普通名詞,一般,*,*,*,ホン,本"),
LatticeMorpheme::new("を", "助詞,格助詞,*,*,*,*,ヲ,を"),
LatticeMorpheme::new("読む", "動詞,一般,*,*,五段-マ行,終止形-一般,ヨム,読む"),
LatticeMorpheme::new("。", "補助記号,句点,*,*,*,*,,。"),
];
let bunsetsu = model.analyze(&sentence).unwrap();
let ranges: Vec<_> = bunsetsu.iter().map(|one| one.morphemes.clone()).collect();
assert_eq!(ranges, [0..1, 1..3, 3..5]);
let positions: Vec<_> = bunsetsu.iter().map(|one| one.positions).collect();
assert_eq!(positions, [Some((0, 0)), Some((0, 1)), Some((0, 0))]);
let heads: Vec<Option<usize>> = bunsetsu.iter().map(|one| one.head).collect();
assert_eq!(heads, [Some(1), Some(2), None]);
let score = bunsetsu[0].score.unwrap();
assert!((score - 3.0).abs() < 1e-6, "{score}");
}
#[test]
fn a_converted_model_is_for_a_dictionary_of_its_set() {
let chunker = crfpp::tests::MODEL;
let parser = svm::tests::MODEL;
let options = svm::tests::unpruned();
assert_eq!(PartOfSpeechSet::Ipa.dictionaries(), ["ipadic"]);
assert_eq!(PartOfSpeechSet::Juman.dictionaries(), ["jumandic"]);
assert_eq!(
PartOfSpeechSet::Unidic.dictionaries(),
["unidic", "unidic-cwj", "unidic-csj"]
);
let unidic = convert(
chunker,
&parser.replace("posset: IPA", "posset: UNIDIC"),
&options,
)
.unwrap();
for dictionary in ["unidic", "unidic-cwj", "unidic-csj"] {
let model = Model::new(unidic.to_bytes_for(dictionary).unwrap()).unwrap();
assert_eq!(model.dictionary(), dictionary);
}
assert_eq!(
unidic.to_bytes_for("ipadic").unwrap_err().to_string(),
"the model is not one for the dictionary ipadic: its part-of-speech set is that of unidic, unidic-cwj, unidic-csj"
);
let ipa = convert(chunker, parser, &options).unwrap();
assert_eq!(ipa.to_bytes_for("ipadic").unwrap(), ipa.to_bytes().unwrap());
assert_eq!(
ipa.to_bytes_for("unidic").unwrap_err().to_string(),
"the model is not one for the dictionary unidic: its part-of-speech set is that of ipadic"
);
}
#[test]
fn refuses_what_is_not_a_model_it_converts() {
let chunker = crfpp::tests::MODEL;
let parser = svm::tests::MODEL;
let message = |chunker: &str, parser: &str, options: &Options| {
convert(chunker, parser, options).unwrap_err().to_string()
};
let options = Options::default();
for (parser, expected) in [
(
parser.replace("posset: IPA", "posset: PENN"),
"the part-of-speech set \"PENN\", which is not one of CaboCha",
),
(parser.replace("posset: IPA\n", ""), "has no `posset`"),
(
parser.replace("degree: 2", "degree: 3"),
"has `degree: 3`, and only 2 is supported",
),
(parser.replace("degree: 2\n", ""), "has no `degree`"),
(
parser.replace("charset: UTF8", "charset: EUC-JP"),
"has `charset: EUC-JP`, and only UTF8 or UTF-8 is supported",
),
(
parser.replace("type: dep", "type: chunk"),
"has `type: chunk`",
),
(
parser.replace("bias: 0.000000", "bias: 0.500000"),
"has no `bias: 0`",
),
(parser.replace("bias: 0.000000\n", ""), "has no `bias: 0`"),
] {
let message = message(chunker, &parser, &options);
assert!(message.contains(expected), "{expected}: {message}");
}
assert!(message(parser, chunker, &options).starts_with("the parser model "));
assert!(message(chunker, chunker, &options).starts_with("the parser model "));
assert!(message(parser, parser, &options).starts_with("the chunker model "));
let three = chunker.replace("xsize: 2", "xsize: 3");
assert!(message(&three, parser, &options).contains("has 3 columns"));
for sigma in [-0.1, f64::NAN, f64::INFINITY] {
let options = Options { sigma, ..options };
assert!(message(chunker, parser, &options).starts_with("sigma is "));
}
}
#[test]
fn the_defaults_are_those_of_cabocha_model_index() {
assert_eq!(
Options::default(),
Options {
sigma: 0.0001,
min_support: 2,
frequent_features: 3000
}
);
assert_eq!(PartOfSpeechSet::Ipa.dictionary(), "ipadic");
assert_eq!(PartOfSpeechSet::Juman.dictionary(), "jumandic");
assert_eq!(PartOfSpeechSet::Unidic.dictionary(), "unidic");
}
}