use std::collections::HashMap;
use bitflags::bitflags;
use crate::types::*;
#[derive(Clone,Debug)]
pub struct VocabValue {
pub text: String,
pub norm: NormString,
pub frequency: u32,
pub tokencount: u8,
pub lexindex: u32,
pub variants: Option<Vec<VariantReference>>,
pub vocabtype: VocabType,
}
bitflags! {
pub struct VocabType: u8 {
const NONE = 0b00000000;
const INDEXED = 0b00000001;
const LM = 0b00000010;
const TRANSPARENT = 0b00000100;
}
}
impl VocabType {
pub fn check(&self, test: VocabType) -> bool {
*self & test == test
}
}
impl From<VocabType> for bool {
fn from(v: VocabType) -> bool {
v != VocabType::NONE
}
}
impl VocabValue {
pub fn new(text: String, vocabtype: VocabType) -> Self {
let tokencount = text.chars().filter(|c| *c == ' ').count() as u8;
VocabValue {
text: text,
norm: Vec::new(),
frequency: 1, tokencount,
lexindex: 0,
variants: None,
vocabtype,
}
}
pub fn in_lexicon(&self, index: u8) -> bool {
self.lexindex & (1 << index) == 1 << index
}
pub fn lexindex_as_vec(&self) -> Vec<u8> {
let mut v = Vec::new();
for i in 0..31 {
if self.in_lexicon(i) {
v.push(i);
}
}
v
}
}
pub type VocabDecoder = Vec<VocabValue>;
pub type VocabEncoder = HashMap<String, VocabId>;
#[derive(Clone,Copy,Debug,PartialEq,Eq)]
pub enum FrequencyHandling {
Sum,
Max,
Min,
Replace,
}
#[derive(Clone,Debug)]
pub struct VocabParams {
pub text_column: u8,
pub freq_column: Option<u8>,
pub freq_handling: FrequencyHandling,
pub vocab_type: VocabType,
pub index: u8,
}
impl Default for VocabParams {
fn default() -> Self {
Self {
text_column: 0,
freq_column: Some(1),
freq_handling: FrequencyHandling::Max,
vocab_type: VocabType::INDEXED,
index: 0,
}
}
}
impl VocabParams {
pub fn with_vocab_type(mut self, vocab_type: VocabType) -> Self {
self.vocab_type = vocab_type;
self
}
pub fn with_freq_handling(mut self, freq_handling: FrequencyHandling) -> Self {
self.freq_handling = freq_handling;
self
}
}
pub const BOS: VocabId = 0;
pub const EOS: VocabId = 1;
pub const UNK: VocabId = 2;
pub(crate) fn init_vocab(decoder: &mut VocabDecoder, encoder: &mut HashMap<String, VocabId>) {
decoder.push(VocabValue {
text: "<bos>".to_string(),
norm: vec!(),
frequency: 0,
tokencount: 1,
lexindex: 0,
variants: None,
vocabtype: VocabType::NONE,
});
decoder.push(VocabValue {
text: "<eos>".to_string(),
norm: vec!(),
frequency: 0,
tokencount: 1,
lexindex: 0,
variants: None,
vocabtype: VocabType::NONE,
});
decoder.push(VocabValue {
text: "<unk>".to_string(),
norm: vec!(),
frequency: 0,
tokencount: 1,
lexindex: 0,
variants: None,
vocabtype: VocabType::NONE,
});
encoder.insert("<bos>".to_string(),BOS);
encoder.insert("<eos>".to_string(),EOS);
encoder.insert("<unk>".to_string(),UNK);
}