File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 88from __future__ import annotations
99
1010import json
11+ import re
1112
1213from . import config
1314
@@ -23,11 +24,17 @@ def is_cjk_char(c: str) -> bool:
2324 )
2425
2526
27+ # The same ranges as `is_cjk_char`, as a single compiled character class.
28+ # Scanning for CJK runs in C (the regex engine) instead of a per-character
29+ # Python loop, so large payloads count CJK chars much faster.
30+ _CJK_RE = re .compile (r"[\u3000-\u9fff\uf900-\ufaff\uff00-\uffef\U00020000-\U0002fa1f]" )
31+
32+
2633def estimate_tokens (text : str ) -> int :
2734 """Estimate tokens in TEXT: Latin ~4 chars/token, CJK ~2 chars/token."""
2835 if not text :
2936 return 0
30- cjk = sum ( 1 for ch in text if is_cjk_char ( ch ))
37+ cjk = len ( _CJK_RE . findall ( text ))
3138 latin = len (text ) - cjk
3239 return round (latin / 4.0 + cjk / 2.0 )
3340
You can’t perform that action at this time.
0 commit comments