1pub(crate) mod table;
97
98use std::fmt;
99use std::ops::Range;
100
101use crate::bytes::{Reader, push_string, push_u32};
102use crate::chunker::model::WEIGHTS_WIDTH;
103use crate::chunker::{Chunker, ChunkerData, ChunkerModel, Column, Template};
104use crate::error::{Error, Result};
105use crate::morpheme::Morpheme;
106use crate::parser::model::ParserLayout;
107use crate::parser::{Parser, ParserModel, ParserPart, Quantization};
108use crate::schema::Schema;
109use crate::sentence::Bunsetsu;
110use table::{Layout, Table};
111
112const MAGIC: &[u8; 8] = b"LDMODEL\0";
114
115pub(crate) const VERSION: u32 = 4;
117
118const OLDEST_VERSION: u32 = 3;
121
122const KIND_CHUNKER: u32 = 1;
124
125const KIND_PARSER: u32 = 2;
127
128const WHAT: &str = "model";
130
131#[derive(Clone)]
138pub struct Model<B> {
139 bytes: B,
141 dictionary: String,
143 schema: Schema,
145 chunker: Option<ChunkerLayout>,
147 parser: Option<ParserLayout>,
149 parts: Vec<(u32, Range<usize>)>,
151}
152
153#[derive(Debug, Clone, PartialEq)]
156struct ChunkerLayout {
157 columns: Vec<Column>,
159 template: Template,
161 transitions: [[f64; 3]; 3],
163 features: Layout,
165}
166
167impl<B: AsRef<[u8]>> Model<B> {
168 pub fn new(bytes: B) -> Result<Self> {
186 let all = bytes.as_ref();
187 let mut reader = Reader::new(all, WHAT, Error::Model);
188 if reader.take(MAGIC.len())? != MAGIC {
189 return Err(Error::Model(
190 "not a model file: the magic number is missing".to_string(),
191 ));
192 }
193 let version = reader.u32()?;
194 if !(OLDEST_VERSION..=VERSION).contains(&version) {
195 return Err(Error::Model(format!(
196 "the model has the version {version}, and this crate reads {OLDEST_VERSION} to {VERSION}"
197 )));
198 }
199 let dictionary = reader.string()?;
200 if dictionary.is_empty() {
201 return Err(reader.error("has no name of a dictionary"));
202 }
203 let schema = Schema::read(&mut reader, version)?;
204
205 let count = reader.u32()?;
206 let mut parts: Vec<(u32, Range<usize>)> = Vec::new();
207 for _ in 0..count {
208 let kind = reader.u32()?;
209 let offset = reader.u64()?;
210 let length = reader.u64()?;
211 let range = usize::try_from(offset)
212 .ok()
213 .zip(usize::try_from(length).ok())
214 .and_then(|(offset, length)| Some(offset..offset.checked_add(length)?))
215 .ok_or_else(|| reader.error("has a part past its end"))?;
216 if parts.iter().any(|(other, _)| *other == kind) {
217 return Err(reader.error(format_args!("has the part of kind {kind} twice")));
218 }
219 parts.push((kind, range));
220 }
221 let mut position = reader.position();
225 for (_, range) in &parts {
226 if range.start != position {
227 return Err(reader.error("has parts that are not one after the other"));
228 }
229 position = range.end;
230 }
231 if position > all.len() {
232 return Err(reader.error(format_args!(
233 "ends early: {position} bytes expected, {} given",
234 all.len()
235 )));
236 }
237 if position < all.len() {
238 return Err(reader.error(format_args!(
239 "has {} bytes after its end",
240 all.len() - position
241 )));
242 }
243
244 let mut chunker = None;
245 let mut parser = None;
246 for (kind, range) in &parts {
247 match *kind {
248 KIND_CHUNKER => {
249 chunker = Some(ChunkerLayout::read(&all[range.clone()], range.start)?)
250 }
251 KIND_PARSER => parser = Some(ParserLayout::read(&all[range.clone()], range.start)?),
252 _ => {
253 return Err(Error::Model(format!(
254 "the model has a part of the unknown kind {kind}"
255 )));
256 }
257 }
258 }
259
260 Ok(Self {
261 bytes,
262 dictionary,
263 schema,
264 chunker,
265 parser,
266 parts,
267 })
268 }
269
270 pub fn dictionary(&self) -> &str {
276 &self.dictionary
277 }
278
279 pub fn check_dictionary(&self, name: &str) -> Result<()> {
300 if name == self.dictionary {
301 Ok(())
302 } else {
303 Err(Error::Dictionary(format!(
304 "the model is for the dictionary {:?}, and the morphemes are of {name:?}",
305 self.dictionary
306 )))
307 }
308 }
309
310 pub fn schema(&self) -> &Schema {
316 &self.schema
317 }
318
319 pub fn chunker(&self) -> Option<Chunker<ChunkerPart<'_>>> {
326 let layout = self.chunker.as_ref()?;
327 Some(Chunker::new(ChunkerPart {
328 schema: &self.schema,
329 layout,
330 features: layout.features.table(self.bytes.as_ref()),
331 }))
332 }
333
334 pub fn parser(&self) -> Option<Parser<ParserPart<'_>>> {
341 let layout = self.parser.as_ref()?;
342 Some(Parser::new(
343 self.schema.clone(),
344 layout.feature_set().clone(),
345 layout.part(self.bytes.as_ref()),
346 ))
347 }
348
349 pub fn analyze<M: Morpheme>(&self, morphemes: &[M]) -> Result<Vec<Bunsetsu>> {
367 let chunker = self
368 .chunker()
369 .ok_or_else(|| Error::Model("the model has no chunker".to_string()))?;
370 let parser = self
371 .parser()
372 .ok_or_else(|| Error::Model("the model has no parser".to_string()))?;
373 parser.parse(morphemes, &chunker.chunk(morphemes)?)
374 }
375
376 pub fn as_bytes(&self) -> &[u8] {
382 self.bytes.as_ref()
383 }
384}
385
386impl<B: AsRef<[u8]>> fmt::Debug for Model<B> {
387 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 f.debug_struct("Model")
390 .field("dictionary", &self.dictionary)
391 .field("bytes", &self.bytes.as_ref().len())
392 .field("chunker", &self.chunker.is_some())
393 .field("parser", &self.parser.is_some())
394 .finish()
395 }
396}
397
398impl ChunkerLayout {
399 fn read(part: &[u8], base: usize) -> Result<Self> {
414 let mut reader = Reader::new(part, WHAT, Error::Model);
415 let count = reader.u32()? as usize;
416 let mut columns = Vec::new();
417 for &code in reader.take(count)? {
418 columns.push(
419 Column::from_code(code)
420 .ok_or_else(|| reader.error(format_args!("has the unknown column {code}")))?,
421 );
422 }
423
424 let template = Template::parse(&reader.string()?).map_err(|error| {
425 reader.error(format_args!("has a template that is not one: {error}"))
426 })?;
427 if template.columns() > columns.len() {
428 return Err(reader.error(format_args!(
429 "has a template that reads {} columns, and {} are given",
430 template.columns(),
431 columns.len()
432 )));
433 }
434
435 let mut transitions = [[0.0; 3]; 3];
436 for weight in transitions.iter_mut().flatten() {
437 *weight = reader.f64()?;
438 }
439
440 let features = Layout::read(&mut reader, WEIGHTS_WIDTH)?;
441 if reader.remaining() != 0 {
442 return Err(reader.error(format_args!(
443 "has {} bytes after its chunker",
444 reader.remaining()
445 )));
446 }
447
448 let table = features.table(part);
449 let finite = transitions
450 .iter()
451 .flatten()
452 .all(|weight| weight.is_finite())
453 && (0..table.len()).all(|index| {
454 weights(table.value(index))
455 .is_some_and(|weights| weights.iter().all(|weight| weight.is_finite()))
456 });
457 if !finite {
458 return Err(reader.error("has a weight that is not finite"));
459 }
460 Ok(Self {
461 columns,
462 template,
463 transitions,
464 features: features.shifted(base),
465 })
466 }
467}
468
469fn weights(value: &[u8]) -> Option<[f64; 2]> {
480 let begin = value.get(..8)?.try_into().ok()?;
481 let inside = value.get(8..16)?.try_into().ok()?;
482 Some([f64::from_le_bytes(begin), f64::from_le_bytes(inside)])
483}
484
485#[derive(Debug, Clone, Copy)]
489pub struct ChunkerPart<'a> {
490 schema: &'a Schema,
492 layout: &'a ChunkerLayout,
494 features: Table<'a>,
496}
497
498impl ChunkerPart<'_> {
499 pub fn feature_count(&self) -> usize {
505 self.features.len()
506 }
507
508 pub fn weight_count(&self) -> usize {
515 let of_features: usize = (0..self.features.len())
516 .filter_map(|index| weights(self.features.value(index)))
517 .map(|weights| weights.iter().filter(|weight| **weight != 0.0).count())
518 .sum();
519 let of_transitions = self
520 .layout
521 .transitions
522 .iter()
523 .flatten()
524 .filter(|weight| **weight != 0.0)
525 .count();
526 of_features + of_transitions
527 }
528}
529
530impl ChunkerData for ChunkerPart<'_> {
531 fn schema(&self) -> &Schema {
532 self.schema
533 }
534
535 fn columns(&self) -> &[Column] {
536 &self.layout.columns
537 }
538
539 fn template(&self) -> &Template {
540 &self.layout.template
541 }
542
543 fn transition(&self, from: usize, to: usize) -> f64 {
544 self.layout
545 .transitions
546 .get(from)
547 .and_then(|row| row.get(to))
548 .copied()
549 .unwrap_or(0.0)
550 }
551
552 fn feature(&self, feature: &str) -> Option<[f64; 2]> {
553 weights(self.features.value(self.features.find(feature)?))
554 }
555}
556
557#[derive(Debug, Clone, PartialEq)]
561pub struct ModelBuilder {
562 dictionary: String,
564 schema: Schema,
566 chunker: Option<Vec<u8>>,
568 parser: Option<Vec<u8>>,
570}
571
572impl ModelBuilder {
573 pub fn new(dictionary: &str, schema: Schema) -> Result<Self> {
586 if dictionary.is_empty() {
587 return Err(Error::Model(
588 "a model needs the name of its dictionary".to_string(),
589 ));
590 }
591 Ok(Self {
592 dictionary: dictionary.to_string(),
593 schema,
594 chunker: None,
595 parser: None,
596 })
597 }
598
599 pub fn from_model<B: AsRef<[u8]>>(model: &Model<B>) -> Self {
610 let part = |kind: u32| {
611 model
612 .parts
613 .iter()
614 .find(|(other, _)| *other == kind)
615 .and_then(|(_, range)| model.bytes.as_ref().get(range.clone()))
616 .map(<[u8]>::to_vec)
617 };
618 Self {
619 dictionary: model.dictionary.clone(),
620 schema: model.schema.clone(),
621 chunker: part(KIND_CHUNKER),
622 parser: part(KIND_PARSER),
623 }
624 }
625
626 pub fn chunker(mut self, model: &ChunkerModel) -> Result<Self> {
637 if model.schema() != &self.schema {
638 return Err(Error::Model(
639 "the chunker has another schema than the model".to_string(),
640 ));
641 }
642 let mut part = Vec::new();
643 model.write_part(&mut part);
644 self.chunker = Some(part);
645 Ok(self)
646 }
647
648 pub fn parser(mut self, model: &ParserModel, quantization: Quantization) -> Result<Self> {
660 if model.schema() != &self.schema {
661 return Err(Error::Model(
662 "the parser has another schema than the model".to_string(),
663 ));
664 }
665 let mut part = Vec::new();
666 model.write_part(&mut part, quantization);
667 self.parser = Some(part);
668 Ok(self)
669 }
670
671 pub fn to_bytes(&self) -> Vec<u8> {
679 let mut bytes = Vec::new();
680 bytes.extend_from_slice(MAGIC);
681 push_u32(&mut bytes, VERSION);
682 push_string(&mut bytes, &self.dictionary);
683 self.schema.write(&mut bytes);
684
685 let parts: Vec<(u32, &[u8])> = [(KIND_CHUNKER, &self.chunker), (KIND_PARSER, &self.parser)]
686 .into_iter()
687 .filter_map(|(kind, part)| Some((kind, part.as_deref()?)))
688 .collect();
689 push_u32(&mut bytes, parts.len() as u32);
690 let mut offset = bytes.len() + parts.len() * 20;
692 for (kind, part) in &parts {
693 push_u32(&mut bytes, *kind);
694 bytes.extend_from_slice(&(offset as u64).to_le_bytes());
695 bytes.extend_from_slice(&(part.len() as u64).to_le_bytes());
696 offset += part.len();
697 }
698 for (_, part) in &parts {
699 bytes.extend_from_slice(part);
700 }
701 bytes
702 }
703}
704
705#[cfg(test)]
706#[allow(clippy::single_range_in_vec_init)]
709mod tests {
710 use super::*;
711 use crate::chunker::model::tests::model as chunker_model;
712 use crate::lattice::LatticeMorpheme;
713 use crate::schema::{HeadFallback, HeadRule, Normalization, Pattern, SentenceSplit};
714
715 fn chunker() -> ChunkerModel {
718 chunker_model(
719 &[
720 ("U12:助詞-係助詞", [0.0, 1.0]),
721 ("U12:助詞-格助詞-一般", [0.0, 1.5]),
722 ("U02:は", [-0.25, 0.125]),
723 ],
724 [[0.0, 0.25, 0.0], [0.0, -0.5, 0.0625], [0.0, 0.125, 0.0]],
725 )
726 }
727
728 fn bytes() -> Vec<u8> {
730 ModelBuilder::new("ipadic", Schema::ipadic())
731 .unwrap()
732 .chunker(&chunker())
733 .unwrap()
734 .to_bytes()
735 }
736
737 fn error(bytes: &[u8]) -> String {
739 let error = Model::new(bytes).unwrap_err();
740 assert!(matches!(error, Error::Model(_)), "{error:?}");
741 error.to_string()
742 }
743
744 fn list() -> usize {
747 let mut schema = Vec::new();
748 Schema::ipadic().write(&mut schema);
749 8 + 4 + 4 + "ipadic".len() + schema.len()
750 }
751
752 fn morphemes() -> Vec<LatticeMorpheme> {
754 vec![
755 LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
756 LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
757 LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
758 LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
759 LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
760 ]
761 }
762
763 #[test]
764 fn a_file_gives_back_what_was_written() {
765 let schema = Schema {
766 part_of_speech: 1..3,
767 conjugation_type: None,
768 conjugation_form: Some(7),
769 base_form: None,
770 function_words: vec![Pattern::new(&["助詞"])],
773 not_heads: vec![Pattern::new(&["名詞", "非自立"]).after(Pattern::default())],
774 particles: vec![Pattern::new(&["助詞", "格助詞"])],
775 lexicalized: vec![Pattern::new(&["副詞"]), Pattern::new(&["連体詞"])],
776 symbols: Schema::ipadic().symbols,
777 normalization: Normalization::new(&[("ガ", "ガ"), ("1", "1")]).unwrap(),
778 head_rule: HeadRule::LastWords,
779 head_fallback: HeadFallback::FirstWord,
780 sentence_split: SentenceSplit::AfterEnds,
781 };
782 let transitions = [
783 [0.0, 0.25, -3.0],
784 [1e-300, -0.5, 1.0],
785 [0.75, f64::MAX, -0.0],
786 ];
787 let features = [
788 ("U00:彼", [-1.5, 2.0]),
789 ("U01:_B-1/連用形", [0.1, -0.2]),
790 ("U00:", [0.0, 3.0]),
791 ];
792 let original = ChunkerModel::new(
793 schema.clone(),
794 vec![
795 Column::Surface,
796 Column::PartOfSpeech,
797 Column::ConjugationForm,
798 ],
799 Template::parse("U00:%x[0,0]\nU01:%x[-1,1]/%x[0,2]\nB\n").unwrap(),
800 transitions,
801 features
802 .iter()
803 .map(|(feature, weights)| (feature.to_string(), *weights))
804 .collect(),
805 )
806 .unwrap();
807 let builder = ModelBuilder::new("a dictionary", schema.clone())
808 .unwrap()
809 .chunker(&original)
810 .unwrap();
811 let bytes = builder.to_bytes();
812 assert_eq!(&bytes[..8], b"LDMODEL\0");
813 assert_eq!(bytes[8..12], [4, 0, 0, 0]);
814 assert_eq!(builder.to_bytes(), bytes);
817 assert_eq!(
818 ModelBuilder::new("a dictionary", schema.clone())
819 .unwrap()
820 .chunker(&original.clone())
821 .unwrap()
822 .to_bytes(),
823 bytes
824 );
825
826 let model = Model::new(bytes.as_slice()).unwrap();
827 assert_eq!(model.dictionary(), "a dictionary");
828 assert_eq!(model.schema(), &schema);
829 assert_eq!(model.as_bytes(), bytes);
830 let chunker = model.chunker().unwrap();
831 let part = chunker.model();
832 assert_eq!(part.schema(), &schema);
833 assert_eq!(part.columns(), original.columns());
834 assert_eq!(part.template(), original.template());
835 for from in 0..4 {
836 for to in 0..4 {
837 let (read, written) = (part.transition(from, to), original.transition(from, to));
838 assert_eq!(read.to_bits(), written.to_bits(), "{from} {to}");
839 }
840 }
841 for (feature, weights) in features {
842 assert_eq!(part.feature(feature), Some(weights), "{feature}");
843 }
844 for missing in ["U00", "U00:彼は", "U02:", ""] {
845 assert_eq!(part.feature(missing), None, "{missing:?}");
846 }
847 assert_eq!(part.feature_count(), 3);
848 assert_eq!(part.feature_count(), original.feature_count());
849 assert_eq!(part.weight_count(), original.weight_count());
850 }
851
852 #[test]
853 fn a_file_without_a_part_is_read() {
854 let bytes = ModelBuilder::new("ipadic", Schema::ipadic())
855 .unwrap()
856 .to_bytes();
857 assert_eq!(bytes.len(), list() + 4);
858 let model = Model::new(bytes).unwrap();
859 assert_eq!(model.dictionary(), "ipadic");
860 assert_eq!(model.schema(), &Schema::ipadic());
861 assert!(model.chunker().is_none());
862 }
863
864 #[test]
865 fn the_chunker_of_a_file_chunks_as_the_model_in_memory() {
866 let in_memory = Chunker::new(chunker());
867 let model = Model::new(bytes()).unwrap();
868 let on_bytes = model.chunker().unwrap();
869 let morphemes = morphemes();
870 assert_eq!(on_bytes.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
871 for range in [0..5, 0..1, 1..4, 1..2, 3..5, 0..0] {
872 let part = &morphemes[range.clone()];
873 assert_eq!(
874 on_bytes.labels(&on_bytes.features(part)),
875 in_memory.labels(&in_memory.features(part)),
876 "{range:?}"
877 );
878 assert_eq!(
879 on_bytes.chunk(part).unwrap(),
880 in_memory.chunk(part).unwrap()
881 );
882 }
883 }
884
885 #[test]
886 fn the_bytes_are_read_at_any_address() {
887 let bytes = bytes();
888 let morphemes = morphemes();
889 for shift in 0..8 {
892 let mut buffer = vec![0xa5; shift];
893 buffer.extend_from_slice(&bytes);
894 let model = Model::new(&buffer[shift..]).unwrap();
895 let chunker = model.chunker().unwrap();
896 assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
897 assert_eq!(chunker.model().feature("U02:は"), Some([-0.25, 0.125]));
898 assert_eq!(chunker.model().transition(1, 2), 0.0625);
899 }
900 }
901
902 #[test]
903 fn a_model_holds_its_bytes_or_borrows_them() {
904 fn assert_send_sync<T: Send + Sync>() {}
905 assert_send_sync::<Model<Vec<u8>>>();
906 assert_send_sync::<Model<&'static [u8]>>();
907
908 fn owned() -> Model<Vec<u8>> {
910 Model::new(bytes()).unwrap()
911 }
912 let model = owned();
913 let morphemes = morphemes();
914 std::thread::scope(|scope| {
915 for _ in 0..2 {
916 scope.spawn(|| {
917 let chunker = model.chunker().unwrap();
918 assert_eq!(chunker.chunk(&morphemes).unwrap(), [0..2, 2..4, 4..5]);
919 });
920 }
921 });
922
923 assert_eq!(
925 format!("{model:?}"),
926 format!(
927 "Model {{ dictionary: \"ipadic\", bytes: {}, chunker: true, parser: false }}",
928 model.as_bytes().len()
929 )
930 );
931 }
932
933 #[test]
934 fn the_name_of_the_dictionary_is_checked() {
935 let model = Model::new(bytes()).unwrap();
936 assert!(model.check_dictionary("ipadic").is_ok());
937 for other in ["unidic", "IPADIC", "ipadic-neologd", ""] {
938 let error = model.check_dictionary(other).unwrap_err();
939 assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
940 assert_eq!(
941 error.to_string(),
942 format!(
943 "the model is for the dictionary \"ipadic\", and the morphemes are of {other:?}"
944 )
945 );
946 }
947 }
948
949 #[test]
950 fn the_builder_refuses_no_name_and_another_schema() {
951 assert_eq!(
952 ModelBuilder::new("", Schema::ipadic())
953 .unwrap_err()
954 .to_string(),
955 "a model needs the name of its dictionary"
956 );
957 let mut other = Schema::ipadic();
958 other.base_form = None;
959 let error = ModelBuilder::new("other", other)
960 .unwrap()
961 .chunker(&chunker())
962 .unwrap_err();
963 assert!(matches!(error, Error::Model(_)), "{error:?}");
964 assert_eq!(
965 error.to_string(),
966 "the chunker has another schema than the model"
967 );
968 }
969
970 #[test]
971 fn refuses_bytes_that_are_not_a_model_file() {
972 let bytes = bytes();
973
974 let mut other = bytes.clone();
975 other[0] = b'X';
976 assert_eq!(
977 error(&other),
978 "not a model file: the magic number is missing"
979 );
980 assert_eq!(
982 error(b"LDCHUNK\0\x03\0\0\0"),
983 "not a model file: the magic number is missing"
984 );
985 for version in [0, 1, 2, 5] {
986 let mut other = bytes.clone();
987 other[8] = version;
988 assert_eq!(
989 error(&other),
990 format!("the model has the version {version}, and this crate reads 3 to 4")
991 );
992 }
993
994 for length in 0..bytes.len() {
996 let message = error(&bytes[..length]);
997 assert!(
998 message.starts_with("the model ends early"),
999 "{length}: {message}"
1000 );
1001 }
1002 let mut other = bytes.clone();
1003 other.push(0);
1004 assert_eq!(error(&other), "the model has 1 bytes after its end");
1005
1006 let mut other = bytes.clone();
1008 other[12] = 0;
1009 other.drain(16..22);
1010 assert_eq!(error(&other), "the model has no name of a dictionary");
1011 }
1012
1013 #[test]
1014 fn refuses_a_list_of_parts_that_is_not_one() {
1015 let bytes = bytes();
1016 let list = list();
1017 assert_eq!(bytes[list..list + 8], [1, 0, 0, 0, 1, 0, 0, 0]);
1019 let offset = list + 4 + 20;
1020 assert_eq!(bytes[list + 8..list + 16], (offset as u64).to_le_bytes());
1021 let length = (bytes.len() - offset) as u64;
1022 assert_eq!(bytes[list + 16..list + 24], length.to_le_bytes());
1023
1024 let mut other = bytes.clone();
1025 other[list + 4] = 3;
1026 assert_eq!(error(&other), "the model has a part of the unknown kind 3");
1027
1028 for start in [offset + 1, offset - 1] {
1030 let mut other = bytes.clone();
1031 other[list + 8..list + 16].copy_from_slice(&(start as u64).to_le_bytes());
1032 assert_eq!(
1033 error(&other),
1034 "the model has parts that are not one after the other"
1035 );
1036 }
1037
1038 let mut other = bytes.clone();
1040 other[list + 16..list + 24].copy_from_slice(&u64::MAX.to_le_bytes());
1041 assert_eq!(error(&other), "the model has a part past its end");
1042
1043 let mut other = bytes.clone();
1046 other[list + 16..list + 24].copy_from_slice(&(length + 1).to_le_bytes());
1047 assert_eq!(
1048 error(&other),
1049 format!(
1050 "the model ends early: {} bytes expected, {} given",
1051 bytes.len() + 1,
1052 bytes.len()
1053 )
1054 );
1055 let mut other = bytes.clone();
1056 other[list + 16..list + 24].copy_from_slice(&(length - 1).to_le_bytes());
1057 assert_eq!(error(&other), "the model has 1 bytes after its end");
1058
1059 let mut other = bytes[..list].to_vec();
1061 push_u32(&mut other, 2);
1062 for (start, length) in [(offset + 20, length), (offset + 20 + length as usize, 0)] {
1063 push_u32(&mut other, KIND_CHUNKER);
1064 other.extend_from_slice(&(start as u64).to_le_bytes());
1065 other.extend_from_slice(&length.to_le_bytes());
1066 }
1067 other.extend_from_slice(&bytes[offset..]);
1068 assert_eq!(error(&other), "the model has the part of kind 1 twice");
1069 }
1070
1071 fn part() -> Vec<u8> {
1073 let mut part = Vec::new();
1074 chunker().write_part(&mut part);
1075 part
1076 }
1077
1078 fn part_error(part: &[u8]) -> String {
1080 let error = ChunkerLayout::read(part, 0).unwrap_err();
1081 assert!(matches!(error, Error::Model(_)), "{error:?}");
1082 error.to_string()
1083 }
1084
1085 #[test]
1086 fn refuses_a_chunker_part_that_is_not_one() {
1087 let part = part();
1088 assert!(ChunkerLayout::read(&part, 0).is_ok());
1089 assert_eq!(part[..6], [2, 0, 0, 0, 0, 1]);
1091
1092 let mut other = part.clone();
1093 other[5] = 9;
1094 assert_eq!(part_error(&other), "the model has the unknown column 9");
1095
1096 let mut other = part.clone();
1098 other[0] = 1;
1099 other.remove(5);
1100 assert_eq!(
1101 part_error(&other),
1102 "the model has a template that reads 2 columns, and 1 are given"
1103 );
1104
1105 assert_eq!(&part[10..14], b"U00:");
1108 let mut other = part.clone();
1109 other[10] = b'X';
1110 let message = part_error(&other);
1111 assert!(
1112 message.starts_with("the model has a template that is not one: "),
1113 "{message}"
1114 );
1115
1116 let mut other = part.clone();
1121 let last = other.len() - 8 * 4 - 8;
1122 assert_eq!(other[last..last + 8], 1.5f64.to_le_bytes());
1123 other[last..last + 8].copy_from_slice(&f64::NAN.to_le_bytes());
1124 assert_eq!(
1125 part_error(&other),
1126 "the model has a weight that is not finite"
1127 );
1128 let template = u32::from_le_bytes(part[6..10].try_into().unwrap()) as usize;
1129 let transitions = 10 + template;
1130 assert_eq!(
1131 part[transitions + 8..transitions + 16],
1132 0.25f64.to_le_bytes()
1133 );
1134 let mut other = part.clone();
1135 other[transitions + 8..transitions + 16].copy_from_slice(&f64::INFINITY.to_le_bytes());
1136 assert_eq!(
1137 part_error(&other),
1138 "the model has a weight that is not finite"
1139 );
1140
1141 let table = transitions + 72;
1143 assert_eq!(
1144 part[table..table + 12],
1145 [3, 0, 0, 0, 16, 0, 0, 0, 8, 0, 0, 0]
1146 );
1147 let mut other = part.clone();
1148 other[table + 4] = 8;
1149 assert_eq!(
1150 part_error(&other),
1151 "the model has a table with values of 8 bytes, and 16 are expected"
1152 );
1153
1154 let mut other = part.clone();
1155 other.push(0);
1156 assert_eq!(
1157 part_error(&other),
1158 "the model has 1 bytes after its chunker"
1159 );
1160 for length in 0..part.len() {
1161 let message = part_error(&part[..length]);
1162 assert!(
1163 message.starts_with("the model ends early"),
1164 "{length}: {message}"
1165 );
1166 }
1167 }
1168
1169 #[test]
1170 fn no_changed_byte_makes_reading_or_chunking_panic() {
1171 let bytes = bytes();
1172 let morphemes = morphemes();
1173 let mut read = 0;
1174 for position in 0..bytes.len() {
1175 for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1176 if value == bytes[position] {
1177 continue;
1178 }
1179 let mut other = bytes.clone();
1180 other[position] = value;
1181 if let Ok(model) = Model::new(other) {
1184 read += 1;
1185 if let Some(chunker) = model.chunker() {
1186 let _ = chunker.chunk(&morphemes);
1187 let _ = chunker.model().weight_count();
1188 }
1189 }
1190 }
1191 }
1192 assert!(read > 0);
1194 }
1195}
1196
1197#[cfg(test)]
1199#[allow(clippy::single_range_in_vec_init)]
1202mod parser_tests {
1203 use super::*;
1204 use crate::chunker::model::tests::model as chunker_model;
1205 use crate::lattice::LatticeMorpheme;
1206 use crate::parser::{Classifier, FeatureSet, PairWeights};
1207
1208 fn chunker() -> ChunkerModel {
1211 chunker_model(
1212 &[
1213 ("U12:助詞-係助詞", [0.0, 1.0]),
1214 ("U12:助詞-格助詞-一般", [0.0, 1.0]),
1215 ],
1216 [[0.0; 3]; 3],
1217 )
1218 }
1219
1220 fn parser() -> ParserModel {
1223 ParserModel::new(
1224 Schema::ipadic(),
1225 FeatureSet::cabocha(),
1226 -1.0,
1227 vec![("DIST:1".to_string(), 0.0), ("SFS:を".to_string(), 0.0)],
1228 PairWeights::Exact(vec![((0, 1), 2.0)]),
1229 )
1230 .unwrap()
1231 }
1232
1233 fn bytes(quantization: Quantization) -> Vec<u8> {
1235 ModelBuilder::new("ipadic", Schema::ipadic())
1236 .unwrap()
1237 .chunker(&chunker())
1238 .unwrap()
1239 .parser(&parser(), quantization)
1240 .unwrap()
1241 .to_bytes()
1242 }
1243
1244 fn morphemes() -> Vec<LatticeMorpheme> {
1246 vec![
1247 LatticeMorpheme::new("彼", "名詞,代名詞,一般,*,*,*,彼,カレ,カレ"),
1248 LatticeMorpheme::new("は", "助詞,係助詞,*,*,*,*,は,ハ,ワ"),
1249 LatticeMorpheme::new("本", "名詞,一般,*,*,*,*,本,ホン,ホン"),
1250 LatticeMorpheme::new("を", "助詞,格助詞,一般,*,*,*,を,ヲ,ヲ"),
1251 LatticeMorpheme::new("読む", "動詞,自立,*,*,五段・マ行,基本形,読む,ヨム,ヨム"),
1252 LatticeMorpheme::new("人", "名詞,一般,*,*,*,*,人,ヒト,ヒト"),
1253 ]
1254 }
1255
1256 #[test]
1257 fn a_file_with_both_parts_analyzes_a_sentence() {
1258 for quantization in [Quantization::F32, Quantization::I16, Quantization::I8] {
1259 let bytes = bytes(quantization);
1260 let model = Model::new(bytes.as_slice()).unwrap();
1261 assert_eq!(
1262 format!("{model:?}"),
1263 format!(
1264 "Model {{ dictionary: \"ipadic\", bytes: {}, chunker: true, parser: true }}",
1265 bytes.len()
1266 )
1267 );
1268 let morphemes = morphemes();
1269 let analyzed = model.analyze(&morphemes).unwrap();
1270 let ranges: Vec<_> = analyzed.iter().map(|one| one.morphemes.clone()).collect();
1271 assert_eq!(ranges, [0..2, 2..4, 4..5, 5..6]);
1272 let heads: Vec<Option<usize>> = analyzed.iter().map(|one| one.head).collect();
1273 assert_eq!(heads, [Some(3), Some(2), Some(3), None]);
1275 assert_eq!(analyzed[1].score, Some(1.0));
1278 assert_eq!(analyzed[1].positions, Some((0, 1)));
1279
1280 let parser_of_file = model.parser().unwrap();
1282 assert_eq!(parser_of_file.feature_set(), &FeatureSet::cabocha());
1283 assert_eq!(parser_of_file.schema(), &Schema::ipadic());
1284 let chunks = model.chunker().unwrap().chunk(&morphemes).unwrap();
1285 assert_eq!(parser_of_file.parse(&morphemes, &chunks).unwrap(), analyzed);
1286 let in_memory = Parser::new(Schema::ipadic(), FeatureSet::cabocha(), parser());
1287 assert_eq!(in_memory.parse(&morphemes, &chunks).unwrap(), analyzed);
1288 assert_eq!(parser_of_file.classifier().id("SFS:を"), Some(1));
1289
1290 let none: [LatticeMorpheme; 0] = [];
1291 assert!(model.analyze(&none).unwrap().is_empty());
1292 }
1293 }
1294
1295 #[test]
1296 fn the_parts_are_listed_in_their_order() {
1297 let bytes = bytes(Quantization::F32);
1298 let mut schema = Vec::new();
1299 Schema::ipadic().write(&mut schema);
1300 let list = 8 + 4 + 4 + "ipadic".len() + schema.len();
1301 assert_eq!(bytes[list..list + 4], [2, 0, 0, 0]);
1302 let entry = |index: usize| {
1304 let start = list + 4 + 20 * index;
1305 let number = |from: usize| {
1306 u64::from_le_bytes(bytes[start + from..start + from + 8].try_into().unwrap())
1307 as usize
1308 };
1309 (bytes[start], number(4), number(12))
1310 };
1311 let (first, second) = (entry(0), entry(1));
1312 assert_eq!(first.0, 1);
1313 assert_eq!(second.0, 2);
1314 assert_eq!(first.1, list + 4 + 40);
1315 assert_eq!(second.1, first.1 + first.2);
1316 assert_eq!(second.1 + second.2, bytes.len());
1317 let other = ModelBuilder::new("ipadic", Schema::ipadic())
1319 .unwrap()
1320 .parser(&parser(), Quantization::F32)
1321 .unwrap()
1322 .chunker(&chunker())
1323 .unwrap()
1324 .to_bytes();
1325 assert_eq!(other, bytes);
1326 }
1327
1328 #[test]
1329 fn a_file_without_a_part_does_not_analyze() {
1330 let only_chunker = ModelBuilder::new("ipadic", Schema::ipadic())
1331 .unwrap()
1332 .chunker(&chunker())
1333 .unwrap()
1334 .to_bytes();
1335 let only_parser = ModelBuilder::new("ipadic", Schema::ipadic())
1336 .unwrap()
1337 .parser(&parser(), Quantization::I8)
1338 .unwrap()
1339 .to_bytes();
1340 let morphemes = morphemes();
1341 for (bytes, message) in [
1342 (only_chunker, "the model has no parser"),
1343 (only_parser, "the model has no chunker"),
1344 ] {
1345 let model = Model::new(bytes).unwrap();
1346 let error = model.analyze(&morphemes).unwrap_err();
1347 assert!(matches!(error, Error::Model(_)), "{error:?}");
1348 assert_eq!(error.to_string(), message);
1349 assert_eq!(model.parser().is_none(), message.ends_with("parser"));
1350 assert_eq!(model.chunker().is_none(), message.ends_with("chunker"));
1351 }
1352 let model = Model::new(bytes(Quantization::I8)).unwrap();
1354 let narrow = [LatticeMorpheme::new("彼", "名詞,代名詞")];
1355 let error = model.analyze(&narrow).unwrap_err();
1356 assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1357 let error = model.parser().unwrap().parse(&narrow, &[0..1]).unwrap_err();
1358 assert!(matches!(error, Error::Dictionary(_)), "{error:?}");
1359 }
1360
1361 #[test]
1362 fn a_file_is_started_from_another_one() {
1363 let only_chunker = ModelBuilder::new("ipadic", Schema::ipadic())
1364 .unwrap()
1365 .chunker(&chunker())
1366 .unwrap()
1367 .to_bytes();
1368 let model = Model::new(only_chunker.as_slice()).unwrap();
1369 let both = ModelBuilder::from_model(&model)
1371 .parser(&parser(), Quantization::I16)
1372 .unwrap()
1373 .to_bytes();
1374 assert_eq!(both, bytes(Quantization::I16));
1375 assert_eq!(ModelBuilder::from_model(&model).to_bytes(), only_chunker);
1377 let full = Model::new(both.as_slice()).unwrap();
1378 assert_eq!(ModelBuilder::from_model(&full).to_bytes(), both);
1379 let again = ModelBuilder::from_model(&full)
1381 .parser(&parser(), Quantization::I8)
1382 .unwrap()
1383 .to_bytes();
1384 assert_eq!(again, bytes(Quantization::I8));
1385 assert_ne!(again, both);
1386
1387 let mut schema = Schema::ipadic();
1389 schema.base_form = None;
1390 let other = ModelBuilder::new("other", schema.clone())
1391 .unwrap()
1392 .to_bytes();
1393 let other = Model::new(other).unwrap();
1394 let copy = Model::new(ModelBuilder::from_model(&other).to_bytes()).unwrap();
1395 assert_eq!(copy.dictionary(), "other");
1396 assert_eq!(copy.schema(), &schema);
1397 }
1398
1399 #[test]
1400 fn the_builder_refuses_a_parser_of_another_schema() {
1401 let mut other = Schema::ipadic();
1402 other.base_form = None;
1403 let error = ModelBuilder::new("other", other)
1404 .unwrap()
1405 .parser(&parser(), Quantization::F32)
1406 .unwrap_err();
1407 assert!(matches!(error, Error::Model(_)), "{error:?}");
1408 assert_eq!(
1409 error.to_string(),
1410 "the parser has another schema than the model"
1411 );
1412 }
1413
1414 #[test]
1415 fn a_parser_part_that_is_not_one_is_refused_with_the_file() {
1416 let bytes = bytes(Quantization::F32);
1417 let mut other = bytes.clone();
1419 let last = other.len() - 4;
1420 assert_eq!(other[last..], 2.0f32.to_le_bytes());
1421 other[last..].copy_from_slice(&f32::NAN.to_le_bytes());
1422 let error = Model::new(other).unwrap_err();
1423 assert!(matches!(error, Error::Model(_)), "{error:?}");
1424 assert_eq!(
1425 error.to_string(),
1426 "the model has a weight that is not finite"
1427 );
1428 for length in 0..bytes.len() {
1429 assert!(Model::new(&bytes[..length]).is_err(), "{length}");
1430 }
1431 }
1432
1433 #[test]
1434 fn no_changed_byte_makes_reading_or_analyzing_panic() {
1435 let bytes = bytes(Quantization::I8);
1436 let morphemes = morphemes();
1437 let mut read = 0;
1438 for position in 0..bytes.len() {
1439 for value in [0, 1, 0x7f, 0x80, 0xff, bytes[position] ^ 1] {
1440 if value == bytes[position] {
1441 continue;
1442 }
1443 let mut other = bytes.clone();
1444 other[position] = value;
1445 if let Ok(model) = Model::new(other) {
1446 read += 1;
1447 let _ = model.analyze(&morphemes);
1448 let _ = ModelBuilder::from_model(&model).to_bytes();
1449 }
1450 }
1451 }
1452 assert!(read > 0);
1453 }
1454
1455 #[test]
1458 fn a_file_of_version_3_is_read_and_takes_the_first_morpheme() {
1459 use crate::schema::{HeadFallback, SentenceSplit};
1460
1461 let directory = concat!(env!("CARGO_MANIFEST_DIR"), "/../resources/dependency");
1462 let old = std::fs::read(format!("{directory}/test_model_ipadic_v3.bin")).unwrap();
1463 let new = std::fs::read(format!("{directory}/test_model_ipadic.bin")).unwrap();
1464 assert_eq!(old[8..12], [3, 0, 0, 0]);
1465 assert_eq!(new[8..12], [VERSION as u8, 0, 0, 0]);
1466 assert_eq!(new.len(), old.len() + 2);
1468
1469 let old = Model::new(old).unwrap();
1470 let new = Model::new(new).unwrap();
1471 assert_eq!(old.dictionary(), "ipadic");
1472 assert_eq!(old.schema().head_fallback, HeadFallback::FirstMorpheme);
1473 assert_eq!(new.schema().head_fallback, HeadFallback::FirstWord);
1474 assert_eq!(old.schema().sentence_split, SentenceSplit::None);
1475 assert_eq!(new.schema().sentence_split, SentenceSplit::AfterEnds);
1476 assert_eq!(
1478 *old.schema(),
1479 Schema {
1480 head_fallback: HeadFallback::FirstMorpheme,
1481 sentence_split: SentenceSplit::None,
1482 ..new.schema().clone()
1483 }
1484 );
1485 let morphemes = morphemes();
1486 let chunks = old.chunker().unwrap().chunk(&morphemes).unwrap();
1487 assert_eq!(chunks, new.chunker().unwrap().chunk(&morphemes).unwrap());
1488 assert_eq!(
1489 old.parser().unwrap().parse(&morphemes, &chunks).unwrap(),
1490 new.parser().unwrap().parse(&morphemes, &chunks).unwrap()
1491 );
1492 }
1493}