Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.
Python calibrationclassificationdecision-modelhuggingfacejevmodernbertmultilingualnlppythonpytorchroutingtyped-decisionszero-shot
fix(lang): bar emphasis capitals and caseless scripts out of the caps veto
Adeshina Lasisi2ac85c02a686
diff --git a/laya/lang.py b/laya/lang.pyindex e31e7315..f8ecb336 100644--- a/laya/lang.py+++ b/laya/lang.py@@ -371,6 +371,12 @@ NON_LATIN_MIN_FRACTION = 0.1NON_LATIN_MIN_LETTERS = 10+def _non_latin_carries(non_latin: float, n_non_latin: int) -> bool:+ """Whether the non-Latin letters of a Latin-plurality text are enough to carry the state."""+ return (non_latin >= NON_LATIN_FRACTION+ or (non_latin >= NON_LATIN_MIN_FRACTION and n_non_latin >= NON_LATIN_MIN_LETTERS))++def _script_of(ch: str) -> Optional[str]:"""The named non-Latin script of one letter, or None for Latin and for unclaimed letters."""cp = ord(ch)@@ -518,37 +524,62 @@ _LETTER_RUN = re.compile(r"[^\W\d_]{2,}")# must therefore show evidence that is more than acronym-shaped before it is believed.## The bar is on the tokens that actually scored, not on the line. Requiring one long word-# anywhere does almost nothing: `ANGELES`, `VEGAS` and `SEGUNDO` are long and are not what named-# Spanish -- `LOS`, `LAS` and `EL` did. Three corpora, measured against this file's own-# `_named_prose_language`: 10,960 MASSIVE test lines upper-cased that the detector names-# correctly (genuine shouted prose, must survive); 500,000 lines of 4-8 acronyms drawn from 5,670-# real ones; 50,000 all-caps address and signage lines built from 18,718 real US city names.+# anywhere does almost nothing by itself: `ANGELES`, `VEGAS` and `SEGUNDO` are long and are not+# what named Spanish -- `LOS`, `LAS` and `EL` did.+#+# Three corpora decide these two numbers, and `research/evals/shouted_bar_corpora.py` builds all+# three and prints the table below: upper-cased MASSIVE test rows that the rule names as their+# own locale with no bar at all (genuine shouted prose, must survive); 500,000 lines of 4-8+# acronyms; 50,000 all-caps US address and signage lines. Pinned to the MASSIVE test split at+# revision 940fd47a and `random.Random(0)`, with the acronym and place-name pools committed in+# that script, so every row here can be rechecked when someone wants to move a constant. Each+# row applies one bar, named in full, so the rows are comparable:#-# rule prose kept acronym FP address FP-# none (before this guard) 10,960 100.00% 410 84-# one word >= 5 anywhere 10,854 99.03% 212 83 <- addresses untouched-# matched stopword >= 3 10,625 96.94% 159 9 <- keeps LOS/LAS/EL-# matched stopword >= 4 8,841 80.67% 14 2-# matched stopword >= 4 AND >=5 8,762 79.95% 6 2 <- chosen-# matched stopword >= 5 6,902 62.97% 0 1+# rule prose kept acronym FP address FP+# none (no bar at all) 10,960 100.00% 4,219 141+# diacritics only 10,960 100.00% 4,219 141+# word >= 5 only 10,854 99.03% 431 141 <- addresses stand+# stopword >= 3 only 10,729 97.89% 3,751 109 <- keeps LOS/LAS/EL+# stopword >= 4 only 8,841 80.67% 0 0+# stopword >= 5 only 6,963 63.53% 0 0+# stopword >= 3 AND word >= 5 10,625 96.94% 386 109+# stopword >= 4 AND word >= 5 8,762 79.95% 0 0 <- chosen+# stopword >= 5 AND word >= 5 6,902 62.97% 0 0+# stopword >= 4 AND word >= 6 8,418 76.81% 0 0+# stopword >= 4 AND word >= 7 7,459 68.06% 0 0+# stopword >= 4 AND word >= 5, no dia 6,749 61.58% 0 0#-# 4 is the lowest bar that rejects `LOS`, `LAS` and `EL`; 3 leaves the reported case standing.-# Going on to 5 is not worth it: it costs 1,860 more real lines to remove 6 more acronym runs in-# 500,000. Non-English diacritics are accepted in place of a long stopword, because the module-# already treats them as non-English evidence (NON_EN_DIACRITIC_RATE) and neither an acronym nor-# a US place name carries any: that disjunct is free on both false-positive corpora (6 and 2-# either way) and lifts prose kept from 61.58% to 79.95%.+# `LOS`, `LAS` and `EL` are three, three and two letters, so any bar of 4 or more rejects them;+# what the table has to decide is the other side of that, and it is 3 that it rules out -- at 3+# the reported address line still reads as Spanish, and 3,751 of 500,000 acronym runs and 109 of+# 50,000 address lines still read as prose. 4 closes both columns outright. Going on to 5 buys+# nothing measurable and costs 1,860 more real lines. Non-English diacritics are accepted in+# place of a long stopword, because the module already treats them as non-English evidence+# (NON_EN_DIACRITIC_RATE) and neither an acronym nor a US place name carries any: that disjunct+# is free on both false-positive corpora (0 and 0 either way) and lifts prose kept from 61.58%+# to 79.95%._SHOUTED_MIN_STOPWORD = 4-# A length bar on the line as well. Weak alone (row two above) but cheap on top of the stopword-# bar -- 79 real lines for 8 of the 14 surviving acronym runs, about 10:1. Swept with the-# stopword bar at 4: no bar 8,841 prose / 14 acronym, >=5 8,762 / 6, >=6 8,418 / 2, >=7 7,459 / 0.-# 6 would cost 344 more real lines for 4 more acronym runs, about 86:1, so it stops at 5.+# A length bar as well: a token of this many letters is a word rather than an acronym. Used+# twice -- here, on an all-caps line, and in `_analyse_text` to decide whether an all-caps run+# inside mixed-case text is an acronym worth blanking.#-# What this costs is not small and is not only short lines: 2,198 of the 10,960 shouted-prose-# lines are given up, 82.62% of them six tokens or longer, the longest a 34-token Dutch sentence.-# Shouted text is the whole of that corpus by construction and a rarity in real input -- on-# MASSIVE as written, routing is unchanged (0.5625 of non-English lines to multilingual, before-# and after) -- but anyone moving these numbers should know the casualties are sentences.+# Stated plainly, this bar is not justified by the table above: at a stopword bar of 4 both+# false-positive columns are already 0, so the 79 real prose lines it costs (8,841 -> 8,762) buy+# nothing those corpora can see. It is powerful on its own -- row three takes acronym false+# positives from 4,219 to 431 -- and it is kept because the corpora it was first chosen against+# were larger than the ones committed here (5,670 acronyms and 18,718 place names, neither+# committed, so their counts are not reproducible and are not quoted) and did report false+# positives surviving a stopword bar of 4. Absence on this corpus is not absence. Anyone who+# wants those 79 lines back should widen the acronym pool in that script first and show the+# column stays at 0. Swept with the stopword bar at 4: no bar 8,841 prose, >= 5 8,762,+# >= 6 8,418, >= 7 7,459.+#+# What the pair costs is not small and is not only short lines: 2,198 of the 10,960+# shouted-prose lines are given up, 1,816 of them (82.62%) six tokens or longer, the longest a+# 34-token Dutch sentence. On MASSIVE as written none of this is visible -- not one of the+# 151,674 rows holds a single uppercase character -- so it has to be measured on rows that do:+# over the 77,324 rows of the 26 non-English Latin locales, upper-cased, the multilingual share+# falls 0.5912 -> 0.5430, which is 3,727 rows. The casualties are sentences._SHOUTED_MIN_WORD = 5@@ -561,6 +592,11 @@ def _shouted(text: str) -> bool:construction. Nothing is routed on that path today (`_STOP["bn"]` is romanised, so aBengali-script line is named by script and never reaches here), but the bar belongs to casedtext and saying so here keeps it that way.++ That argument covers *pure* caseless text, which never reaches a caps bar at all. Text that+ merely contains some has no lowercase either and does reach one; `_analyse_text` keeps both+ bars off it, because a bar that works by discarding Latin evidence has nothing to say about+ the half of the state it cannot read."""return any(ch.isupper() for ch in text) and not any(ch.islower() for ch in text)@@ -637,9 +673,8 @@ def _analyse_text(text: str) -> Dict[str, object]:script = _script_from_counts(counts)non_latin = round(1.0 - prof.get("latin", 0.0), 4) if prof else 0.0n_non_latin = round(non_latin * sum(ch.isalpha() for ch in text))- if script == "latin" and _non_latin_words(text) and (- non_latin >= NON_LATIN_FRACTION or (- non_latin >= NON_LATIN_MIN_FRACTION and n_non_latin >= NON_LATIN_MIN_LETTERS)):+ if (script == "latin" and _non_latin_words(text)+ and _non_latin_carries(non_latin, n_non_latin)):script = max((s for s in prof if s != "latin"), key=prof.get)if script == "unknown":return {"script": "unknown", "script_profile": prof, "language": None,@@ -657,7 +692,17 @@ def _analyse_text(text: str) -> Dict[str, object]:# and was named foreign outright: `MON DES EST LA` routed multilingual on its own, and so did# the same line under one or two lines of English. Vetoing here leaves the text undecided, so# `looks_non_english` still decides it: a shouted line with non-English diacritics is kept.- if lang not in (None, "en"):+ # Neither bar applies when the state is carried by a caseless script. Both of them answer+ # the verdict by taking evidence *away* from the Latin letters, and `looks_non_english`,+ # which decides what is left, reads Latin diacritics only -- it cannot see the caseless half.+ # Nothing else catches the fall, either: the script promotion above needs+ # `_non_latin_words`, which drops any run starting with a capital, so a shouted mixed-script+ # line has no promotable word by construction. `ПРИВЕТ MON DES EST LA` is 35% Cyrillic+ # letters and was being sent to the English checkpoint on the strength of disbelieving `MON+ # DES EST LA`. Whatever the Latin part is worth, text this far from Latin is not English, so+ # there is nothing for either bar to buy here and a wrong language name costs nothing: the+ # checkpoint is chosen on `is_english`.+ if lang not in (None, "en") and not _non_latin_carries(non_latin, n_non_latin):if _shouted(text):if not _shouted_evidence(_WORD.findall(text), lang,float(prof_lat["diacritic_rate"])):@@ -670,9 +715,25 @@ def _analyse_text(text: str) -> Dict[str, object]:# win the margin. Re-take the verdict without the all-caps runs. `looks_non_english`# and `diacritic_rate` stay measured on the original text, so a foreign word that# happens to be shouted cannot be blanked out of the diacritic safety net.- blanked = _LETTER_RUN.sub(lambda m: " " if m.group().isupper() else m.group(), text)- if blanked != text:- lang = latin_profile(blanked)["language"]+ #+ # Only *acronym-shaped* runs are blanked. Blanking every all-caps run deleted+ # emphasis capitals, which are ordinary in real prose and are usually on the words+ # that carry the sentence, so when the shouted words were the ones that named the+ # language the evidence simply went: `sag mir das HEUTIGE DATUM` and `quiero+ # cancelar mi PEDIDO POR FAVOR` both lost their verdict and routed english. It also+ # broke monotonicity -- the fully upper-cased form held the shouted bar, but adding+ # one lowercase English token moved the text to this branch, where it had no bar at+ # all. So a run is blanked only while every one of them is short enough to be an+ # acronym, by `_shouted_evidence`'s own first test: a run of `_SHOUTED_MIN_WORD`+ # letters is a word, and a word is not blanked out of its own sentence. Measured+ # over the 20,708 Latin-locale MASSIVE test rows, emphasis-capitalised two ways+ # (see the commit message): regressions 1,753 -> 293 and 3,835 -> 752.+ caps = [m.group() for m in _LETTER_RUN.finditer(text) if m.group().isupper()]+ if caps and not any(len(c) >= _SHOUTED_MIN_WORD for c in caps):+ blanked = _LETTER_RUN.sub(+ lambda m: " " if m.group().isupper() else m.group(), text)+ if blanked != text:+ lang = latin_profile(blanked)["language"]# Undecided is not English. Treating it as English sent every Latin-script language we hold no# stopwords for to the checkpoint that cannot read it, silently. When nothing identifies the# language, non-English letters or a shared Swedish-Danish marker can still prefer the@@ -717,11 +778,17 @@ def _leaf_non_english(leaf: str) -> Optional[Dict[str, object]]:# A named language still has to survive `_named_prose_language`: acronyms and slash# compounds are not words. But a veto is not a verdict of English. Dropping the line here# skipped the diacritic branch below, which exists for exactly this -- text that carries- # non-English letters and that no stopword list can name. `WIE SPAET IST ES IN KOELN`- # with its umlauts was vetoed for having no long stopword and then thrown away, so a- # German field routed english. A vetoed line now falls through to that branch, which is- # also why `language_undecided` is no longer required there: the language was named and- # then disbelieved, which is the same evidential position as never having named one.+ # non-English letters and that no stopword list can name. `WIE SPÄT IST ES IN KÖLN`+ # was vetoed for having no long stopword and then thrown away, so a German field routed+ # english; now it falls through and its umlauts carry it. That is also why+ # `language_undecided` is no longer required below: a language named and then disbelieved+ # is in the same evidential position as one never named.+ #+ # The ASCII spelling `WIE SPAET IST ES IN KOELN` is a different case and is not fixed+ # here. It has no diacritics to fall through to, and its longest matched German stopword+ # is `wie`, three letters, so `_SHOUTED_MIN_STOPWORD` vetoes it and nothing recovers it:+ # genuine German on the English checkpoint, one of the 3,727 upper-cased casualties+ # counted above and not an example of what this branch buys.named = (det["language"] not in (None, "en")and _named_prose_language(sample) is not None)if not named:diff --git a/research/evals/shouted_bar_corpora.py b/research/evals/shouted_bar_corpora.pynew file mode 100644index 00000000..82f8f88b--- /dev/null+++ b/research/evals/shouted_bar_corpora.py@@ -0,0 +1,300 @@+"""Rebuild the three corpora behind `_SHOUTED_MIN_STOPWORD` and `_SHOUTED_MIN_WORD`.++`laya.lang` holds an all-caps line to an evidence bar before it will name it as foreign prose:+a matched stopword of `_SHOUTED_MIN_STOPWORD` letters (or non-English diacritics), and one word+of `_SHOUTED_MIN_WORD` letters. Those two constants were chosen against three corpora, and the+corpora were not committed, so the trade behind them could not be rechecked when someone wanted+to move them. This script rebuilds all three from pinned sources and sweeps the bar over them.++ prose MASSIVE test split @ REVISION, every row upper-cased, keeping the rows the+ *unguarded* rule names as their own locale. Genuine shouted prose: it must survive.+ acronym `ACRONYM_LLINES` lines of 4-8 tokens drawn from `ACRONYMS` below, a hand-checked+ list of real abbreviations. A false positive is a line the bar lets through.+ address `ADDRESS_LINES` all-caps US address and signage lines built from `PLACES`,+ `STREETS` and `SIGNAGE` below. Same false-positive definition.++Deterministic: `random.Random(SEED)` and nothing else. Run from the repository root:++ python research/evals/shouted_bar_corpora.py # the table+ python research/evals/shouted_bar_corpora.py --out x.json++The pools here are smaller than the ones the bar was originally chosen against (that run used+5,670 acronyms and 18,718 place names, neither committed, so its absolute counts are not+reproducible and are not quoted anywhere). What this script pins is the shape of the trade: the+ordering of the rows, and the marginal cost in real prose of each step of the bar.++No model weights, no network beyond the dataset download `massive_route_comparison.py` already+does, and no dependency on the current value of either constant -- the bar is applied here from+the swept parameters, so the table stays meaningful after the constants move.+"""+from __future__ import annotations++import argparse+import gzip+import json+import random+import sys+from pathlib import Path+from typing import Dict, List, Optional, Tuple++REPO_ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(REPO_ROOT))++from laya.lang import ( # noqa: E402+ _CODE_LINE, _JOINED, _LETTER_RUN, _STOP, _WORD, NON_EN_DIACRITIC_RATE, latin_profile)++DATASET = "mteb/amazon_massive_intent"+REVISION = "940fd47a81eaa7f2cc7b129674d945d618ac38c2"+SEED = 0+ACRONYM_LINES = 500_000+ADDRESS_LINES = 50_000++# The 51 MASSIVE locales, as the snapshot names its test files.+LOCALES = [+ "af", "am", "ar", "az", "bn", "cy", "da", "de", "el", "en", "es", "fa", "fi", "fr", "he",+ "hi", "hu", "hy", "id", "is", "it", "ja", "jv", "ka", "km", "kn", "ko", "lv", "ml", "mn",+ "ms", "my", "nb", "nl", "pl", "pt", "ro", "ru", "sl", "sq", "sv", "sw", "ta", "te", "th",+ "tl", "tr", "ur", "vi", "zh-CN", "zh-TW",+]++# Real abbreviations, upper-cased as they are written. Chosen for breadth, and deliberately+# including the ones that collide with a Romance or Germanic stopword -- MON, DES, EST, LA, COM,+# DOS, LOS, LAS, EL, QUE, LES, UNO, SON, VAN, DAS -- because those are what the bar exists for.+ACRONYMS = """+ABS ACH ACL ADA ADD ADHD ADSL AFK AGI AIDS AKA ALS AMA AMD AML ANSI AOL API APR APT ARM ARP+ASAP ASCII ASIC ASL ASM ASP ATM ATP AVI AWOL AWS BBC BBQ BBS BCC BIOS BLT BMI BMW BPM BRB BSD+BTU BTW CAD CAM CAPTCHA CBC CBS CCTV CDC CDN CEO CFO CGI CIA CIO CLI CMS CNC CNN COD COM CPA+CPI CPR CPU CRM CRT CSI CSS CSV CTO CUDA CV DAB DARPA DAW DBA DDL DDOS DEA DEF DEI DES DHCP+DHL DIY DJ DLC DLL DMA DMV DNA DNS DOB DOC DOD DOE DOJ DOS DPI DRAM DSL DST DUI DVD DVI EAP+EBCDIC ECG ECU EDI EDT EEG EEOC EFT EKG EMI EMS EMT EOD EOF EOL EPA EPS ERP ESA ESL ESP ESPN+EST ETA ETC ETF ETL EULA EUR EVP FAA FAQ FBI FCC FDA FDIC FEMA FIFA FIFO FM FOIA FPGA FPS FTC+FTP FWD FYI GAAP GB GBP GDP GIF GIS GMO GMT GNU GOP GPA GPS GPU GSM GUI HBO HDD HDMI HIPAA+HIV HMO HOA HP HR HTML HTTP HUD HVAC IBM ICBM ICU IDE IEEE IETF IMAP IMDB IMF IMO INC IP IPO+IQ IRA IRC IRS ISBN ISO ISP ISS IT IV JDK JPEG JPG JSON JVM KB KFC KGB KPI KYC LAN LAPD LAS+LATAM LCD LED LES LIFO LLC LLM LMS LNG LOL LOS LPG LSAT LTD LTE LTS MAC MBA MBPS MCAT MIA MIB+MIDI MIT MLB MLS MMO MMS MON MPA MPEG MPG MPH MRI MRP MSDS MSG MSRP MTA MTV MVP NAACP NAFTA+NAS NASA NASCAR NATO NBA NBC NCAA NDA NFC NFL NGO NHL NHS NIC NIH NIST NLP NOAA NPR NRA NSA+NSF NTP NTSB NVME NYC NYPD NYSE OCD OCR ODBC OECD OEM OLED OPEC ORM OSHA OTC OTP PAC PAN PBS+PCB PCI PDA PDF PDT PEM PGA PGP PHD PHP PIN PLC PLZ PMS PNG PO POP POS PPE PPI PPM PPO PPP+PPT PSA PSI PST PTA PTO PTSD PVC PWD QA QC QED QOS QUE RAID RAM RBI RCA RDBMS REIT REM RFC+RFID RGB RIP RNA ROI ROM RPG RPM RSA RSS RSVP RTF RTO RV SAAS SAE SAN SAS SAT SCSI SDK SEC+SEO SFO SGML SHA SIM SKU SLA SMB SMS SMTP SNMP SOAP SOC SOP SOS SPF SQL SRAM SSD SSH SSID SSL+SSN SSO STD STEM SUV SVG SWAT SYN TARP TBA TBD TCP TDD TED TGIF TIFF TLC TLD TLS TMI TNT TSA+TTL TTY TV TXT UAE UAV UDP UEFA UFC UFO UHD UI UK UML UNESCO UNICEF UNO UPC UPS URI URL USA+USB USD USDA USGS USPS UTC UTF UUID UV UX VA VAT VGA VHF VHS VIN VIP VLAN VOIP VPN VPS VR WAN+WAV WBC WEP WHO WIFI WMA WPA WTO WWF WWII WWW XHTML XML XSD XSS YMCA YOLO YTD ZIP+LA EL AL AZ CA CO CT DC DE FL GA HI IA ID IL IN KS KY MA MD ME MI MN MO MS MT NC ND NE NH NJ+NM NV NY OH OK OR PA RI SC SD TN TX UT VT WA WI WV WY AB BC MB NB NL NS NT NU ON PE QC SK YT+ATL BOS CDG DEN DFW DTW EWR FRA HKG IAD IAH JFK LAX LGA LHR MCO MDW MEX MIA MSP MUC NRT ORD+PDX PHL PHX SAN SEA SFO SJC SLC STL SYD YUL YVR YYZ ZRH+""".split()++# Real US place names, written as a sign would write them. The Spanish-derived ones are the+# point: `LOS`, `LAS` and `EL` are what named Spanish in the defect this bar closed.+PLACES = """+ALBUQUERQUE ALEXANDRIA ALLENTOWN AMARILLO ANAHEIM ANCHORAGE ANN_ARBOR ANTIOCH APPLETON ARLINGTON+ARVADA ASHEVILLE ATHENS ATLANTA AUGUSTA AURORA AUSTIN BAKERSFIELD BALTIMORE BATON_ROUGE BEAUMONT+BELLEVUE BERKELEY BETHLEHEM BILLINGS BIRMINGHAM BLOOMINGTON BOISE BOSTON BOULDER BRIDGEPORT+BROCKTON BROKEN_ARROW BROWNSVILLE BUFFALO BURBANK CAMBRIDGE CAMDEN CANTON CAPE_CORAL CARLSBAD+CARROLLTON CARY CEDAR_RAPIDS CHANDLER CHARLESTON CHARLOTTE CHATTANOOGA CHESAPEAKE CHEYENNE+CHICAGO CHULA_VISTA CINCINNATI CLARKSVILLE CLEARWATER CLEVELAND CLOVIS COLLEGE_STATION+COLORADO_SPRINGS COLUMBIA COLUMBUS CONCORD CORAL_SPRINGS CORONA CORPUS_CHRISTI COSTA_MESA+DALLAS DALY_CITY DANBURY DAVENPORT DAYTON DEARBORN DENTON DENVER DES_MOINES DETROIT DOWNEY+DULUTH DURHAM EL_CAJON EL_MONTE EL_PASO EL_SEGUNDO ELGIN ELIZABETH ELK_GROVE ERIE ESCONDIDO+EUGENE EVANSVILLE EVERETT FAIRFIELD FARGO FAYETTEVILLE FLINT FONTANA FORT_COLLINS FORT_LAUDERDALE+FORT_WAYNE FORT_WORTH FREMONT FRESNO FRISCO FULLERTON GAINESVILLE GARDEN_GROVE GARLAND GARY+GILBERT GLENDALE GRAND_PRAIRIE GRAND_RAPIDS GREELEY GREEN_BAY GREENSBORO GREENVILLE HAMPTON+HARTFORD HAYWARD HENDERSON HIALEAH HIGH_POINT HOLLYWOOD HONOLULU HOUSTON HUNTINGTON_BEACH+HUNTSVILLE INDEPENDENCE INDIANAPOLIS INGLEWOOD IRVINE IRVING JACKSON JACKSONVILLE JERSEY_CITY+JOLIET KANSAS_CITY KENOSHA KILLEEN KNOXVILLE LA_CROSSE LA_HABRA LA_MESA LA_PORTE LAFAYETTE+LAKEWOOD LANCASTER LANSING LAREDO LAS_CRUCES LAS_VEGAS LEWISVILLE LEXINGTON LINCOLN LITTLE_ROCK+LIVONIA LONG_BEACH LONGMONT LOS_ANGELES LOS_BANOS LOUISVILLE LOWELL LUBBOCK LYNN MACON MADISON+MANCHESTER MCALLEN MCKINNEY MEMPHIS MERIDIAN MESA MESQUITE MIAMI MIDLAND MILWAUKEE MINNEAPOLIS+MIRAMAR MOBILE MODESTO MONTGOMERY MORENO_VALLEY MURFREESBORO MURRIETA NAPERVILLE NASHUA NASHVILLE+NEW_HAVEN NEW_ORLEANS NEW_YORK NEWARK NEWPORT_NEWS NORFOLK NORMAN NORTH_LAS_VEGAS NORWALK OAKLAND+OCEANSIDE ODESSA OKLAHOMA_CITY OLATHE OMAHA ONTARIO ORANGE ORLANDO OVERLAND_PARK OXNARD PALM_BAY+PALMDALE PALO_ALTO PASADENA PATERSON PEMBROKE_PINES PEORIA PHILADELPHIA PHOENIX PITTSBURGH PLANO+POMONA PORT_ST_LUCIE PORTLAND PROVIDENCE PROVO PUEBLO RALEIGH RANCHO_CUCAMONGA READING RENO+RICHARDSON RICHMOND RIVERSIDE ROANOKE ROCHESTER ROCKFORD ROSEVILLE ROUND_ROCK SACRAMENTO SAGINAW+SALEM SALINAS SALT_LAKE_CITY SAN_ANTONIO SAN_BERNARDINO SAN_DIEGO SAN_FRANCISCO SAN_JOSE+SAN_MATEO SANDY_SPRINGS SANTA_ANA SANTA_BARBARA SANTA_CLARA SANTA_CLARITA SANTA_FE SANTA_MARIA+SANTA_MONICA SANTA_ROSA SAVANNAH SCOTTSDALE SEATTLE SHREVEPORT SIMI_VALLEY SIOUX_CITY SIOUX_FALLS+SOUTH_BEND SPARKS SPOKANE SPRINGFIELD ST_LOUIS ST_PAUL ST_PETERSBURG STAMFORD STERLING_HEIGHTS+STOCKTON SUNNYVALE SURPRISE SYRACUSE TACOMA TALLAHASSEE TAMPA TEMECULA TEMPE THORNTON THOUSAND_OAKS+TOLEDO TOPEKA TORRANCE TRENTON TUCSON TULSA TUSCALOOSA TYLER VACAVILLE VALLEJO VANCOUVER VENTURA+VICTORVILLE VIRGINIA_BEACH VISALIA WACO WARREN WASHINGTON WATERBURY WEST_COVINA WEST_JORDAN+WESTMINSTER WICHITA WILMINGTON WINSTON_SALEM WORCESTER YONKERS YUMA+""".split()++STREETS = """+AVE BLVD CIR CT DR EXPY HWY LN PKWY PL RD ROUTE ST TER TRL WAY+""".split()++SIGNAGE = """+ACCESS ALL ARRIVALS CLOSED CUSTOMER DAILY DELIVERIES DELIVERY DEPARTURES DEPOT DOCK ENTRANCE+EXIT FREIGHT GATE HOURS LOADING LOT NO OFFICE ONLY OPEN PARKING PERMIT PICKUP PLANT RECEIVING+RETURNS SERVICE SHIP SHIPPING STAFF STORE STORES SUITE TERMINAL TO UNIT VEHICLES VISITOR+WAREHOUSE YARD+""".split()+++def name_unguarded(segment: str) -> Optional[Tuple[str, List[str], float]]:+ """`_named_prose_language` with the all-caps evidence bar left off.++ Returns (language, tokens, diacritic_rate) when the rule would name the segment foreign+ with no bar at all, else None. Reimplemented here rather than imported so the sweep below+ does not depend on the value of either constant it is sweeping.+ """+ if not segment.strip() or _CODE_LINE.search(segment):+ return None+ prose = " ".join(tok for tok in segment.split() if not _JOINED.search(tok))+ shouted = any(ch.isupper() for ch in prose) and not any(ch.islower() for ch in prose)+ if not shouted:+ prose = _LETTER_RUN.sub(lambda m: " " if m.group().isupper() else m.group(), prose)+ tokens = _WORD.findall(prose)+ if len(tokens) < 4:+ return None+ prof = latin_profile(prose)+ lang = prof["language"]+ if lang in (None, "en"):+ return None+ if len({w.lower() for w in tokens} & _STOP.get(lang, set())) < 2:+ return None+ return lang, tokens, float(prof["diacritic_rate"])+++def accepts(named: Tuple[str, List[str], float], sw_bar: int, wd_bar: int, dia: bool) -> bool:+ """Whether a bar of (`sw_bar`, `wd_bar`, diacritic escape `dia`) lets a named line through."""+ lang, tokens, rate = named+ if wd_bar and not any(len(t) >= wd_bar for t in tokens):+ return False+ if dia and rate >= NON_EN_DIACRITIC_RATE:+ return True+ if not sw_bar:+ return True+ matched = {t.lower() for t in tokens} & _STOP.get(lang, set())+ return any(len(w) >= sw_bar for w in matched)+++def massive_rows() -> Dict[str, List[str]]:+ """The pinned test split, from the hub or from an already-downloaded snapshot of it."""+ from huggingface_hub import hf_hub_download+ rows: Dict[str, List[str]] = {}+ for loc in LOCALES:+ name = "test/%s.json.gz" % loc+ try:+ path = hf_hub_download(DATASET, name, revision=REVISION, repo_type="dataset")+ except Exception: # offline: the same revision, already in the local cache+ path = (Path.home() / ".cache/huggingface/hub"+ / ("datasets--%s" % DATASET.replace("/", "--"))+ / "snapshots" / REVISION / name)+ if not path.exists():+ raise+ with gzip.open(str(path), "rt", encoding="utf-8") as fh:+ rows[loc] = [json.loads(line)["text"] for line in fh if line.strip()]+ return rows+++def build_prose(rows: Dict[str, List[str]]) -> List[Tuple[str, Tuple]]:+ """Upper-cased MASSIVE rows the unguarded rule names as their own locale."""+ out = []+ for loc, texts in rows.items():+ for text in texts:+ named = name_unguarded(text.upper())+ if named is not None and named[0] == loc:+ out.append((text.upper(), named))+ return out+++def build_acronyms(rng: random.Random, n: int) -> List[Tuple[str, Optional[Tuple]]]:+ out = []+ for _ in range(n):+ k = rng.randint(4, 8)+ line = " ".join(rng.choice(ACRONYMS) for _ in range(k))+ out.append((line, name_unguarded(line)))+ return out+++def build_addresses(rng: random.Random, n: int) -> List[Tuple[str, Optional[Tuple]]]:+ """All-caps address and signage lines. `_` in a place name stands for a space."""+ place = lambda: rng.choice(PLACES).replace("_", " ")+ out = []+ for _ in range(n):+ shape = rng.randint(0, 4)+ if shape == 0: # a store list+ line = "%s %s %s %s %s" % (rng.choice(SIGNAGE), place(), place(), place(),+ rng.choice(SIGNAGE))+ elif shape == 1: # a shipping label+ line = "%s %s %d %s %s %s" % (rng.choice(SIGNAGE), rng.choice(SIGNAGE),+ rng.randint(1, 9999), rng.choice(STREETS), place(),+ place())+ elif shape == 2: # a depot sign+ line = "%s %s %s %s %s" % (place(), rng.choice(SIGNAGE), rng.choice(SIGNAGE),+ rng.choice(SIGNAGE), place())+ elif shape == 3: # a route board+ line = "%s %d %s %s %s %s" % (rng.choice(STREETS), rng.randint(1, 99),+ place(), place(), place(), rng.choice(SIGNAGE))+ else: # a terminal board+ line = "%s %s %s %s %s %s" % (rng.choice(SIGNAGE), place(), place(),+ rng.choice(SIGNAGE), place(), rng.choice(SIGNAGE))+ out.append((line, name_unguarded(line)))+ return out+++BARS = [+ ("none (no bar at all)", 0, 0, False),+ ("diacritics only", 0, 0, True),+ ("word >= 5 only", 0, 5, True),+ ("stopword >= 3 only", 3, 0, True),+ ("stopword >= 4 only", 4, 0, True),+ ("stopword >= 5 only", 5, 0, True),+ ("stopword >= 3 AND word >= 5", 3, 5, True),+ ("stopword >= 4 AND word >= 5", 4, 5, True),+ ("stopword >= 5 AND word >= 5", 5, 5, True),+ ("stopword >= 4 AND word >= 6", 4, 6, True),+ ("stopword >= 4 AND word >= 7", 4, 7, True),+ ("stopword >= 4 AND word >= 5, no diacritic escape", 4, 5, False),+]+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__)+ ap.add_argument("--out", help="write the table and corpus sizes as JSON")+ ap.add_argument("--acronym-lines", type=int, default=ACRONYM_LINES)+ ap.add_argument("--address-lines", type=int, default=ADDRESS_LINES)+ args = ap.parse_args()++ rng = random.Random(SEED)+ prose = build_prose(massive_rows())+ acr = build_acronyms(rng, args.acronym_lines)+ adr = build_addresses(rng, args.address_lines)+ total = len(prose)+ print("dataset %s @ %s seed %d" % (DATASET, REVISION, SEED))+ print("pools: %d acronyms, %d place names, %d street types, %d signage words"+ % (len(ACRONYMS), len(PLACES), len(STREETS), len(SIGNAGE)))+ print("corpora: prose %d (upper-cased MASSIVE rows named as their own locale), "+ "acronym %d lines, address %d lines\n" % (total, len(acr), len(adr)))+ fmt = "%-48s %8s %8s %11s %11s"+ print(fmt % ("rule", "kept", "pct", "acronym FP", "address FP"))+ table = []+ for label, sw, wd, dia in BARS:+ kept = sum(1 for _, n in prose if accepts(n, sw, wd, dia))+ afp = sum(1 for _, n in acr if n is not None and accepts(n, sw, wd, dia))+ dfp = sum(1 for _, n in adr if n is not None and accepts(n, sw, wd, dia))+ print(fmt % (label, kept, "%.2f%%" % (100.0 * kept / total), afp, dfp))+ table.append({"rule": label, "stopword_bar": sw, "word_bar": wd, "diacritic_escape": dia,+ "prose_kept": kept, "prose_pct": round(100.0 * kept / total, 2),+ "acronym_fp": afp, "address_fp": dfp})+ if args.out:+ Path(args.out).write_text(json.dumps(+ {"dataset": DATASET, "revision": REVISION, "seed": SEED,+ "pools": {"acronyms": len(ACRONYMS), "places": len(PLACES),+ "streets": len(STREETS), "signage": len(SIGNAGE)},+ "corpora": {"prose": total, "acronym": len(acr), "address": len(adr)},+ "table": table}, indent=2) + "\n", encoding="utf-8")+ print("\nwrote %s" % args.out)+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/test_lang_guess.py b/tests/test_lang_guess.pyindex d34ecd9c..ce23facf 100644--- a/tests/test_lang_guess.py+++ b/tests/test_lang_guess.py@@ -503,6 +503,74 @@ check("veto/shouted german with umlauts routes multilingual",_route.route("WIE SPÄT IST ES IN KÖLN")["model"], "multilingual")+# Emphasis capitals, which the mixed-case half of the guard got wrong. The whole-state verdict+# re-takes itself with the all-caps runs blanked, so an acronym run cannot outvote the English+# prose around it -- but blanking *every* all-caps run deleted ordinary emphasis too, and+# emphasis falls on the words that carry the sentence, so the words that named the language were+# exactly the ones removed. No test covered this branch for genuine foreign prose, and all of+# these routed english. A run of `_SHOUTED_MIN_WORD` letters is a word, not an acronym, and is+# not blanked out of its own sentence. Eight of the ten are real MASSIVE test rows, shouted+# where a person would shout them; the other two are hand-written, one of them the Spanish case+# the review reported.+EMPHASIS_STILL_FOREIGN = [+ ("de", "sag mir das HEUTIGE DATUM"),+ ("de", "welche wecker habe ICH GESTELLT"),+ ("es", "quiero cancelar mi PEDIDO POR FAVOR"),+ ("es", "QUIERO EL ESTADO DEL brillo de mi pantalla"),+ ("pt", "quero o meu DINHEIRO DE VOLTA"),+ ("pt", "DIZ ME O TEMPO EM barcelona daqui a dois dias"),+ ("nl", "VERTEL ME HET weer deze week"),+ ("fr", "passer l'aspirateur dans LE COULOIR"),+ ("it", "CANCELLA LA MIA sveglia delle sette"),+ ("ro", "SPUNE-MI VREMEA pentru saptamana aceasta"),+]+for _want, _line in EMPHASIS_STILL_FOREIGN:+ check("emphasis/%s prose routes multilingual: %s" % (_want, _line[:30]),+ _route.route(_line)["model"], "multilingual")+ check("emphasis/%s prose keeps its language: %s" % (_want, _line[:30]),+ analyse(_line)["language"], _want)++# Monotonicity: adding one lowercase English token must not make foreign detection worse. The+# fully upper-cased form is held to the shouted bar and clears it; the same text with `ok ` in+# front used to fall into the mixed-case branch instead, which had no bar at all, and routed+# english. 4,285 MASSIVE rows moved that way; 316 still do, against 279 at the parent.+_SHOUT = "QUIERO CANCELAR MI PEDIDO POR FAVOR"+check("emphasis/upper-cased spanish routes multilingual",+ _route.route(_SHOUT)["model"], "multilingual")+check("emphasis/one lowercase token does not undo it",+ _route.route("ok " + _SHOUT)["model"], "multilingual")++# and the acronym side the blanking exists for is still closed, which is what keeps the bar on+# the length of the run rather than on nothing at all.+check("emphasis/acronym run inside english prose still routes english",+ _route.route("The MON DES EST LA codes were sent today")["model"], "english")+check("emphasis/acronym settings line inside english prose still routes english",+ _route.route("Please confirm the COM DOS LAN WAN VPN settings before Friday")["model"],+ "english")+check("emphasis/acronym run after one lowercase token still routes english",+ _route.route("ok MON DES EST LA")["model"], "english")++# Mixed cased and caseless script. Both caps bars answer by taking evidence *away* from the+# Latin letters, and `looks_non_english`, which decides what is left, reads Latin diacritics+# only -- so on a state that is 35% Cyrillic letters there was nothing left and an acronym run+# with a Russian greeting in front of it went to the English checkpoint. The script promotion+# cannot catch that fall: it needs `_non_latin_words`, which drops any run starting with a+# capital, and in a shouted line every run does. Neither bar applies once the caseless letters+# carry the state -- a wrong language name costs nothing there, because the checkpoint is+# chosen on `is_english`.+MIXED_SCRIPT_NOT_ENGLISH = [+ "\u041f\u0420\u0418\u0412\u0415\u0422 MON DES EST LA", # all caps: the shouted bar+ "\u041f\u0440\u0438\u0432\u0435\u0442 MON DES EST LA", # mixed case: the blanking+]+for _line in MIXED_SCRIPT_NOT_ENGLISH:+ check("mixed-script/routes multilingual: %s" % _line[:12],+ _route.route(_line)["model"], "multilingual")+ check("mixed-script/is not english: %s" % _line[:12],+ analyse(_line)["is_english"], False)+# with no caseless letters to carry it, the same run is vetoed as before+check("mixed-script/latin-only acronym run is still english",+ _route.route("MON DES EST LA")["model"], "english")+print("\n%d passed, %d failed" % (len(PASS), len(FAIL)))for f in FAIL:print(" FAIL " + f)