Spaces:
Running
Running
Download g2p.js from datmt24/tiny-voca-vi: direct link, hf CLI and curl.
- Browser
- Download file 42.3 kB
-
https://huggingface.co/spaces/datmt24/tiny-voca-vi/resolve/main/g2p.js
- Command line
-
hf download hf://spaces/datmt24/tiny-voca-vi/g2p.js
-
curl -L -o g2p.js https://huggingface.co/spaces/datmt24/tiny-voca-vi/resolve/main/g2p.js
42.3 kB
| // Deterministic rule-based Northern (Hanoi) Vietnamese text normalizer, G2P, and chunker. | |
| // Bit-for-bit mirror of src/tiny_voca_vi/g2p.py (~15 KB gzipped, zero binary dictionary). | |
| // Works in classic Web Workers (self.TinyVocaG2P), browser window, and Node. | |
| (function (root) { | |
| const SPECIALS = ["<pad>", "<bos>", "<eos>", "<sp>", ",", ".", "?", "!", ";", ":", "—"]; | |
| const PUNCTUATION = new Set([",", ".", "?", "!", ";", ":", "—"]); | |
| const ONSETS = [ | |
| "b", "m", "f", "v", "t", "tʰ", "d", "n", "l", "s", "z", | |
| "tɕ", "ɲ", "k", "x", "ɣ", "ŋ", "h", "p", | |
| ]; | |
| const VOWELS = [ | |
| "i", "e", "ɛ", "ɯ", "ɤ", "ə", "aː", "a", "u", "o", "ɔ", | |
| "iə", "ɯə", "uə", | |
| ]; | |
| const GLIDES = ["w", "j"]; | |
| const EXTRA_CODAS = ["c"]; | |
| const SYMBOLS = [...SPECIALS, ...ONSETS, ...VOWELS, ...GLIDES, ...EXTRA_CODAS]; | |
| const SYMBOL_TO_ID = Object.fromEntries(SYMBOLS.map((s, i) => [s, i])); | |
| const TONE_COMBINING = { | |
| "\u0300": 2, // huyền | |
| "\u0301": 3, // sắc | |
| "\u0309": 4, // hỏi | |
| "\u0303": 5, // ngã | |
| "\u0323": 6, // nặng | |
| }; | |
| const ONSET_RULES = [ | |
| ["ngh", "ŋ"], ["ng", "ŋ"], ["nh", "ɲ"], ["ch", "tɕ"], ["tr", "tɕ"], | |
| ["th", "tʰ"], ["ph", "f"], ["kh", "x"], ["gh", "ɣ"], ["gi", "z"], | |
| ["qu", "kw"], | |
| ["b", "b"], ["m", "m"], ["v", "v"], ["t", "t"], ["đ", "d"], | |
| ["n", "n"], ["l", "l"], ["s", "s"], ["x", "s"], ["d", "z"], | |
| ["r", "z"], ["c", "k"], ["k", "k"], ["g", "ɣ"], ["h", "h"], ["p", "p"], | |
| ]; | |
| const CODA_RULES = [ | |
| ["ng", "ŋ"], ["nh", "ɲ"], ["ch", "c"], | |
| ["m", "m"], ["n", "n"], ["p", "p"], ["t", "t"], ["c", "k"], | |
| ]; | |
| const OVERRIDES = { | |
| internet: [["i", 1, 1], ["n", 1, 2], ["t", 1, 0], ["ɤ", 1, 1], ["n", 3, 0], ["ɛ", 3, 1], ["t", 3, 2]], | |
| email: [["i", 1, 1], ["m", 1, 0], ["e", 1, 1], ["w", 1, 2]], | |
| video: [["v", 1, 0], ["i", 1, 1], ["d", 1, 0], ["e", 1, 1], ["o", 1, 1]], | |
| ai: [["aː", 1, 1], ["j", 1, 2]], | |
| }; | |
| const DIGITS_VI = ["không", "một", "hai", "ba", "bốn", "năm", "sáu", "bảy", "tám", "chín"]; | |
| const VOWEL_CHARS = "aăâeêioôơuưy"; | |
| const NUCLEUS_MAP = { | |
| i: "i", y: "i", ê: "e", e: "ɛ", ư: "ɯ", ơ: "ɤ", â: "ə", | |
| a: "aː", ă: "a", u: "u", ô: "o", o: "ɔ", | |
| ia: "iə", iê: "iə", ya: "iə", yê: "iə", | |
| ưa: "ɯə", ươ: "ɯə", ua: "uə", uô: "uə", | |
| }; | |
| const J_RHYMES = new Set(["ai", "ay", "ây", "oi", "ôi", "ơi", "ui", "ưi"]); | |
| const W_RHYMES = new Set(["ao", "au", "âu", "eo", "êu", "iu", "ưu"]); | |
| const J_PREFIX = new Set(["a", "ă", "â", "o", "ô", "ơ", "u", "ư", "iê", "ươ", "uô"]); | |
| function stripTone(syllable) { | |
| const nfd = syllable.toLowerCase().normalize("NFD"); | |
| let tone = 1; | |
| let kept = ""; | |
| for (const ch of nfd) { | |
| if (ch in TONE_COMBINING) tone = TONE_COMBINING[ch]; | |
| else kept += ch; | |
| } | |
| return [kept.normalize("NFC"), tone]; | |
| } | |
| function numberToWords(n) { | |
| if (n < 0) return "âm " + numberToWords(-n); | |
| if (n < 10) return DIGITS_VI[n]; | |
| if (n < 20) { | |
| if (n === 10) return "mười"; | |
| if (n === 15) return "mười lăm"; | |
| return "mười " + DIGITS_VI[n - 10]; | |
| } | |
| if (n < 100) { | |
| const tens = Math.floor(n / 10), ones = n % 10; | |
| const head = DIGITS_VI[tens] + " mươi"; | |
| if (ones === 0) return head; | |
| if (ones === 1) return head + " mốt"; | |
| if (ones === 4) return head + " tư"; | |
| if (ones === 5) return head + " lăm"; | |
| return head + " " + DIGITS_VI[ones]; | |
| } | |
| if (n < 1000) { | |
| const hundreds = Math.floor(n / 100), rem = n % 100; | |
| const head = DIGITS_VI[hundreds] + " trăm"; | |
| if (rem === 0) return head; | |
| if (rem < 10) return head + " linh " + DIGITS_VI[rem]; | |
| return head + " " + numberToWords(rem); | |
| } | |
| const units = [[1_000_000_000, "tỷ"], [1_000_000, "triệu"], [1_000, "nghìn"]]; | |
| for (const [scale, label] of units) { | |
| if (n >= scale) { | |
| const major = Math.floor(n / scale), rem = n % scale; | |
| const head = numberToWords(major) + " " + label; | |
| if (rem === 0) return head; | |
| if (rem < 100 && scale >= 1_000) { | |
| if (rem < 10) return head + " không trăm linh " + DIGITS_VI[rem]; | |
| return head + " không trăm " + numberToWords(rem); | |
| } | |
| return head + " " + numberToWords(rem); | |
| } | |
| } | |
| return String(n); | |
| } | |
| // <lexicon> generated by scripts/sync_g2p_lexicon.py - do not edit | |
| const CURRENCY = {"USD": "đô la Mỹ", "EUR": "ơ rô", "GBP": "bảng Anh", "JPY": "yên Nhật", "CNY": "nhân dân tệ", "RMB": "nhân dân tệ", "KRW": "uôn", "THB": "bạt Thái", "AUD": "đô la Úc", "CAD": "đô la Ca na đa", "SGD": "đô la Sinh ga po", "HKD": "đô la Hồng Kông", "TWD": "đô la Đài Loan", "NZD": "đô la Niu Di lân", "CHF": "phờ răng Thụy Sĩ", "INR": "ru pi", "RUB": "rúp", "LAK": "kíp Lào", "KHR": "riên", "MYR": "rinh gít", "IDR": "ru pi a", "PHP": "pê sô", "VND": "đồng", "VNĐ": "đồng", "BTC": "bít coi", "ETH": "ê thơ"}; | |
| const SYMBOL_CURRENCY = {"$": "đô la", "€": "ơ rô", "£": "bảng Anh", "¥": "yên", "₫": "đồng", "₩": "uôn", "฿": "bạt"}; | |
| const UNITS = {"km/h": "ki lô mét trên giờ", "kmh": "ki lô mét trên giờ", "km²": "ki lô mét vuông", "km2": "ki lô mét vuông", "m²": "mét vuông", "m2": "mét vuông", "cm²": "xen ti mét vuông", "cm2": "xen ti mét vuông", "m³": "mét khối", "m3": "mét khối", "cm³": "xen ti mét khối", "cm3": "xen ti mét khối", "km": "ki lô mét", "m": "mét", "dm": "đề xi mét", "cm": "xen ti mét", "mm": "mi li mét", "nm": "na nô mét", "kg": "ki lô gam", "g": "gam", "mg": "mi li gam", "l": "lít", "ml": "mi li lít", "mL": "mi li lít", "ha": "héc ta", "s": "giây", "h": "giờ", "°C": "độ xê", "°F": "độ ép", "ºC": "độ xê", "°": "độ", "kW": "ki lô oát", "MW": "mê ga oát", "GW": "gi ga oát", "kWh": "ki lô oát giờ", "MWh": "mê ga oát giờ", "W": "oát", "V": "vôn", "Hz": "héc", "kHz": "ki lô héc", "MHz": "mê ga héc", "GHz": "gi ga héc", "KB": "ki lô bai", "MB": "mê ga bai", "GB": "gi ga bai", "TB": "tê ra bai", "Mbps": "mê ga bít trên giây", "Gbps": "gi ga bít trên giây", "kcal": "ki lô ca lo", "cal": "ca lo", "oz": "ao xơ", "lb": "pao", "lbs": "pao", "ft": "phít", "mph": "dặm trên giờ"}; | |
| const PER_WORDS = ["lượng", "chỉ", "thùng", "giờ", "phút", "giây", "ngày", "tuần", "tháng", "quý", "năm", "người", "lít", "tấn", "tạ", "kg", "cổ phiếu", "suất", "căn", "lần", "học sinh", "đêm", "vé", "chiếc"]; | |
| const ABBREV = {"TP": "thành phố", "Tp": "thành phố", "TPHCM": "thành phố Hồ Chí Minh", "HCM": "Hồ Chí Minh", "HN": "Hà Nội", "VN": "Việt Nam", "TW": "trung ương", "TƯ": "trung ương", "UBND": "ủy ban nhân dân", "HĐND": "hội đồng nhân dân", "MTTQ": "mặt trận tổ quốc", "UBTVQH": "ủy ban thường vụ quốc hội", "CSGT": "cảnh sát giao thông", "PCCC": "phòng cháy chữa cháy", "CHXHCN": "cộng hòa xã hội chủ nghĩa", "GS": "giáo sư", "PGS": "phó giáo sư", "TS": "tiến sĩ", "ThS": "thạc sĩ", "BS": "bác sĩ", "KTS": "kiến trúc sư", "LS": "luật sư", "NSND": "nghệ sĩ nhân dân", "NSƯT": "nghệ sĩ ưu tú", "ĐBQH": "đại biểu quốc hội", "BHXH": "bảo hiểm xã hội", "BHYT": "bảo hiểm y tế", "BHTN": "bảo hiểm thất nghiệp", "GTGT": "giá trị gia tăng", "TNCN": "thu nhập cá nhân", "TNHH": "trách nhiệm hữu hạn", "CTCP": "công ty cổ phần", "DN": "doanh nghiệp", "HTX": "hợp tác xã", "BĐS": "bất động sản", "NHNN": "ngân hàng nhà nước", "TTCK": "thị trường chứng khoán", "KCN": "khu công nghiệp", "THPT": "trung học phổ thông", "THCS": "trung học cơ sở", "ĐH": "đại học", "CĐ": "cao đẳng", "CLB": "câu lạc bộ", "HLV": "huấn luyện viên", "HCV": "huy chương vàng", "HCB": "huy chương bạc", "HCĐ": "huy chương đồng", "SVĐ": "sân vận động", "ĐT": "điện thoại", "SĐT": "số điện thoại", "CMND": "chứng minh nhân dân", "CCCD": "căn cước công dân", "GPLX": "giấy phép lái xe", "KTX": "ký túc xá", "GD": "giáo dục", "BV": "bệnh viện", "ATTP": "an toàn thực phẩm", "ATGT": "an toàn giao thông", "QL": "quốc lộ", "TNGT": "tai nạn giao thông", "NXB": "nhà xuất bản", "BTV": "biên tập viên", "PV": "phóng viên", "MC": "em xi", "NLĐ": "người lao động", "AI": "ây ai", "IT": "ai ti", "CEO": "xi i âu", "CFO": "xi ép âu", "GDP": "gi đi pi", "GNP": "gi en pi", "CPI": "xi pi ai", "FDI": "ép đi ai", "ODA": "âu đi ây", "IPO": "ai pi âu", "ETF": "i ti ép", "FED": "phét", "Fed": "phét", "IMF": "ai em ép", "WB": "ngân hàng thế giới", "WTO": "đáp liu ti âu", "WHO": "đáp liu ếch âu", "UN": "liên hợp quốc", "EU": "i iu", "US": "iu ét", "USA": "iu ét ây", "UK": "iu cây", "UAE": "iu ây i", "UAV": "iu ây vi", "NATO": "na tô", "ASEAN": "a xê an", "UNESCO": "u nét cô", "UNICEF": "iu ni xép", "FIFA": "phi pha", "UEFA": "u ê pha", "AFF": "ây ép ép", "AFC": "ây ép xi", "VAR": "va", "NASA": "na xa", "OPEC": "ô pếch", "APEC": "a péc", "CIA": "xi ai ây", "FBI": "ép bi ai", "PR": "pi a", "VIP": "víp", "SMS": "ét em ét", "PIN": "pin", "SIM": "xim", "ATM": "ây ti em", "OTP": "âu ti pi", "QR": "quy rờ", "GPS": "gi pi ét", "USB": "iu ét bi", "PC": "pi xi", "TV": "ti vi", "LED": "lét", "CPU": "xi pi iu", "GPU": "gi pi iu", "RAM": "ram", "URL": "iu a eo", "PDF": "pi đi ép", "CD": "xi đi", "DVD": "đi vi đi", "ID": "ai đi", "TOEIC": "tô ích", "VAT": "vát", "ISO": "i sô", "DNA": "đi en ây", "ADN": "a đê en", "HIV": "hát i vê", "AIDS": "ết", "COVID": "cô vít", "Covid": "cô vít", "VTV": "vê tê vê", "VOV": "vê ô vê", "KOL": "cây âu eo", "ESG": "i ét gi", "SUV": "ét iu vi", "HOSE": "hô xê", "SJC": "ét gi xi", "PNJ": "pi en gi", "DOJI": "đô gi", "VIB": "vê i bê", "FPT": "ép pê tê", "HSBC": "hát ét bê xê", "km": "ki lô mét", "kg": "ki lô gam", "cm": "xen ti mét", "mm": "mi li mét", "ml": "mi li lít", "kWh": "ki lô oát giờ"}; | |
| const ENGLISH = {"ounce": "ao xơ", "ounces": "ao xơ", "pound": "pao", "pounds": "pao", "inch": "in", "inches": "in", "feet": "phít", "foot": "phít", "mile": "mai", "miles": "mai", "gallon": "ga lông", "barrel": "ba reo", "yard": "da", "euro": "ơ rô", "euros": "ơ rô", "dollar": "đô la", "dollars": "đô la", "cent": "xen", "cents": "xen", "yen": "yên", "won": "uôn", "bitcoin": "bít coi", "bitcoins": "bít coi", "ethereum": "ê thơ ri âm", "crypto": "cờ ríp tô", "blockchain": "bờ lóc chen", "token": "tô cần", "online": "on lai", "offline": "óp lai", "website": "oép sai", "web": "oép", "wifi": "oai phai", "gmail": "gi meo", "clip": "cờ líp", "livestream": "lai sờ trim", "stream": "sờ trim", "podcast": "pót cát", "blog": "bờ lóc", "smartphone": "sờ mát phôn", "laptop": "láp tóp", "computer": "com piu tơ", "tablet": "táp lét", "chip": "chíp", "robot": "rô bốt", "app": "áp", "software": "sóp oe", "server": "sơ vơ", "cloud": "cờ lao", "data": "đa ta", "startup": "sờ tát ấp", "marketing": "'ma két tinh", "sale": "seo", "sales": "seo", "shop": "sóp", "shopping": "sóp ping", "show": "sâu", "showroom": "sâu rum", "studio": "sờ tu đi ô", "casino": "ca 'xi nô", "resort": "ri 'sót", "homestay": "hôm sờ tây", "hotel": "hô 'teo", "tour": "tua", "visa": "vi da", "taxi": "tắc xi", "container": "công ten nơ", "logistics": "lô gít tích", "golf": "gôn", "tennis": "ten nít", "marathon": "ma ra tông", "game": "gêm", "games": "gêm", "gamer": "gêm mơ", "fan": "phan", "fans": "phan", "hot": "hót", "trend": "tren", "style": "sờ tai", "stress": "sờ trét", "vaccine": "vắc xin", "virus": "vi rút", "vitamin": "vi ta min", "protein": "pờ rô tê in", "calo": "ca lo", "cafe": "cà phê", "pizza": "pi da", "hamburger": "hăm bơ gơ", "cocktail": "cốc teo", "album": "an bum", "radio": "ra đi ô", "list": "lít", "top": "tóp", "file": "phai", "link": "linh", "click": "cờ lích", "chat": "chát", "check": "chéc", "test": "tét", "team": "tim", "leader": "li đơ", "manager": "'me ni gờ", "deadline": "đét lai", "meeting": "mít tinh", "okay": "âu 'kê", "ok": "âu 'kê", "mr": "mít tơ", "mrs": "mít xít", "dr": "đốc tơ", "mc": "mác", "st": "xanh", "hello": "hê lô", "bye": "bai", "photo": "phô tô", "photocopy": "phô tô cóp pi", "facebook": "phây búc", "google": "gu gồ", "youtube": "diu túp", "tiktok": "tích tóc", "zalo": "da lô", "twitter": "tuýt tơ", "instagram": "in sờ ta gam", "microsoft": "mai cờ rô sóp", "apple": "áp pồ", "iphone": "'ai -phôn", "ipad": "ai pát", "android": "an đờ roi", "samsung": "sam sung", "windows": "uyn đâu", "tesla": "tét la", "amazon": "a ma dôn", "netflix": "nét phờ lích", "chatgpt": "chát gi pi ti", "messenger": "'mét sen gơ", "telegram": "te lê gam", "shopee": "sóp pi", "grab": "gờ ráp", "honda": "hon đa", "toyota": "tô ô ta", "vinfast": "vin phát", "vingroup": "vin gờ rúp", "vietcombank": "việt com banh", "techcombank": "tếch com banh", "singapore": "sinh ga po", "malaysia": "ma lai xi a", "indonesia": "in đô nê xi a", "campuchia": "cam pu chia", "philippines": "phi líp pin", "australia": "ô xờ trây li a", "canada": "ca na đa", "brazil": "bờ ra xin", "argentina": "ác hen ti na", "ukraine": "u cờ rai na", "israel": "ít xa ra en", "iran": "i ran", "washington": "'oa sinh tơn", "london": "luân đôn", "paris": "pa ri", "tokyo": "tô ki ô", "new": "niu", "york": "óc", "trump": "trăm", "donald": "đô nan", "biden": "bai đừn", "schwarzenegger": "'soát dơ ne gơ", "putin": "pu tin", "josé": "hô xê", "video": "vi đê ô", "videos": "vi đê ô", "internet": "in tơ nét", "email": "i meo", "emails": "i meo", "ebook": "i búc", "tech": "tếch", "dont": "đôn", "cant": "can", "isnt": "i dần", "doesnt": "đa dần", "didnt": "đít đần", "wont": "uôn", "hanoi": "hà nội", "vietnam": "việt nam", "saigon": "sài gòn", "danang": "đà nẵng", "asean": "a xê an", "daniel": "đa ni en", "charles": "sác lơ", "jean": "dăng", "jacques": "dắc", "louis": "lu i", "henri": "hăng ri", "oscar": "ốt ca", "québec": "quê béc", "quebec": "quê béc", "roma": "rô ma", "berlin": "béc lin", "korea": "kô rê a", "deepseek": "đíp xích", "openai": "âu pần ây ai", "gemini": "gem mi nai", "nvidia": "en vi đi a", "huawei": "hoa uây", "xiaomi": "sao mi", "spacex": "sờ pết ích", "covid": "cô vít", "spotify": "sờ po ti phai", "whatsapp": "oát áp", "linkedin": "linh đin", "shein": "si in", "temu": "te mu", "lazada": "la da đa", "vnindex": "vê en in đếch", "ronaldo": "rô nan đô", "messi": "mét xi", "mbappe": "báp pê", "mbappé": "báp pê", "neymar": "nây ma"}; | |
| const SHORT_PARTS = ["air", "app", "bit", "box", "car", "day", "eye", "fan", "hot", "job", "key", "net", "pay", "sea", "sky", "sun", "tax", "top", "way", "web"]; | |
| const NO_STRESS = ["dollar", "dollars", "euro", "euros", "calo", "taxi", "virus", "vitamin", "vaccine", "robot", "radio", "container", "ounce", "ounces", "album", "visa", "pizza", "canada", "iran"]; | |
| const LETTERS = {"a": "a", "b": "bê", "c": "xê", "d": "đê", "đ": "đê", "e": "e", "f": "ép", "g": "giê", "h": "hát", "i": "i", "j": "gi", "k": "ca", "l": "lờ", "m": "mờ", "n": "nờ", "o": "ô", "p": "pê", "q": "quy", "r": "rờ", "s": "ét", "t": "tê", "u": "u", "ư": "ư", "v": "vê", "w": "vê kép", "x": "ích", "y": "i", "z": "dét", "ă": "á", "â": "ớ", "ê": "ê", "ô": "ô", "ơ": "ơ"}; | |
| const F_VOWELS = {"a": "a", "ă": "ă", "â": "â", "e": "ê", "ê": "ê", "i": "i", "o": "ô", "ô": "ô", "ơ": "ơ", "u": "u", "ư": "ư", "y": "i", "ai": "ai", "ay": "ai", "au": "au", "aw": "o", "ao": "ao", "aa": "a", "ei": "ây", "ey": "ây", "ee": "i", "eu": "êu", "ew": "iu", "oi": "ôi", "oy": "ôi", "oo": "u", "ou": "u", "ow": "âu", "ui": "ui", "uu": "u", "ii": "i", "ie": "i", "ea": "i"}; | |
| const F_CLOSED = {"ê": "e"}; | |
| const F_ONSET = {"tch": "ch", "sch": "s", "tsch": "ch", "gi": "d", "ch": "ch", "sh": "s", "th": "th", "ph": "ph", "kh": "kh", "gh": "gh", "ng": "ng", "nh": "nh", "tr": "tr", "ck": "k", "qu": "qu", "wh": "w", "zh": "d", "dh": "đ", "bh": "b", "rh": "r", "ts": "x", "tz": "x", "cz": "x", "sz": "x", "b": "b", "c": "k", "ç": "x", "d": "đ", "đ": "đ", "f": "ph", "g": "g", "h": "h", "j": "d", "k": "k", "l": "l", "m": "m", "n": "n", "p": "p", "q": "k", "r": "r", "s": "s", "t": "t", "v": "v", "w": "w", "x": "x", "y": "y", "z": "d"}; | |
| const F_CODA = {"m": "m", "n": "n", "ng": "ng", "nh": "nh", "p": "p", "b": "p", "f": "p", "v": "p", "ph": "p", "bh": "p", "t": "t", "d": "t", "đ": "t", "dh": "t", "s": "t", "z": "t", "th": "t", "sh": "t", "ch": "t", "tch": "t", "sch": "t", "tsch": "t", "ts": "t", "tz": "t", "cz": "t", "sz": "t", "zh": "t", "j": "t", "ç": "t", "gi": "t", "c": "c", "k": "c", "ck": "c", "g": "c", "gh": "c", "kh": "c", "q": "c", "x": "c", "l": "n", "r": "c"}; | |
| const SYLLABLE_RE = new RegExp("^(?:ngh|ng|nh|ch|tr|th|ph|kh|gh|gi|qu|[bcdđghklmnprstvx])?(?:(?:uyê|iê|yê|ươ|uô|oa|oă|oe|uâ|uê|uơ|uy|[aăâeêioôơuưy])(?:ng|nh|ch|[mnptc])?|iêu|yêu|ươi|ươu|uôi|oai|oay|oao|oeo|uây|uya|uyu|ai|ay|ây|oi|ôi|ơi|ui|ưi|ao|au|âu|eo|êu|iu|ưu|ia|ua|ưa|uê|uơ|oo(?:ng|c))$"); | |
| const F_SILENT_E = new RegExp("(?:c|g|v|ll|tl|ak|it|id|in|il|ir|ur|ar|iz|as|am|yp|at)e$"); | |
| // </lexicon> | |
| const LT = "A-Za-zÀ-ỹ"; | |
| const alt = (keys) => [...keys].sort((a, b) => b.length - a.length || (a < b ? -1 : 1)).map((k) => k.replace(/[.*+?^${}()|[\]\\\/]/g, "\\$&")).join("|"); | |
| const SIGNS = Object.keys(SYMBOL_CURRENCY).join(""); | |
| const MAG = "nghìn|ngàn|triệu|tỷ|tỉ"; | |
| const CUR_PRE = new RegExp(`(?:US)?([${SIGNS}])\\s?(\\d+(?:[.,]\\d+)*)(\\s(?:${MAG})(?:\\s(?:${MAG}))*(?![${LT}]))?`, "g"); | |
| const CUR_SUF = new RegExp(`(?<=\\d)\\s?([${SIGNS}])`, "g"); | |
| const SLASH = new RegExp(`([${LT}°²³$€£¥₫]+)\\s?/\\s?(${alt([...Object.keys(UNITS), ...Object.keys(ENGLISH), ...PER_WORDS])})(?![${LT}\\d²³])`, "g"); | |
| const PAIR = new RegExp(`(?<![${LT}])(${alt(Object.keys(CURRENCY))})\\s?/\\s?(${alt(Object.keys(CURRENCY))})(?![${LT}])`, "g"); | |
| const TIME = new RegExp(`(?<![\\d.,])(\\d{1,2})[hg](\\d{2})?(?![${LT}\\d])`, "g"); | |
| const UNIT = new RegExp(`(?<=\\d)\\s?(${alt(Object.keys(UNITS))})(?![${LT}\\d²³])`, "g"); | |
| const TITLE = new RegExp(`(?<![${LT}])(TP|Tp|PGS|GS|TS|ThS|BS|KTS|LS|NSND|NSƯT)\\.\\s?(?=[${LT}])`, "g"); | |
| const WORD = new RegExp(`[${LT}]+`, "g"); | |
| const PER_LEFT = new Set(["đ", "đồng", "la", "rô", "Anh", "yên", "tệ"]); | |
| const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k); | |
| function isSyllable(word) { | |
| return SYLLABLE_RE.test(stripTone(word)[0]); | |
| } | |
| function fracWords(digits) { | |
| if (digits.startsWith("0") || digits.length > 2) return [...digits].map((c) => DIGITS_VI[Number(c)]).join(" "); | |
| return numberToWords(Number(digits)); | |
| } | |
| function expandSymbols(s) { | |
| s = s.replace(CUR_PRE, (_, sign, num, mag) => { | |
| if (/^\d{1,3}(?:,\d{3})+(?:\.\d{1,2})?$/.test(num)) num = num.replaceAll(",", "\0").replaceAll(".", ",").replaceAll("\0", "."); | |
| return `${num}${mag || ""} ${SYMBOL_CURRENCY[sign]}`; | |
| }); | |
| s = s.replace(CUR_SUF, (_, sign) => " " + SYMBOL_CURRENCY[sign]); | |
| s = s.replace(PAIR, (_, a, b) => `${CURRENCY[a]} ${CURRENCY[b]}`); | |
| s = s.replace(SLASH, (m, left, right) => { | |
| if (!has(UNITS, left) && !has(CURRENCY, left) && !PER_LEFT.has(left)) return m; | |
| if (has(UNITS, left + "/" + right)) return m; | |
| return left + (has(UNITS, left) ? " trên " : " một ") + (has(UNITS, right) ? UNITS[right] : has(ENGLISH, right) ? ENGLISH[right] : right); | |
| }); | |
| s = s.replace(TIME, (_, h, mi) => `${h} giờ` + (mi && Number(mi) ? ` ${mi}` : "")); | |
| s = s.replace(UNIT, (_, u) => " " + UNITS[u]); | |
| s = s.replace(/(?<!\d)(?<!\d\.)(\d+)\.(\d{1,2})(?![\d.,])/g, (_, w, f) => `${w} chấm ${fracWords(f)}`); | |
| s = s.replace(/(?<=[A-Za-zĐ])-?(?=\d)|(?<=\d)(?=[A-Za-zĐ])/g, " "); | |
| s = s.replace(/(?<![A-Za-zÀ-ỹ])TP\.?\s?HCM(?![A-Za-zÀ-ỹ])/g, ABBREV.TPHCM); | |
| return s.replace(TITLE, (_, t) => ABBREV[t] + " "); | |
| } | |
| const F_BASE = { ø: "o", æ: "e", œ: "e", ß: "s", ł: "l", ð: "đ", þ: "t", ı: "i" }; | |
| const F_V = "aăâeêioôơuưy"; | |
| const TONE_MARK = ["", "", "̀", "́", "̉", "̃", "̣"]; | |
| const isV = (c) => c !== undefined && c !== "" && F_V.includes(c); | |
| function addTone(syl, tone) { | |
| if (tone < 2) return syl; | |
| let vs = [...syl].map((ch, i) => (isV(ch) ? i : -1)).filter((i) => i >= 0); | |
| if (syl.startsWith("qu") && vs.length > 1) vs = vs.slice(1); | |
| let i = vs[0]; | |
| for (const j of vs) if ("ăâêôơư".includes(syl[j])) i = j; | |
| if (vs.length > 1 && "ou".includes(syl[vs[0]]) && "aey".includes(syl[vs[1]]) && i === vs[0]) i = vs[1]; | |
| return (syl.slice(0, i + 1) + TONE_MARK[tone] + syl.slice(i + 1)).normalize("NFC"); | |
| } | |
| function respellForeign(word) { | |
| let chars = []; | |
| for (const ch of word.toLowerCase().normalize("NFC")) { | |
| let [base, tone] = stripTone(ch); | |
| if (!has(F_ONSET, base) && !isV(base)) base = F_BASE[base] || base.normalize("NFD").slice(0, 1); | |
| if (isV(base)) chars.push([base, tone]); | |
| else if (has(F_ONSET, base)) chars.push([base, 1]); | |
| } | |
| const plain = chars.map((c) => c[0]).join(""); | |
| if (chars.length > 3 && chars[chars.length - 1][1] === 1 && F_SILENT_E.test(plain) && [...plain.slice(0, -1)].some(isV)) chars = chars.slice(0, -1); | |
| const src = chars; | |
| chars = src.filter((c, i) => !(i && c[0] === src[i - 1][0] && !isV(c[0]))); | |
| const text = chars.map((c) => c[0]).join(""); | |
| const segs = []; | |
| const n = text.length; | |
| let i = 0; | |
| while (i < n) { | |
| const ch = text[i]; | |
| if (isV(ch) && !(ch === "y" && i + 1 < n && isV(text[i + 1]) && (!segs.length || segs[segs.length - 1][0] === "V"))) { | |
| const two = text.slice(i, i + 2); | |
| const ok = two.length === 2 && has(F_VOWELS, two) && !("wy".includes(two[1]) && i + 2 < n && isV(text[i + 2])) && !(two === "ie" && i + 2 < n) && !(two === "ea" && i + 2 === n); | |
| const size = ok ? 2 : 1; | |
| segs.push(["V", F_VOWELS[text.slice(i, i + size)], Math.max(...chars.slice(i, i + size).map((c) => c[1]))]); | |
| i += size; | |
| continue; | |
| } | |
| let unit = ""; | |
| for (const size of [4, 3, 2, 1]) { | |
| unit = text.slice(i, i + size); | |
| if (unit.length === size && has(F_ONSET, unit)) break; | |
| } | |
| if (unit === "qu" && !(i + 2 < n && isV(text[i + 2]))) unit = "q"; | |
| if (unit === "gi" && !(i + 2 < n && isV(text[i + 2]))) unit = "g"; | |
| if (unit === "c" && i + 1 < n && "eêiy".includes(text[i + 1])) unit = "ç"; | |
| segs.push(["C", unit, 1]); | |
| i += unit === "q" || unit === "ç" ? 1 : unit.length; | |
| } | |
| if (!segs.some((x) => x[0] === "V")) return null; | |
| if (segs.filter((x) => x[0] === "V").length > 1) for (const x of segs) x[2] = 1; | |
| let clean = true; | |
| const syls = []; | |
| let pending = []; | |
| for (let [kind, val, tone] of segs) { | |
| if (kind === "C") { pending.push(val); continue; } | |
| const onset = pending.length ? pending.pop() : ""; | |
| if (pending.length && syls.length && syls[syls.length - 1][2] === "") { | |
| const first = pending.shift(); | |
| syls[syls.length - 1][2] = F_CODA[first] ?? ""; | |
| if (syls[syls.length - 1][2] === "") clean = false; | |
| if (["m", "n", "ng"].includes(syls[syls.length - 1][2]) && onset !== "r" && onset !== "l") { | |
| const rest = pending.filter((u) => !["d", "t", "p"].includes(u)); | |
| clean = clean && rest.length === pending.length; | |
| pending = rest; | |
| } | |
| } | |
| for (const u of pending) { | |
| const w = F_ONSET[u]; | |
| syls.push(w === "y" ? ["", "i", "", 1] : w === "w" ? ["", "u", "", 1] : [w === "k" ? "c" : w, "ơ", "", 2, true]); | |
| clean = false; | |
| } | |
| pending = []; | |
| let o = onset ? F_ONSET[onset] : ""; | |
| if (o === "y") { | |
| if (val !== "i") syls.push(["", "i", "", 1]); | |
| o = ""; | |
| } else if (o === "w") { | |
| const glide = ({ a: "oa", ai: "oai", ê: "oe", i: "uy", u: "u", ây: "uây" })[val]; | |
| if (glide) { o = ""; val = glide; } else o = "v"; | |
| } else if (o === "g" && "eêi".includes(val[0])) o = "gh"; | |
| else if (o === "qu" && val[0] === "u") o = "k"; | |
| syls.push([o, val, "", tone]); | |
| } | |
| if (pending.length) { | |
| const first = pending.shift(); | |
| const last = syls[syls.length - 1]; | |
| if (first === "r" && last[1] === "ê") last[1] = "ơ"; | |
| else if (first !== "r") { | |
| last[2] = F_CODA[first] ?? ""; | |
| clean = clean && last[2] !== ""; | |
| } | |
| if (pending.length) clean = false; | |
| } | |
| const out = []; | |
| for (let [o, v, c, tone] of syls) { | |
| if (c) { | |
| if (v.length === 1 || v === "oa" || v === "oe" || v === "uy") { | |
| v = F_CLOSED[v] ?? v; | |
| if ("iy".includes(v[v.length - 1]) || v === "ê") c = c === "ng" ? "nh" : c === "c" ? "ch" : c; | |
| else if (c === "nh" && !"ae".includes(v[v.length - 1])) c = "n"; | |
| } else { c = ""; clean = false; } | |
| } | |
| if (["p", "t", "c", "ch"].includes(c) && tone !== 3 && tone !== 6) tone = 3; | |
| out.push(addTone(o + v + c, tone)); | |
| } | |
| return [guessStress(out, syls.map((x) => x.length > 4)), clean]; | |
| } | |
| // English words respelled in Vietnamese (web/en_lexicon.js; optional, without it unknown words use letter rules) | |
| const EN = new Map(); | |
| function setEnglishLexicon(text) { | |
| EN.clear(); | |
| for (const p of text.split(";")) { | |
| const k = p.indexOf("="); | |
| if (k > 0) EN.set(p.slice(0, k), p.slice(k + 1)); | |
| } | |
| } | |
| if (typeof module !== "undefined" && module.exports) { try { setEnglishLexicon(require("./en_lexicon.js")); } catch (_) {} } | |
| else if (root.TINYVOCA_EN) setEnglishLexicon(root.TINYVOCA_EN); | |
| // Stress inside one foreign word: syllables are tied with "‿"; "↑" main stress, "→" secondary, "↓" inserted weak vowel, none = unstressed | |
| const MARKS = { " ": "‿", "'": "↑", "-": "→", "`": "↓" }; | |
| const tie = (stored) => (stored.includes(" ") ? stored.replace(/[ '`-]/g, (c) => MARKS[c]) : stored); | |
| // Latin rule over the full syllables: the second-last if heavy (closed or diphthong), otherwise the one before it. | |
| function guessStress(syls, weak) { | |
| const full = syls.map((_, i) => i).filter((i) => !weak[i]); | |
| if (syls.length < 2 || !full.length) return syls.join(" "); | |
| let k = 0; | |
| if (full.length > 2) { | |
| k = full.length - 2; | |
| if (stripTone(syls[full[k]])[0].replace(new RegExp(`^(?:qu|gi(?=[${F_V}])|[^${F_V}]*)`), "").length < 2) k -= 1; | |
| } | |
| return tie(syls.map((x, i) => (weak[i] ? "`" : i === full[k] ? "'" : "") + x).join(" ")); | |
| } | |
| function curated(low) { | |
| if (!has(ENGLISH, low)) return undefined; | |
| const v = ENGLISH[low]; | |
| if (!v.includes(" ") || NO_STRESS.includes(low)) return v; | |
| if (/['`-]/.test(v)) return tie(v); | |
| const syls = v.split(" "); | |
| const weak = syls.map((x, i) => i + 1 < syls.length && (x === "sờ" || (/(?:[bcgđp]|ph|th)ờ$/.test(x) && "lr".includes(syls[i + 1][0])))); | |
| for (let i = 0; i < syls.length; i++) { // Vietnamese words (cà phê, việt nam) are not stressed | |
| const x = syls[i]; | |
| if (!weak[i] && ![1, 3].includes(stripTone(x)[1]) && !((i + 1 === syls.length && "ờồ".includes(x.slice(-1))) || ["ần", "ừn"].includes(x.slice(-2)))) return v; | |
| } | |
| return guessStress(syls, weak); | |
| } | |
| function english(low) { | |
| const v = curated(low) ?? EN.get(low); | |
| return v === undefined || v.includes("‿") || has(ENGLISH, low) ? v : tie(v); | |
| } | |
| // Accented spelling (José) or a compound of two known words (livescore). | |
| function englishParts(low) { | |
| let r = undefined; | |
| if ([...low].length >= 4 && /[a-z]$/.test(low) && !/[ăâđêôơư]/.test(stripTone(low)[0].normalize("NFC"))) { | |
| const plain = low.normalize("NFD").replace(/[\u0300-\u036f]/g, ""); | |
| if (plain !== low) r = english(plain); | |
| } | |
| if (r || !/^[a-z]{7,}$/.test(low)) return r; | |
| let best = 0; | |
| for (let i = 3; i < low.length - 2; i++) { | |
| const a = english(low.slice(0, i)), b = english(low.slice(i)); | |
| const short = Math.min(i, low.length - i); | |
| if (a && b && short > best && [low.slice(0, i), low.slice(i)].every((p) => p.length > 3 || SHORT_PARTS.includes(p))) { | |
| r = a + " " + b; | |
| best = short; | |
| } | |
| } | |
| return r; | |
| } | |
| function readUnknown(w) { | |
| if (isSyllable(w) || w.length < 2) return w; | |
| const known = englishParts(w.toLowerCase()); | |
| if (known) return known; | |
| const r = respellForeign(w); | |
| if (r) return r[0]; | |
| const ls = [...w.toLowerCase()].map((ch) => stripTone(ch)[0]); | |
| if (w.length <= 4 && ls.every((c) => has(LETTERS, c))) return ls.map((c) => LETTERS[c]).join(" "); | |
| return w; | |
| } | |
| function oneWord(w) { | |
| return (has(ABBREV, w) && ABBREV[w]) || english(w.toLowerCase()) || readUnknown(w); | |
| } | |
| function expandWords(s) { | |
| s = s.replace(/(?<=[A-Za-z])[’'][sS](?![A-Za-zÀ-ỹ])/g, ""); // McDonald's | |
| s = s.replace(/(?<=[nN])[’'](?=[tT](?![A-Za-zÀ-ỹ]))/g, ""); // don't | |
| const shouting = !/\p{Ll}/u.test(s); | |
| return s.replace(WORD, (w) => { | |
| const syll = isSyllable(w); | |
| if (!(shouting && syll)) { | |
| if (has(CURRENCY, w)) return CURRENCY[w]; | |
| if (has(ABBREV, w)) return ABBREV[w]; | |
| } | |
| const low = w.toLowerCase(); | |
| if (has(ENGLISH, low)) return curated(low); | |
| // short unknown all-caps words are abbreviations, not English words | |
| if (EN.has(low) && !(w === w.toUpperCase() && w !== low && w.length <= 3 && !syll)) return tie(EN.get(low)); | |
| if (w === w.toUpperCase() && w !== low && w.length <= 6 && !syll) { | |
| const r = w.length >= 4 ? respellForeign(w) : null; | |
| if (r && r[1]) return r[0]; | |
| return [...low].map((ch) => LETTERS[stripTone(ch)[0]] ?? ch).join(" "); | |
| } | |
| const parts = w.match(/[A-ZĐ]?[^A-ZĐ]+|[A-ZĐ]+(?![^A-ZĐ])/g) ?? []; | |
| if (parts.length > 1 && w.length > 4 && parts.join("") === w && parts.every((p) => p.length > 1)) return parts.map(oneWord).join(" "); | |
| return readUnknown(w); | |
| }); | |
| } | |
| // Turn layout and brackets into punctuation the model can pause on. | |
| function pauseMarks(s) { | |
| const low = (ch) => ch !== "" && ch.toLowerCase() === ch && ch.toUpperCase() !== ch; | |
| s = s.replaceAll("\r\n", "\n").replaceAll("\r", "\n").trim(); | |
| s = s.replace(/(?:^|(?<=\n))[ \t]*[-*•+–—][ \t]+/g, "•"); | |
| if (s.startsWith("•")) s = s.slice(1); | |
| s = s.replace(/([^\s•])([ \t]*\n[\s•]*)([^\s•])/g, (_, prev, brk, nxt) => { | |
| if (".,;:?!—…".includes(prev)) return prev + " " + nxt; | |
| return prev + (low(nxt) && brk.split("\n").length === 2 && !brk.includes("•") ? " " : ". ") + nxt; | |
| }); | |
| s = s.replace(/•/g, " "); | |
| s = s.replace(/(?<![A-Za-zÀ-ỹ])[vV]\.\s?[vV]\.?(?![A-Za-zÀ-ỹ])/g, "vân vân"); | |
| s = s.replace(/(?:…|\.{2,})(\s*)(\S?)/g, (_, _w, n) => (n ? (low(n) ? ", " : ". ") + n : ".")); | |
| s = s.replace(/(?<![A-Za-zÀ-ỹ])([A-ZĐ])\.(?=\s?[A-ZĐ])/g, "$1 "); | |
| s = s.replace(/(?<=\s)[-–—](?=\s)/g, "—"); | |
| s = s.replace(/(?<![\p{L}\p{N}_.,/–—-])([0-9]+(?:[.,][0-9]+)*)\s?[-–]\s?([0-9]+(?:[.,][0-9]+)*)(?![\p{L}\p{N}_/–—-]|[.,][0-9])/gu, (m, a, b) => | |
| Number(a.replaceAll(".", "").replaceAll(",", ".")) < Number(b.replaceAll(".", "").replaceAll(",", ".")) ? `${a} đến ${b}` : m); | |
| s = s.replace(/\s*[(\[{]\s*/g, ", "); | |
| s = s.replace(/\s*[)\]}]/g, ","); | |
| s = s.replace(/\s+([,.;:?!])/g, "$1"); | |
| s = s.replace(/,(?:\s*,)+/g, ","); | |
| s = s.replace(/,\s*([.;:?!—])/g, "$1"); | |
| s = s.replace(/([.;:?!—])\s*,/g, "$1"); | |
| s = s.replace(/,(?=[^\s\d])/g, ", "); | |
| return s.replace(/^[,\s]+/, ""); | |
| } | |
| function normalizeText(text) { | |
| let s = text.normalize("NFC") | |
| .replace(/[\u00d0\u0189]/g, "Đ").replace(/[\u00f0\u0256]/g, "đ") | |
| .replace(/[\u00ad\u200b-\u200d\u2060\ufeff]/g, "") | |
| ; | |
| s = pauseMarks(s).replaceAll("–", "—") | |
| .replaceAll("“", "").replaceAll("”", "").replaceAll('"', ""); | |
| s = s.replace(/(ngày\s+)?\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/gi, (_, p, d, mo, y) => | |
| `${p || "ngày "}${numberToWords(Number(d))} tháng ${numberToWords(Number(mo))} năm ${numberToWords(Number(y))}`); | |
| s = expandSymbols(s); | |
| s = s.replace(/\b(\d+(?:\.\d{3})*)(?:,(\d+))?%/g, (_, w, f) => { | |
| const whole = Number(w.replaceAll(".", "")); | |
| if (f) { | |
| return `${numberToWords(whole)} phẩy ${fracWords(f)} phần trăm`; | |
| } | |
| return `${numberToWords(whole)} phần trăm`; | |
| }); | |
| s = s.replace(/(?<![\d.,])(\d+(?:\.\d{3})*)(?:,(\d+))?\s?(?:đ|VND|VNĐ)(?![A-Za-zÀ-ỹà-ỹ])/g, (_, w, f) => | |
| `${numberToWords(Number(w.replaceAll(".", "")))}${f ? " phẩy " + fracWords(f) : ""} đồng`); | |
| s = s.replace(/\b(\d+(?:\.\d{3})*),(\d+)\b/g, (_, w, f) => | |
| `${numberToWords(Number(w.replaceAll(".", "")))} phẩy ${fracWords(f)}`); | |
| s = s.replace(/\b\d{1,3}(?:\.\d{3})+\b|\b\d+\b/g, (m) => { | |
| const raw = m.replaceAll(".", ""); | |
| if (raw.length > 12) return [...raw].map((c) => DIGITS_VI[Number(c)]).join(" "); | |
| return numberToWords(Number(raw)); | |
| }); | |
| s = expandWords(s); | |
| return s.replace(/\s+/g, " ").trim(); | |
| } | |
| function phonemizeSyllable(raw) { | |
| const low = raw.toLowerCase().normalize("NFC"); | |
| if (low in OVERRIDES) return [...OVERRIDES[low]]; | |
| const [base, tone] = stripTone(low); | |
| if (!base) return []; | |
| const out = []; | |
| let rest = base; | |
| let medialW = false; | |
| if (rest === "gi" || (rest.startsWith("gi") && rest.length > 2 && !VOWEL_CHARS.includes(rest[2]))) { | |
| out.push(["z", tone, 0]); | |
| rest = "i" + rest.slice(2); | |
| } else if (rest.startsWith("giê")) { | |
| out.push(["z", tone, 0]); | |
| rest = "iê" + rest.slice(3); | |
| } else { | |
| for (const [pat, ph] of ONSET_RULES) { | |
| if (rest.startsWith(pat)) { | |
| if (ph === "kw") { | |
| out.push(["k", tone, 0]); | |
| medialW = true; | |
| rest = rest.slice(pat.length); | |
| if (!rest || !VOWEL_CHARS.includes(rest[0])) { | |
| medialW = false; | |
| rest = "u" + rest; | |
| } | |
| } else { | |
| out.push([ph, tone, 0]); | |
| rest = rest.slice(pat.length); | |
| } | |
| break; | |
| } | |
| } | |
| } | |
| if (!rest) return out; | |
| let coda = null; | |
| for (const [pat, ph] of CODA_RULES) { | |
| if (rest.endsWith(pat) && rest.length > pat.length) { | |
| coda = ph; | |
| rest = rest.slice(0, -pat.length); | |
| break; | |
| } | |
| } | |
| if (!medialW && rest.length >= 2) { | |
| if (rest[0] === "o" && "aăe".includes(rest[1])) { | |
| medialW = true; | |
| rest = rest.slice(1); | |
| } else if (rest[0] === "u" && "âêơy".includes(rest[1])) { | |
| medialW = true; | |
| rest = rest.slice(1); | |
| } | |
| } | |
| if (coda === null && rest.length >= 2) { | |
| if (rest === "iêu" || rest === "yêu") { rest = "iê"; coda = "w"; } | |
| else if (rest === "ươi") { rest = "ươ"; coda = "j"; } | |
| else if (rest === "ươu") { rest = "ươ"; coda = "w"; } | |
| else if (rest === "uôi") { rest = "uô"; coda = "j"; } | |
| else if (rest === "uyê") { /* keep */ } | |
| else if ((rest.endsWith("i") || rest.endsWith("y")) && !J_RHYMES.has(rest)) { | |
| if (J_PREFIX.has(rest.slice(0, -1))) { coda = "j"; rest = rest.slice(0, -1); } | |
| } else if (J_RHYMES.has(rest)) { | |
| coda = "j"; | |
| rest = rest === "ay" ? "ă" : rest.slice(0, -1); | |
| } else if (W_RHYMES.has(rest)) { | |
| coda = "w"; | |
| rest = rest === "au" ? "ă" : rest.slice(0, -1); | |
| } else if (rest === "uya") { | |
| medialW = true; | |
| rest = "iê"; | |
| } | |
| } | |
| const nuc = rest === "a" && (coda === "ɲ" || coda === "c") ? "ɛ" : NUCLEUS_MAP[rest]; | |
| if (medialW) out.push(["w", tone, 1]); | |
| if (nuc) out.push([nuc, tone, 1]); | |
| else { | |
| for (const ch of rest) { | |
| if (NUCLEUS_MAP[ch]) out.push([NUCLEUS_MAP[ch], tone, 1]); | |
| } | |
| } | |
| if (coda !== null) out.push([coda, tone, 2]); | |
| return out; | |
| } | |
| const TOKEN_SPLIT_RE = /([↑↓→]?)([A-Za-zÀ-ỹà-ỹ]+)(‿?)|([,.;:!?—])/g; | |
| // level -> [onset, vowel, coda duration, pitch in semitones, energy] | |
| const STRESS_TABLE = { 1: [1.15, 1, 1, 1.5, 0.3], 2: [0.75, 0.45, 0.5, -0.8, -0.3], 3: [0.65, 0.35, 0.35, -0.8, -0.6], 5: [0.8, 1, 1, -0.8, -0.3] }; | |
| const STRESS_LEVEL = { "↑": 1, "→": 0, "↓": 3, "": 2 }; | |
| // Flat [duration factor, pitch offset, energy offset] per token for the model's `stress` input. | |
| function stressFeatures(utt, amount = 1) { | |
| return utt.stress.flatMap((level, i) => { | |
| const row = STRESS_TABLE[level]; | |
| if (!row) return [level === 4 && amount > 0 ? 0 : 1, 0, 0]; | |
| return [Math.max(0.3, 1 + (row[utt.sylPos[i]] - 1) * amount), row[3] * amount, row[4] * amount]; | |
| }); | |
| } | |
| function phonemize(text) { | |
| const normalizedText = normalizeText(text); | |
| const symbols = ["<bos>"]; | |
| const toneIds = [0]; | |
| const sylPos = [3]; | |
| const stress = [0]; // 0 neutral, 1 main stress, 2 unstressed, 3 weak, 4 gap inside a foreign word, 5 unstressed at the end | |
| let prevWasWord = false; | |
| let tied = false; // previous syllable belongs to the same foreign word | |
| for (const [, mark, piece, tieMark, punct] of normalizedText.matchAll(TOKEN_SPLIT_RE)) { | |
| if (punct) { | |
| symbols.push(punct); toneIds.push(0); sylPos.push(3); stress.push(0); | |
| prevWasWord = tied = false; | |
| } else { | |
| if (prevWasWord) { symbols.push("<sp>"); toneIds.push(0); sylPos.push(3); stress.push(tied ? 4 : 0); } | |
| const level = tied || tieMark ? (mark === "" && !tieMark ? 5 : STRESS_LEVEL[mark]) : 0; | |
| tied = Boolean(tieMark); | |
| for (const [ph, t, pos] of phonemizeSyllable(piece)) { | |
| if (ph in SYMBOL_TO_ID) { symbols.push(ph); toneIds.push(t); sylPos.push(pos); stress.push(level); } | |
| } | |
| prevWasWord = true; | |
| } | |
| } | |
| symbols.push("<eos>"); toneIds.push(0); sylPos.push(3); stress.push(0); | |
| return { | |
| symbols, | |
| phonemeIds: symbols.map((s) => SYMBOL_TO_ID[s]), | |
| toneIds, | |
| sylPos, | |
| stress, | |
| normalizedText, | |
| }; | |
| } | |
| // Natural Vietnamese syntactic break words (conjunctions / prepositions) for emergency splits | |
| // of very long unpunctuated clauses (> 35 syllables), so we never chop inside 2-syllable compounds | |
| // like "ủng hộ", "tổ chức", "thành công". | |
| const BREAK_BEFORE = new Set([ | |
| "và", "nhưng", "tuy", "để", "khi", "nếu", "vì", "bởi", "mà", "rằng", | |
| "trong", "tại", "với", "cho", "theo", "trên", "dưới", "sau", "trước", "cùng", | |
| ]); | |
| function splitLongClause(clause, maxWords) { | |
| const words = clause.split(/\s+/); | |
| if (words.length <= maxWords) return [clause]; | |
| const parts = []; | |
| let start = 0; | |
| while (start < words.length) { | |
| if (words.length - start <= maxWords) { | |
| parts.push(words.slice(start).join(" ")); | |
| break; | |
| } | |
| // Search backward from start+maxWords down to start+maxWords/2 for a safe function-word boundary | |
| let cut = start + maxWords; | |
| const minCut = start + Math.max(6, Math.floor(maxWords * 0.55)); | |
| for (let i = Math.min(start + maxWords, words.length - 2); i >= minCut; i--) { | |
| const clean = words[i].toLowerCase().replace(/^[,.;:!?—]+|[,.;:!?—]+$/g, ""); | |
| if (BREAK_BEFORE.has(clean)) { | |
| cut = i; | |
| break; | |
| } | |
| } | |
| parts.push(words.slice(start, cut).join(" ")); | |
| start = cut; | |
| } | |
| return parts; | |
| } | |
| // Split text cleanly at sentence/clause punctuation ONLY (never blindly mid-word). | |
| // Short first chunk splits at the first real punctuation mark (comma/semicolon/colon) when available; | |
| // clauses up to ~38 syllables stay intact so 2-syllable Vietnamese compounds are never split. | |
| function chunkText(text, firstMaxWords = 14, maxWords = 38) { | |
| const norm = normalizeText(text); | |
| if (!norm) return []; | |
| const rawSents = norm.split(/(?<=[.!?])\s+/).map((s) => s.trim()).filter(Boolean); | |
| const chunks = []; | |
| for (let sIdx = 0; sIdx < rawSents.length; sIdx++) { | |
| let sent = rawSents[sIdx]; | |
| if (!/[.!?]$/.test(sent)) sent += "."; | |
| const sentWords = sent.split(/\s+/); | |
| // Keep normal sentences intact when not first chunk (or when already short) | |
| const isFirst = chunks.length === 0; | |
| if (sentWords.length <= (isFirst ? firstMaxWords : maxWords)) { | |
| chunks.push(sent); | |
| continue; | |
| } | |
| // Split on real clause punctuation (, ; : —) first | |
| const clauses = sent.split(/(?<=[,;:—])\s+/).map((c) => c.trim()).filter(Boolean); | |
| if (clauses.length > 1) { | |
| let buf = []; | |
| for (const clause of clauses) { | |
| const cw = clause.split(/\s+/); | |
| const cap = chunks.length === 0 ? firstMaxWords : maxWords; | |
| if (buf.length > 0 && buf.length + cw.length > cap) { | |
| chunks.push(buf.join(" ")); | |
| buf = []; | |
| } | |
| // Recompute cap AFTER flushing buf! | |
| const curCap = chunks.length === 0 ? firstMaxWords : maxWords; | |
| if (cw.length > curCap) { | |
| if (buf.length > 0) { chunks.push(buf.join(" ")); buf = []; } | |
| chunks.push(...splitLongClause(clause, maxWords)); | |
| } else { | |
| buf.push(...cw); | |
| } | |
| } | |
| if (buf.length > 0) chunks.push(buf.join(" ")); | |
| } else { | |
| // Single unpunctuated sentence: only split if truly long (> maxWords) using syntactic boundaries | |
| chunks.push(...splitLongClause(sent, maxWords)); | |
| } | |
| } | |
| return chunks.filter((c) => /[A-Za-zÀ-ỹà-ỹ]/.test(c)); | |
| } | |
| const api = { SYMBOLS, SYMBOL_TO_ID, normalizeText, phonemizeSyllable, phonemize, chunkText, setEnglishLexicon, stressFeatures }; | |
| if (typeof module !== "undefined" && module.exports) module.exports = api; | |
| root.TinyVocaG2P = api; | |
| })(typeof self !== "undefined" ? self : globalThis); | |