unicode : add opt-in NFC normalization for Unigram tokenizers (#30390)

* unicode : add opt-in NFC normalization for Unigram tokenizers

Note: used help from Codex, Sol 6.1 Medium

* Fixing initial bot comments + linter error (using existing out instead of print)

* removed test_nfc_tokenizer
This commit is contained in:
Sandro Hanea authored and GitHub committed 2026-10-14 08:33:24 +03:00
1 parent eca5458ce0
commit 10da8c463f
12 files changed
+4165 -7

No files matched your search

+42 -4
View File
@@ -1,10 +1,50 @@
from __future__ import annotations
import array
import sys
import unicodedata
import requests
def out(line=""):
print(line, end='\n') # noqa
def normalization_tables():
out(f"// Canonical normalization tables: Unicode {unicodedata.unidata_version}.")
out("const std::unordered_map<uint32_t, uint8_t> unicode_combining_class = {")
for cpt in range(0x110000):
if value := unicodedata.combining(chr(cpt)):
out(f"{{0x{cpt:06X}, {value}}},")
out("};\n")
out("const std::unordered_map<uint32_t, std::pair<uint32_t, uint32_t>> unicode_decomposition = {")
compositions = []
for cpt in range(0x110000):
if 0xAC00 <= cpt < 0xAC00 + 11172:
continue
raw = unicodedata.decomposition(chr(cpt))
if not raw or raw.startswith("<"):
continue
parts = [int(part, 16) for part in raw.split()]
assert 1 <= len(parts) <= 2
first, second = parts[0], parts[1] if len(parts) == 2 else 0
out(f"{{0x{cpt:06X}, {{0x{first:06X}, 0x{second:06X}}}}},")
if second and unicodedata.normalize("NFC", chr(first) + chr(second)) == chr(cpt):
compositions.append((first, second, cpt))
out("};\n")
out("const std::unordered_map<uint64_t, uint32_t> unicode_composition = {")
for first, second, cpt in compositions:
out(f"{{0x{((first << 32) | second):016X}ULL, 0x{cpt:06X}}},")
out("};")
# Generate only canonical tables, without downloading the UCD data.
if sys.argv[1:] == ["--normalization-only"]:
normalization_tables()
sys.exit(0)
MAX_CODEPOINTS = 0x110000
UNICODE_DATA_URL = "https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt"
@@ -155,10 +195,6 @@ for codepoint, norm in table_nfd:
# Generate 'unicode-data.cpp':
# python ./scripts//gen-unicode-data.py > unicode-data.cpp
def out(line=""):
print(line, end='\n') # noqa
out("""\
// generated with scripts/gen-unicode-data.py
@@ -194,3 +230,5 @@ out("const std::vector<range_nfd> unicode_ranges_nfd = { // start, last, nfd")
for triple in ranges_nfd:
out("{0x%06X, 0x%06X, 0x%06X}," % triple)
out("};\n")
normalization_tables()