Uunan commited on
Commit
41e1660
·
verified ·
1 Parent(s): b8ec498

Upload tokenizer.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tokenizer.py +37 -0
tokenizer.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A tiny character-level tokenizer for Turkish names.
2
+
3
+ Every token is a single character. The vocabulary is built directly from the
4
+ names file, so it contains exactly the characters that appear in the data
5
+ (29 Turkish letters + the newline "\n", which we use as the start/end-of-name
6
+ marker).
7
+
8
+ Usage:
9
+ tok = CharTokenizer.from_file("temiz_isimler.txt")
10
+ ids = tok.encode("ali") # -> [..]
11
+ tok.decode(ids) # -> "ali"
12
+ tok.newline_id # id of "\n", the name separator / stop token
13
+ """
14
+
15
+
16
+ class CharTokenizer:
17
+ def __init__(self, chars: list[str]):
18
+ self.chars = chars
19
+ self.stoi = {ch: i for i, ch in enumerate(chars)} # char -> id
20
+ self.itos = {i: ch for i, ch in enumerate(chars)} # id -> char
21
+ self.vocab_size = len(chars)
22
+ # The newline both separates names and marks end-of-sequence (EOS).
23
+ self.newline_id = self.stoi["\n"]
24
+ self.eos_id = self.newline_id
25
+
26
+ @classmethod
27
+ def from_file(cls, path: str) -> "CharTokenizer":
28
+ text = open(path, encoding="utf-8").read()
29
+ if "\n" not in text: # make sure the stop token always exists
30
+ text += "\n"
31
+ return cls(sorted(set(text)))
32
+
33
+ def encode(self, s: str) -> list[int]:
34
+ return [self.stoi[c] for c in s]
35
+
36
+ def decode(self, ids: list[int]) -> str:
37
+ return "".join(self.itos[i] for i in ids)