Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : SP Keyboard10# File : Scripts/build_lexicons.py11# Description : Rebuilds Resources/Lexicons/{fr,en,es}.lex and12# {fr,en,es}.bigrams reproducibly. Word lists:13# hermitdave/FrequencyWords 2018 (CC-BY-SA-4.0, derived from14# OpenSubtitles 2018), filtered with the macOS spell15# checker, plus hand-written supplements (Quebec French,16# English contractions) and hand-written bigram tables. See17# docs/LEXICONS.md. usage: build_lexicons.py [--offline]18# [--stats]19# Module : Scripts20# Repository : https://git.spboucher.ai/sp-keyboard21# Created : 2026-12-0122# Last Modified : 2026-12-0123#24# =============================================================================25# AUTHOR & PROFESSIONAL AFFILIATION26# =============================================================================27#28# Author : Simon-Pierre Boucher29# Position : Professor of Finance30# Institution : Université du Québec en Outaouais (UQO)31# Department : Département des sciences administratives32# Organization : SP Boucher33#34# Website : https://spboucher.ai35# Git : https://git.spboucher.ai36#37# =============================================================================38# OFFICIAL CONTACT DIRECTORY39# =============================================================================40#41# General : info@spboucher.ai42# Professional : contact@spboucher.ai43# Direct : simon@spboucher.ai44# Research : research@spboucher.ai45# Development : dev@spboucher.ai46# Support : support@spboucher.ai47# Security/Admin : admin@spboucher.ai48# Notifications : notifications@spboucher.ai49#50# Preferred Contact: support@spboucher.ai51#52# =============================================================================53# COPYRIGHT & INTELLECTUAL PROPERTY54# =============================================================================55#56# Copyright (c) 202657# Simon-Pierre Boucher58#59# All rights reserved where applicable.60#61# This file is governed by the applicable project license,62# copyright notices, institutional agreements and relevant law.63#64# Unless expressly authorized by the applicable license or65# rights holder, copying, redistribution, sublicensing,66# publication and commercial exploitation are not permitted.67#68# Existing third-party rights and notices remain unaffected.69#70# =============================================================================71# CONFIDENTIALITY & SECURITY72# =============================================================================73#74# Classification : Public75# Distribution : Public repository; use is governed by the project license76# Security Contact : admin@spboucher.ai77#78# Access to this source does not independently grant permission79# to redistribute or disclose confidential materials.80#81# Do not embed credentials, private keys, access tokens,82# certificates or confidential personal information.83#84# =============================================================================85# LICENSE & MAINTENANCE86# =============================================================================87#88# License : None specified (no license file in this repository)89# Maintainer : Simon-Pierre Boucher90# Technical Contact: dev@spboucher.ai91#92# =============================================================================93# END OF SP BOUCHER SOURCE HEADER94# =============================================================================9596import json97import os98import subprocess99import sys100import unicodedata101import urllib.request102103ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))104CACHE = os.path.join(ROOT, "Scripts", ".lexicon-cache")105OUT = os.path.join(ROOT, "Resources", "Lexicons")106SOURCE = "https://raw.githubusercontent.com/hermitdave/FrequencyWords/master/content/2018/{l}/{l}_50k.txt"107LANGS = ["fr", "en", "es"]108TARGET_WORDS = 30000109MIN_COUNT = 40 # occurrences in the source corpus below which a token is ignored110111LETTERS = {112 "fr": set("abcdefghijklmnopqrstuvwxyzàâäæçéèêëîïôöœùûüÿ"),113 "en": set("abcdefghijklmnopqrstuvwxyz"),114 "es": set("abcdefghijklmnopqrstuvwxyzáéíóúüñ"),115}116ONE_LETTER = {"fr": {"a", "à", "y", "ô"}, "en": {"a", "i"}, "es": {"a", "e", "o", "u", "y"}}117118# Tokens the subtitle tokenizer produced by splitting contractions ("don't" -> "don" + "'t"): their counts are artefacts.119EN_DROP = {"don", "doesn", "didn", "isn", "wasn", "aren", "weren", "couldn", "wouldn", "shouldn", "hasn", "haven",120 "hadn", "ain", "ll", "ve", "re", "il", "im", "th", "st", "nd", "rd", "mr", "mrs", "dr", "ok", "tv",121 "gon", "na", "wan", "ta", "em", "er", "uh", "um", "hmm", "mm", "ah", "eh", "oh", "ooh", "aah", "huh", "shh",122 "la", "le", "de", "da", "un", "el", "et", "en", "es", "se", "si", "du", "que", "des", "les", "une",123 # contractions typed without their apostrophe: accepted by the spell checker, wanted as corrections instead124 "thats", "dont", "cant", "wont", "ive", "youre", "theyre", "whats", "hes", "shes", "isnt", "arent",125 "didnt", "doesnt", "wasnt", "werent", "couldnt", "wouldnt", "shouldnt", "havent", "hasnt", "hadnt",126 "theres", "heres", "wheres", "youll", "youve", "weve", "theyll", "theyve"}127FR_DROP = {"ok", "ah", "oh", "eh", "hé", "euh", "hein", "hum", "mm", "hmm", "ouh", "aah", "ooh", "uh", "the", "you",128 "and", "of", "to", "is", "it", "my", "that", "what", "this", "for", "be", "are", "was", "love",129 "all", "one", "we", "he", "she", "they", "with", "have", "not", "your", "yes", "mr", "mrs", "dr",130 "st", "th", "na", "da", "el", "hi", "yeah", "hey", "baby", "ii", "iii", "xx", "tv"}131ES_DROP = {"ok", "ah", "oh", "eh", "uh", "mm", "hmm", "the", "you", "and", "of", "to", "is", "it", "my", "in", "that",132 "what", "this", "for", "be", "are", "was", "all", "we", "he", "she", "they", "with", "have", "not", "your",133 "yes", "mr", "mrs", "dr", "st", "th", "ii", "iii", "xx", "tv", "hey", "yeah", "baby", "love"}134# Genuine French / Spanish words (or everyday Quebec anglicisms) that are far more frequent in the English corpus and135# would otherwise be removed as English noise. Hand-reviewed from the filter's own rejection list.136FR_RESCUE = set("""an long or but excuse course second mine top front job miles figure do lot four local record continues137extra social fun case pop regret location stage positive parts cure weekend mate laid post sentence grade promise palace138court lie massive serve assume tank pair pet mention plate motion habit offense tend bug strip pack abuse pass plane139sorts pie constant cake distant senior gain patch hit motive figures bin exam ride us fit sale stop go show team boss140business cash crash design party sex golf star stars relax cool fan club tennis match football notice staff dude row141report truck cut cases pen press drag bit jump command pal lots mass fed pool cute bet trash pay smart card led tone142lies plastic goal gas jacket tip lock cab cos hits lift plant flat fake count trail cover quarter guard shop shooting143games lunch kick coffee phone online focus cell standing fashion lead share target player slow living speech if so144me in on son pour main pain car note date table simple air point place page image message village force service145police train route minute moment action question nation station situation position condition attention direction146information solution opinion religion union mission passion version vision occasion prison chance change charge danger147double fruit film sport taxi piano radio photo menu final total normal original central animal capital cruel principal148national international style type test signal journal canal festival budget ticket concert accident agent client149parent patient excellent innocent instant important restaurant silence science absence distance importance assurance150alliance ambulance patience violence justice prince machine routine cuisine magazine discipline surprise base phase151phrase pause cause rose pose dose chose source""".split())152ES_RESCUE = set("""don come show do once as use hall pop top test quite bus set film cool tour prepare post data ring153place manager imagine record usual tires strike note light vice alien bro master fine per drag series coach cause dad154serial express round ticket temple chips invite bowl cookie hop reality aliens chat dance yen swing parking closet155cure mouse ye prime vote mail cowboy dark hit arrow tickets mister stand pin films click declare pen tech prior156instrumental trailer aha burger examine link plus bug strip status yay sketch puzzle camp argh ton stock resume twist157rally rolls complete ruin ate fly tip ignore pee cos led cave sec performance target fashion shopping card excuse158affair check match lay staff split tape track weekend gym slip switch me la el en es se si un no sin son mi tu te lo159los las una le les real general final total normal animal capital hotel hospital doctor director actor color error160honor humor motor favor terror horror superior interior exterior mayor menor mejor peor idea persona""".split())161RESCUE = {"fr": FR_RESCUE, "en": set(), "es": ES_RESCUE}162EN_PROBE = ("the you and of is that it what this for have your with they was are not we be he know she there think "163 "right her him would been were about them going").split()164DROP = {"fr": FR_DROP, "en": EN_DROP, "es": ES_DROP}165166# Interjections and everyday short forms worth keeping even though the filters above would reject them.167KEEP = {168 "fr": {"ok": 300000, "ah": 250000, "oh": 400000, "eh": 150000, "hé": 120000, "euh": 90000, "hein": 200000,169 "lol": 30000, "mdr": 9000, "stp": 15000, "svp": 30000, "wifi": 6000},170 "en": {"ok": 900000, "oh": 2500000, "ah": 500000, "uh": 700000, "um": 300000, "hmm": 200000, "huh": 400000,171 "gonna": 1800000, "wanna": 700000, "gotta": 600000, "TV": 120000, "Mr": 600000, "Mrs": 250000, "Dr": 350000,172 "lol": 60000, "omg": 30000, "btw": 15000, "idk": 12000, "thx": 9000, "pls": 12000, "wifi": 9000},173 "es": {"ok": 150000, "ah": 250000, "oh": 400000, "eh": 300000, "jaja": 30000, "jajaja": 20000, "wifi": 6000},174}175176# English contractions (hand-written, approximate counts on the scale of the source corpus: 725 M tokens).177EN_CONTRACTIONS = {178 "I'm": 4600000, "don't": 4100000, "it's": 4000000, "that's": 2600000, "you're": 2300000, "I'll": 1500000,179 "can't": 1300000, "I've": 1100000, "didn't": 1000000, "he's": 1000000, "what's": 950000, "there's": 800000,180 "we're": 800000, "I'd": 600000, "let's": 600000, "she's": 550000, "they're": 550000, "won't": 500000,181 "doesn't": 470000, "isn't": 400000, "we'll": 330000, "you'll": 320000, "wasn't": 300000, "you've": 300000,182 "couldn't": 220000, "wouldn't": 220000, "haven't": 210000, "aren't": 180000, "who's": 180000, "we've": 180000,183 "ain't": 150000, "here's": 150000, "he'll": 110000, "you'd": 110000, "they'll": 90000, "it'll": 90000,184 "shouldn't": 80000, "where's": 80000, "they've": 70000, "hasn't": 60000, "weren't": 60000, "how's": 60000,185 "she'll": 55000, "he'd": 50000, "hadn't": 40000, "we'd": 40000, "they'd": 35000, "she'd": 30000, "that'll": 25000,186 "o'clock": 60000, "y'all": 30000, "ma'am": 90000, "would've": 20000, "could've": 18000, "should've": 18000,187 "there'll": 6000, "who'd": 6000, "who'll": 5000, "mustn't": 6000, "needn't": 3000, "it'd": 8000, "what'd": 9000,188 "I": 27000000,189}190191# Quebec French supplement (hand-written; counts are plausible everyday-use estimates on the scale of the source192# corpus, 313 M tokens — they only need to rank these words sensibly among their neighbours).193QC_FR = {194 # communications / technology (OQLF terms in everyday use)195 "courriel": 60000, "courriels": 25000, "pourriel": 6000, "pourriels": 4000, "clavarder": 3000,196 "clavardage": 3500, "texto": 30000, "textos": 15000, "texter": 9000, "cellulaire": 40000, "cellulaires": 8000,197 "téléverser": 2500, "télécharger": 20000, "baladodiffusion": 2500, "balado": 4000, "balados": 2500,198 "infolettre": 4000, "hameçonnage": 2500, "mot-clic": 1500, "égoportrait": 1500, "divulgâcher": 1200,199 "divulgâcheur": 900, "infonuagique": 1500, "témoin": 30000, "clavier": 9000, "ordi": 8000, "portable": 30000,200 "gazouillis": 1500, "nuagique": 900, "fureteur": 1200, "logiciel": 12000, "logiciels": 6000, "pilote": 30000,201 "afficheur": 1500, "boîte vocale": 0,202 # everyday life203 "dépanneur": 25000, "dépanneurs": 5000, "magasiner": 15000, "magasinage": 12000, "magasine": 6000,204 "magasiné": 3500, "tuque": 9000, "tuques": 3500, "mitaine": 2500, "mitaines": 5000, "foulard": 9000,205 "poutine": 12000, "poutines": 2500, "cégep": 15000, "cégeps": 4000, "cégépien": 1500, "cégépienne": 1200,206 "garderie": 15000, "garderies": 3500, "épicerie": 25000, "épiceries": 4000, "souper": 45000, "soupers": 5000,207 "dîner": 80000, "déjeuner": 70000, "déjeuners": 6000, "breuvage": 6000, "breuvages": 3500, "liqueur": 9000,208 "chandail": 12000, "chandails": 4500, "bas": 90000, "bobettes": 3000, "soulier": 5000, "souliers": 12000,209 "espadrilles": 4000, "sacoche": 5000, "laveuse": 5000, "sécheuse": 5000, "cuisinière": 6000,210 "frigidaire": 5000, "balayeuse": 3500, "vadrouille": 2500, "chaudière": 5000, "débarbouillette": 2000,211 "bécosse": 900, "bécosses": 1200, "cabanon": 2500, "galerie": 15000, "tabagie": 1500, "buanderie": 4000,212 "nettoyeur": 4000, "quincaillerie": 4500, "pharmacie": 20000, "caisse": 30000, "guichet": 12000,213 "stationnement": 20000, "stationner": 6000, "stationné": 4500, "char": 20000, "chars": 8000, "pick-up": 3000,214 "camion": 45000, "autobus": 20000, "métro": 30000, "traversier": 3500, "motoneige": 4500, "motoneiges": 2000,215 "traîneau": 6000, "pneus": 12000, "déneigement": 3500, "déneiger": 2500, "déneigeuse": 1500, "souffleuse": 3000,216 "poudrerie": 2500, "verglas": 4500, "sloche": 1500, "banc de neige": 0, "frette": 6000, "tempête": 30000,217 "érable": 9000, "érablière": 3000, "cabane": 20000, "tire": 30000, "tourtière": 3500, "tourtières": 1200,218 "cretons": 2000, "pâté chinois": 0, "bleuet": 2500, "bleuets": 6000, "atoca": 800, "atocas": 1000,219 "blé d'Inde": 0, "guédille": 900, "pogo": 1500, "beigne": 3500, "beignes": 3500, "pouding": 3000,220 "chômeur": 3500, "fèves": 5000, "patate": 9000, "patates": 12000, "casse-croûte": 4000, "cantine": 8000,221 "dépanner": 5000, "jaser": 9000, "jase": 6000, "jasette": 2500, "placoter": 2500, "placotage": 1500,222 "niaiser": 9000, "niaise": 6000, "niaisage": 2500, "niaiseux": 6000, "niaiseuse": 2500, "niaiserie": 3500,223 "niaiseries": 6000, "achaler": 3000, "achale": 3500, "achalant": 3500, "achalante": 1800, "tanné": 9000,224 "tannée": 6000, "tannant": 5000, "tannante": 2500, "écœurant": 9000, "écœurante": 3500, "capoter": 5000,225 "capote": 8000, "capoté": 4500, "pogner": 6000, "pogne": 6000, "pogné": 6000, "pognée": 2500, "gosser": 2500,226 "gosse": 20000, "gossant": 2500, "garrocher": 2000, "garroche": 1800, "barrer": 6000, "barre": 30000,227 "barré": 6000, "barrée": 4500, "débarrer": 2500, "embarquer": 12000, "embarque": 12000, "débarquer": 12000,228 "débarque": 9000, "chialer": 6000, "chiale": 4500, "chialeux": 1800, "bretter": 900, "zigonner": 900,229 "bardasser": 800, "brasser": 5000, "brasse": 5000, "maganer": 1500, "magané": 3000, "maganée": 2000,230 "quétaine": 3500, "quétaines": 1500, "poche": 30000, "plate": 12000, "platte": 3000, "correct": 45000,231 "correcte": 12000, "pantoute": 6000, "icitte": 5000, "astheure": 3500, "asteure": 2500, "tantôt": 20000,232 "présentement": 15000, "dispendieux": 4000, "dispendieuse": 2000, "piasse": 4500, "piasses": 6000,233 "piastre": 3500, "piastres": 4500, "sous": 200000, "cenne": 3000, "cennes": 4500, "huard": 1500,234 "blonde": 60000, "chum": 25000, "chums": 9000, "gang": 45000, "matante": 3500, "mononcle": 3500,235 "bébelle": 1500, "bébelles": 2500, "cossin": 900, "cossins": 1800, "patente": 5000, "patentes": 2500,236 "patenter": 900, "gugusse": 1200, "bibitte": 3000, "bibittes": 4500, "maringouin": 1500, "maringouins": 3500,237 "ouaouaron": 600, "siffleux": 700, "orignal": 4500, "orignaux": 2000, "chevreuil": 6000, "chevreuils": 3000,238 "outarde": 1200, "outardes": 2000, "caribou": 4500, "caribous": 2500, "ouananiche": 500, "doré": 6000,239 "fin de semaine": 0, "fins de semaine": 0, "fête": 150000, "magasin": 60000, "party": 20000, "partys": 4500,240 "bienvenue": 120000, "bonjour": 600000, "allô": 60000, "bye": 60000, "salut": 500000, "merci": 900000,241 "tabarnak": 6000, "tabarnouche": 2000, "câlisse": 6000, "câline": 3000, "crisse": 9000, "ostie": 6000,242 "esti": 6000, "calvaire": 9000, "maudit": 45000, "maudite": 20000, "sacrer": 3500, "sacre": 9000,243 # informal spoken Quebec French, as people actually text it244 "pis": 60000, "faque": 20000, "ben": 80000, "tsé": 15000, "ouin": 15000, "ouais": 300000, "nenon": 2500,245 "coudonc": 3000, "voyons": 30000, "mettons": 9000, "anyway": 6000, "genre": 60000, "full": 9000, "cute": 6000,246 "lunch": 9000, "toast": 9000, "toasts": 5000, "fun": 20000, "job": 30000, "jobs": 6000, "boss": 20000,247 "québécois": 20000, "québécoise": 12000, "québécoises": 4500, "Québec": 90000, "Montréal": 80000,248 "Gatineau": 9000, "Laval": 15000, "Longueuil": 6000, "Sherbrooke": 9000, "Saguenay": 6000,249 "Trois-Rivières": 6000, "Lévis": 4500, "Rimouski": 3500, "Outaouais": 6000, "Gaspésie": 4500,250 "Abitibi": 3500, "Estrie": 3000, "Mauricie": 2500, "Laurentides": 4500, "Lanaudière": 2500,251 "Montérégie": 2500, "Charlevoix": 2500, "Ottawa": 20000, "Toronto": 25000, "Canada": 90000,252 "Canadien": 20000, "Canadiens": 20000, "canadien": 20000, "canadienne": 12000, "montréalais": 4500,253 "montréalaise": 2500, "UQO": 2500, "UQAM": 4500, "REER": 3500, "CELI": 3500, "TPS": 3000, "TVQ": 3000,254 "NAS": 2000, "RAMQ": 3000, "SAQ": 4500, "SAAQ": 3500, "STM": 3000, "CLSC": 3500, "CPE": 3000, "CHSLD": 2500,255 "polyvalente": 3000, "baccalauréat": 4500, "bac": 20000, "maîtrise": 15000, "doctorat": 6000,256 "session": 20000, "plan de cours": 0, "travail pratique": 0, "chargé": 12000, "chargée": 6000,257 "condo": 12000, "condos": 6000, "duplex": 6000, "triplex": 4500, "plex": 2500, "bungalow": 4500,258 "loyer": 30000, "logement": 30000, "logements": 12000, "propriétaire": 60000, "locataire": 15000,259 "locataires": 9000, "hypothèque": 15000, "hypothécaire": 6000, "courtier": 9000, "courtière": 2500,260 "évaluateur": 3000, "évaluation": 20000, "municipale": 6000, "arrondissement": 9000,261}262263# Words never proposed as an automatic correction target are flagged in the engine (PredictionCore/Profanity.swift);264# they stay in the lexicon so that typing them on purpose is not "corrected" away.265266# Hand-written bigram tables. "head: w1 w2 w3 …" — continuations in decreasing likelihood (weights 9, 8, 7 … min 2).267# "<s>" = sentence start, "*" = generic fallback when the previous word has no entry.268BIGRAMS = {269 "fr": """270<s>: Je Bonjour Merci Salut Oui C'est Tu On Il Non Ça Est-ce271*: de et à le la que pas272je: suis vais ne peux veux pense sais voulais dois te vous crois273j'ai: pas un une besoin hâte été eu vu fait reçu oublié274j'étais: en là pas au sûr275j'aimerais: bien savoir que te avoir276j'arrive: dans bientôt à tantôt277tu: es peux as veux vas sais fais penses viens me278il: est y a faut fait va me n'y était279elle: est a va me fait était dit280on: se peut va est a pourrait devrait y281nous: avons sommes allons pouvons devons282vous: êtes avez pouvez allez voulez283ils: sont ont vont284elles: sont ont vont285ça: va me fait marche dépend te serait286c'est: bon correct vrai pas le un une parfait noté gentil287ce: soir matin qui que n'est sera serait288cette: semaine fin année fois289ne: pas sais suis peux veux290n'est: pas plus291pas: de encore du grave mal trop besoin sûr292est: en pas très à un une293est-ce: que qu'on qu'il294suis: en là pas à désolé arrivé d'accord295sont: en là pas à296ai: pas un une besoin297as: tu pas un une298a: pas un une été299vais: te y être au à faire300va: bien être y te falloir301peux: tu pas te venir être302peut: se être pas y303veux: tu pas bien dire304dois: te y partir aller305faut: que pas se y306merci: beaucoup pour à bien encore d'avance307bonne: journée soirée nuit fin semaine chance fête308bon: matin appétit retour courage voyage309bonjour: à tout monsieur madame310salut: ça comment tout311à: la tout quelle demain plus bientôt tantôt312au: revoir plaisir moins bureau travail313aux: autres314de: la rien ne plus te mon ma315du: tout coup temps bureau316des: nouvelles317le: plus temps même monde plaisir318la: semaine maison journée fin même319les: enfants gens deux autres320un: peu bon moment autre courriel321une: bonne fois autre heure petite322et: toi je de le puis323ou: bien pas demain324mais: je pas c'est on325que: je tu ça c'est le vous326qui: est a va327quoi: de faire328comment: ça vas va allez329pourquoi: pas tu330quand: tu même on je331où: es est tu332si: tu ça je on vous333dans: la le les une un334sur: la le mon335pour: le la toi vous moi ton votre336avec: toi moi plaisir vous les337sans: problème faute338chez: moi toi nous339en: train route fait ce plus retard340tout: va le à est de341très: bien bon bonne342bien: sûr reçu merci à noté343trop: tard de bien344plus: tard de que345demain: matin soir à346ce soir: à347fin: de348semaine: prochaine dernière349prochaine: fois semaine350passe: une351bientôt: à352d'accord: merci je on353désolé: pour de du je354oui: je c'est merci355non: merci pas je356tantôt: à357mon: nom chum courriel numéro358ma: blonde mère fille359ton: message courriel360votre: message courriel réponse retour361te: voir dire rappelle362me: dire rappeler363se: voit parle rejoint364y: a aller vais365""",366 "en": """367<s>: I Thanks Hi Yes The It's Hello We You No Can368*: the to and of a in is369i: am have think will can was don't would just need370i'm: not going on in sorry so here a371i'll: be get call let see do372i've: been got never373i'd: like love be374you: are can have know want should375we: are can have will should need376they: are have will were377he: is was has will378she: is was has will379it: is was will would380it's: a not the ok fine been381that's: a what great fine not382this: is week weekend383that: is was would sounds384the: same best first other way385a: lot few little good great386an: hour email387to: be the do get see you388of: the course a389in: the a my390on: the my it391at: the home work392for: the you your a me393with: you the me a394and: I the then395but: I it not396or: not something397is: a the not it398are: you we not they399was: a the not400will: be do not401would: be like you love402can: you we I be403can't: wait believe404could: you be405should: be I we406do: you not it407don't: know worry think have408did: you not409have: a to you been410has: been a411thank: you412thanks: for a so again413sorry: for I about to414see: you if415talk: to soon416let: me us417let's: go do get418let me: know419how: are is about do420what: is are do time about421when: you are I422where: are is423why: not do424good: morning night luck job to425have a: good great nice426great: thanks job to427happy: birthday to428looking: forward for429forward: to430no: problem worries I thanks431yes: I please it432not: sure a yet433so: much I sorry434very: much good435as: soon well436soon: as437my: name phone438your: message email439be: there a able440on my: way441there: is are was will442there's: a no nothing443here: is are you444i think: it we you that445i have: a to been no446i am: not going so a447i will: be call let send448i can: do see help be449you can: do see call450we can: do meet talk451if: you I we it452then: I we you453because: I it of454about: the it that455from: the my a456by: the then tomorrow457need: to a you458want: to you a459going: to on460got: it a to461get: back a it the462know: if what that how463think: so about it that464call: me you465send: me you it466tell: me him her467give: me you468please: let call send469tomorrow: morning at night470tonight: at471today: at is472morning: I473see you: soon tomorrow later there474talk to: you475thank you: so for very476how are: you things477i love: you it478love: you it479just: a got wanted480still: at in481really: appreciate good sorry482all: the good right483any: time questions484some: time of485""",486 "es": """487<s>: Hola Gracias Sí Yo No Buenos Me Qué El Es488*: de que la el y a en489yo: no también creo estoy tengo490tú: también eres491él: es no492no: es sé te puedo hay tengo493sí: claro por494es: un una el que muy495está: bien en muy aquí496estoy: en bien aquí de497estás: bien en498son: las los499soy: yo de un500hay: que un una501tengo: que un una502tienes: que razón503voy: a504vas: a505vamos: a506quiero: que ir saber507puedo: ir hacer508puedes: venir509me: gusta voy parece510te: quiero veo llamo511se: puede que512lo: siento que sé513la: casa semana verdad514el: día fin mismo515los: dos niños516las: dos cosas517un: poco día momento518una: vez cosa semana519de: la nada los acuerdo520del: día521a: la las ver casa522al: menos final523en: la el casa un524con: el la mucho525por: favor qué la eso526para: ti mí el527que: no es tengas te528qué: tal pasa es bueno529cómo: estás está te530cuándo: es531dónde: estás está532y: tú yo el la533o: no534pero: no es535si: quieres no536muy: bien bueno537más: tarde o que538muchas: gracias539gracias: por a540buenos: días541buenas: tardes noches542buen: día fin543hasta: luego mañana pronto la544nos: vemos545feliz: cumpleaños día546fin: de547hola: cómo qué548todo: bien el549bien: gracias y550mañana: por a551ella: es no está552nosotros: somos tenemos553ellos: son están554usted: es puede tiene555eres: muy un una556somos: amigos557tiene: que razón un558tenemos: que un559puede: ser que560podemos: ir hacer hablar561quieres: ir que venir562quiere: que decir563sé: que nada564creo: que565gusta: mucho el la566le: gusta dije567nos: vemos gusta568ya: no está lo voy569aquí: está estoy570ahora: mismo no571hoy: es no por572esta: noche tarde semana mañana573este: fin es año574esto: es no575eso: es no sí576mucho: gusto tiempo577mucha: suerte578muchos: besos579todos: los580toda: la581cada: día vez582otra: vez cosa583otro: día584también: es585cuando: quieras puedas586porque: no es587como: tú siempre588estamos: en bien aquí589están: en bien aquí590fue: un una591era: un una592ha: sido593he: estado594tal: vez595por favor: no596de nada: no597lo siento: mucho no598claro: que599perdón: por600vale: gracias pues601bueno: pues no602desde: que el603entre: los604sobre: el la605sin: embargo problema606su: casa nombre607mis: amigos608tus: amigos609días: de610noches: a611tardes: a612semana: que pasada613luego: te nos614pronto: nos615""",616}617618SPELL_SWIFT = r"""619import AppKit620let checker = NSSpellChecker.shared621func ok(_ word: String, _ lang: String) -> Bool {622 checker.checkSpelling(of: word, startingAt: 0, language: lang, wrap: false, inSpellDocumentWithTag: 0, wordCount: nil).location == NSNotFound623}624while let line = readLine() {625 let parts = line.split(separator: "\t", omittingEmptySubsequences: false)626 guard parts.count == 2 else { continue }627 let lang = String(parts[0]), word = String(parts[1])628 let cap = word.prefix(1).uppercased() + word.dropFirst()629 print("\(lang)\t\(word)\t\(ok(word, lang) ? 1 : 0)\t\(ok(cap, lang) ? 1 : 0)")630}631"""632633634def fold(word):635 """Must stay identical to TextFolding.fold in PredictionCore."""636 word = word.lower().replace("’", "'").replace("‘", "'").replace("œ", "oe").replace("æ", "ae")637 return "".join(c for c in unicodedata.normalize("NFD", word) if unicodedata.category(c) != "Mn")638639640def fetch(lang, offline):641 path = os.path.join(CACHE, f"{lang}_50k.txt")642 if not os.path.exists(path):643 if offline:644 sys.exit(f"missing {path} (offline)")645 with urllib.request.urlopen(SOURCE.format(l=lang), timeout=60) as r:646 data = r.read()647 with open(path, "wb") as f:648 f.write(data)649 rows = []650 with open(path, encoding="utf-8") as f:651 for line in f:652 parts = line.split()653 if len(parts) == 2 and parts[1].isdigit():654 rows.append((unicodedata.normalize("NFC", parts[0]), int(parts[1])))655 return rows656657658def spell_helper():659 src = os.path.join(CACHE, "spell.swift")660 exe = os.path.join(CACHE, "spell")661 if not os.path.exists(src) or open(src).read() != SPELL_SWIFT or not os.path.exists(exe):662 with open(src, "w") as f:663 f.write(SPELL_SWIFT)664 subprocess.run(["swiftc", "-O", src, "-o", exe], check=True)665 return exe666667668def spell_check(pairs):669 """pairs: [(lang, word)] -> {(lang, word): (lower_ok, capitalised_ok)} using the macOS spell checker (cached)."""670 cache_path = os.path.join(CACHE, "spell-cache.json")671 cache = json.load(open(cache_path)) if os.path.exists(cache_path) else {}672 todo = [p for p in pairs if f"{p[0]}\t{p[1]}" not in cache]673 if todo:674 out = subprocess.run([spell_helper()], input="".join(f"{l}\t{w}\n" for l, w in todo), capture_output=True,675 text=True, check=True).stdout676 for line in out.splitlines():677 l, w, a, b = line.split("\t")678 cache[f"{l}\t{w}"] = [int(a), int(b)]679 with open(cache_path, "w") as f:680 json.dump(cache, f)681 return {p: tuple(cache.get(f"{p[0]}\t{p[1]}", (0, 0))) for p in pairs}682683684def candidate(lang, token):685 """Shape filter: letters of the language, inner hyphen/apostrophe only, no elision stubs."""686 if token in DROP[lang] or not token:687 return False688 if token[0] in "'-" or token[-1] in "'-":689 return False690 if any(c not in LETTERS[lang] and c not in "'-" for c in token):691 return False692 if len(token) == 1:693 return token in ONE_LETTER[lang]694 if len(token) > 24 or "''" in token or "--" in token:695 return False696 return True697698699def build(lang, sources, stats):700 rows = [(w, c) for w, c in sources[lang] if c >= MIN_COUNT and candidate(lang, w)]701 total = {l: sum(c for _, c in sources[l]) for l in LANGS}702 en_rel = {w: c / total["en"] for w, c in sources["en"]}703 en_top = {w for w, _ in sources["en"][:3000]}704 # Leakage rate: share of this language's corpus that is untranslated English, estimated on English function words.705 own = dict(sources[lang])706 leak = sorted((own.get(w, 0) / total[lang]) / en_rel[w] for w in EN_PROBE)[len(EN_PROBE) // 2]707 checks = [(lang, w) for w, _ in rows]708 if lang != "en":709 checks += [("en", w) for w, _ in rows if w in en_rel]710 verdict = spell_check(checks)711 words = {}712 dropped = {"spelling": 0, "foreign": 0, "unaccented_capital": 0}713 lower_folds = {fold(w) for w, _ in rows if verdict[(lang, w)][0]}714 for w, c in rows:715 lower_ok, cap_ok = verdict[(lang, w)]716 if not lower_ok and not cap_ok:717 dropped["spelling"] += 1718 continue719 # "ecole" is rejected but "Ecole" is accepted (capitals may drop their accents): that is the accent-less720 # spelling of a word we already have ("école"), not a proper noun.721 if not lower_ok and fold(w) in lower_folds:722 dropped["unaccented_capital"] += 1723 continue724 # English noise in the French/Spanish subtitle lists: far more frequent in English than here, and English.725 # Removed when (a) its count here is what leakage alone would produce, or (b) it is a top-3000 English word at726 # least four times more frequent there than here — unless hand-rescued as a genuine word of this language.727 if lang != "en" and len(w) > 1 and w not in RESCUE[lang] and w in en_rel and verdict.get(("en", w), (0, 0))[0]:728 rel = c / total[lang]729 if rel < 6 * leak * en_rel[w] or (w in en_top and en_rel[w] > 4 * rel):730 dropped["foreign"] += 1731 continue732 form = w if lower_ok else w[0].upper() + w[1:]733 if lang == "en" and (w == "i" or w.startswith("i'")):734 form = "I" + w[1:]735 words[form] = max(words.get(form, 0), c)736 ranked = sorted(words.items(), key=lambda kv: (-kv[1], kv[0]))[:TARGET_WORDS]737 words = dict(ranked)738 extra = dict(KEEP[lang])739 if lang == "en":740 extra.update(EN_CONTRACTIONS)741 if lang == "fr":742 extra.update({w: c for w, c in QC_FR.items() if c > 0 and " " not in w})743 for w, c in extra.items():744 if w.lower() != w:745 words.pop(w.lower(), None) # the supplement's capitalisation wins746 words[w] = max(words.get(w, 0), c)747 lines = sorted(words.items(), key=lambda kv: (fold(kv[0]).encode(), kv[0].encode()))748 path = os.path.join(OUT, f"{lang}.lex")749 with open(path, "w", encoding="utf-8", newline="\n") as f:750 for w, c in lines:751 f.write(f"{w}\t{c}\n")752 stats[lang] = {"source": len(sources[lang]), "shape_ok": len(rows), **dropped, "words": len(lines),753 "bytes": os.path.getsize(path), "capitalised": sum(1 for w, _ in lines if w[0].isupper())}754 return {fold(w) for w in words}755756757def build_bigrams(lang, known, stats):758 pairs, unknown = [], set()759 for line in BIGRAMS[lang].strip().splitlines():760 head, _, tail = line.partition(":")761 head = head.strip()762 for i, nxt in enumerate(tail.split()):763 pairs.append((head.lower() if head not in ("<s>", "*") else head, nxt, max(2, 9 - i)))764 for part in nxt.replace("’", "'").split("'")[-1:]:765 if fold(part) not in known and fold(nxt) not in known:766 unknown.add(nxt)767 path = os.path.join(OUT, f"{lang}.bigrams")768 with open(path, "w", encoding="utf-8", newline="\n") as f:769 for head, nxt, weight in pairs:770 f.write(f"{head}\t{nxt}\t{weight}\n")771 stats[lang]["bigrams"] = len(pairs)772 stats[lang]["bigram_words_outside_lexicon"] = sorted(unknown)773774775def main():776 offline = "--offline" in sys.argv777 os.makedirs(CACHE, exist_ok=True)778 os.makedirs(OUT, exist_ok=True)779 sources = {l: fetch(l, offline) for l in LANGS}780 stats = {}781 for lang in LANGS:782 known = build(lang, sources, stats)783 build_bigrams(lang, known, stats)784 print(json.dumps(stats, ensure_ascii=False, indent=1))785786787if __name__ == "__main__":788 main()789