ihhereanth commited on
Commit
b4a4dcf
·
verified ·
1 Parent(s): 86dc1b0

Create tokens.py

Browse files
Files changed (1) hide show
  1. app/tokens.py +41 -0
app/tokens.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app/tokens.py
2
+ _MODEL = "Qwen/Qwen3-30B-A3B-Instruct-2507"
3
+ _tok = None
4
+ _tried = False
5
+
6
+
7
+ def _get_tok():
8
+ """โหลด tokenizer แบบ lazy + ไม่พังถ้าโหลดไม่ได้"""
9
+ global _tok, _tried
10
+ if _tried:
11
+ return _tok
12
+ _tried = True
13
+ try:
14
+ from transformers import AutoTokenizer
15
+ _tok = AutoTokenizer.from_pretrained(_MODEL)
16
+ print("[tokens] real tokenizer loaded", flush=True)
17
+ except Exception as e:
18
+ print(f"[tokens] fallback to char estimate: {e}", flush=True)
19
+ _tok = None
20
+ return _tok
21
+
22
+
23
+ def count(text: str) -> int:
24
+ if not text:
25
+ return 0
26
+ t = _get_tok()
27
+ if t is None:
28
+ return max(1, len(text) // 4) # fallback: ~4 chars/token
29
+ return len(t.encode(text, add_special_tokens=False))
30
+
31
+
32
+ def fit(text: str, budget: int) -> str:
33
+ if not text or budget <= 0:
34
+ return ""
35
+ t = _get_tok()
36
+ if t is None:
37
+ return text[: budget * 4]
38
+ ids = t.encode(text, add_special_tokens=False)
39
+ if len(ids) <= budget:
40
+ return text
41
+ return t.decode(ids[:budget])