File size: 1,342 Bytes
be99550 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | // ๐ BioPhys ํ
์คํธ ํ์ดํ๋ผ์ธ (Tokenizer)
use std::collections::HashMap;
pub struct BioPhysTokenizer {
vocab: HashMap<String, u32>,
reverse_vocab: HashMap<u32, String>,
}
impl BioPhysTokenizer {
pub fn new() -> Self {
let mut tokenizer = Self {
vocab: HashMap::new(),
reverse_vocab: HashMap::new(),
};
// ์ต์ํ์ ๊ธฐ๋ณธ ๋๋ฏธ ์ดํ(BPE ๋ชจ์ฌ)
tokenizer.add_token(" ", 0);
tokenizer.add_token("Hello", 1);
tokenizer.add_token("Universe", 2);
tokenizer.add_token("BioPhys", 3);
tokenizer.add_token("Ecosystem", 4);
tokenizer.add_token("Evolution", 5);
tokenizer
}
fn add_token(&mut self, text: &str, id: u32) {
self.vocab.insert(text.to_string(), id);
self.reverse_vocab.insert(id, text.to_string());
}
pub fn encode(&self, text: &str) -> Vec<u32> {
// ์ค์ ๋ก๋ BPE๋ SentencePiece ๋ก์ง์ด ๋ค์ด๊ฐ
text.split_whitespace()
.map(|word| *self.vocab.get(word).unwrap_or(&999))
.collect()
}
pub fn decode(&self, tokens: &[u32]) -> String {
tokens.iter()
.map(|t| self.reverse_vocab.get(t).unwrap_or(&"[UNK]".to_string()).clone())
.collect::<Vec<String>>()
.join(" ")
}
}
|