use std::collections::{HashMap, HashSet};
use serde::Deserialize;
#[derive(Deserialize)]
struct RawWordLevel {
#[serde(default)]
vocab: HashMap<String, u32>,
#[serde(default)]
unk_token: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(from = "RawWordLevel")]
pub struct WordLevel {
vocab: HashSet<String>,
unk_in_vocab: bool,
}
impl From<RawWordLevel> for WordLevel {
fn from(raw: RawWordLevel) -> Self {
let unk_in_vocab = raw.vocab.contains_key(&raw.unk_token);
Self {
vocab: raw.vocab.into_keys().collect(),
unk_in_vocab,
}
}
}
impl WordLevel {
#[inline]
pub fn count_tokens(&self, input: &str) -> Result<usize, String> {
if self.vocab.contains(input) || self.unk_in_vocab {
Ok(1)
} else {
Err(format!(
"WordLevel: `{input}` not in vocab and unk token is missing"
))
}
}
}