use crate::error::TokenizerError;
use crate::vocab::base_vocab::swap_key_values;
use crate::vocab::sentencepiece_proto::sentencepiece_model::ModelProto;
use crate::vocab::Vocab;
use protobuf::Message;
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;
#[derive(Debug, Clone)]
pub struct SentencePieceVocab {
pub values: HashMap<String, i64>,
pub indices: HashMap<i64, String>,
pub unknown_value: &'static str,
pub special_values: HashMap<String, i64>,
pub special_indices: HashMap<i64, String>,
}
impl SentencePieceVocab {
pub fn pad_value() -> &'static str {
"<pad>"
}
pub fn sep_value() -> &'static str {
"<sep>"
}
pub fn cls_value() -> &'static str {
"<cls>"
}
pub fn mask_value() -> &'static str {
"<mask>"
}
pub fn bos_value() -> &'static str {
"<s>"
}
pub fn eos_value() -> &'static str {
"</s>"
}
}
impl Vocab for SentencePieceVocab {
fn unknown_value() -> &'static str {
"<unk>"
}
fn get_unknown_value(&self) -> &'static str {
"<unk>"
}
fn values(&self) -> &HashMap<String, i64> {
&self.values
}
fn indices(&self) -> &HashMap<i64, String> {
&self.indices
}
fn special_values(&self) -> &HashMap<String, i64> {
&self.special_values
}
fn special_indices(&self) -> &HashMap<i64, String> {
&self.special_indices
}
fn from_file(path: &str) -> Result<SentencePieceVocab, TokenizerError> {
let mut f = match File::open(path) {
Ok(file) => file,
Err(_) => {
return Err(TokenizerError::FileNotFound(format!(
"{} vocabulary file not found",
path
)));
}
};
let mut contents = Vec::new();
let proto = match f.read_to_end(&mut contents) {
Ok(_) => match ModelProto::parse_from_bytes(contents.as_slice()) {
Ok(proto_value) => proto_value,
Err(e) => {
return Err(TokenizerError::VocabularyParsingError(e.to_string()));
}
},
Err(e) => {
return Err(TokenizerError::VocabularyParsingError(e.to_string()));
}
};
let mut values = HashMap::new();
for (idx, piece) in proto.get_pieces().iter().enumerate() {
values.insert(piece.get_piece().to_owned(), idx as i64);
}
let mut special_values = HashMap::new();
let unknown_value = SentencePieceVocab::unknown_value();
SentencePieceVocab::_register_as_special_value(
unknown_value,
&values,
&mut special_values,
)?;
let indices = swap_key_values(&values);
let special_indices = swap_key_values(&special_values);
Ok(SentencePieceVocab {
values,
indices,
unknown_value,
special_values,
special_indices,
})
}
fn token_to_id(&self, token: &str) -> i64 {
self._token_to_id(
token,
&self.values,
&self.special_values,
self.unknown_value,
)
}
fn id_to_token(&self, id: &i64) -> String {
self._id_to_token(id, &self.indices, &self.special_indices, self.unknown_value)
}
}